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