Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerForwarding.ts

275 lines10.3 KB

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 Crypto from "effect/Crypto";
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* Crypto.Crypto;
98 const threads = yield* ThreadManagement.ThreadManagementService;
99​
100 /**
101 * The caller's own limits, 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 callerLimits = (scope: Scope) =>
107 readCaller().pipe(
108 Effect.tap((caller) => assertNotLinked(caller, "use this environment's links")),
109 Effect.map((caller) => caller.limits),
110 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
111 Effect.provideService(ThreadManagement.ThreadManagementService, threads),
112 );
113​
114 /**
115 * Every caller here reaches the peer as the one link session, so a retry
116 * key is scoped to its caller before it leaves: two agents here reusing a
117 * key never collide there, and one agent retrying gets its first result.
118 */
119 const scopedRequestId = (namespace: string, clientRequestId: string) =>
120 crypto.digest("SHA-256", new TextEncoder().encode(`${namespace}\n${clientRequestId}`)).pipe(
121 Effect.map((digest) => `fwd:${Hex.encode(digest)}`),
122 Effect.orDie,
123 );
124​
125 /** Tool and contract schemas are plain data: they encode and decode without services. */
126 const forward = Effect.fn("PeerForwarding.forward")(function* <A>(
127 scope: Scope,
128 toolName: string,
129 parameters: Schema.Top,
130 success: Schema.Top,
131 environmentId: EnvironmentId,
132 params: unknown,
133 ) {
134 const limits = yield* callerLimits(scope);
135 const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder<unknown>)(
136 params,
137 ).pipe(Effect.mapError(unavailable))) as Record<string, unknown>;
138 const { environmentId: _target, ...args } = encoded;
139 // A pending upload lives here, so it cannot go with the call.
140 if (Array.isArray(args.attachments) && args.attachments.length > 0) {
141 return yield* new OrchestratorMcpFailure({
142 code: "invalid_request",
143 message: "A launch in a linked environment cannot carry attachments yet.",
144 });
145 }
146 if (typeof args.clientRequestId === "string") {
147 args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId);
148 }
149 return yield* peers.call({
150 environmentId,
151 tool: toolName,
152 arguments: args,
153 limits,
154 success: success as Schema.Decoder<A>,
155 });
156 });
157​
158 const readThread: PeerForwarding["Service"]["readThread"] = (scope, environmentId, input) =>
159 forward<OrchestratorMcpThreadReadResult>(
160 scope,
161 "t3_thread_read",
162 OrchestratorMcpThreadReadInput,
163 OrchestratorMcpThreadReadResult,
164 environmentId,
165 input,
166 );
167​
168 const interruptThread: PeerForwarding["Service"]["interruptThread"] = (
169 scope,
170 environmentId,
171 input,
172 ) =>
173 forward<OrchestratorMcpThreadInterruptResult>(
174 scope,
175 "t3_thread_interrupt",
176 OrchestratorMcpThreadInterruptInput,
177 OrchestratorMcpThreadInterruptResult,
178 environmentId,
179 input,
180 );
181​
182 const waitForThread: PeerForwarding["Service"]["waitForThread"] = Effect.fn(
183 "PeerForwarding.waitForThread",
184 )(function* (scope, environmentId, input) {
185 let remaining = Math.min(
186 MAX_WAIT_TIMEOUT_MS,
187 Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
188 );
189 let runId = input.runId;
190 while (true) {
191 const chunk = Math.min(remaining, FORWARDED_WAIT_CHUNK_MS);
192 const result = yield* forward<OrchestratorMcpThreadWaitResult>(
193 scope,
194 "t3_thread_wait",
195 OrchestratorMcpThreadWaitInput,
196 OrchestratorMcpThreadWaitResult,
197 environmentId,
198 {
199 threadId: input.threadId,
200 ...(runId === undefined ? {} : { runId }),
201 timeoutMs: chunk,
202 ...(input.untilDelegatedWorkSettled === undefined
203 ? {}
204 : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }),
205 },
206 );
207 remaining -= chunk;
208 if (!result.timedOut || remaining <= 0) return result;
209 // Later pieces wait for the run the first one picked, not a newer one.
210 runId = result.runId ?? undefined;
211 }
212 });
213​
214 // While the beta is off, agents start nothing over links. Tasks already running there keep
215 // following through readThread, waitForThread and interruptThread, so they still finish.
216 const requireEnabled = links.enabled.pipe(
217 Effect.flatMap((enabled) => (enabled ? Effect.void : Effect.fail(linkedEnvironmentsOff))),
218 );
219​
220 const call: PeerForwarding["Service"]["call"] = (scope, tool, environmentId, params) => {
221 const forwarded: Effect.Effect<
222 Tool.Success<typeof tool>,
223 OrchestratorMcpFailure
224 > = tool.name === "t3_thread_wait"
225 ? (waitForThread(
226 scope,
227 environmentId,
228 params as OrchestratorMcpThreadWaitInput,
229 ) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
230 : forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params);
231 return Effect.andThen(requireEnabled, forwarded);
232 };
233​
234 /**
235 * The next step for an agent whose machine is not linked: without it, an
236 * empty list reads as a dead end and agents go looking elsewhere.
237 */
238 const NOT_LISTED =
239 "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words.";
240​
241 const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
242 function* (scope) {
243 yield* callerLimits(scope);
244 yield* requireEnabled;
245 const listed = yield* links.list.pipe(
246 Effect.mapError(
247 (error) =>
248 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
249 ),
250 );
251 return {
252 environmentId: scope.environmentId,
253 links: listed.map((link) => ({
254 environmentId: link.environmentId,
255 label: link.label,
256 status: link.status,
257 access: link.access,
258 expiresAt: DateTime.formatIso(link.expiresAt),
259 lastError: link.lastError,
260 })),
261 notListed: NOT_LISTED,
262 };
263 },
264 );
265​
266 return PeerForwarding.of({
267 call,
268 readThread,
269 interruptThread,
270 waitForThread,
271 links: listLinks,
272 });
273});
274​
275export const layer = Layer.effect(PeerForwarding, make);