Open History to see the last commit
1import { appendUserInputAttachmentPaths } from "../provider/userInputAttachments.ts";
2import type { ChatAttachment, OrchestrationV2Command } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as Schema from "effect/Schema";
5import { resolveAttachmentPath } from "../attachmentStore.ts";
6import * as ServerConfig from "../config.ts";
7import * as Orchestrator from "./Orchestrator.ts";
8
9import * as AttachmentClaims from "./AttachmentClaims.ts";
10import * as ThreadLaunch from "./ThreadLaunchService.ts";
11import * as ThreadManagement from "./ThreadManagementService.ts";
12
13// These dispatcher failures occur in receipt validation or planning, before
14// commitCommand. Generic dispatch errors can follow a commit and remain uncertain.
15function dispatchWasNotAccepted(
16 error: Orchestrator.OrchestratorV2Error | ThreadManagement.ThreadManagementError,
17) {
18 switch (error._tag) {
19 case "OrchestratorProjectionError":
20 case "OrchestratorProviderAdapterError":
21 case "OrchestratorCommandPreviouslyRejectedError":
22 case "OrchestratorCommandIdConflictError":
23 return true;
24 default:
25 return false;
26 }
27}
28const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error);
29
30const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")(function* (
31 claimed: AttachmentClaims.ClaimedAttachments,
32 accepted: ReadonlyArray<ChatAttachment>,
33) {
34 if (claimed.claimedPaths.length === 0) return;
35 const config = yield* ServerConfig.ServerConfig;
36 const retained = new Set(
37 accepted.map((attachment) =>
38 resolveAttachmentPath({
39 attachmentsDir: config.attachmentsDir,
40 attachment,
41 }),
42 ),
43 );
44 yield* AttachmentClaims.releaseClaimedAttachments(
45 claimed.claimedPaths.filter((path) => !retained.has(path)),
46 );
47});
48
49export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
50 command: OrchestrationV2Command,
51) {
52 const threads = yield* ThreadManagement.ThreadManagementService;
53 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
54 const config = yield* ServerConfig.ServerConfig;
55 const attachmentsByQuestionId: import("@t3tools/contracts").UserInputAttachments = {};
56 for (const [questionId, attachments] of Object.entries(command.attachmentsByQuestionId)) {
57 const claimed = yield* AttachmentClaims.claimPendingAttachments({
58 threadId: command.threadId,
59 attachments,
60 });
61 Object.defineProperty(attachmentsByQuestionId, questionId, {
62 value: claimed.attachments,
63 enumerable: true,
64 });
65 }
66 const answers = yield* appendUserInputAttachmentPaths({
67 answers: command.answers ?? {},
68 attachmentsByQuestionId,
69 attachmentsDir: config.attachmentsDir,
70 }).pipe(
71 Effect.mapError(
72 (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }),
73 ),
74 );
75 return yield* threads.dispatch({ ...command, answers, attachmentsByQuestionId });
76 }
77 if (command.type !== "message.dispatch") return yield* threads.dispatch(command);
78 const claimed = yield* AttachmentClaims.claimPendingAttachments({
79 threadId: command.threadId,
80 attachments: command.attachments,
81 });
82 return yield* threads.dispatch({ ...command, attachments: claimed.attachments }).pipe(
83 Effect.tap((result) =>
84 releaseUnusedClaims(
85 claimed,
86 result.storedEvents.flatMap(({ event }) =>
87 event.type === "message.updated" ? event.payload.attachments : [],
88 ),
89 ),
90 ),
91 Effect.tapError((error) =>
92 dispatchWasNotAccepted(error)
93 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
94 : Effect.void,
95 ),
96 );
97});
98
99export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(function* (
100 input: ThreadManagement.ThreadManagementSendInput,
101) {
102 const threads = yield* ThreadManagement.ThreadManagementService;
103 const claimed = yield* AttachmentClaims.claimPendingAttachments(input);
104 return yield* threads.sendToThread({ ...input, attachments: claimed.attachments }).pipe(
105 Effect.tap((result) => releaseUnusedClaims(claimed, result.message.attachments)),
106 Effect.tapError((error) =>
107 dispatchWasNotAccepted(error)
108 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
109 : Effect.void,
110 ),
111 );
112});
113
114export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* (
115 input: ThreadLaunch.ThreadLaunchInput,
116) {
117 const launches = yield* ThreadLaunch.ThreadLaunchService;
118 if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
119 return yield* launches.launch(input);
120 }
121 if (input.threadId === undefined) {
122 return yield* new AttachmentClaims.AttachmentClaimError({
123 message: "Uploaded attachments need a thread id at launch.",
124 });
125 }
126 const claimed = yield* AttachmentClaims.claimPendingAttachments({
127 threadId: input.threadId,
128 attachments: input.initialMessage.attachments,
129 });
130 return yield* launches
131 .launch({
132 ...input,
133 initialMessage: { ...input.initialMessage, attachments: claimed.attachments },
134 })
135 .pipe(
136 Effect.tap((result) =>
137 releaseUnusedClaims(
138 claimed,
139 result.projection.messages.flatMap((message) => message.attachments),
140 ),
141 ),
142 Effect.tapError((error) => {
143 // Project/receipt reads precede message dispatch. The create-thread error
144 // also wraps post-message projection reads, so its tag alone is not proof.
145 const notAccepted =
146 error.operation === "resolve-project" ||
147 error.operation === "read-receipt" ||
148 ((error.operation === "create-thread" || error.operation === "dispatch-message") &&
149 isOrchestratorError(error.cause) &&
150 // Projection errors under create-thread can occur after the message commit.
151 (error.operation !== "create-thread" ||
152 error.cause._tag !== "OrchestratorProjectionError") &&
153 dispatchWasNotAccepted(error.cause));
154 return notAccepted
155 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
156 : Effect.void;
157 }),
158 );
159});