@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 282 lines 10.9 KB
Raw
1 import type {
2 ProjectionRecordField,
3 ProjectionRecordFilter,
4 } from "../orchestration-v2/ProjectionStore.ts";
5 import {
6 CommandId,
7 type EnvironmentId,
8 OrchestratorMcpFailure,
9 type ProjectId,
10 type ProviderInstanceId,
11 type ProviderInteractionMode,
12 type RuntimeMode,
13 ThreadId,
14 type OrchestrationV2ThreadShell,
15 } from "@t3tools/contracts";
16 import {
17 hasThreadLinks,
18 parseThreadLinkHref,
19 threadLinkCandidates,
20 threadLinkRefs,
21 } from "@t3tools/shared/threadLinks";
22 import { hasPendingBackgroundSubagent } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
23 import * as SecureRandom from "effect/crypto/SecureRandom";
24 import * as Effect from "effect/Effect";
25
26 import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts";
27 import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
28 import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";
29 import { fencingLinkOrigin } from "./linkOrigin.ts";
30 import * as McpInvocationContext from "./McpInvocationContext.ts";
31
32 const delegatedTaskPrefix = "thread:delegated-task:";
33
34 const suggestedThreadId = (threadId: ThreadId) => {
35 if (!threadId.startsWith(delegatedTaskPrefix)) return ThreadId.make(`mcp:${threadId}`);
36 const rest = threadId.slice(delegatedTaskPrefix.length);
37 // encodeURIComponent throws on lone surrogates, which a JSON string can carry.
38 if (!rest.isWellFormed()) return null;
39 const encoded = encodeURIComponent(rest);
40 return encoded === rest ? null : ThreadId.make(`${delegatedTaskPrefix}${encoded}`);
41 };
42
43 // A pasted link (bare, Markdown, or hosted) names its thread; only this environment's can be read here.
44 const candidateThreadIds = (threadId: ThreadId, environmentId: EnvironmentId) => {
45 if (!hasThreadLinks(threadId)) {
46 const suggested = suggestedThreadId(threadId);
47 return suggested === null ? [] : [suggested];
48 }
49 const link = parseThreadLinkHref(threadId);
50 const refs =
51 link === null
52 ? threadLinkRefs(threadId, environmentId)
53 : threadLinkCandidates(link, environmentId);
54 return refs.filter((ref) => ref.environmentId === environmentId).map((ref) => ref.threadId);
55 };
56
57 /**
58 * Agents paste bare uuids for `mcp:<uuid>` threads, unencoded delegated-task ids, and thread links.
59 * The id is never rewritten, so permission checks keyed on it still hold; the miss
60 * only names a live thread the caller could read by its full id. Ids from another
61 * machine miss here too. The link hint is static: listing links probes peers.
62 */
63 export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* (
64 threads: Pick<ThreadManagement.ThreadManagementService["Service"], "getThreadShell">,
65 scope: McpInvocationContext.McpInvocationScope,
66 threadId: ThreadId,
67 message: string,
68 ) {
69 let suggested: ThreadId | null = null;
70 for (const candidate of candidateThreadIds(threadId, scope.environmentId)) {
71 const shell = yield* threads.getThreadShell(candidate).pipe(Effect.orElseSucceed(() => null));
72 if (shell !== null && shell.deletedAt === null) {
73 suggested = candidate;
74 break;
75 }
76 }
77 if (suggested !== null && hasThreadLinks(threadId)) {
78 return yield* new OrchestratorMcpFailure({
79 code: "thread_not_found",
80 message: `\`${threadId}\` is a thread link, not a thread id. Pass \`${suggested}\` instead.`,
81 });
82 }
83 const mcpHint = suggested === null ? "" : ` Did you mean \`${suggested}\`?`;
84 const caller =
85 scope.thread === undefined
86 ? null
87 : yield* threads.getThreadShell(scope.thread.threadId).pipe(Effect.orElseSucceed(() => null));
88 // A peer link's caller would be pointed at this machine's links, and a fenced one may not use them.
89 const linksHint =
90 scope.linkedEnvironments === false ||
91 scope.client?.linked === true ||
92 fencingLinkOrigin({ scope, caller: caller ?? undefined }) !== undefined
93 ? ""
94 : " Thread ids belong to one environment: for a thread on a linked one, find it with `t3_environment_links` and pass its `environmentId` to a tool that takes one.";
95 return yield* new OrchestratorMcpFailure({
96 code: "thread_not_found",
97 message: `${message}${mcpHint}${linksHint}`,
98 });
99 });
100
101 export const unavailable = () =>
102 new OrchestratorMcpFailure({
103 code: "orchestration_error",
104 message: "The operation could not be completed.",
105 });
106
107 export const dispatchFailure = (
108 error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
109 ) =>
110 error._tag === "ThreadManagementProviderInstanceDisabledError" ||
111 error._tag === "OrchestratorRuntimeModeAboveCeilingError" ||
112 error._tag === "OrchestratorProviderSelectionBusyError"
113 ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
114 : (error._tag === "OrchestratorDispatchError" ||
115 error._tag === "OrchestratorCommandRejectedError") &&
116 typeof error.cause === "string" &&
117 error.cause.length > 0
118 ? new OrchestratorMcpFailure({
119 code: "orchestration_error",
120 message: Array.from(error.cause).slice(0, 1000).join(""),
121 })
122 : unavailable();
123
124 export interface CallerLimits {
125 readonly runtimeMode: RuntimeMode;
126 readonly interactionMode: ProviderInteractionMode;
127 }
128
129 export interface Caller {
130 readonly scope: McpInvocationContext.McpInvocationScope;
131 readonly threads: ThreadManagement.ThreadManagementService["Service"];
132 readonly caller: OrchestrationV2ThreadShell | undefined;
133 readonly limits: CallerLimits;
134 }
135
136 export const readCaller = Effect.fn("mcp.readCaller")(function* () {
137 const scope = yield* McpInvocationContext.McpInvocationContext;
138 if (!scope.capabilities.has("orchestration")) {
139 return yield* new OrchestratorMcpFailure({
140 code: "capability_denied",
141 message: "This credential cannot control threads.",
142 });
143 }
144 return yield* loadCaller();
145 });
146
147 export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
148 const scope = yield* McpInvocationContext.McpInvocationContext;
149 const threads = yield* ThreadManagement.ThreadManagementService;
150 if (scope.thread === undefined) {
151 return {
152 scope,
153 threads,
154 caller: undefined,
155 limits: McpInvocationContext.clientModeCeiling(scope.client),
156 } satisfies Caller;
157 }
158 const caller = yield* threads
159 .getThreadShell(scope.thread.threadId)
160 .pipe(Effect.mapError(unavailable));
161 if (caller === null || caller.deletedAt !== null) {
162 return yield* new OrchestratorMcpFailure({
163 code: "thread_not_found",
164 message: "The calling thread was not found.",
165 });
166 }
167 return {
168 scope,
169 threads,
170 caller,
171 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
172 } satisfies Caller;
173 });
174
175 export const assertTargetWithinLimits = (
176 limits: CallerLimits,
177 target: Pick<OrchestrationV2ThreadShell, "id" | "runtimeMode" | "interactionMode">,
178 ) =>
179 resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
180 Effect.andThen(resolveInteractionMode(limits.interactionMode, target.interactionMode)),
181 Effect.asVoid,
182 Effect.mapError(
183 (error) =>
184 new OrchestratorMcpFailure({
185 code: error.code,
186 message: `Thread "${target.id}" runs in ${target.runtimeMode}/${target.interactionMode}, above this caller's ${limits.runtimeMode}/${limits.interactionMode} limit. For linked calls, this limit is also capped by the link's approved access. This call does not create an approval request. Have the user act directly in the target thread through an authorized client.`,
187 }),
188 ),
189 );
190
191 /** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */
192 export const isLiveCallerShell = (
193 shell: Pick<
194 OrchestrationV2ThreadShell,
195 "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"
196 > | null,
197 providerInstanceId: ProviderInstanceId | undefined,
198 ) =>
199 shell !== null &&
200 shell.archivedAt === null &&
201 shell.providerInstanceId === providerInstanceId &&
202 (shell.activeRunId !== null ||
203 hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, providerInstanceId));
204
205 /** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */
206 export function assertLiveCaller({ caller, scope }: Caller) {
207 if (caller === undefined) return Effect.void;
208 return isLiveCallerShell(caller, scope.thread?.providerInstanceId)
209 ? Effect.void
210 : Effect.fail(
211 new OrchestratorMcpFailure({
212 code: "parent_not_active",
213 message: "The calling provider no longer owns an active thread run.",
214 }),
215 );
216 }
217
218 export const assertFullAccess = (context: Caller, message: string) =>
219 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
220 ? Effect.void
221 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
222
223 export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
224 projectId !== undefined
225 ? Effect.succeed(projectId)
226 : context.caller !== undefined
227 ? Effect.succeed(context.caller.projectId)
228 : Effect.fail(
229 new OrchestratorMcpFailure({
230 code: "target_required",
231 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
232 }),
233 );
234
235 const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
236 threadId !== undefined
237 ? Effect.succeed(threadId)
238 : context.caller !== undefined
239 ? Effect.succeed(context.caller.id)
240 : Effect.fail(
241 new OrchestratorMcpFailure({
242 code: "target_required",
243 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
244 }),
245 );
246
247 export const readThread = Effect.fn("mcp.readThread")(function* <
248 K extends ProjectionRecordField = never,
249 >(threadId?: ThreadId, fields: ReadonlyArray<K> = [], filter?: ProjectionRecordFilter) {
250 const context = yield* readCaller();
251 const targetId = yield* resolveThreadId(context, threadId);
252 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
253 if (shell === null || shell.deletedAt !== null) {
254 return yield* threadNotFound(
255 context.threads,
256 context.scope,
257 targetId,
258 "The thread was not found.",
259 );
260 }
261 const projection = yield* context.threads
262 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
263 turnItemTypes: ["user_input_request"],
264 ...filter,
265 })
266 .pipe(
267 Effect.mapError((error) =>
268 error._tag === "ThreadManagementThreadNotFoundError"
269 ? new OrchestratorMcpFailure({
270 code: "thread_not_found",
271 message: "The thread was not found.",
272 })
273 : unavailable(),
274 ),
275 );
276 return { ...context, projection };
277 });
278
279 export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
280 const random = yield* SecureRandom.SecureRandom;
281 return CommandId.make(`mcp:${yield* random.uuidV4()}`);
282 });