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

ThreadMessageIntake.ts

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