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

ThreadMessageIntake.ts

238 lines9.1 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 dispatcher failures occur in receipt validation or planning, before
15// commitCommand. Generic dispatch errors can follow a commit and remain uncertain.
16function dispatchWasNotAccepted(
17 error: Orchestrator.OrchestratorV2Error | ThreadManagement.ThreadManagementError,
18) {
19 switch (error._tag) {
20 case "OrchestratorCommandRejectedError":
21 case "OrchestratorProjectionError":
22 case "OrchestratorProviderAdapterError":
23 case "OrchestratorCommandPreviouslyRejectedError":
24 case "OrchestratorCommandIdConflictError":
25 return true;
26 default:
27 return false;
28 }
30const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error);
31​
32const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")(function* (
33 claimedPaths: ReadonlyArray<string>,
34 accepted: ReadonlyArray<ChatAttachment>,
35) {
36 if (claimedPaths.length === 0) return;
37 const config = yield* ServerConfig.ServerConfig;
38 const retained = new Set(
39 accepted.map((attachment) =>
40 resolveAttachmentPath({
41 attachmentsDir: config.attachmentsDir,
42 attachment,
43 }),
44 ),
45 );
46 yield* AttachmentClaims.releaseClaimedAttachments(
47 claimedPaths.filter((path) => !retained.has(path)),
48 );
49});
50​
51export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
52 command: OrchestrationV2Command,
53) {
54 const threads = yield* ThreadManagement.ThreadManagementService;
55 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
56 const config = yield* ServerConfig.ServerConfig;
57 const incomingByQuestionId = command.attachmentsByQuestionId;
58 yield* AttachmentClaims.validateAttachmentLimits(Object.values(incomingByQuestionId).flat());
59 // Claims accumulate across questions, so all of preparation shares one
60 // rollback boundary: any failure before dispatch removes every new copy.
61 const claimedPaths: string[] = [];
62 const prepared = yield* Effect.gen(function* () {
63 const attachmentsByQuestionId: import("@t3tools/contracts").UserInputAttachments = {};
64 for (const [questionId, attachments] of Object.entries(incomingByQuestionId)) {
65 const claimed = yield* AttachmentClaims.claimPendingAttachments({
66 threadId: command.threadId,
67 attachments,
68 });
69 claimedPaths.push(...claimed.claimedPaths);
70 Object.defineProperty(attachmentsByQuestionId, questionId, {
71 value: claimed.attachments,
72 enumerable: true,
73 });
74 }
75 const answers = yield* appendUserInputAttachmentPaths({
76 answers: command.answers ?? {},
77 attachmentsByQuestionId,
78 attachmentsDir: config.attachmentsDir,
79 }).pipe(
80 Effect.mapError(
81 (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }),
82 ),
83 );
84 return { answers, attachmentsByQuestionId };
85 }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths)));
86 return yield* threads
87 .dispatch({
88 ...command,
89 answers: prepared.answers,
90 attachmentsByQuestionId: prepared.attachmentsByQuestionId,
91 })
92 .pipe(
93 Effect.tap((result) => {
94 // A replayed receipt reports the first attempt's answer, so this
95 // attempt's copies go unreferenced and are released. The resolved
96 // turn item proves the respond was applied; questionAnswer is only
97 // recorded when the accepted command carried attachments, so its
98 // absence means the accepted answer referenced no copies. With no
99 // resolved item at all the outcome is ambiguous and everything stays.
100 const answeredItems = result.storedEvents.flatMap(({ event }) =>
101 event.type === "turn-item.updated" &&
102 event.payload.type === "user_input_request" &&
103 event.payload.requestId === command.requestId
104 ? [event.payload]
105 : [],
106 );
107 return answeredItems.length > 0
108 ? releaseUnusedClaims(
109 claimedPaths,
110 answeredItems.flatMap((item) =>
111 item.questionAnswer === undefined
112 ? []
113 : Object.values(item.questionAnswer.attachmentsByQuestionId).flat(),
114 ),
115 )
116 : Effect.void;
117 }),
118 Effect.tapError((error) =>
119 dispatchWasNotAccepted(error)
120 ? AttachmentClaims.releaseClaimedAttachments(claimedPaths)
121 : Effect.void,
122 ),
123 );
124 }
125 if (
126 command.type !== "message.dispatch" &&
127 (command.type !== "queued-run.edit" || command.attachments === undefined)
128 )
129 return yield* threads.dispatch(command);
130 const claimed = yield* AttachmentClaims.claimPendingAttachments({
131 threadId: command.threadId,
132 attachments: command.attachments ?? [],
133 });
134 return yield* threads
135 .dispatch({
136 ...command,
137 attachments: claimed.attachments,
138 ...(command.context
139 ? {
140 context: remapComposerContextAttachments(
141 command.context,
142 command.attachments ?? [],
143 claimed.attachments,
144 ),
145 }
146 : {}),
147 })
148 .pipe(
149 Effect.tap((result) =>
150 releaseUnusedClaims(
151 claimed.claimedPaths,
152 result.storedEvents.flatMap(({ event }) =>
153 event.type === "message.updated" ? event.payload.attachments : [],
154 ),
155 ),
156 ),
157 Effect.tapError((error) =>
158 dispatchWasNotAccepted(error)
159 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
160 : Effect.void,
161 ),
162 );
163});
164​
165export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(function* (
166 input: ThreadManagement.ThreadManagementSendInput,
167) {
168 const threads = yield* ThreadManagement.ThreadManagementService;
169 const claimed = yield* AttachmentClaims.claimPendingAttachments(input);
170 return yield* threads.sendToThread({ ...input, attachments: claimed.attachments }).pipe(
171 Effect.tap((result) => releaseUnusedClaims(claimed.claimedPaths, result.message.attachments)),
172 Effect.tapError((error) =>
173 dispatchWasNotAccepted(error)
174 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
175 : Effect.void,
176 ),
177 );
178});
179​
180export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* (
181 input: ThreadLaunch.ThreadLaunchInput,
182) {
183 const launches = yield* ThreadLaunch.ThreadLaunchService;
184 yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []);
185 if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
186 return yield* launches.launch(input);
187 }
188 if (input.threadId === undefined) {
189 return yield* new AttachmentClaims.AttachmentClaimError({
190 message: "Uploaded attachments need a thread id at launch.",
191 });
192 }
193 const claimed = yield* AttachmentClaims.claimPendingAttachments({
194 threadId: input.threadId,
195 attachments: input.initialMessage.attachments,
196 });
197 return yield* launches
198 .launch({
199 ...input,
200 initialMessage: {
201 ...input.initialMessage,
202 attachments: claimed.attachments,
203 ...(input.initialMessage.context
204 ? {
205 context: remapComposerContextAttachments(
206 input.initialMessage.context,
207 input.initialMessage.attachments,
208 claimed.attachments,
209 ),
210 }
211 : {}),
212 },
213 })
214 .pipe(
215 Effect.tap((result) =>
216 releaseUnusedClaims(
217 claimed.claimedPaths,
218 result.projection.messages.flatMap((message) => message.attachments),
219 ),
220 ),
221 Effect.tapError((error) => {
222 // Project/receipt reads precede message dispatch. The create-thread error
223 // also wraps post-message projection reads, so its tag alone is not proof.
224 const notAccepted =
225 error.operation === "resolve-project" ||
226 error.operation === "read-receipt" ||
227 ((error.operation === "create-thread" || error.operation === "dispatch-message") &&
228 isOrchestratorError(error.cause) &&
229 // Projection errors under create-thread can occur after the message commit.
230 (error.operation !== "create-thread" ||
231 error.cause._tag !== "OrchestratorProjectionError") &&
232 dispatchWasNotAccepted(error.cause));
233 return notAccepted
234 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
235 : Effect.void;
236 }),
237 );
238});