Open History to see the last commit
1import {
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";
14import * as Context from "effect/Context";
15import * as Digest from "effect/crypto/Digest";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Hex from "effect/encoding/Hex";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Schema from "effect/Schema";
22import type * as Tool from "effect/ai/Tool";
23
24import { runtimeModeRank } from "../mcp/delegatedTaskModes.ts";
25import { assertNotLinked } from "../mcp/linkOrigin.ts";
26import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
27import { readCaller, unavailable } from "../mcp/threadAccess.ts";
28import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
29import * as PeerLinks from "./PeerLinks.ts";
30import * as PeerMcpClient from "./PeerMcpClient.ts";
31
32// Match local waits: return before MCP client timeouts and T3 Connect's ~100 s idle drop.
33const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
34const MAX_WAIT_TIMEOUT_MS = 45_000;
35
36type 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 */
44export 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. */
83export 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
89const isRuntimeMode = Schema.is(RuntimeMode);
90
91const 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. */
95export const remoteTarget = (scope: Scope, environmentId: EnvironmentId | undefined) =>
96 environmentId === scope.environmentId ? undefined : environmentId;
97
98// Older peers reject beforePosition during parameter validation.
99const BEFORE_POSITION_REFUSAL =
100 /^Invalid parameters for tool 't3_thread_read': Unknown arguments? (?:"[^"]+", )*"beforePosition"(?:, "[^"]+")*\. Accepted arguments: /;
101export const refusesBeforePosition = (failure: {
102 readonly code: string;
103 readonly message: string;
104}) => failure.code === "invalid_request" && BEFORE_POSITION_REFUSAL.test(failure.message);
105
106/** A newest-page read, retried as the peer always served it when the peer refuses the cursor. */
107export const readNewestOrRetry = Effect.fn("PeerForwarding.readNewestOrRetry")(function* <A>(
108 read: (args: unknown) => Effect.Effect<A, OrchestratorMcpFailure>,
109 newest: unknown,
110 params: unknown,
111) {
112 return yield* read(newest).pipe(Effect.catchIf(refusesBeforePosition, () => read(params)));
113});
114
115const make = Effect.gen(function* () {
116 const peers = yield* PeerMcpClient.PeerMcpClient;
117 const links = yield* PeerLinks.PeerLinks;
118 const crypto = yield* Digest.Digest;
119 const threads = yield* ThreadManagement.ThreadManagementService;
120
121 /**
122 * The caller's own limits and thread, which travel with every forwarded call: the peer sees only the
123 * link's credential, so a caller that may not control threads here is refused here. Work a
124 * link started never uses this environment's links, since the peer would see this
125 * environment's session instead of that link, and its fence could not hold.
126 */
127 const forwardingCaller = (scope: Scope) =>
128 readCaller().pipe(
129 Effect.tap((caller) => assertNotLinked(caller, "use this environment's links")),
130 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
131 Effect.provideService(ThreadManagement.ThreadManagementService, threads),
132 );
133
134 /**
135 * Every caller here reaches the peer as the one link session, so a retry
136 * key is scoped to its caller before it leaves: two agents here reusing a
137 * key never collide there, and one agent retrying gets its first result.
138 */
139 const scopedRequestId = (namespace: string, clientRequestId: string) =>
140 crypto.digest(Digest.sha256, new TextEncoder().encode(`${namespace}\n${clientRequestId}`)).pipe(
141 Effect.map((digest) => `fwd:${Hex.encode(digest)}`),
142 Effect.orDie,
143 );
144
145 /**
146 * The linked environment refuses a mode above the link's access too, but as
147 * "broader than parent mode", which misleads when the parent here is broader.
148 * A read-only link refuses the launch there with its own capability error,
149 * and an expired one is left to say it expired.
150 */
151 const assertWithinLinkAccess = Effect.fn("PeerForwarding.assertWithinLinkAccess")(function* (
152 environmentId: EnvironmentId,
153 requested: unknown,
154 ) {
155 if (!isRuntimeMode(requested)) return;
156 const link = yield* links.get(environmentId).pipe(Effect.mapError(linkStorageFailure));
157 if (Option.isNone(link)) return;
158 if (DateTime.isLessThanOrEqualTo(link.value.expiresAt, yield* DateTime.now)) return;
159 const { label, access } = link.value;
160 if (access === "read-only" || runtimeModeRank(requested) <= runtimeModeRank(access)) return;
161 return yield* new OrchestratorMcpFailure({
162 code: "runtime_mode_escalation_denied",
163 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.`,
164 });
165 });
166
167 /** Tool and contract schemas are plain data: they encode and decode without services. */
168 const forward = Effect.fn("PeerForwarding.forward")(function* <A>(
169 scope: Scope,
170 toolName: string,
171 parameters: Schema.Top,
172 success: Schema.Top,
173 environmentId: EnvironmentId,
174 params: unknown,
175 ) {
176 const { caller, limits } = yield* forwardingCaller(scope);
177 const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder<unknown>)(
178 params,
179 ).pipe(Effect.mapError(unavailable))) as Record<string, unknown>;
180 const { environmentId: _target, ...args } = encoded;
181 yield* assertWithinLinkAccess(environmentId, args.runtimeMode);
182 // A pending upload lives here, so it cannot go with the call.
183 if (Array.isArray(args.attachments) && args.attachments.length > 0) {
184 return yield* new OrchestratorMcpFailure({
185 code: "invalid_request",
186 message: "A launch in a linked environment cannot carry attachments yet.",
187 });
188 }
189 if (typeof args.clientRequestId === "string") {
190 args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId);
191 }
192 // So a message sent there names the thread that sent it, even to a client that cannot reach here.
193 const sender =
194 caller === undefined
195 ? undefined
196 : {
197 environmentId: scope.environmentId,
198 threadId: caller.id,
199 title: caller.title,
200 };
201 return yield* peers.call({
202 environmentId,
203 tool: toolName,
204 arguments: args,
205 limits,
206 ...(sender === undefined ? {} : { sender }),
207 success: success as Schema.Decoder<A>,
208 });
209 });
210
211 const readThread: PeerForwarding["Service"]["readThread"] = (scope, environmentId, input) =>
212 forward<OrchestratorMcpThreadReadResult>(
213 scope,
214 "t3_thread_read",
215 OrchestratorMcpThreadReadInput,
216 OrchestratorMcpThreadReadResult,
217 environmentId,
218 input,
219 );
220
221 const interruptThread: PeerForwarding["Service"]["interruptThread"] = (
222 scope,
223 environmentId,
224 input,
225 ) =>
226 forward<OrchestratorMcpThreadInterruptResult>(
227 scope,
228 "t3_thread_interrupt",
229 OrchestratorMcpThreadInterruptInput,
230 OrchestratorMcpThreadInterruptResult,
231 environmentId,
232 input,
233 );
234
235 const waitForThread: PeerForwarding["Service"]["waitForThread"] = (scope, environmentId, input) =>
236 forward<OrchestratorMcpThreadWaitResult>(
237 scope,
238 "t3_thread_wait",
239 OrchestratorMcpThreadWaitInput,
240 OrchestratorMcpThreadWaitResult,
241 environmentId,
242 {
243 ...input,
244 timeoutMs: Math.min(
245 MAX_WAIT_TIMEOUT_MS,
246 Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
247 ),
248 },
249 );
250
251 // While the beta is off, agents start nothing over links. Tasks already running there keep
252 // following through readThread, waitForThread and interruptThread, so they still finish.
253 const requireEnabled = links.enabled.pipe(
254 Effect.flatMap((enabled) => (enabled ? Effect.void : Effect.fail(linkedEnvironmentsOff))),
255 );
256
257 // A peer pages a client's cursorless read forward; an agent's gets the newest page, as it does here.
258 const newestPageForAgent = (scope: Scope, toolName: string, params: unknown) => {
259 if (toolName !== "t3_thread_read" || scope.thread === undefined) return undefined;
260 const input = params as OrchestratorMcpThreadReadInput;
261 return input.afterPosition === undefined && input.beforePosition === undefined
262 ? { ...input, beforePosition: Number.MAX_SAFE_INTEGER }
263 : undefined;
264 };
265
266 const call: PeerForwarding["Service"]["call"] = (scope, tool, environmentId, params) => {
267 const forwardTool = (
268 args: unknown,
269 ): Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure> =>
270 forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, args);
271 const newest = newestPageForAgent(scope, tool.name, params);
272 const forwarded: Effect.Effect<
273 Tool.Success<typeof tool>,
274 OrchestratorMcpFailure
275 > = tool.name === "t3_thread_wait"
276 ? (waitForThread(
277 scope,
278 environmentId,
279 params as OrchestratorMcpThreadWaitInput,
280 ) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
281 : newest === undefined
282 ? forwardTool(params)
283 : readNewestOrRetry(forwardTool, newest, params);
284 return Effect.andThen(requireEnabled, forwarded);
285 };
286
287 /**
288 * The next step for an agent whose machine is not linked: without it, an
289 * empty list reads as a dead end and agents go looking elsewhere.
290 */
291 const NOT_LISTED =
292 "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words.";
293
294 const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
295 function* (scope) {
296 yield* forwardingCaller(scope);
297 yield* requireEnabled;
298 const listed = yield* links.list.pipe(Effect.mapError(linkStorageFailure));
299 return {
300 environmentId: scope.environmentId,
301 links: listed.map((link) => ({
302 environmentId: link.environmentId,
303 label: link.label,
304 status: link.status,
305 access: link.access,
306 expiresAt: DateTime.formatIso(link.expiresAt),
307 lastError: link.lastError,
308 })),
309 notListed: NOT_LISTED,
310 };
311 },
312 );
313
314 return PeerForwarding.of({
315 call,
316 readThread,
317 interruptThread,
318 waitForThread,
319 links: listLinks,
320 });
321});
322
323export const layer = Layer.effect(PeerForwarding, make);