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