@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 488 lines 17.6 KB
Raw
1 import {
2 type EnvironmentId,
3 type OrchestrationV2LinkOrigin,
4 OrchestratorMcpEnvironmentTarget,
5 OrchestratorMcpFailure,
6 type ProviderInteractionMode,
7 type RuntimeMode,
8 type ThreadId,
9 } from "@t3tools/contracts";
10 import * as Context from "effect/Context";
11 import * as Effect from "effect/Effect";
12 import * as Option from "effect/Option";
13 import * as Predicate from "effect/Predicate";
14 import * as Ref from "effect/Ref";
15 import * as Struct from "effect/Struct";
16 import type * as Layer from "effect/Layer";
17 import type * as Scope from "effect/Scope";
18 import { McpSchema } from "effect/ai";
19 import type { Tool, Toolkit } from "effect/ai";
20
21 import {
22 DispatchModeLimit,
23 type DispatchModeRefusal,
24 } from "../orchestration-v2/DispatchModeLimit.ts";
25 import * as PeerForwarding from "../peer/PeerForwarding.ts";
26 import {
27 assertFullAccessNamingLink,
28 assertNotLinked,
29 assertSameLink,
30 callerLinkOrigin,
31 } from "./linkOrigin.ts";
32 import * as McpInvocationContext from "./McpInvocationContext.ts";
33 import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";
34 import {
35 assertFullAccess,
36 assertLiveCaller,
37 assertTargetWithinLimits,
38 type Caller,
39 loadCaller,
40 readCaller,
41 unavailable,
42 } from "./threadAccess.ts";
43
44 /** Private constructors only enforce types; the token also blocks runtime construction. */
45 const builtHere: unique symbol = Symbol("t3/mcp/McpToolAccess/builtHere");
46
47 const refuseOutsideConstruction = (token: symbol) => {
48 if (token !== builtHere) {
49 throw new TypeError("Only McpToolAccess builds MCP tool declarations and handler layers.");
50 }
51 };
52
53 let declare: <P, A, E, R>(
54 handle: (params: P) => Effect.Effect<A, E, R>,
55 remote: RemoteCheck<P> | undefined,
56 forwarded?: Forwarded<P, A, E, R>,
57 ) => Declaration<(params: P) => Effect.Effect<A, E, R>>;
58
59 /**
60 * What a call bound for a linked environment checks here before it goes: the
61 * caller, not the thread or project it names, which live there and are
62 * checked there. `undefined` for tools that act as the calling thread itself.
63 */
64 type RemoteCheck<P> = (
65 params: P,
66 ) => Effect.Effect<unknown, OrchestratorMcpFailure, Effect.Services<typeof writingCaller>>;
67 let remoteCheckOf: <Handler>(declaration: Declaration<Handler>) => RemoteCheck<never> | undefined;
68
69 /** What a call answered in a linked environment does here before it returns. */
70 type Forwarded<P, A, E, R> = (
71 params: P,
72 environmentId: EnvironmentId,
73 result: A,
74 ) => Effect.Effect<A, E, R>;
75 let forwardedOf: <Handler>(
76 declaration: Declaration<Handler>,
77 ) => Forwarded<never, unknown, unknown, unknown> | undefined;
78
79 type CheckedHandlerOf<D> = D extends Declaration<infer Handler> ? Handler : never;
80
81 interface CheckedHandler extends Struct.Lambda {
82 <Handler>(declaration: Declaration<Handler>): Handler;
83 readonly "~lambda.out": CheckedHandlerOf<this["~lambda.in"]>;
84 }
85 let checkedHandler: CheckedHandler;
86
87 let handlersLayer: <Tools extends Record<string, Tool.Any>, EX, RX>(
88 layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>,
89 ) => HandlersLayer<Tools, EX, RX>;
90
91 /** t3code/no-raw-mcp-registration confines Effect's unchecked registration API to McpHttpServer. */
92 export class Declaration<out Handler> {
93 readonly #handle: Handler;
94 readonly #remote: RemoteCheck<never> | undefined;
95 readonly #forwarded: Forwarded<never, unknown, unknown, unknown> | undefined;
96 private constructor(
97 token: typeof builtHere,
98 handle: Handler,
99 remote: RemoteCheck<never> | undefined,
100 forwarded: Forwarded<never, unknown, unknown, unknown> | undefined,
101 ) {
102 refuseOutsideConstruction(token);
103 this.#handle = handle;
104 this.#remote = remote;
105 this.#forwarded = forwarded;
106 }
107 static {
108 declare = (handle, remote, forwarded) =>
109 new Declaration(
110 builtHere,
111 handle,
112 remote,
113 forwarded as Forwarded<never, unknown, unknown, unknown> | undefined,
114 );
115 checkedHandler = Struct.lambda<CheckedHandler>((declaration) => declaration.#handle);
116 remoteCheckOf = (declaration) => declaration.#remote;
117 forwardedOf = (declaration) => declaration.#forwarded;
118 }
119 }
120
121 const refuseReadOnlyClient = McpInvocationContext.McpInvocationContext.pipe(
122 Effect.flatMap((scope) =>
123 scope.client?.access === "read-only"
124 ? Effect.fail(
125 new OrchestratorMcpFailure({
126 code: "capability_denied",
127 message:
128 "This tool changes the environment, and this MCP client was approved for read-only access.",
129 }),
130 )
131 : Effect.void,
132 ),
133 );
134
135 const writingCaller = refuseReadOnlyClient.pipe(
136 Effect.andThen(loadCaller()),
137 Effect.tap(assertLiveCaller),
138 );
139
140 const orchestratingCaller = refuseReadOnlyClient.pipe(
141 Effect.andThen(readCaller()),
142 Effect.tap(assertLiveCaller),
143 );
144
145 const requireThreadCaller = McpInvocationContext.McpInvocationContext.pipe(
146 Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "This tool")),
147 );
148
149 export const reads = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
150 declare(
151 (params: P) => handle(params),
152 () => Effect.void,
153 );
154
155 export const readsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
156 declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))), undefined);
157
158 export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
159 declare(
160 (params: P) =>
161 requireThreadCaller.pipe(
162 Effect.andThen(writingCaller),
163 Effect.flatMap(() => handle(params)),
164 ),
165 undefined,
166 );
167
168 /**
169 * Changes something that belongs to no thread, such as a pending upload or a
170 * scheduled task. Work a linked environment started may not: none of it
171 * carries the link's origin, so none of it is that link's.
172 */
173 export const writes = <P, A, E, R>(
174 handle: (params: P) => Effect.Effect<A, E, R>,
175 options?: {
176 /** Whether a linked caller may make it, as for uploads its own sends need. */
177 readonly linkedCallers?: "allowed";
178 },
179 ) =>
180 declare(
181 (params: P) =>
182 orchestratingCaller.pipe(
183 Effect.tap((caller) =>
184 options?.linkedCallers === "allowed"
185 ? Effect.void
186 : assertNotLinked(caller, "change this environment's scheduled tasks"),
187 ),
188 Effect.flatMap(() => handle(params)),
189 ),
190 () => orchestratingCaller,
191 );
192
193 /** Requires handler capability checks, not thread control; linked work is refused the same way. */
194 export const writesWithCapability = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
195 declare(
196 (params: P) =>
197 writingCaller.pipe(
198 Effect.tap((caller) => assertNotLinked(caller, "start work here that is not its link's")),
199 Effect.flatMap(() => handle(params)),
200 ),
201 () => writingCaller,
202 );
203
204 export const writesThreads = <P, A, E, R>(
205 threads: (params: P) => ReadonlyArray<ThreadId | undefined>,
206 handle: (params: P) => Effect.Effect<A, E, R>,
207 ) =>
208 declare(
209 (params: P) =>
210 Effect.gen(function* () {
211 const caller = yield* writingCaller;
212 for (const threadId of threads(params)) {
213 if (threadId === undefined || threadId === caller.scope.thread?.threadId) continue;
214 const target = yield* caller.threads
215 .getThreadShell(threadId)
216 .pipe(Effect.mapError(unavailable));
217 if (target !== null && target.deletedAt === null) {
218 yield* assertTargetWithinLimits(caller.limits, target);
219 yield* assertSameLink(caller, target);
220 }
221 }
222 // Modes can rise after this check; the orchestrator rechecks under lock and records refusal before handlers wrap errors.
223 const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
224 return yield* handle(params).pipe(
225 Effect.provideService(DispatchModeLimit, { ...caller.limits, refused }),
226 Effect.catch((error) =>
227 Effect.flatMap(Ref.get(refused), (refusal) =>
228 Effect.fail<E | OrchestratorMcpFailure>(
229 refusal === undefined ? error : escalationDenied(refusal),
230 ),
231 ),
232 ),
233 );
234 }),
235 () => writingCaller,
236 );
237
238 const escalationDenied = (refusal: DispatchModeRefusal) =>
239 new OrchestratorMcpFailure({
240 code:
241 refusal.mode === "runtime"
242 ? "runtime_mode_escalation_denied"
243 : "interaction_mode_escalation_denied",
244 message: `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this caller's. Its user changed it while this call ran.`,
245 });
246
247 export interface StartedModes {
248 readonly runtimeMode: RuntimeMode;
249 readonly interactionMode: ProviderInteractionMode;
250 /** The linked environment the caller acts for. The thread must carry it. */
251 readonly linkOrigin: OrchestrationV2LinkOrigin | undefined;
252 }
253
254 /**
255 * Starts threads with the modes `modes` requests, which may not be broader
256 * than the caller's. `linked` says what a linked caller gets: threads stamped
257 * with its `linkOrigin`, or a refusal where the tool cannot carry one.
258 */
259 export const startsThreads = <P, A, E, R>(
260 modes: (params: P) => {
261 readonly runtimeMode?: RuntimeMode | undefined;
262 readonly interactionMode?: ProviderInteractionMode | undefined;
263 },
264 handle: (params: P, modes: StartedModes) => Effect.Effect<A, E, R>,
265 linked: "stamped" | { readonly refused: string },
266 ) => {
267 const started = Effect.fn("McpToolAccess.started")(function* (caller: Caller, params: P) {
268 const requested = modes(params);
269 return {
270 runtimeMode: yield* resolveRuntimeMode(caller.limits.runtimeMode, requested.runtimeMode),
271 interactionMode: yield* resolveInteractionMode(
272 caller.limits.interactionMode,
273 requested.interactionMode,
274 ),
275 linkOrigin: callerLinkOrigin(caller),
276 } satisfies StartedModes;
277 });
278 return declare(
279 (params: P) =>
280 Effect.gen(function* () {
281 const caller = yield* writingCaller;
282 if (linked !== "stamped") yield* assertNotLinked(caller, linked.refused);
283 return yield* handle(params, yield* started(caller, params));
284 }),
285 (params: P) => Effect.flatMap(writingCaller, (caller) => started(caller, params)),
286 );
287 };
288
289 /** One tool with two access rules, picked per call, such as create versus update. */
290 export const either = <P, A, E, R, A2, E2, R2>(
291 useFirst: (params: P) => boolean,
292 first: Declaration<(params: P) => Effect.Effect<A, E, R>>,
293 second: Declaration<(params: P) => Effect.Effect<A2, E2, R2>>,
294 ) => {
295 const remotes = [remoteCheckOf(first), remoteCheckOf(second)] as ReadonlyArray<
296 RemoteCheck<P> | undefined
297 >;
298 return declare(
299 (params: P): Effect.Effect<A | A2, E | E2, R | R2> =>
300 useFirst(params) ? checkedHandler(first)(params) : checkedHandler(second)(params),
301 (params) =>
302 remotes[useFirst(params) ? 0 : 1]?.(params) ??
303 Effect.fail(
304 new OrchestratorMcpFailure({
305 code: "invalid_request",
306 message: "This action acts as the calling thread, which is here. Omit environmentId.",
307 }),
308 ),
309 );
310 };
311
312 /**
313 * `declaration`, whose result from a linked environment then goes through
314 * `forwarded` here, for what this environment records about the call.
315 */
316 export const afterForwarding = <P, A, E, R, E2, R2>(
317 declaration: Declaration<(params: P) => Effect.Effect<A, E, R>>,
318 forwarded: Forwarded<P, A, E2, R2>,
319 ) =>
320 declare(
321 checkedHandler(declaration) as (params: P) => Effect.Effect<A, E | E2, R | R2>,
322 remoteCheckOf(declaration) as RemoteCheck<P> | undefined,
323 forwarded,
324 );
325
326 const fullAccessRequired =
327 "Changing projects or environment settings needs a live full-access/default calling thread or a full-access client.";
328 const changesEnvironment = "change projects or environment settings";
329
330 /** Recheck after waits before writing; caller modes may have changed. */
331 export const writesEnvironment = <P, A, E, R>(
332 handle: (
333 params: P,
334 check: Effect.Effect<Caller, OrchestratorMcpFailure, CheckServices>,
335 ) => Effect.Effect<A, E, R>,
336 options?: {
337 /**
338 * Whether a linked caller may make it, as for adding a project: it leaves
339 * everything already here as it was.
340 */
341 readonly linkedCallers?: "allowed";
342 },
343 ) => {
344 const check = orchestratingCaller.pipe(
345 Effect.tap((caller) =>
346 options?.linkedCallers === "allowed"
347 ? Effect.void
348 : assertNotLinked(caller, changesEnvironment),
349 ),
350 Effect.tap((caller) =>
351 assertFullAccessNamingLink(caller, fullAccessRequired, changesEnvironment),
352 ),
353 );
354 return declare(
355 (params: P) => check.pipe(Effect.flatMap(() => handle(params, check))),
356 // Linked work never reaches a link at all; that is checked as the call goes.
357 () =>
358 orchestratingCaller.pipe(
359 Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
360 ),
361 );
362 };
363
364 type CheckServices = Effect.Services<typeof orchestratingCaller>;
365
366 type Declarations<Handlers> = {
367 readonly [Name in keyof Handlers]: Declaration<Handlers[Name]> & NotCallable;
368 };
369
370 type NotCallable = { readonly call?: never } & { readonly apply?: never };
371
372 export type Handlers<Tools extends Record<string, Tool.Any>> = Declarations<
373 Toolkit.HandlersFrom<Tools>
374 >;
375
376 export class HandlersLayer<Tools extends Record<string, Tool.Any>, EX = never, RX = never> {
377 readonly #layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>;
378 private constructor(
379 token: typeof builtHere,
380 layer: Layer.Layer<Tool.HandlersFor<Tools>, EX, RX>,
381 ) {
382 refuseOutsideConstruction(token);
383 this.#layer = layer;
384 }
385 static {
386 handlersLayer = (layer) => new HandlersLayer(builtHere, layer);
387 }
388 static layer<Tools extends Record<string, Tool.Any>, EX, RX>(
389 handlers: HandlersLayer<Tools, EX, RX>,
390 ) {
391 return handlers.#layer;
392 }
393 }
394
395 const checkedHandlers = <Handlers>(declarations: Declarations<Handlers>): Handlers =>
396 Struct.map(declarations, checkedHandler);
397
398 /**
399 * A tool runs in a linked environment when its parameters take this target
400 * as `environmentId`. Other tools may name an environment for their own
401 * reasons, such as the one to link or to move a thread to.
402 */
403 const takesLinkedEnvironment = (tool: Tool.Any) => {
404 const parameters: unknown = tool.parametersSchema;
405 return (
406 Predicate.hasProperty(parameters, "fields") &&
407 Predicate.hasProperty(parameters.fields, "environmentId") &&
408 parameters.fields.environmentId === OrchestratorMcpEnvironmentTarget
409 );
410 };
411
412 const linksUnavailable = new OrchestratorMcpFailure({
413 code: "orchestration_error",
414 message: "This environment cannot reach linked environments.",
415 });
416
417 const THREAD_ONLY = new Set<unknown>([
418 McpInvocationContext.hiddenFromOutsideClients,
419 McpInvocationContext.hiddenWithoutBackgroundWait,
420 ]);
421
422 /**
423 * Every tool that takes a linked environment runs there the same way: its
424 * declaration checks the caller here, and the same call goes to the other
425 * environment, which checks the rest. The handler here never sees
426 * `environmentId`, so it cannot leak into what it writes.
427 */
428 const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record<string, Tool.Any>>(
429 toolkit: Toolkit.Toolkit<Tools>,
430 declarations: Handlers<Tools>,
431 checked: Toolkit.HandlersFrom<Tools>,
432 ) {
433 // Optional so toolkits that never leave this environment build without it.
434 const forwarding = yield* Effect.serviceOption(PeerForwarding.PeerForwarding);
435 const handlers: Record<string, unknown> = { ...checked };
436 for (const [name, declaration] of Object.entries<Declaration<unknown>>(declarations)) {
437 const tool = toolkit.tools[name];
438 if (tool === undefined) continue;
439 const remote = remoteCheckOf(declaration);
440 if (
441 remote === undefined &&
442 !THREAD_ONLY.has(Context.getOrUndefined(tool.annotations, McpSchema.EnabledWhen))
443 )
444 return yield* Effect.die(
445 `${name} acts as its calling thread, so outside clients must not be offered it.`,
446 );
447 if (!takesLinkedEnvironment(tool)) continue;
448 const forwarded = forwardedOf(declaration) as
449 | Forwarded<object, unknown, Tool.Failure<Tools[keyof Tools]>, never>
450 | undefined;
451 if (remote === undefined)
452 return yield* Effect.die(
453 `${name} takes a linked environment, but it acts as its calling thread, which is here.`,
454 );
455 const here = handlers[name] as (
456 params: object,
457 ) => Effect.Effect<unknown, Tool.Failure<Tools[keyof Tools]>>;
458 handlers[name] = ({ environmentId, ...params }: { readonly environmentId?: EnvironmentId }) =>
459 Effect.gen(function* () {
460 const scope = yield* McpInvocationContext.McpInvocationContext;
461 const target = PeerForwarding.remoteTarget(scope, environmentId);
462 if (target === undefined) return yield* here(params);
463 if (scope.linkedEnvironments === false) return yield* PeerForwarding.linkedEnvironmentsOff;
464 yield* (remote as RemoteCheck<typeof params>)(params);
465 if (Option.isNone(forwarding)) return yield* linksUnavailable;
466 const result = yield* forwarding.value.call(scope, tool, target, {
467 ...params,
468 environmentId,
469 });
470 return forwarded === undefined ? result : yield* forwarded(params, target, result);
471 });
472 }
473 return handlers as Toolkit.HandlersFrom<Tools>;
474 });
475
476 export const toLayer = <Tools extends Record<string, Tool.Any>, EX = never, RX = never>(
477 toolkit: Toolkit.Toolkit<Tools>,
478 build: Handlers<Tools> | Effect.Effect<Handlers<Tools>, EX, RX>,
479 ): HandlersLayer<Tools, EX, Exclude<RX, Scope.Scope>> => {
480 // Checked as soon as they are given, so a forged declaration fails here.
481 const withDeclarations = (declarations: Handlers<Tools>) =>
482 routed(toolkit, declarations, checkedHandlers(declarations));
483 return handlersLayer(
484 toolkit.toLayer(
485 Effect.isEffect(build) ? Effect.flatMap(build, withDeclarations) : withDeclarations(build),
486 ),
487 );
488 };