Open History to see the last commit
1import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences";
2import { appendUserInputAttachmentPaths } from "../provider/userInputAttachments.ts";
3import {
4 AuthProvidersManageScope,
5 type ChatAttachment,
6 type OrchestrationV2Command,
7} from "@t3tools/contracts";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Schema from "effect/Schema";
11import { resolveAttachmentPath } from "../attachmentStore.ts";
12import { rpcAuthorizationError } from "../auth/RpcAuthorization.ts";
13import * as ServerConfig from "../config.ts";
14import * as Orchestrator from "./Orchestrator.ts";
15
16import * as AttachmentClaims from "./AttachmentClaims.ts";
17import { isProviderSignOutPrompt } from "./CommandPolicy.ts";
18import * as ThreadLaunch from "./ThreadLaunchService.ts";
19import * as ThreadManagement from "./ThreadManagementService.ts";
20
21// These failures precede commitCommand; generic dispatch errors can follow commits and remain ambiguous.
22function dispatchWasNotAccepted(
23 error: Orchestrator.OrchestratorV2Error | ThreadManagement.ThreadManagementError,
24) {
25 switch (error._tag) {
26 case "OrchestratorCommandRejectedError":
27 case "OrchestratorThreadAlreadyExistsError":
28 case "OrchestratorProjectionError":
29 case "OrchestratorProviderAdapterError":
30 case "OrchestratorCommandPreviouslyRejectedError":
31 case "OrchestratorCommandIdConflictError":
32 case "OrchestratorSubagentThreadReadOnlyError":
33 case "OrchestratorThreadAboveModeLimitError":
34 case "OrchestratorProviderSelectionBusyError":
35 case "OrchestratorRuntimeModeAboveCeilingError":
36 case "ThreadManagementProviderInstanceDisabledError":
37 case "ThreadManagementWorktreeRestoreError":
38 return true;
39 default:
40 return false;
41 }
42}
43const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error);
44const isThreadManagementError = Schema.is(ThreadManagement.ThreadManagementError);
45
46const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")(function* (
47 claimedPaths: ReadonlyArray<string>,
48 accepted: ReadonlyArray<ChatAttachment>,
49) {
50 if (claimedPaths.length === 0) return;
51 const config = yield* ServerConfig.ServerConfig;
52 const retained = new Set(
53 accepted.flatMap((attachment) => {
54 const path = resolveAttachmentPath({
55 attachmentsDir: config.attachmentsDir,
56 attachment,
57 });
58 return path ? [path, `${path}.txt`] : [];
59 }),
60 );
61 yield* AttachmentClaims.releaseClaimedAttachments(
62 claimedPaths.filter((path) => !retained.has(path)),
63 );
64});
65
66/**
67 * A guest message goes out with the files the guest attached, never ones a client names. They
68 * are already the thread's attachments. A message no longer waiting gets none; the orchestrator
69 * then refuses or replays the send.
70 */
71const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments")(function* (
72 command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
73) {
74 if (command.guestMessageId === undefined) return command;
75 const threads = yield* ThreadManagement.ThreadManagementService;
76 // Only the thread record is needed; the window keeps the read small.
77 const { projection } = yield* threads
78 .getThreadSnapshotWindow(command.threadId, { rowLimit: 1 })
79 .pipe(
80 Effect.mapError(
81 (cause) =>
82 new AttachmentClaims.AttachmentClaimError({
83 message: "Failed to read the guest message.",
84 cause,
85 }),
86 ),
87 );
88 const message = projection.thread.guestShare?.messages.find(
89 (candidate) => candidate.id === command.guestMessageId && candidate.status === "pending",
90 );
91 return { ...command, attachments: message?.attachments ?? [] };
92});
93
94/**
95 * For a caller without `providers:manage`. An edit that omits `attachments` keeps the queued
96 * ones, so `/logout` signs out only when the queued message has none. The edit goes on with
97 * the files read here, so an edit racing this one cannot strip them afterwards.
98 */
99export const withQueuedAttachmentsOnSignOutText = Effect.fn(
100 "ThreadMessageIntake.withQueuedAttachmentsOnSignOutText",
101)(function* (command: Extract<OrchestrationV2Command, { readonly type: "queued-run.edit" }>) {
102 if (
103 command.attachments !== undefined ||
104 !isProviderSignOutPrompt({ text: command.text, attachments: [] })
105 ) {
106 return command;
107 }
108 const threads = yield* ThreadManagement.ThreadManagementService;
109 // A retry of an accepted edit replays its receipt, even after its run left the queue.
110 if (yield* threads.hasReceipt(command.commandId)) return command;
111 const { runs } = yield* threads.getThreadRecords(command.threadId, ["runs"], {
112 runIds: [command.runId],
113 });
114 const queuedRun = runs.find((run) => run.id === command.runId && run.status === "queued");
115 const attachments =
116 queuedRun === undefined
117 ? []
118 : ((yield* threads.getMessagesById(command.threadId, [queuedRun.userMessageId])).get(
119 queuedRun.userMessageId,
120 )?.attachments ?? []);
121 if (attachments.length === 0) return yield* rpcAuthorizationError(AuthProvidersManageScope);
122 return { ...command, attachments };
123});
124
125/**
126 * `sender.managesProviders` is whether the caller holds `providers:manage`. RPC authorization
127 * has already checked every command whose payload shows a provider sign-out; a queued edit
128 * that keeps its attachments is the one case decided here.
129 */
130export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
131 incoming: OrchestrationV2Command,
132 sender: { readonly managesProviders: boolean },
133) {
134 const command =
135 incoming.type === "message.dispatch"
136 ? yield* withGuestAttachments(incoming)
137 : incoming.type === "queued-run.edit" && !sender.managesProviders
138 ? yield* withQueuedAttachmentsOnSignOutText(incoming)
139 : incoming;
140 const threads = yield* ThreadManagement.ThreadManagementService;
141 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
142 const config = yield* ServerConfig.ServerConfig;
143 const incomingByQuestionId = command.attachmentsByQuestionId;
144 yield* AttachmentClaims.validateAttachmentLimits(Object.values(incomingByQuestionId).flat());
145 const claimedPaths: string[] = [];
146 const prepared = yield* Effect.gen(function* () {
147 const attachmentsByQuestionId: import("@t3tools/contracts").UserInputAttachments = {};
148 for (const [questionId, attachments] of Object.entries(incomingByQuestionId)) {
149 const claimed = yield* AttachmentClaims.claimPendingAttachments({
150 threadId: command.threadId,
151 attachments,
152 });
153 claimedPaths.push(...claimed.claimedPaths);
154 Object.defineProperty(attachmentsByQuestionId, questionId, {
155 value: claimed.attachments,
156 enumerable: true,
157 });
158 }
159 // An answer by message carries its files as message attachments, not paths in its text.
160 const { runtimeRequests } = yield* threads
161 .getThreadRecords(command.threadId, ["runtimeRequests"], {
162 runtimeRequestStatuses: ["pending"],
163 })
164 .pipe(
165 Effect.mapError(
166 (cause) =>
167 new AttachmentClaims.AttachmentClaimError({
168 message: "Failed to read the question.",
169 cause,
170 }),
171 ),
172 );
173 const answersByMessage =
174 runtimeRequests.find((request) => request.id === command.requestId)?.responseCapability
175 .type === "message";
176 const answers = answersByMessage
177 ? (command.answers ?? {})
178 : yield* appendUserInputAttachmentPaths({
179 answers: command.answers ?? {},
180 attachmentsByQuestionId,
181 attachmentsDir: config.attachmentsDir,
182 }).pipe(
183 Effect.mapError(
184 (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }),
185 ),
186 );
187 return { answers, attachmentsByQuestionId };
188 }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths)));
189 return yield* threads
190 .dispatch({
191 ...command,
192 answers: prepared.answers,
193 attachmentsByQuestionId: prepared.attachmentsByQuestionId,
194 })
195 .pipe(
196 Effect.tap((result) => {
197 // Replayed receipts refer to the first answer; release this attempt's unused copies only with a resolved item.
198 // Missing questionAnswer means no accepted attachments; missing resolution leaves delivery ambiguous.
199 const answeredItems = result.storedEvents.flatMap(({ event }) =>
200 event.type === "turn-item.updated" &&
201 event.payload.type === "user_input_request" &&
202 event.payload.requestId === command.requestId
203 ? [event.payload]
204 : [],
205 );
206 return answeredItems.length > 0
207 ? releaseUnusedClaims(
208 claimedPaths,
209 answeredItems.flatMap((item) =>
210 item.questionAnswer === undefined
211 ? []
212 : Object.values(item.questionAnswer.attachmentsByQuestionId).flat(),
213 ),
214 )
215 : Effect.void;
216 }),
217 Effect.tapError((error) =>
218 dispatchWasNotAccepted(error)
219 ? AttachmentClaims.releaseClaimedAttachments(claimedPaths)
220 : Effect.void,
221 ),
222 );
223 }
224 if (
225 command.type !== "message.dispatch" &&
226 (command.type !== "queued-run.edit" || command.attachments === undefined)
227 )
228 return yield* threads.dispatch(command);
229 // An accepted edit's retry replays its receipt even if a later cleanup removed its files.
230 if (command.type === "queued-run.edit" && !(yield* threads.hasReceipt(command.commandId))) {
231 const config = yield* ServerConfig.ServerConfig;
232 const fileSystem = yield* FileSystem.FileSystem;
233 // A stale view can keep a file that another client's edit dropped and deleted.
234 for (const attachment of command.attachments ?? []) {
235 if (AttachmentClaims.attachmentIsPendingUpload(attachment)) continue;
236 const path = resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment });
237 if (
238 path !== null &&
239 !(yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false)))
240 ) {
241 return yield* new AttachmentClaims.AttachmentClaimError({
242 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
243 });
244 }
245 }
246 }
247 const claimed = yield* AttachmentClaims.claimPendingAttachments({
248 threadId: command.threadId,
249 attachments: command.attachments ?? [],
250 });
251 return yield* threads
252 .dispatch({
253 ...command,
254 attachments: claimed.attachments,
255 ...(command.context
256 ? {
257 context: remapComposerContextAttachments(
258 command.context,
259 command.attachments ?? [],
260 claimed.attachments,
261 ),
262 }
263 : {}),
264 })
265 .pipe(
266 Effect.tap((result) =>
267 releaseUnusedClaims(
268 claimed.claimedPaths,
269 result.storedEvents.flatMap(({ event }) =>
270 event.type === "message.updated" ? event.payload.attachments : [],
271 ),
272 ),
273 ),
274 Effect.tapError((error) =>
275 dispatchWasNotAccepted(error)
276 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
277 : Effect.void,
278 ),
279 );
280});
281
282export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(function* (
283 input: ThreadManagement.ThreadManagementSendInput,
284) {
285 const threads = yield* ThreadManagement.ThreadManagementService;
286 const claimed = yield* AttachmentClaims.claimPendingAttachments(input);
287 return yield* threads.sendToThread({ ...input, attachments: claimed.attachments }).pipe(
288 Effect.tap((result) => releaseUnusedClaims(claimed.claimedPaths, result.message.attachments)),
289 Effect.tapError((error) =>
290 dispatchWasNotAccepted(error)
291 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
292 : Effect.void,
293 ),
294 );
295});
296
297export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* (
298 input: ThreadLaunch.ThreadLaunchInput,
299) {
300 const launches = yield* ThreadLaunch.ThreadLaunchService;
301 yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []);
302 if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
303 return yield* launches.launch(input);
304 }
305 if (input.threadId === undefined) {
306 return yield* new AttachmentClaims.AttachmentClaimError({
307 message: "Uploaded attachments need a thread id at launch.",
308 });
309 }
310 const claimed = yield* AttachmentClaims.claimPendingAttachments({
311 threadId: input.threadId,
312 attachments: input.initialMessage.attachments,
313 });
314 return yield* launches
315 .launch({
316 ...input,
317 initialMessage: {
318 ...input.initialMessage,
319 attachments: claimed.attachments,
320 ...(input.initialMessage.context
321 ? {
322 context: remapComposerContextAttachments(
323 input.initialMessage.context,
324 input.initialMessage.attachments,
325 claimed.attachments,
326 ),
327 }
328 : {}),
329 },
330 })
331 .pipe(
332 Effect.tap((result) =>
333 releaseUnusedClaims(
334 claimed.claimedPaths,
335 result.projection.messages.flatMap((message) => message.attachments),
336 ),
337 ),
338 Effect.tapError((error) => {
339 if (error._tag === "ThreadManagementProviderInstanceDisabledError") {
340 return AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths);
341 }
342 // Project/receipt reads precede dispatch; create-thread errors can wrap post-message reads and prove nothing alone.
343 const notAccepted =
344 error.operation === "resolve-project" ||
345 error.operation === "read-receipt" ||
346 ((error.operation === "create-thread" || error.operation === "dispatch-message") &&
347 (isOrchestratorError(error.cause) || isThreadManagementError(error.cause)) &&
348 // Projection errors under create-thread can occur after the message commit.
349 (error.operation !== "create-thread" ||
350 error.cause._tag !== "OrchestratorProjectionError") &&
351 dispatchWasNotAccepted(error.cause));
352 return notAccepted
353 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
354 : Effect.void;
355 }),
356 );
357});