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