Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadMessageIntake.ts

291 lines11.6 KB

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 FileSystem from "effect/FileSystem";
6import * as Schema from "effect/Schema";
7import { resolveAttachmentPath } from "../attachmentStore.ts";
8import * as ServerConfig from "../config.ts";
9import * as Orchestrator from "./Orchestrator.ts";
10​
11import * as AttachmentClaims from "./AttachmentClaims.ts";
12import * as ThreadLaunch from "./ThreadLaunchService.ts";
13import * as ThreadManagement from "./ThreadManagementService.ts";
14​
15// These failures precede commitCommand; generic dispatch errors can follow commits and remain ambiguous.
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 "OrchestratorProviderSelectionBusyError":
29 case "OrchestratorRuntimeModeAboveCeilingError":
30 case "ThreadManagementProviderInstanceDisabledError":
31 case "ThreadManagementWorktreeRestoreError":
32 return true;
33 default:
34 return false;
35 }
37const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error);
38const isThreadManagementError = Schema.is(ThreadManagement.ThreadManagementError);
39​
40const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")(function* (
41 claimedPaths: ReadonlyArray<string>,
42 accepted: ReadonlyArray<ChatAttachment>,
43) {
44 if (claimedPaths.length === 0) return;
45 const config = yield* ServerConfig.ServerConfig;
46 const retained = new Set(
47 accepted.flatMap((attachment) => {
48 const path = resolveAttachmentPath({
49 attachmentsDir: config.attachmentsDir,
50 attachment,
51 });
52 return path ? [path, `${path}.txt`] : [];
53 }),
54 );
55 yield* AttachmentClaims.releaseClaimedAttachments(
56 claimedPaths.filter((path) => !retained.has(path)),
57 );
58});
59​
60/**
61 * A guest message goes out with the files the guest attached, never ones a client names. They
62 * are already the thread's attachments. A message no longer waiting gets none; the orchestrator
63 * then refuses or replays the send.
64 */
65const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments")(function* (
66 command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
67) {
68 if (command.guestMessageId === undefined) return command;
69 const threads = yield* ThreadManagement.ThreadManagementService;
70 // Only the thread record is needed; the window keeps the read small.
71 const { projection } = yield* threads
72 .getThreadSnapshotWindow(command.threadId, { rowLimit: 1 })
73 .pipe(
74 Effect.mapError(
75 (cause) =>
76 new AttachmentClaims.AttachmentClaimError({
77 message: "Failed to read the guest message.",
78 cause,
79 }),
80 ),
81 );
82 const message = projection.thread.guestShare?.messages.find(
83 (candidate) => candidate.id === command.guestMessageId && candidate.status === "pending",
84 );
85 return { ...command, attachments: message?.attachments ?? [] };
86});
87​
88export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
89 incoming: OrchestrationV2Command,
90) {
91 const command =
92 incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming;
93 const threads = yield* ThreadManagement.ThreadManagementService;
94 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
95 const config = yield* ServerConfig.ServerConfig;
96 const incomingByQuestionId = command.attachmentsByQuestionId;
97 yield* AttachmentClaims.validateAttachmentLimits(Object.values(incomingByQuestionId).flat());
98 const claimedPaths: string[] = [];
99 const prepared = yield* Effect.gen(function* () {
100 const attachmentsByQuestionId: import("@t3tools/contracts").UserInputAttachments = {};
101 for (const [questionId, attachments] of Object.entries(incomingByQuestionId)) {
102 const claimed = yield* AttachmentClaims.claimPendingAttachments({
103 threadId: command.threadId,
104 attachments,
105 });
106 claimedPaths.push(...claimed.claimedPaths);
107 Object.defineProperty(attachmentsByQuestionId, questionId, {
108 value: claimed.attachments,
109 enumerable: true,
110 });
111 }
112 const answers = yield* appendUserInputAttachmentPaths({
113 answers: command.answers ?? {},
114 attachmentsByQuestionId,
115 attachmentsDir: config.attachmentsDir,
116 }).pipe(
117 Effect.mapError(
118 (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }),
119 ),
120 );
121 return { answers, attachmentsByQuestionId };
122 }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths)));
123 return yield* threads
124 .dispatch({
125 ...command,
126 answers: prepared.answers,
127 attachmentsByQuestionId: prepared.attachmentsByQuestionId,
128 })
129 .pipe(
130 Effect.tap((result) => {
131 // Replayed receipts refer to the first answer; release this attempt's unused copies only with a resolved item.
132 // Missing questionAnswer means no accepted attachments; missing resolution leaves delivery ambiguous.
133 const answeredItems = result.storedEvents.flatMap(({ event }) =>
134 event.type === "turn-item.updated" &&
135 event.payload.type === "user_input_request" &&
136 event.payload.requestId === command.requestId
137 ? [event.payload]
138 : [],
139 );
140 return answeredItems.length > 0
141 ? releaseUnusedClaims(
142 claimedPaths,
143 answeredItems.flatMap((item) =>
144 item.questionAnswer === undefined
145 ? []
146 : Object.values(item.questionAnswer.attachmentsByQuestionId).flat(),
147 ),
148 )
149 : Effect.void;
150 }),
151 Effect.tapError((error) =>
152 dispatchWasNotAccepted(error)
153 ? AttachmentClaims.releaseClaimedAttachments(claimedPaths)
154 : Effect.void,
155 ),
156 );
157 }
158 if (
159 command.type !== "message.dispatch" &&
160 (command.type !== "queued-run.edit" || command.attachments === undefined)
161 )
162 return yield* threads.dispatch(command);
163 // An accepted edit's retry replays its receipt even if a later cleanup removed its files.
164 if (command.type === "queued-run.edit" && !(yield* threads.hasReceipt(command.commandId))) {
165 const config = yield* ServerConfig.ServerConfig;
166 const fileSystem = yield* FileSystem.FileSystem;
167 // A stale view can keep a file that another client's edit dropped and deleted.
168 for (const attachment of command.attachments ?? []) {
169 if (AttachmentClaims.attachmentIsPendingUpload(attachment)) continue;
170 const path = resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment });
171 if (
172 path !== null &&
173 !(yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false)))
174 ) {
175 return yield* new AttachmentClaims.AttachmentClaimError({
176 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
177 });
178 }
179 }
180 }
181 const claimed = yield* AttachmentClaims.claimPendingAttachments({
182 threadId: command.threadId,
183 attachments: command.attachments ?? [],
184 });
185 return yield* threads
186 .dispatch({
187 ...command,
188 attachments: claimed.attachments,
189 ...(command.context
190 ? {
191 context: remapComposerContextAttachments(
192 command.context,
193 command.attachments ?? [],
194 claimed.attachments,
195 ),
196 }
197 : {}),
198 })
199 .pipe(
200 Effect.tap((result) =>
201 releaseUnusedClaims(
202 claimed.claimedPaths,
203 result.storedEvents.flatMap(({ event }) =>
204 event.type === "message.updated" ? event.payload.attachments : [],
205 ),
206 ),
207 ),
208 Effect.tapError((error) =>
209 dispatchWasNotAccepted(error)
210 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
211 : Effect.void,
212 ),
213 );
214});
215​
216export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(function* (
217 input: ThreadManagement.ThreadManagementSendInput,
218) {
219 const threads = yield* ThreadManagement.ThreadManagementService;
220 const claimed = yield* AttachmentClaims.claimPendingAttachments(input);
221 return yield* threads.sendToThread({ ...input, attachments: claimed.attachments }).pipe(
222 Effect.tap((result) => releaseUnusedClaims(claimed.claimedPaths, result.message.attachments)),
223 Effect.tapError((error) =>
224 dispatchWasNotAccepted(error)
225 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
226 : Effect.void,
227 ),
228 );
229});
230​
231export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* (
232 input: ThreadLaunch.ThreadLaunchInput,
233) {
234 const launches = yield* ThreadLaunch.ThreadLaunchService;
235 yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []);
236 if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
237 return yield* launches.launch(input);
238 }
239 if (input.threadId === undefined) {
240 return yield* new AttachmentClaims.AttachmentClaimError({
241 message: "Uploaded attachments need a thread id at launch.",
242 });
243 }
244 const claimed = yield* AttachmentClaims.claimPendingAttachments({
245 threadId: input.threadId,
246 attachments: input.initialMessage.attachments,
247 });
248 return yield* launches
249 .launch({
250 ...input,
251 initialMessage: {
252 ...input.initialMessage,
253 attachments: claimed.attachments,
254 ...(input.initialMessage.context
255 ? {
256 context: remapComposerContextAttachments(
257 input.initialMessage.context,
258 input.initialMessage.attachments,
259 claimed.attachments,
260 ),
261 }
262 : {}),
263 },
264 })
265 .pipe(
266 Effect.tap((result) =>
267 releaseUnusedClaims(
268 claimed.claimedPaths,
269 result.projection.messages.flatMap((message) => message.attachments),
270 ),
271 ),
272 Effect.tapError((error) => {
273 if (error._tag === "ThreadManagementProviderInstanceDisabledError") {
274 return AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths);
275 }
276 // Project/receipt reads precede dispatch; create-thread errors can wrap post-message reads and prove nothing alone.
277 const notAccepted =
278 error.operation === "resolve-project" ||
279 error.operation === "read-receipt" ||
280 ((error.operation === "create-thread" || error.operation === "dispatch-message") &&
281 (isOrchestratorError(error.cause) || isThreadManagementError(error.cause)) &&
282 // Projection errors under create-thread can occur after the message commit.
283 (error.operation !== "create-thread" ||
284 error.cause._tag !== "OrchestratorProjectionError") &&
285 dispatchWasNotAccepted(error.cause));
286 return notAccepted
287 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
288 : Effect.void;
289 }),
290 );
291});