Open History to see the last commit
1import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences";
2import { appendUserInputAttachmentPaths } from "../provider/userInputAttachments.ts";
3import type { ChatAttachment, OrchestrationV2Command } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Schema from "effect/Schema";
6import { resolveAttachmentPath } from "../attachmentStore.ts";
7import * as ServerConfig from "../config.ts";
8import * as Orchestrator from "./Orchestrator.ts";
9
10import * as AttachmentClaims from "./AttachmentClaims.ts";
11import * as ThreadLaunch from "./ThreadLaunchService.ts";
12import * as ThreadManagement from "./ThreadManagementService.ts";
13
14// These dispatcher failures occur in receipt validation or planning, before
15// commitCommand. Generic dispatch errors can follow a commit and remain uncertain.
16function dispatchWasNotAccepted(
17 error: Orchestrator.OrchestratorV2Error | ThreadManagement.ThreadManagementError,
18) {
19 switch (error._tag) {
20 case "OrchestratorCommandRejectedError":
21 case "OrchestratorProjectionError":
22 case "OrchestratorProviderAdapterError":
23 case "OrchestratorCommandPreviouslyRejectedError":
24 case "OrchestratorCommandIdConflictError":
25 return true;
26 default:
27 return false;
28 }
29}
30const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error);
31
32const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")(function* (
33 claimedPaths: ReadonlyArray<string>,
34 accepted: ReadonlyArray<ChatAttachment>,
35) {
36 if (claimedPaths.length === 0) return;
37 const config = yield* ServerConfig.ServerConfig;
38 const retained = new Set(
39 accepted.map((attachment) =>
40 resolveAttachmentPath({
41 attachmentsDir: config.attachmentsDir,
42 attachment,
43 }),
44 ),
45 );
46 yield* AttachmentClaims.releaseClaimedAttachments(
47 claimedPaths.filter((path) => !retained.has(path)),
48 );
49});
50
51export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
52 command: OrchestrationV2Command,
53) {
54 const threads = yield* ThreadManagement.ThreadManagementService;
55 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
56 const config = yield* ServerConfig.ServerConfig;
57 const incomingByQuestionId = command.attachmentsByQuestionId;
58 // Claims accumulate across questions, so all of preparation shares one
59 // rollback boundary: any failure before dispatch removes every new copy.
60 const claimedPaths: string[] = [];
61 const prepared = yield* Effect.gen(function* () {
62 const attachmentsByQuestionId: import("@t3tools/contracts").UserInputAttachments = {};
63 for (const [questionId, attachments] of Object.entries(incomingByQuestionId)) {
64 const claimed = yield* AttachmentClaims.claimPendingAttachments({
65 threadId: command.threadId,
66 attachments,
67 });
68 claimedPaths.push(...claimed.claimedPaths);
69 Object.defineProperty(attachmentsByQuestionId, questionId, {
70 value: claimed.attachments,
71 enumerable: true,
72 });
73 }
74 const answers = yield* appendUserInputAttachmentPaths({
75 answers: command.answers ?? {},
76 attachmentsByQuestionId,
77 attachmentsDir: config.attachmentsDir,
78 }).pipe(
79 Effect.mapError(
80 (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }),
81 ),
82 );
83 return { answers, attachmentsByQuestionId };
84 }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths)));
85 return yield* threads
86 .dispatch({
87 ...command,
88 answers: prepared.answers,
89 attachmentsByQuestionId: prepared.attachmentsByQuestionId,
90 })
91 .pipe(
92 Effect.tap((result) => {
93 // A replayed receipt reports the first attempt's answer, so this
94 // attempt's copies go unreferenced and are released. The resolved
95 // turn item proves the respond was applied; questionAnswer is only
96 // recorded when the accepted command carried attachments, so its
97 // absence means the accepted answer referenced no copies. With no
98 // resolved item at all the outcome is ambiguous and everything stays.
99 const answeredItems = result.storedEvents.flatMap(({ event }) =>
100 event.type === "turn-item.updated" &&
101 event.payload.type === "user_input_request" &&
102 event.payload.requestId === command.requestId
103 ? [event.payload]
104 : [],
105 );
106 return answeredItems.length > 0
107 ? releaseUnusedClaims(
108 claimedPaths,
109 answeredItems.flatMap((item) =>
110 item.questionAnswer === undefined
111 ? []
112 : Object.values(item.questionAnswer.attachmentsByQuestionId).flat(),
113 ),
114 )
115 : Effect.void;
116 }),
117 Effect.tapError((error) =>
118 dispatchWasNotAccepted(error)
119 ? AttachmentClaims.releaseClaimedAttachments(claimedPaths)
120 : Effect.void,
121 ),
122 );
123 }
124 if (
125 command.type !== "message.dispatch" &&
126 (command.type !== "queued-run.edit" || command.attachments === undefined)
127 )
128 return yield* threads.dispatch(command);
129 const claimed = yield* AttachmentClaims.claimPendingAttachments({
130 threadId: command.threadId,
131 attachments: command.attachments ?? [],
132 });
133 return yield* threads
134 .dispatch({
135 ...command,
136 attachments: claimed.attachments,
137 ...(command.context
138 ? {
139 context: remapComposerContextAttachments(
140 command.context,
141 command.attachments ?? [],
142 claimed.attachments,
143 ),
144 }
145 : {}),
146 })
147 .pipe(
148 Effect.tap((result) =>
149 releaseUnusedClaims(
150 claimed.claimedPaths,
151 result.storedEvents.flatMap(({ event }) =>
152 event.type === "message.updated" ? event.payload.attachments : [],
153 ),
154 ),
155 ),
156 Effect.tapError((error) =>
157 dispatchWasNotAccepted(error)
158 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
159 : Effect.void,
160 ),
161 );
162});
163
164export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(function* (
165 input: ThreadManagement.ThreadManagementSendInput,
166) {
167 const threads = yield* ThreadManagement.ThreadManagementService;
168 const claimed = yield* AttachmentClaims.claimPendingAttachments(input);
169 return yield* threads.sendToThread({ ...input, attachments: claimed.attachments }).pipe(
170 Effect.tap((result) => releaseUnusedClaims(claimed.claimedPaths, result.message.attachments)),
171 Effect.tapError((error) =>
172 dispatchWasNotAccepted(error)
173 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
174 : Effect.void,
175 ),
176 );
177});
178
179export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* (
180 input: ThreadLaunch.ThreadLaunchInput,
181) {
182 const launches = yield* ThreadLaunch.ThreadLaunchService;
183 if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
184 return yield* launches.launch(input);
185 }
186 if (input.threadId === undefined) {
187 return yield* new AttachmentClaims.AttachmentClaimError({
188 message: "Uploaded attachments need a thread id at launch.",
189 });
190 }
191 const claimed = yield* AttachmentClaims.claimPendingAttachments({
192 threadId: input.threadId,
193 attachments: input.initialMessage.attachments,
194 });
195 return yield* launches
196 .launch({
197 ...input,
198 initialMessage: {
199 ...input.initialMessage,
200 attachments: claimed.attachments,
201 ...(input.initialMessage.context
202 ? {
203 context: remapComposerContextAttachments(
204 input.initialMessage.context,
205 input.initialMessage.attachments,
206 claimed.attachments,
207 ),
208 }
209 : {}),
210 },
211 })
212 .pipe(
213 Effect.tap((result) =>
214 releaseUnusedClaims(
215 claimed.claimedPaths,
216 result.projection.messages.flatMap((message) => message.attachments),
217 ),
218 ),
219 Effect.tapError((error) => {
220 // Project/receipt reads precede message dispatch. The create-thread error
221 // also wraps post-message projection reads, so its tag alone is not proof.
222 const notAccepted =
223 error.operation === "resolve-project" ||
224 error.operation === "read-receipt" ||
225 ((error.operation === "create-thread" || error.operation === "dispatch-message") &&
226 isOrchestratorError(error.cause) &&
227 // Projection errors under create-thread can occur after the message commit.
228 (error.operation !== "create-thread" ||
229 error.cause._tag !== "OrchestratorProjectionError") &&
230 dispatchWasNotAccepted(error.cause));
231 return notAccepted
232 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
233 : Effect.void;
234 }),
235 );
236});