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 failures precede commitCommand; generic dispatch errors can follow commits and remain ambiguous.
15function dispatchWasNotAccepted(
16 error: Orchestrator.OrchestratorV2Error | ThreadManagement.ThreadManagementError,
17) {
18 switch (error._tag) {
19 case "OrchestratorCommandRejectedError":
20 case "OrchestratorThreadAlreadyExistsError":
21 case "OrchestratorProjectionError":
22 case "OrchestratorProviderAdapterError":
23 case "OrchestratorCommandPreviouslyRejectedError":
24 case "OrchestratorCommandIdConflictError":
25 case "OrchestratorSubagentThreadReadOnlyError":
26 case "OrchestratorThreadAboveModeLimitError":
27 case "ThreadManagementProviderInstanceDisabledError":
28 return true;
29 default:
30 return false;
31 }
32}
33const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error);
34const isThreadManagementError = Schema.is(ThreadManagement.ThreadManagementError);
35
36const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")(function* (
37 claimedPaths: ReadonlyArray<string>,
38 accepted: ReadonlyArray<ChatAttachment>,
39) {
40 if (claimedPaths.length === 0) return;
41 const config = yield* ServerConfig.ServerConfig;
42 const retained = new Set(
43 accepted.map((attachment) =>
44 resolveAttachmentPath({
45 attachmentsDir: config.attachmentsDir,
46 attachment,
47 }),
48 ),
49 );
50 yield* AttachmentClaims.releaseClaimedAttachments(
51 claimedPaths.filter((path) => !retained.has(path)),
52 );
53});
54
55/**
56 * A guest message goes out with the files the guest attached, never ones a client names. They
57 * are already the thread's attachments. A message no longer waiting gets none; the orchestrator
58 * then refuses or replays the send.
59 */
60const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments")(function* (
61 command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
62) {
63 if (command.guestMessageId === undefined) return command;
64 const threads = yield* ThreadManagement.ThreadManagementService;
65 // Only the thread record is needed; the window keeps the read small.
66 const { projection } = yield* threads
67 .getThreadSnapshotWindow(command.threadId, { rowLimit: 1 })
68 .pipe(
69 Effect.mapError(
70 (cause) =>
71 new AttachmentClaims.AttachmentClaimError({
72 message: "Failed to read the guest message.",
73 cause,
74 }),
75 ),
76 );
77 const message = projection.thread.guestShare?.messages.find(
78 (candidate) => candidate.id === command.guestMessageId && candidate.status === "pending",
79 );
80 return { ...command, attachments: message?.attachments ?? [] };
81});
82
83export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
84 incoming: OrchestrationV2Command,
85) {
86 const command =
87 incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming;
88 const threads = yield* ThreadManagement.ThreadManagementService;
89 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
90 const config = yield* ServerConfig.ServerConfig;
91 const incomingByQuestionId = command.attachmentsByQuestionId;
92 yield* AttachmentClaims.validateAttachmentLimits(Object.values(incomingByQuestionId).flat());
93 const claimedPaths: string[] = [];
94 const prepared = yield* Effect.gen(function* () {
95 const attachmentsByQuestionId: import("@t3tools/contracts").UserInputAttachments = {};
96 for (const [questionId, attachments] of Object.entries(incomingByQuestionId)) {
97 const claimed = yield* AttachmentClaims.claimPendingAttachments({
98 threadId: command.threadId,
99 attachments,
100 });
101 claimedPaths.push(...claimed.claimedPaths);
102 Object.defineProperty(attachmentsByQuestionId, questionId, {
103 value: claimed.attachments,
104 enumerable: true,
105 });
106 }
107 const answers = yield* appendUserInputAttachmentPaths({
108 answers: command.answers ?? {},
109 attachmentsByQuestionId,
110 attachmentsDir: config.attachmentsDir,
111 }).pipe(
112 Effect.mapError(
113 (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }),
114 ),
115 );
116 return { answers, attachmentsByQuestionId };
117 }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths)));
118 return yield* threads
119 .dispatch({
120 ...command,
121 answers: prepared.answers,
122 attachmentsByQuestionId: prepared.attachmentsByQuestionId,
123 })
124 .pipe(
125 Effect.tap((result) => {
126 // Replayed receipts refer to the first answer; release this attempt's unused copies only with a resolved item.
127 // Missing questionAnswer means no accepted attachments; missing resolution leaves delivery ambiguous.
128 const answeredItems = result.storedEvents.flatMap(({ event }) =>
129 event.type === "turn-item.updated" &&
130 event.payload.type === "user_input_request" &&
131 event.payload.requestId === command.requestId
132 ? [event.payload]
133 : [],
134 );
135 return answeredItems.length > 0
136 ? releaseUnusedClaims(
137 claimedPaths,
138 answeredItems.flatMap((item) =>
139 item.questionAnswer === undefined
140 ? []
141 : Object.values(item.questionAnswer.attachmentsByQuestionId).flat(),
142 ),
143 )
144 : Effect.void;
145 }),
146 Effect.tapError((error) =>
147 dispatchWasNotAccepted(error)
148 ? AttachmentClaims.releaseClaimedAttachments(claimedPaths)
149 : Effect.void,
150 ),
151 );
152 }
153 if (
154 command.type !== "message.dispatch" &&
155 (command.type !== "queued-run.edit" || command.attachments === undefined)
156 )
157 return yield* threads.dispatch(command);
158 const claimed = yield* AttachmentClaims.claimPendingAttachments({
159 threadId: command.threadId,
160 attachments: command.attachments ?? [],
161 });
162 return yield* threads
163 .dispatch({
164 ...command,
165 attachments: claimed.attachments,
166 ...(command.context
167 ? {
168 context: remapComposerContextAttachments(
169 command.context,
170 command.attachments ?? [],
171 claimed.attachments,
172 ),
173 }
174 : {}),
175 })
176 .pipe(
177 Effect.tap((result) =>
178 releaseUnusedClaims(
179 claimed.claimedPaths,
180 result.storedEvents.flatMap(({ event }) =>
181 event.type === "message.updated" ? event.payload.attachments : [],
182 ),
183 ),
184 ),
185 Effect.tapError((error) =>
186 dispatchWasNotAccepted(error)
187 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
188 : Effect.void,
189 ),
190 );
191});
192
193export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(function* (
194 input: ThreadManagement.ThreadManagementSendInput,
195) {
196 const threads = yield* ThreadManagement.ThreadManagementService;
197 const claimed = yield* AttachmentClaims.claimPendingAttachments(input);
198 return yield* threads.sendToThread({ ...input, attachments: claimed.attachments }).pipe(
199 Effect.tap((result) => releaseUnusedClaims(claimed.claimedPaths, result.message.attachments)),
200 Effect.tapError((error) =>
201 dispatchWasNotAccepted(error)
202 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
203 : Effect.void,
204 ),
205 );
206});
207
208export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* (
209 input: ThreadLaunch.ThreadLaunchInput,
210) {
211 const launches = yield* ThreadLaunch.ThreadLaunchService;
212 yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []);
213 if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
214 return yield* launches.launch(input);
215 }
216 if (input.threadId === undefined) {
217 return yield* new AttachmentClaims.AttachmentClaimError({
218 message: "Uploaded attachments need a thread id at launch.",
219 });
220 }
221 const claimed = yield* AttachmentClaims.claimPendingAttachments({
222 threadId: input.threadId,
223 attachments: input.initialMessage.attachments,
224 });
225 return yield* launches
226 .launch({
227 ...input,
228 initialMessage: {
229 ...input.initialMessage,
230 attachments: claimed.attachments,
231 ...(input.initialMessage.context
232 ? {
233 context: remapComposerContextAttachments(
234 input.initialMessage.context,
235 input.initialMessage.attachments,
236 claimed.attachments,
237 ),
238 }
239 : {}),
240 },
241 })
242 .pipe(
243 Effect.tap((result) =>
244 releaseUnusedClaims(
245 claimed.claimedPaths,
246 result.projection.messages.flatMap((message) => message.attachments),
247 ),
248 ),
249 Effect.tapError((error) => {
250 if (error._tag === "ThreadManagementProviderInstanceDisabledError") {
251 return AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths);
252 }
253 // Project/receipt reads precede dispatch; create-thread errors can wrap post-message reads and prove nothing alone.
254 const notAccepted =
255 error.operation === "resolve-project" ||
256 error.operation === "read-receipt" ||
257 ((error.operation === "create-thread" || error.operation === "dispatch-message") &&
258 (isOrchestratorError(error.cause) || isThreadManagementError(error.cause)) &&
259 // Projection errors under create-thread can occur after the message commit.
260 (error.operation !== "create-thread" ||
261 error.cause._tag !== "OrchestratorProjectionError") &&
262 dispatchWasNotAccepted(error.cause));
263 return notAccepted
264 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
265 : Effect.void;
266 }),
267 );
268});