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