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

PeerForwarding.ts

248 lines9.1 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/** The linked environment a call names, or nothing when it names this one. */
84export const remoteTarget = (scope: Scope, environmentId: EnvironmentId | undefined) =>
85 environmentId === scope.environmentId ? undefined : environmentId;
86​
87const make = Effect.gen(function* () {
88 const peers = yield* PeerMcpClient.PeerMcpClient;
89 const links = yield* PeerLinks.PeerLinks;
90 const crypto = yield* Crypto.Crypto;
91 const threads = yield* ThreadManagement.ThreadManagementService;
92​
93 /**
94 * The caller's own limits, which travel with every forwarded call: the peer sees only the
95 * link's credential, so a caller that may not control threads here is refused here. Work a
96 * link started never uses this environment's links, since the peer would see this
97 * environment's session instead of that link, and its fence could not hold.
98 */
99 const callerLimits = (scope: Scope) =>
100 readCaller().pipe(
101 Effect.tap((caller) => assertNotLinked(caller, "use this environment's links")),
102 Effect.map((caller) => caller.limits),
103 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
104 Effect.provideService(ThreadManagement.ThreadManagementService, threads),
105 );
106​
107 /**
108 * Every caller here reaches the peer as the one link session, so a retry
109 * key is scoped to its caller before it leaves: two agents here reusing a
110 * key never collide there, and one agent retrying gets its first result.
111 */
112 const scopedRequestId = (namespace: string, clientRequestId: string) =>
113 crypto.digest("SHA-256", new TextEncoder().encode(`${namespace}\n${clientRequestId}`)).pipe(
114 Effect.map((digest) => `fwd:${Hex.encode(digest)}`),
115 Effect.orDie,
116 );
117​
118 /** Tool and contract schemas are plain data: they encode and decode without services. */
119 const forward = Effect.fn("PeerForwarding.forward")(function* <A>(
120 scope: Scope,
121 toolName: string,
122 parameters: Schema.Top,
123 success: Schema.Top,
124 environmentId: EnvironmentId,
125 params: unknown,
126 ) {
127 const limits = yield* callerLimits(scope);
128 const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder<unknown>)(
129 params,
130 ).pipe(Effect.mapError(unavailable))) as Record<string, unknown>;
131 const { environmentId: _target, ...args } = encoded;
132 // A pending upload lives here, so it cannot go with the call.
133 if (Array.isArray(args.attachments) && args.attachments.length > 0) {
134 return yield* new OrchestratorMcpFailure({
135 code: "invalid_request",
136 message: "A launch in a linked environment cannot carry attachments yet.",
137 });
138 }
139 if (typeof args.clientRequestId === "string") {
140 args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId);
141 }
142 return yield* peers.call({
143 environmentId,
144 tool: toolName,
145 arguments: args,
146 limits,
147 success: success as Schema.Decoder<A>,
148 });
149 });
150​
151 const readThread: PeerForwarding["Service"]["readThread"] = (scope, environmentId, input) =>
152 forward<OrchestratorMcpThreadReadResult>(
153 scope,
154 "t3_thread_read",
155 OrchestratorMcpThreadReadInput,
156 OrchestratorMcpThreadReadResult,
157 environmentId,
158 input,
159 );
160​
161 const interruptThread: PeerForwarding["Service"]["interruptThread"] = (
162 scope,
163 environmentId,
164 input,
165 ) =>
166 forward<OrchestratorMcpThreadInterruptResult>(
167 scope,
168 "t3_thread_interrupt",
169 OrchestratorMcpThreadInterruptInput,
170 OrchestratorMcpThreadInterruptResult,
171 environmentId,
172 input,
173 );
174​
175 const waitForThread: PeerForwarding["Service"]["waitForThread"] = Effect.fn(
176 "PeerForwarding.waitForThread",
177 )(function* (scope, environmentId, input) {
178 let remaining = Math.min(
179 MAX_WAIT_TIMEOUT_MS,
180 Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
181 );
182 let runId = input.runId;
183 while (true) {
184 const chunk = Math.min(remaining, FORWARDED_WAIT_CHUNK_MS);
185 const result = yield* forward<OrchestratorMcpThreadWaitResult>(
186 scope,
187 "t3_thread_wait",
188 OrchestratorMcpThreadWaitInput,
189 OrchestratorMcpThreadWaitResult,
190 environmentId,
191 {
192 threadId: input.threadId,
193 ...(runId === undefined ? {} : { runId }),
194 timeoutMs: chunk,
195 ...(input.untilDelegatedWorkSettled === undefined
196 ? {}
197 : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }),
198 },
199 );
200 remaining -= chunk;
201 if (!result.timedOut || remaining <= 0) return result;
202 // Later pieces wait for the run the first one picked, not a newer one.
203 runId = result.runId ?? undefined;
204 }
205 });
206​
207 const call: PeerForwarding["Service"]["call"] = (scope, tool, environmentId, params) =>
208 tool.name === "t3_thread_wait"
209 ? (waitForThread(
210 scope,
211 environmentId,
212 params as OrchestratorMcpThreadWaitInput,
213 ) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
214 : forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params);
215​
216 const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
217 function* (scope) {
218 yield* callerLimits(scope);
219 const listed = yield* links.list.pipe(
220 Effect.mapError(
221 (error) =>
222 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
223 ),
224 );
225 return {
226 environmentId: scope.environmentId,
227 links: listed.map((link) => ({
228 environmentId: link.environmentId,
229 label: link.label,
230 status: link.status,
231 access: link.access,
232 expiresAt: DateTime.formatIso(link.expiresAt),
233 lastError: link.lastError,
234 })),
235 };
236 },
237 );
238​
239 return PeerForwarding.of({
240 call,
241 readThread,
242 interruptThread,
243 waitForThread,
244 links: listLinks,
245 });
246});
247​
248export const layer = Layer.effect(PeerForwarding, make);