@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 338 lines 13.6 KB
Raw
1 import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences";
2 import { appendUserInputAttachmentPaths } from "../provider/userInputAttachments.ts";
3 import {
4 AuthProvidersManageScope,
5 type ChatAttachment,
6 type OrchestrationV2Command,
7 } from "@t3tools/contracts";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Schema from "effect/Schema";
11 import { resolveAttachmentPath } from "../attachmentStore.ts";
12 import { rpcAuthorizationError } from "../auth/RpcAuthorization.ts";
13 import * as ServerConfig from "../config.ts";
14 import * as Orchestrator from "./Orchestrator.ts";
15
16 import * as AttachmentClaims from "./AttachmentClaims.ts";
17 import { isProviderSignOutPrompt } from "./CommandPolicy.ts";
18 import * as ThreadLaunch from "./ThreadLaunchService.ts";
19 import * as ThreadManagement from "./ThreadManagementService.ts";
20
21 // These failures precede commitCommand; generic dispatch errors can follow commits and remain ambiguous.
22 function dispatchWasNotAccepted(
23 error: Orchestrator.OrchestratorV2Error | ThreadManagement.ThreadManagementError,
24 ) {
25 switch (error._tag) {
26 case "OrchestratorCommandRejectedError":
27 case "OrchestratorThreadAlreadyExistsError":
28 case "OrchestratorProjectionError":
29 case "OrchestratorProviderAdapterError":
30 case "OrchestratorCommandPreviouslyRejectedError":
31 case "OrchestratorCommandIdConflictError":
32 case "OrchestratorSubagentThreadReadOnlyError":
33 case "OrchestratorThreadAboveModeLimitError":
34 case "OrchestratorProviderSelectionBusyError":
35 case "OrchestratorRuntimeModeAboveCeilingError":
36 case "ThreadManagementProviderInstanceDisabledError":
37 case "ThreadManagementWorktreeRestoreError":
38 return true;
39 default:
40 return false;
41 }
42 }
43 const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error);
44 const isThreadManagementError = Schema.is(ThreadManagement.ThreadManagementError);
45
46 const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")(function* (
47 claimedPaths: ReadonlyArray<string>,
48 accepted: ReadonlyArray<ChatAttachment>,
49 ) {
50 if (claimedPaths.length === 0) return;
51 const config = yield* ServerConfig.ServerConfig;
52 const retained = new Set(
53 accepted.flatMap((attachment) => {
54 const path = resolveAttachmentPath({
55 attachmentsDir: config.attachmentsDir,
56 attachment,
57 });
58 return path ? [path, `${path}.txt`] : [];
59 }),
60 );
61 yield* AttachmentClaims.releaseClaimedAttachments(
62 claimedPaths.filter((path) => !retained.has(path)),
63 );
64 });
65
66 /**
67 * A guest message goes out with the files the guest attached, never ones a client names. They
68 * are already the thread's attachments. A message no longer waiting gets none; the orchestrator
69 * then refuses or replays the send.
70 */
71 const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments")(function* (
72 command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
73 ) {
74 if (command.guestMessageId === undefined) return command;
75 const threads = yield* ThreadManagement.ThreadManagementService;
76 // Only the thread record is needed; the window keeps the read small.
77 const { projection } = yield* threads
78 .getThreadSnapshotWindow(command.threadId, { rowLimit: 1 })
79 .pipe(
80 Effect.mapError(
81 (cause) =>
82 new AttachmentClaims.AttachmentClaimError({
83 message: "Failed to read the guest message.",
84 cause,
85 }),
86 ),
87 );
88 const message = projection.thread.guestShare?.messages.find(
89 (candidate) => candidate.id === command.guestMessageId && candidate.status === "pending",
90 );
91 return { ...command, attachments: message?.attachments ?? [] };
92 });
93
94 /**
95 * For a caller without `providers:manage`. An edit that omits `attachments` keeps the queued
96 * ones, so `/logout` signs out only when the queued message has none. The edit goes on with
97 * the files read here, so an edit racing this one cannot strip them afterwards.
98 */
99 export const withQueuedAttachmentsOnSignOutText = Effect.fn(
100 "ThreadMessageIntake.withQueuedAttachmentsOnSignOutText",
101 )(function* (command: Extract<OrchestrationV2Command, { readonly type: "queued-run.edit" }>) {
102 if (
103 command.attachments !== undefined ||
104 !isProviderSignOutPrompt({ text: command.text, attachments: [] })
105 ) {
106 return command;
107 }
108 const threads = yield* ThreadManagement.ThreadManagementService;
109 // A retry of an accepted edit replays its receipt, even after its run left the queue.
110 if (yield* threads.hasReceipt(command.commandId)) return command;
111 const { runs } = yield* threads.getThreadRecords(command.threadId, ["runs"], {
112 runIds: [command.runId],
113 });
114 const queuedRun = runs.find((run) => run.id === command.runId && run.status === "queued");
115 const attachments =
116 queuedRun === undefined
117 ? []
118 : ((yield* threads.getMessagesById(command.threadId, [queuedRun.userMessageId])).get(
119 queuedRun.userMessageId,
120 )?.attachments ?? []);
121 if (attachments.length === 0) return yield* rpcAuthorizationError(AuthProvidersManageScope);
122 return { ...command, attachments };
123 });
124
125 /**
126 * `sender.managesProviders` is whether the caller holds `providers:manage`. RPC authorization
127 * has already checked every command whose payload shows a provider sign-out; a queued edit
128 * that keeps its attachments is the one case decided here.
129 */
130 export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
131 incoming: OrchestrationV2Command,
132 sender: { readonly managesProviders: boolean },
133 ) {
134 const command =
135 incoming.type === "message.dispatch"
136 ? yield* withGuestAttachments(incoming)
137 : incoming.type === "queued-run.edit" && !sender.managesProviders
138 ? yield* withQueuedAttachmentsOnSignOutText(incoming)
139 : incoming;
140 const threads = yield* ThreadManagement.ThreadManagementService;
141 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
142 const config = yield* ServerConfig.ServerConfig;
143 const incomingByQuestionId = command.attachmentsByQuestionId;
144 yield* AttachmentClaims.validateAttachmentLimits(Object.values(incomingByQuestionId).flat());
145 const claimedPaths: string[] = [];
146 const prepared = yield* Effect.gen(function* () {
147 const attachmentsByQuestionId: import("@t3tools/contracts").UserInputAttachments = {};
148 for (const [questionId, attachments] of Object.entries(incomingByQuestionId)) {
149 const claimed = yield* AttachmentClaims.claimPendingAttachments({
150 threadId: command.threadId,
151 attachments,
152 });
153 claimedPaths.push(...claimed.claimedPaths);
154 Object.defineProperty(attachmentsByQuestionId, questionId, {
155 value: claimed.attachments,
156 enumerable: true,
157 });
158 }
159 const answers = yield* appendUserInputAttachmentPaths({
160 answers: command.answers ?? {},
161 attachmentsByQuestionId,
162 attachmentsDir: config.attachmentsDir,
163 }).pipe(
164 Effect.mapError(
165 (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }),
166 ),
167 );
168 return { answers, attachmentsByQuestionId };
169 }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths)));
170 return yield* threads
171 .dispatch({
172 ...command,
173 answers: prepared.answers,
174 attachmentsByQuestionId: prepared.attachmentsByQuestionId,
175 })
176 .pipe(
177 Effect.tap((result) => {
178 // Replayed receipts refer to the first answer; release this attempt's unused copies only with a resolved item.
179 // Missing questionAnswer means no accepted attachments; missing resolution leaves delivery ambiguous.
180 const answeredItems = result.storedEvents.flatMap(({ event }) =>
181 event.type === "turn-item.updated" &&
182 event.payload.type === "user_input_request" &&
183 event.payload.requestId === command.requestId
184 ? [event.payload]
185 : [],
186 );
187 return answeredItems.length > 0
188 ? releaseUnusedClaims(
189 claimedPaths,
190 answeredItems.flatMap((item) =>
191 item.questionAnswer === undefined
192 ? []
193 : Object.values(item.questionAnswer.attachmentsByQuestionId).flat(),
194 ),
195 )
196 : Effect.void;
197 }),
198 Effect.tapError((error) =>
199 dispatchWasNotAccepted(error)
200 ? AttachmentClaims.releaseClaimedAttachments(claimedPaths)
201 : Effect.void,
202 ),
203 );
204 }
205 if (
206 command.type !== "message.dispatch" &&
207 (command.type !== "queued-run.edit" || command.attachments === undefined)
208 )
209 return yield* threads.dispatch(command);
210 // An accepted edit's retry replays its receipt even if a later cleanup removed its files.
211 if (command.type === "queued-run.edit" && !(yield* threads.hasReceipt(command.commandId))) {
212 const config = yield* ServerConfig.ServerConfig;
213 const fileSystem = yield* FileSystem.FileSystem;
214 // A stale view can keep a file that another client's edit dropped and deleted.
215 for (const attachment of command.attachments ?? []) {
216 if (AttachmentClaims.attachmentIsPendingUpload(attachment)) continue;
217 const path = resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment });
218 if (
219 path !== null &&
220 !(yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false)))
221 ) {
222 return yield* new AttachmentClaims.AttachmentClaimError({
223 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
224 });
225 }
226 }
227 }
228 const claimed = yield* AttachmentClaims.claimPendingAttachments({
229 threadId: command.threadId,
230 attachments: command.attachments ?? [],
231 });
232 return yield* threads
233 .dispatch({
234 ...command,
235 attachments: claimed.attachments,
236 ...(command.context
237 ? {
238 context: remapComposerContextAttachments(
239 command.context,
240 command.attachments ?? [],
241 claimed.attachments,
242 ),
243 }
244 : {}),
245 })
246 .pipe(
247 Effect.tap((result) =>
248 releaseUnusedClaims(
249 claimed.claimedPaths,
250 result.storedEvents.flatMap(({ event }) =>
251 event.type === "message.updated" ? event.payload.attachments : [],
252 ),
253 ),
254 ),
255 Effect.tapError((error) =>
256 dispatchWasNotAccepted(error)
257 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
258 : Effect.void,
259 ),
260 );
261 });
262
263 export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(function* (
264 input: ThreadManagement.ThreadManagementSendInput,
265 ) {
266 const threads = yield* ThreadManagement.ThreadManagementService;
267 const claimed = yield* AttachmentClaims.claimPendingAttachments(input);
268 return yield* threads.sendToThread({ ...input, attachments: claimed.attachments }).pipe(
269 Effect.tap((result) => releaseUnusedClaims(claimed.claimedPaths, result.message.attachments)),
270 Effect.tapError((error) =>
271 dispatchWasNotAccepted(error)
272 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
273 : Effect.void,
274 ),
275 );
276 });
277
278 export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* (
279 input: ThreadLaunch.ThreadLaunchInput,
280 ) {
281 const launches = yield* ThreadLaunch.ThreadLaunchService;
282 yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []);
283 if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
284 return yield* launches.launch(input);
285 }
286 if (input.threadId === undefined) {
287 return yield* new AttachmentClaims.AttachmentClaimError({
288 message: "Uploaded attachments need a thread id at launch.",
289 });
290 }
291 const claimed = yield* AttachmentClaims.claimPendingAttachments({
292 threadId: input.threadId,
293 attachments: input.initialMessage.attachments,
294 });
295 return yield* launches
296 .launch({
297 ...input,
298 initialMessage: {
299 ...input.initialMessage,
300 attachments: claimed.attachments,
301 ...(input.initialMessage.context
302 ? {
303 context: remapComposerContextAttachments(
304 input.initialMessage.context,
305 input.initialMessage.attachments,
306 claimed.attachments,
307 ),
308 }
309 : {}),
310 },
311 })
312 .pipe(
313 Effect.tap((result) =>
314 releaseUnusedClaims(
315 claimed.claimedPaths,
316 result.projection.messages.flatMap((message) => message.attachments),
317 ),
318 ),
319 Effect.tapError((error) => {
320 if (error._tag === "ThreadManagementProviderInstanceDisabledError") {
321 return AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths);
322 }
323 // Project/receipt reads precede dispatch; create-thread errors can wrap post-message reads and prove nothing alone.
324 const notAccepted =
325 error.operation === "resolve-project" ||
326 error.operation === "read-receipt" ||
327 ((error.operation === "create-thread" || error.operation === "dispatch-message") &&
328 (isOrchestratorError(error.cause) || isThreadManagementError(error.cause)) &&
329 // Projection errors under create-thread can occur after the message commit.
330 (error.operation !== "create-thread" ||
331 error.cause._tag !== "OrchestratorProjectionError") &&
332 dispatchWasNotAccepted(error.cause));
333 return notAccepted
334 ? AttachmentClaims.releaseClaimedAttachments(claimed.claimedPaths)
335 : Effect.void;
336 }),
337 );
338 });