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

main
ts 290 lines 11.2 KB
Raw
1 import {
2 type EnvironmentId,
3 OrchestratorMcpFailure,
4 type OrchestratorMcpEnvironmentLinksResult,
5 OrchestratorMcpThreadInterruptInput,
6 OrchestratorMcpThreadInterruptResult,
7 OrchestratorMcpThreadReadInput,
8 OrchestratorMcpThreadReadResult,
9 OrchestratorMcpThreadWaitInput,
10 OrchestratorMcpThreadWaitResult,
11 type PeerLinkError,
12 RuntimeMode,
13 } from "@t3tools/contracts";
14 import * as Context from "effect/Context";
15 import * as Digest from "effect/crypto/Digest";
16 import * as DateTime from "effect/DateTime";
17 import * as Effect from "effect/Effect";
18 import * as Hex from "effect/encoding/Hex";
19 import * as Layer from "effect/Layer";
20 import * as Option from "effect/Option";
21 import * as Schema from "effect/Schema";
22 import type * as Tool from "effect/ai/Tool";
23
24 import { runtimeModeRank } from "../mcp/delegatedTaskModes.ts";
25 import { assertNotLinked } from "../mcp/linkOrigin.ts";
26 import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
27 import { readCaller, unavailable } from "../mcp/threadAccess.ts";
28 import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
29 import * as PeerLinks from "./PeerLinks.ts";
30 import * as PeerMcpClient from "./PeerMcpClient.ts";
31
32 // Match local waits: return before MCP client timeouts and T3 Connect's ~100 s idle drop.
33 const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
34 const MAX_WAIT_TIMEOUT_MS = 45_000;
35
36 type Scope = McpInvocationContext.McpInvocationScope;
37
38 /**
39 * Runs T3 MCP tools in a linked environment for an agent here. The tool's own
40 * declaration checks the agent here first; the linked environment then holds
41 * the call to the link's access, narrowed to the agent's modes, which every
42 * forwarded call carries.
43 */
44 export class PeerForwarding extends Context.Service<
45 PeerForwarding,
46 {
47 /**
48 * Runs `tool` in the linked environment `environmentId` with `params`. A
49 * `t3_thread_wait` goes in pieces short enough to survive any route.
50 */
51 readonly call: <T extends Tool.Any>(
52 scope: Scope,
53 tool: T,
54 environmentId: EnvironmentId,
55 params: Tool.Parameters<T>,
56 ) => Effect.Effect<Tool.Success<T>, OrchestratorMcpFailure>;
57 /** `t3_thread_read` there. */
58 readonly readThread: (
59 scope: Scope,
60 environmentId: EnvironmentId,
61 input: OrchestratorMcpThreadReadInput,
62 ) => Effect.Effect<OrchestratorMcpThreadReadResult, OrchestratorMcpFailure>;
63 /** `t3_thread_interrupt` there. */
64 readonly interruptThread: (
65 scope: Scope,
66 environmentId: EnvironmentId,
67 input: OrchestratorMcpThreadInterruptInput,
68 ) => Effect.Effect<OrchestratorMcpThreadInterruptResult, OrchestratorMcpFailure>;
69 /** `t3_thread_wait` there, bounded like a local wait. */
70 readonly waitForThread: (
71 scope: Scope,
72 environmentId: EnvironmentId,
73 input: OrchestratorMcpThreadWaitInput,
74 ) => Effect.Effect<OrchestratorMcpThreadWaitResult, OrchestratorMcpFailure>;
75 /** The environments this one links to, as an agent sees them. */
76 readonly links: (
77 scope: Scope,
78 ) => Effect.Effect<OrchestratorMcpEnvironmentLinksResult, OrchestratorMcpFailure>;
79 }
80 >()("t3/peer/PeerForwarding") {}
81
82 /** What an agent hears when it names another machine while the beta is off here. */
83 export const linkedEnvironmentsOff = new OrchestratorMcpFailure({
84 code: "capability_denied",
85 message:
86 "Linked environments is off on this machine, so no tool can act on another machine. Leave out environmentId to work here; the user can turn it on in Settings → Labs.",
87 });
88
89 const isRuntimeMode = Schema.is(RuntimeMode);
90
91 const linkStorageFailure = (error: PeerLinkError) =>
92 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message });
93
94 /** The linked environment a call names, or nothing when it names this one. */
95 export const remoteTarget = (scope: Scope, environmentId: EnvironmentId | undefined) =>
96 environmentId === scope.environmentId ? undefined : environmentId;
97
98 const make = Effect.gen(function* () {
99 const peers = yield* PeerMcpClient.PeerMcpClient;
100 const links = yield* PeerLinks.PeerLinks;
101 const crypto = yield* Digest.Digest;
102 const threads = yield* ThreadManagement.ThreadManagementService;
103
104 /**
105 * The caller's own limits and thread, which travel with every forwarded call: the peer sees only the
106 * link's credential, so a caller that may not control threads here is refused here. Work a
107 * link started never uses this environment's links, since the peer would see this
108 * environment's session instead of that link, and its fence could not hold.
109 */
110 const forwardingCaller = (scope: Scope) =>
111 readCaller().pipe(
112 Effect.tap((caller) => assertNotLinked(caller, "use this environment's links")),
113 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
114 Effect.provideService(ThreadManagement.ThreadManagementService, threads),
115 );
116
117 /**
118 * Every caller here reaches the peer as the one link session, so a retry
119 * key is scoped to its caller before it leaves: two agents here reusing a
120 * key never collide there, and one agent retrying gets its first result.
121 */
122 const scopedRequestId = (namespace: string, clientRequestId: string) =>
123 crypto.digest(Digest.sha256, new TextEncoder().encode(`${namespace}\n${clientRequestId}`)).pipe(
124 Effect.map((digest) => `fwd:${Hex.encode(digest)}`),
125 Effect.orDie,
126 );
127
128 /**
129 * The linked environment refuses a mode above the link's access too, but as
130 * "broader than parent mode", which misleads when the parent here is broader.
131 * A read-only link refuses the launch there with its own capability error,
132 * and an expired one is left to say it expired.
133 */
134 const assertWithinLinkAccess = Effect.fn("PeerForwarding.assertWithinLinkAccess")(function* (
135 environmentId: EnvironmentId,
136 requested: unknown,
137 ) {
138 if (!isRuntimeMode(requested)) return;
139 const link = yield* links.get(environmentId).pipe(Effect.mapError(linkStorageFailure));
140 if (Option.isNone(link)) return;
141 if (DateTime.isLessThanOrEqualTo(link.value.expiresAt, yield* DateTime.now)) return;
142 const { label, access } = link.value;
143 if (access === "read-only" || runtimeModeRank(requested) <= runtimeModeRank(access)) return;
144 return yield* new OrchestratorMcpFailure({
145 code: "runtime_mode_escalation_denied",
146 message: `Linked environment "${label}" was linked with ${access} access, so work there cannot run in ${requested}. Omit runtimeMode to run it at a mode up to ${access}, or link it again with broader access.`,
147 });
148 });
149
150 /** Tool and contract schemas are plain data: they encode and decode without services. */
151 const forward = Effect.fn("PeerForwarding.forward")(function* <A>(
152 scope: Scope,
153 toolName: string,
154 parameters: Schema.Top,
155 success: Schema.Top,
156 environmentId: EnvironmentId,
157 params: unknown,
158 ) {
159 const { caller, limits } = yield* forwardingCaller(scope);
160 const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder<unknown>)(
161 params,
162 ).pipe(Effect.mapError(unavailable))) as Record<string, unknown>;
163 const { environmentId: _target, ...args } = encoded;
164 yield* assertWithinLinkAccess(environmentId, args.runtimeMode);
165 // A pending upload lives here, so it cannot go with the call.
166 if (Array.isArray(args.attachments) && args.attachments.length > 0) {
167 return yield* new OrchestratorMcpFailure({
168 code: "invalid_request",
169 message: "A launch in a linked environment cannot carry attachments yet.",
170 });
171 }
172 if (typeof args.clientRequestId === "string") {
173 args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId);
174 }
175 // So a message sent there names the thread that sent it, even to a client that cannot reach here.
176 const sender =
177 caller === undefined
178 ? undefined
179 : {
180 environmentId: scope.environmentId,
181 threadId: caller.id,
182 title: caller.title,
183 };
184 return yield* peers.call({
185 environmentId,
186 tool: toolName,
187 arguments: args,
188 limits,
189 ...(sender === undefined ? {} : { sender }),
190 success: success as Schema.Decoder<A>,
191 });
192 });
193
194 const readThread: PeerForwarding["Service"]["readThread"] = (scope, environmentId, input) =>
195 forward<OrchestratorMcpThreadReadResult>(
196 scope,
197 "t3_thread_read",
198 OrchestratorMcpThreadReadInput,
199 OrchestratorMcpThreadReadResult,
200 environmentId,
201 input,
202 );
203
204 const interruptThread: PeerForwarding["Service"]["interruptThread"] = (
205 scope,
206 environmentId,
207 input,
208 ) =>
209 forward<OrchestratorMcpThreadInterruptResult>(
210 scope,
211 "t3_thread_interrupt",
212 OrchestratorMcpThreadInterruptInput,
213 OrchestratorMcpThreadInterruptResult,
214 environmentId,
215 input,
216 );
217
218 const waitForThread: PeerForwarding["Service"]["waitForThread"] = (scope, environmentId, input) =>
219 forward<OrchestratorMcpThreadWaitResult>(
220 scope,
221 "t3_thread_wait",
222 OrchestratorMcpThreadWaitInput,
223 OrchestratorMcpThreadWaitResult,
224 environmentId,
225 {
226 ...input,
227 timeoutMs: Math.min(
228 MAX_WAIT_TIMEOUT_MS,
229 Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
230 ),
231 },
232 );
233
234 // While the beta is off, agents start nothing over links. Tasks already running there keep
235 // following through readThread, waitForThread and interruptThread, so they still finish.
236 const requireEnabled = links.enabled.pipe(
237 Effect.flatMap((enabled) => (enabled ? Effect.void : Effect.fail(linkedEnvironmentsOff))),
238 );
239
240 const call: PeerForwarding["Service"]["call"] = (scope, tool, environmentId, params) => {
241 const forwarded: Effect.Effect<
242 Tool.Success<typeof tool>,
243 OrchestratorMcpFailure
244 > = tool.name === "t3_thread_wait"
245 ? (waitForThread(
246 scope,
247 environmentId,
248 params as OrchestratorMcpThreadWaitInput,
249 ) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
250 : forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params);
251 return Effect.andThen(requireEnabled, forwarded);
252 };
253
254 /**
255 * The next step for an agent whose machine is not linked: without it, an
256 * empty list reads as a dead end and agents go looking elsewhere.
257 */
258 const NOT_LISTED =
259 "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words.";
260
261 const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
262 function* (scope) {
263 yield* forwardingCaller(scope);
264 yield* requireEnabled;
265 const listed = yield* links.list.pipe(Effect.mapError(linkStorageFailure));
266 return {
267 environmentId: scope.environmentId,
268 links: listed.map((link) => ({
269 environmentId: link.environmentId,
270 label: link.label,
271 status: link.status,
272 access: link.access,
273 expiresAt: DateTime.formatIso(link.expiresAt),
274 lastError: link.lastError,
275 })),
276 notListed: NOT_LISTED,
277 };
278 },
279 );
280
281 return PeerForwarding.of({
282 call,
283 readThread,
284 interruptThread,
285 waitForThread,
286 links: listLinks,
287 });
288 });
289
290 export const layer = Layer.effect(PeerForwarding, make);