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

ThreadMessageIntake.ts

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