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

ThreadMessageIntake.ts

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