@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, 04:45 UTC

main
ts 137 lines 5.66 KB
Raw
1 import {
2 ATTACHMENT_UPLOAD_URL_TTL_MS,
3 type ChatAttachment,
4 MessageId,
5 OrchestratorMcpFailure,
6 } from "@t3tools/contracts";
7 import * as Clock from "effect/Clock";
8 import * as Effect from "effect/Effect";
9 import * as AssetSigner from "../../../assets/AssetSigner.ts";
10 import * as McpInvocationContext from "../../McpInvocationContext.ts";
11 import * as Upload from "../../../assets/AttachmentUpload.ts";
12 import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
13 import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
14 import * as McpToolAccess from "../../McpToolAccess.ts";
15 import { isThreadManagementError, threadManagementFailure } from "../../OrchestratorMcpService.ts";
16 import { dispatchFailure, newCommandId, readThread, unavailable } from "../../threadAccess.ts";
17 import { AttachmentToolkit } from "./tools.ts";
18
19 export function resolveAttachmentReferences(
20 requested: ReadonlyArray<ChatAttachment>,
21 stored: ReadonlyArray<ChatAttachment>,
22 ) {
23 const owned = new Map(stored.map((attachment) => [attachment.id, attachment]));
24 return Effect.forEach(requested, (attachment) => {
25 const canonical = Claims.attachmentIsPendingUpload(attachment)
26 ? attachment
27 : owned.get(attachment.id);
28 return canonical === undefined
29 ? Effect.fail(
30 new OrchestratorMcpFailure({
31 code: "invalid_request",
32 message: "Attachments must be pending uploads or already belong to the target thread.",
33 }),
34 )
35 : Effect.succeed(canonical);
36 });
37 }
38
39 /** The 24-hour sweep starts at upload completion, possibly one upload-URL lifetime after issue. */
40 const UPLOAD_OWNER_TTL_MS = 24 * 60 * 60 * 1000 + ATTACHMENT_UPLOAD_URL_TTL_MS;
41
42 const uploadOwner = McpInvocationContext.McpInvocationContext.pipe(
43 Effect.map((scope) => scope.thread?.threadId ?? scope.requestNamespace),
44 );
45
46 export const layer = McpToolAccess.toLayer(
47 AttachmentToolkit,
48 Effect.gen(function* () {
49 const assetSigner = yield* AssetSigner.AssetSigner;
50 const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();
51 return {
52 // A pending upload belongs to its caller until a send claims it, so
53 // linked callers may stage the uploads their own sends need.
54 t3_attachment_prepare_upload: McpToolAccess.writes(
55 (input) =>
56 Effect.gen(function* () {
57 const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(
58 Effect.provideService(AssetSigner.AssetSigner, assetSigner),
59 Effect.mapError(unavailable),
60 );
61 const now = yield* Clock.currentTimeMillis;
62 for (const [id, entry] of uploadOwners) {
63 if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
64 }
65 uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now });
66 const { origin } = yield* McpInvocationContext.McpInvocationContext;
67 return origin === undefined
68 ? result
69 : { ...result, uploadUrl: `${origin}${result.relativeUrl}` };
70 }),
71 { linkedCallers: "allowed" },
72 ),
73 t3_attachment_discard: McpToolAccess.writes(
74 (input) =>
75 Effect.gen(function* () {
76 if (uploadOwners.get(input.attachmentId)?.owner !== (yield* uploadOwner)) {
77 return yield* new OrchestratorMcpFailure({
78 code: "invalid_request",
79 message: "Only the caller that prepared a pending upload can discard it.",
80 });
81 }
82 yield* Upload.deletePendingAttachment(input.attachmentId);
83 uploadOwners.delete(input.attachmentId);
84 return {};
85 }),
86 { linkedCallers: "allowed" },
87 ),
88 t3_thread_send_attachments: McpToolAccess.writesThreads(
89 (input) => [input.threadId],
90 (input) =>
91 Effect.gen(function* () {
92 const { caller, projection } = yield* readThread(input.threadId, ["messages"]);
93 if (projection.thread.archivedAt !== null)
94 return yield* new OrchestratorMcpFailure({
95 code: "invalid_request",
96 message: "Unarchive the target thread before sending attachments.",
97 });
98 const attachments = yield* resolveAttachmentReferences(
99 input.attachments,
100 projection.messages.flatMap((message) => message.attachments),
101 );
102 const commandId = yield* newCommandId();
103 const messageId = MessageId.make(commandId);
104 const result = yield* ThreadMessageIntake.sendToThread({
105 projectId: projection.thread.projectId,
106 threadId: projection.thread.id,
107 commandId,
108 messageId,
109 ...(caller === undefined ? {} : { senderThreadId: caller.id }),
110 text: input.message ?? "",
111 attachments,
112 mode: "auto",
113 createdBy: "agent",
114 creationSource: "mcp",
115 }).pipe(
116 Effect.mapError((error) =>
117 error._tag === "AttachmentClaimError"
118 ? new OrchestratorMcpFailure({
119 code: "orchestration_error",
120 message: error.message,
121 })
122 : isThreadManagementError(error)
123 ? threadManagementFailure(error)
124 : dispatchFailure(error),
125 ),
126 );
127 return {
128 threadId: projection.thread.id,
129 messageId,
130 runId: result.run.id,
131 status: result.run.status,
132 };
133 }),
134 ),
135 };
136 }),
137 );