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