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

PeerForwarding.test.ts

840 lines34.2 KB

1import * as DocumentText from "../provider/DocumentText.ts";
2import { NodeHttpServer } from "@effect/platform-node";
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import {
6 EnvironmentId,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadShell,
9 type SourceControlCloneRepositoryInput,
10 ProjectId,
11 OrchestratorMcpFailure,
12 ProviderInstanceId,
13 RunId,
14 ThreadId,
15} from "@t3tools/contracts";
16import { expect, it } from "@effect/vitest";
17import * as Context from "effect/Context";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Ref from "effect/Ref";
23import * as TestClock from "effect/testing/TestClock";
24import { McpSchema, McpServer } from "effect/ai";
25​
26import * as ServerConfig from "../config.ts";
27import type { ProjectionTimelinePageOptions } from "../orchestration-v2/ProjectionStore.ts";
28import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
29import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
30import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
31import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
32import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
33import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
34import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
35import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
36import * as ProjectService from "../project/ProjectService.ts";
37import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
38import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
39import * as SecretRequests from "../secrets/SecretRequests.ts";
40import * as ServerSettings from "../serverSettings.ts";
41import * as RemoteDelegation from "./RemoteDelegation.ts";
42import * as McpHttpServer from "../mcp/McpHttpServer.ts";
43import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
44import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
45import * as PeerForwarding from "./PeerForwarding.ts";
46import * as PeerLinks from "./PeerLinks.ts";
47import * as PeerLinkRequests from "./PeerLinkRequests.ts";
48import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
49​
50const laptop = descriptorOf("environment-laptop", "Laptop");
51const box = descriptorOf("environment-box", "Box");
52const boxProject = ProjectId.make("project:box");
53const boxThread = ThreadId.make("thread:box-auto");
54const boxRun = RunId.make("run:box-auto");
55​
56/** What B's thread service was asked to do. */
57interface Seen {
58 readonly sends: ReadonlyArray<ThreadManagement.ThreadManagementSendInput>;
59 readonly waits: ReadonlyArray<ThreadManagement.ThreadManagementWaitInput>;
60 readonly reads: ReadonlyArray<ProjectionTimelinePageOptions>;
61 readonly launches: ReadonlyArray<ThreadLaunch.ThreadLaunchInput>;
62 readonly projects: ReadonlyArray<ProjectService.ProjectCreateInput>;
63 readonly clones: ReadonlyArray<SourceControlCloneRepositoryInput>;
64 /** Commands dispatched and delegated-task stops, as `<type> <threadId>`. */
65 readonly stops: ReadonlyArray<string>;
67const nothingSeen: Seen = {
68 sends: [],
69 waits: [],
70 reads: [],
71 launches: [],
72 projects: [],
73 clones: [],
74 stops: [],
75};
76​
77/** The box user's own thread, which no link started. */
78const usersThread = ThreadId.make("thread:box-users-own");
79​
80/**
81 * B's threads: one `auto` thread in `boxProject` that the laptop's link
82 * started, whose run finishes on the third wait, and the box user's own.
83 * Every send and wait is recorded.
84 */
85const boxThreads = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) => {
86 const base = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
87 const linked = Ref.get(linkSession).pipe(
88 Effect.map((sessionId) => ({ ...base, linkOrigin: { sessionId, label: "T3 Code · Laptop" } })),
89 );
90 const users = { ...liveThreadShell(usersThread, { runtimeMode: "auto" }), projectId: boxProject };
91 const run = (status: OrchestrationV2Run["status"]) =>
92 ({
93 id: boxRun,
94 ordinal: 1,
95 status,
96 modelSelection: base.modelSelection,
97 requestedAt: base.createdAt,
98 startedAt: null,
99 completedAt: null,
100 }) as unknown as OrchestrationV2Run;
101 const shellOf = (threadId: ThreadId): Effect.Effect<OrchestrationV2ThreadShell | null> =>
102 threadId === boxThread ? linked : Effect.succeed(threadId === usersThread ? users : null);
103 const projectionOf = (threadId: ThreadId) =>
104 shellOf(threadId).pipe(
105 Effect.map(
106 (thread) =>
107 ({ thread, runs: [run("running")], runtimeRequests: [], providerTurns: [] }) as never,
108 ),
109 );
110 return Layer.mock(ThreadManagement.ThreadManagementService)({
111 getThreadShell: shellOf,
112 getProjectThreadRecords: (input) => projectionOf(input.threadId),
113 getThreadRecords: (threadId) => projectionOf(threadId),
114 getRunCount: () => Effect.succeed(1),
115 getTimelinePage: (_threadId, options) =>
116 Ref.update(seen, (current) => ({ ...current, reads: [...current.reads, options] })).pipe(
117 Effect.as({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }),
118 ),
119 listProjectThreads: () => linked.pipe(Effect.map((shell) => [shell] as never)),
120 getShellSnapshot: () => linked.pipe(Effect.map((shell) => ({ threads: [shell] }) as never)),
121 sendToThread: (input) =>
122 Ref.update(seen, (current) => ({ ...current, sends: [...current.sends, input] })).pipe(
123 Effect.as({ run: run("running"), delivery: "started" } as never),
124 ),
125 dispatch: (command) =>
126 Ref.update(seen, (current) => ({
127 ...current,
128 stops: [
129 ...current.stops,
130 `${command.type} ${"threadId" in command ? command.threadId : ""}`,
131 ],
132 })).pipe(
133 // The stop asks the provider to interrupt the thread's running turn.
134 Effect.as({
135 sequence: 0,
136 storedEvents: [
137 {
138 sequence: 1,
139 commandId: command.commandId,
140 event: {
141 type: "turn-item.updated",
142 runId: boxRun,
143 payload: {
144 type: "run_interrupt_request",
145 providerTurnId: "provider-turn:box-auto",
146 },
147 },
148 },
149 ],
150 } as never),
151 ),
152 stopDelegatedTasks: (input) =>
153 Ref.update(seen, (current) => ({
154 ...current,
155 stops: [...current.stops, `delegated-tasks.stop ${input.threadId}`],
156 })),
157 waitForThread: (input) =>
158 Ref.update(seen, (current) => ({ ...current, waits: [...current.waits, input] })).pipe(
159 Effect.as({ threadId: input.threadId, run: run("completed"), timedOut: false }),
160 ),
161 });
162};
163​
164/** B launches whatever it is asked to, and records it. */
165const boxLaunches = (seen: Ref.Ref<Seen>) =>
166 Layer.mock(ThreadLaunch.ThreadLaunchService)({
167 launch: (input) =>
168 Ref.update(seen, (current) => ({ ...current, launches: [...current.launches, input] })).pipe(
169 Effect.as({
170 threadId: input.threadId,
171 projection: {
172 thread: {
173 id: input.threadId,
174 projectId: input.projectId,
175 modelSelection: input.modelSelection,
176 title: input.title,
177 },
178 runs: [],
179 },
180 resumed: false,
181 } as unknown as ThreadLaunch.ThreadLaunchResult),
182 ),
183 });
184​
185/** B clones and registers whatever it is asked to, and records it. */
186const boxProjects = (seen: Ref.Ref<Seen>) =>
187 Layer.merge(
188 Layer.mock(ProjectService.ProjectService)({
189 getById: (id) =>
190 Effect.succeed(
191 id === boxProject
192 ? Option.some({
193 id,
194 title: "t3code",
195 workspaceRoot: "/box/t3code",
196 defaultModelSelection: null,
197 scripts: [],
198 createdAt: "2026-10-18T00:00:00.000Z",
199 updatedAt: "2026-10-18T00:00:00.000Z",
200 deletedAt: null,
201 })
202 : Option.none(),
203 ),
204 create: (input) =>
205 Ref.update(seen, (current) => ({
206 ...current,
207 projects: [...current.projects, input],
208 })).pipe(
209 Effect.as({
210 id: input.projectId,
211 title: input.title,
212 workspaceRoot: input.workspaceRoot,
213 defaultModelSelection: null,
214 scripts: [],
215 createdAt: "2026-10-18T00:00:00.000Z",
216 updatedAt: "2026-10-18T00:00:00.000Z",
217 deletedAt: null,
218 }),
219 ),
220 }),
221 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
222 cloneRepository: (input) =>
223 Ref.update(seen, (current) => ({ ...current, clones: [...current.clones, input] })).pipe(
224 Effect.as({
225 cwd: input.destinationPath,
226 remoteUrl: "https://github.com/pingdotgg/t3code.git",
227 repository: null,
228 }),
229 ),
230 }),
231 );
232​
233/**
234 * The orchestrator and project toolkits on B's real `/mcp`, behind its real
235 * OAuth. `linkSession` is filled in once A links, so B's fixture thread reads
236 * as one that link started.
237 */
238const serveBox = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) =>
239 servePeer(
240 box,
241 Layer.mergeAll(
242 McpHttpServer.layerOrchestratorToolkit,
243 McpHttpServer.layerProjectRegistration,
244 McpHttpServer.layerThreadToolkit,
245 ).pipe(
246 Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
247 Layer.provide(NodeCrypto.layer),
248 Layer.provide(boxThreads(seen, linkSession)),
249 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
250 Layer.provide(boxLaunches(seen)),
251 Layer.provide(
252 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
253 ),
254 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
255 Layer.provide(boxProjects(seen)),
256 Layer.provide(
257 ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-forwarding-box-" }).pipe(
258 Layer.provide(NodeServices.layer),
259 ),
260 ),
261 Layer.provide(NodeServices.layer),
262 Layer.provide(
263 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
264 ),
265 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
266 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
267 Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})),
268 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
269 Layer.provide(ServerSettings.layerTest()),
270 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
271 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
272 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
273 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
274 ),
275 );
276​
277const mcpClient = McpSchema.McpServerClient.of({
278 clientId: 1,
279 protocolVersion: "2025-06-18",
280 clientCapabilities: {},
281 clientInfo: { name: "peer-forwarding-test", version: "1" },
282 initializePayload: {
283 protocolVersion: "2025-06-18",
284 capabilities: {},
285 clientInfo: { name: "peer-forwarding-test", version: "1" },
286 },
287 getClient: Effect.die("unused"),
288});
289​
290/**
291 * Environment A: its own orchestrator toolkit with forwarding, and a thread
292 * caller whose modes the test picks. Its local threads never matter here.
293 */
294const makeLaptop = Effect.gen(function* () {
295 const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
296 const layerHere = Layer.mergeAll(
297 McpHttpServer.layerOrchestratorToolkit,
298 McpHttpServer.layerProjectRegistration,
299 McpHttpServer.layerThreadToolkit,
300 ).pipe(
301 Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
302 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
303 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
304 Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
305 Layer.provide(
306 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
307 ),
308 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
309 Layer.provide(Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({})),
310 Layer.provide(
311 ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-forwarding-laptop-" }).pipe(
312 Layer.provide(NodeServices.layer),
313 ),
314 ),
315 Layer.provide(NodeServices.layer),
316 Layer.provide(PeerForwarding.layer),
317 Layer.provide(Layer.succeedContext(linking)),
318 Layer.provide(NodeCrypto.layer),
319 Layer.provideMerge(
320 Layer.mock(ThreadManagement.ThreadManagementService)({
321 getThreadShell: (threadId) =>
322 Effect.succeed(
323 threadId === ThreadId.make("thread:laptop-from-desk")
324 ? {
325 ...liveThreadShell(threadId, { runtimeMode: "full-access" }),
326 // Work another environment's link started on this laptop.
327 linkOrigin: { sessionId: "session:desk", label: "T3 Code · Desk" },
328 }
329 : liveThreadShell(
330 threadId,
331 threadId === ThreadId.make("thread:laptop-plan")
332 ? { runtimeMode: "full-access", interactionMode: "plan" }
333 : { runtimeMode: "full-access" },
334 ),
335 ),
336 getProjectThreadRecords: ({ threadId }) =>
337 Effect.succeed({
338 thread: liveThreadShell(threadId, { runtimeMode: "full-access" }),
339 } as never),
340 }),
341 ),
342 Layer.provide(
343 Layer.mergeAll(
344 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
345 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
346 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
347 Layer.mock(ProjectService.ProjectService)({}),
348 Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}),
349 Layer.mock(SecretRequests.SecretRequests)({}),
350 ServerSettings.layerTest(),
351 // No thread here delegated to the box, so a send there is no follow-up.
352 Layer.mock(RemoteDelegation.RemoteDelegation)({
353 followUp: (_scope, _environmentId, _request, sent) => Effect.succeed(sent),
354 }),
355 Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
356 ),
357 ),
358 Layer.fresh,
359 );
360 const here = yield* Layer.build(layerHere);
361 const server = Context.get(here, McpServer.McpServer);
362 const scopeOf = (
363 caller: string,
364 capabilities: ReadonlySet<McpInvocationContext.McpCapability> = new Set(["orchestration"]),
365 ): McpInvocationContext.McpInvocationScope => ({
366 environmentId: laptop.environmentId,
367 requestNamespace: `provider-session:${caller}`,
368 thread: {
369 threadId: ThreadId.make(caller),
370 providerSessionId: `provider-session:${caller}`,
371 providerInstanceId: ProviderInstanceId.make("codex"),
372 },
373 client: undefined,
374 capabilities,
375 issuedAt: 1,
376 });
377 const call = (
378 caller: string,
379 name: string,
380 args: Record<string, unknown>,
381 capabilities?: ReadonlySet<McpInvocationContext.McpCapability>,
382 ) =>
383 server
384 .callTool({ name, arguments: args })
385 .pipe(
386 Effect.provideService(
387 McpInvocationContext.McpInvocationContext,
388 scopeOf(caller, capabilities),
389 ),
390 Effect.provideService(McpSchema.McpServerClient, mcpClient),
391 );
392 const callAsClient = (name: string, args: Record<string, unknown>) =>
393 server.callTool({ name, arguments: args }).pipe(
394 Effect.provideService(McpInvocationContext.McpInvocationContext, {
395 ...scopeOf("outside-client"),
396 requestNamespace: "client:session-1",
397 thread: undefined,
398 client: { sessionId: "session-1", label: "claude.ai", access: "read-only" },
399 }),
400 Effect.provideService(McpSchema.McpServerClient, mcpClient),
401 );
402 return { links: Context.get(linking, PeerLinks.PeerLinks), call, callAsClient };
403});
404​
405const failureOf = (result: McpSchema.CallToolResult) => {
406 const text = result.content[0];
407 return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
408};
409​
410it.effect("an agent here works on a linked environment's threads within its own modes", () =>
411 Effect.scoped(
412 Effect.gen(function* () {
413 const seen = yield* Ref.make<Seen>(nothingSeen);
414 const linkSession = yield* Ref.make("");
415 const b = yield* serveBox(seen, linkSession);
416 const a = yield* makeLaptop;
417 yield* linkTo(a.links, b, "auto");
418 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
419​
420 const listed = yield* a.call("thread:laptop-full", "t3_environment_links", {});
421 expect(listed.structuredContent).toMatchObject({
422 environmentId: laptop.environmentId,
423 links: [
424 { environmentId: box.environmentId, label: "Box", status: "reachable", access: "auto" },
425 ],
426 });
427​
428 const threads = yield* a.call("thread:laptop-full", "t3_thread_list", {
429 environmentId: box.environmentId,
430 projectId: boxProject,
431 });
432 expect(threads.isError).toBe(false);
433 expect(threads.structuredContent).toMatchObject({
434 projectId: boxProject,
435 threads: [{ threadId: boxThread, runtimeMode: "auto" }],
436 });
437​
438 // A full-access agent here is held to the link's `auto` there, which
439 // the box's `auto` thread is within.
440 const sent = yield* a.call("thread:laptop-full", "t3_thread_send", {
441 environmentId: box.environmentId,
442 threadId: boxThread,
443 message: "Carry on there.",
444 clientRequestId: "send-1",
445 });
446 expect(sent.isError).toBe(false);
447 expect(sent.structuredContent).toMatchObject({ threadId: boxThread, delivery: "started" });
448 // The box records which thread here sent it.
449 expect((yield* Ref.get(seen)).sends[0]?.linkedSender).toEqual({
450 environmentId: laptop.environmentId,
451 threadId: "thread:laptop-full",
452 title: "thread:laptop-full",
453 });
454​
455 // A plan-mode agent here may not steer that thread there: the box
456 // refuses it, because the call carries the agent's own modes.
457 const planned = yield* a.call("thread:laptop-plan", "t3_thread_send", {
458 environmentId: box.environmentId,
459 threadId: boxThread,
460 message: "Change course.",
461 });
462 expect(failureOf(planned)).toMatchObject({ code: "interaction_mode_escalation_denied" });
463 expect((yield* Ref.get(seen)).sends).toHaveLength(1);
464​
465 // stop=true stops the thread there as its Stop button does: the whole
466 // thread and the tasks it delegated, not just the running turn.
467 const stopped = yield* a.call("thread:laptop-full", "t3_thread_interrupt", {
468 environmentId: box.environmentId,
469 threadId: boxThread,
470 stop: true,
471 clientRequestId: "stop-1",
472 });
473 expect(stopped.structuredContent).toMatchObject({
474 threadId: boxThread,
475 runId: boxRun,
476 status: "interrupt_requested",
477 });
478 expect((yield* Ref.get(seen)).stops).toEqual([
479 `thread.stop ${boxThread}`,
480 `delegated-tasks.stop ${boxThread}`,
481 ]);
482 }),
483 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
484);
485​
486it.effect("keeps a forwarded wait short and its retries scoped to the caller", () =>
487 Effect.scoped(
488 Effect.gen(function* () {
489 const seen = yield* Ref.make<Seen>(nothingSeen);
490 const linkSession = yield* Ref.make("");
491 const b = yield* serveBox(seen, linkSession);
492 const a = yield* makeLaptop;
493 yield* linkTo(a.links, b, "auto");
494 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
495​
496 const waited = yield* a.call("thread:laptop-full", "t3_thread_wait", {
497 environmentId: box.environmentId,
498 threadId: boxThread,
499 timeoutMs: 600_000,
500 });
501 expect(waited.structuredContent).toEqual({
502 threadId: boxThread,
503 runId: boxRun,
504 status: "completed",
505 timedOut: false,
506 });
507 // One capped piece, so the caller's MCP request returns before its client times out.
508 expect((yield* Ref.get(seen)).waits.map(({ timeoutMs }) => timeoutMs)).toEqual([45_000]);
509​
510 const send = (caller: string, clientRequestId: string) =>
511 a.call(caller, "t3_thread_send", {
512 environmentId: box.environmentId,
513 threadId: boxThread,
514 message: "Once.",
515 clientRequestId,
516 });
517 yield* send("thread:laptop-full", "same-key");
518 yield* send("thread:laptop-full", "same-key");
519 yield* send("thread:laptop-other", "same-key");
520 const [first, retried, other] = (yield* Ref.get(seen)).sends.map((input) => input.commandId);
521 // The box sees every caller here as the one link, so the key is scoped
522 // to its caller before it leaves: a retry matches, another agent's same
523 // key does not.
524 expect(retried).toBe(first);
525 expect(other).not.toBe(first);
526 expect(first).not.toContain("same-key");
527 }),
528 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
529);
530​
531it.effect("launches in a linked environment with the caller's modes, retry-safe", () =>
532 Effect.scoped(
533 Effect.gen(function* () {
534 const seen = yield* Ref.make<Seen>(nothingSeen);
535 const linkSession = yield* Ref.make("");
536 const b = yield* serveBox(seen, linkSession);
537 const a = yield* makeLaptop;
538 yield* linkTo(a.links, b, "full-access");
539 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
540 const codex = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };
541 const launch = (caller: string, args: Record<string, unknown> = {}) =>
542 a.call(caller, "t3_thread_launch", {
543 environmentId: box.environmentId,
544 projectId: boxProject,
545 title: "Run the suite there",
546 modelSelection: codex,
547 message: "Run the suite.",
548 clientRequestId: "launch-1",
549 ...args,
550 });
551​
552 const first = yield* launch("thread:laptop-plan");
553 expect(first.isError).toBe(false);
554 expect(first.structuredContent).toMatchObject({
555 projectId: boxProject,
556 modelSelection: codex,
557 });
558 const retried = yield* launch("thread:laptop-plan");
559 const [launched, relaunched] = (yield* Ref.get(seen)).launches;
560 // The thread there runs with the caller's own modes here, below the
561 // link's full access, and a retry asks for the same thread.
562 expect(launched).toMatchObject({ runtimeMode: "full-access", interactionMode: "plan" });
563 expect(relaunched?.threadId).toBe(launched?.threadId);
564 expect(retried.structuredContent).toEqual(first.structuredContent);
565​
566 // An escalation past the caller's own modes is refused here.
567 const escalated = yield* launch("thread:laptop-plan", { interactionMode: "default" });
568 expect(failureOf(escalated)).toMatchObject({ code: "interaction_mode_escalation_denied" });
569 // A pending upload lives here, so it cannot go along.
570 yield* Ref.set(b.bearers, []);
571 const withUpload = yield* launch("thread:laptop-full", {
572 clientRequestId: "launch-2",
573 attachments: [
574 { type: "image", id: "upload-1", name: "a.png", mimeType: "image/png", sizeBytes: 1 },
575 ],
576 });
577 expect(failureOf(withUpload)).toMatchObject({ code: "invalid_request" });
578 expect(yield* Ref.get(b.bearers)).toEqual([]);
579 expect((yield* Ref.get(seen)).launches).toHaveLength(2);
580 }),
581 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
582);
583​
584it.effect("brings a repository to a linked environment, only through full access", () =>
585 Effect.scoped(
586 Effect.gen(function* () {
587 const seen = yield* Ref.make<Seen>(nothingSeen);
588 const b = yield* serveBox(seen, yield* Ref.make(""));
589 const a = yield* makeLaptop;
590 const clone = { repository: "pingdotgg/t3code", destinationPath: "/home/box/t3code" };
591 const register = { title: "t3code", workspaceRoot: "/home/box/t3code" };
592​
593 yield* linkTo(a.links, b, "full-access");
594 const cloned = yield* a.call("thread:laptop-full", "t3_project_clone", {
595 environmentId: box.environmentId,
596 ...clone,
597 });
598 expect(cloned.structuredContent).toMatchObject({ cwd: clone.destinationPath });
599 const created = yield* a.call("thread:laptop-full", "t3_project_create", {
600 environmentId: box.environmentId,
601 ...register,
602 });
603 expect(created.structuredContent).toMatchObject(register);
604 expect((yield* Ref.get(seen)).clones).toEqual([clone]);
605 expect((yield* Ref.get(seen)).projects).toMatchObject([register]);
606​
607 // A plan-mode agent here may not, and nothing leaves.
608 yield* Ref.set(b.bearers, []);
609 const planned = yield* a.call("thread:laptop-plan", "t3_project_create", {
610 environmentId: box.environmentId,
611 ...register,
612 });
613 expect(failureOf(planned)).toMatchObject({ code: "capability_denied" });
614 expect(yield* Ref.get(b.bearers)).toEqual([]);
615​
616 // Nor may a full-access agent through a link with less: the box holds it.
617 yield* linkTo(a.links, b, "auto");
618 for (const [name, args] of [
619 ["t3_project_clone", clone],
620 ["t3_project_create", register],
621 ] as const) {
622 const refused = yield* a.call("thread:laptop-full", name, {
623 environmentId: box.environmentId,
624 ...args,
625 });
626 const failure = failureOf(refused);
627 expect(failure, name).toMatchObject({ code: "capability_denied" });
628 // The agent's thread is full access; what holds it is the link's access.
629 expect(failure.message, name).toContain("linked environment");
630 expect(failure.message, name).not.toContain("calling thread");
631 }
632 expect((yield* Ref.get(seen)).clones).toHaveLength(1);
633 expect((yield* Ref.get(seen)).projects).toHaveLength(1);
634 }),
635 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
636);
637​
638it.effect("runs any tool that takes a linked environment there", () =>
639 Effect.scoped(
640 Effect.gen(function* () {
641 const seen = yield* Ref.make<Seen>(nothingSeen);
642 const linkSession = yield* Ref.make("");
643 const b = yield* serveBox(seen, linkSession);
644 const a = yield* makeLaptop;
645 yield* linkTo(a.links, b, "auto");
646 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
647​
648 const there = yield* a.call("thread:laptop-full", "t3_thread_configure", {
649 environmentId: box.environmentId,
650 threadId: boxThread,
651 });
652 expect(there.structuredContent).toMatchObject({ threadId: boxThread, runtimeMode: "auto" });
653 const archived = yield* a.call("thread:laptop-full", "t3_thread_organize", {
654 environmentId: box.environmentId,
655 threadId: boxThread,
656 action: "archive",
657 });
658 expect(archived.isError).toBe(false);
659 expect((yield* Ref.get(seen)).stops).toEqual([`thread.archive ${boxThread}`]);
660 // A cursorless read from here gets the newest page there, as it does locally.
661 const read = yield* a.call("thread:laptop-full", "t3_thread_read", {
662 environmentId: box.environmentId,
663 threadId: boxThread,
664 });
665 expect(read.isError).toBe(false);
666 const clientRead = yield* a.callAsClient("t3_thread_read", {
667 environmentId: box.environmentId,
668 threadId: boxThread,
669 });
670 expect(clientRead.isError).toBe(false);
671 expect((yield* Ref.get(seen)).reads).toEqual([
672 { beforePosition: Number.MAX_SAFE_INTEGER, limit: 10, view: "messages" },
673 { beforePosition: Number.MAX_SAFE_INTEGER, limit: 10, view: "messages" },
674 ]);
675​
676 // This environment's own id keeps the call here.
677 const own = yield* a.call("thread:laptop-full", "t3_thread_configure", {
678 environmentId: laptop.environmentId,
679 });
680 expect(own.structuredContent).toMatchObject({
681 threadId: "thread:laptop-full",
682 runtimeMode: "full-access",
683 });
684 }),
685 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
686);
687​
688it.effect("refuses what a linked environment cannot take before anything leaves", () =>
689 Effect.scoped(
690 Effect.gen(function* () {
691 const seen = yield* Ref.make<Seen>(nothingSeen);
692 const linkSession = yield* Ref.make("");
693 const b = yield* serveBox(seen, linkSession);
694 const a = yield* makeLaptop;
695 yield* linkTo(a.links, b, "auto");
696 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
697 yield* Ref.set(b.bearers, []);
698​
699 const unknown = yield* a.call("thread:laptop-full", "t3_thread_read", {
700 environmentId: EnvironmentId.make("environment-elsewhere"),
701 threadId: boxThread,
702 });
703 expect(failureOf(unknown)).toMatchObject({ code: "invalid_request" });
704 expect(yield* Ref.get(b.bearers)).toEqual([]);
705​
706 // The box sees only the link's credential, so one that may not control
707 // threads here may not reach them there either.
708 const previewOnly = new Set<McpInvocationContext.McpCapability>(["preview"]);
709 for (const [name, args] of [
710 ["t3_environment_links", {}],
711 ["t3_project_list", { environmentId: box.environmentId }],
712 ["t3_thread_list", { environmentId: box.environmentId, projectId: boxProject }],
713 ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
714 ["t3_thread_wait", { environmentId: box.environmentId, threadId: boxThread }],
715 [
716 "t3_thread_send",
717 { environmentId: box.environmentId, threadId: boxThread, message: "Carry on there." },
718 ],
719 [
720 "t3_thread_organize",
721 { environmentId: box.environmentId, threadId: boxThread, action: "archive" },
722 ],
723 [
724 "t3_thread_launch",
725 {
726 environmentId: box.environmentId,
727 projectId: boxProject,
728 title: "Start there",
729 modelSelection: { instanceId: "codex", model: "gpt-5" },
730 message: "Start there.",
731 },
732 ],
733 ] as const) {
734 const refused = yield* a.call("thread:laptop-full", name, args, previewOnly);
735 expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" });
736 }
737 expect(yield* Ref.get(b.bearers)).toEqual([]);
738​
739 // Work a desk's link started here never uses this laptop's links: the
740 // box would see the laptop, not the desk, so its fence could not hold.
741 for (const [name, args] of [
742 ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
743 [
744 "t3_thread_send",
745 { environmentId: box.environmentId, threadId: boxThread, message: "From the desk." },
746 ],
747 [
748 "t3_thread_launch",
749 { environmentId: box.environmentId, projectId: boxProject, title: "x" },
750 ],
751 ] as const) {
752 const relayed = yield* a.call("thread:laptop-from-desk", name, args);
753 expect(failureOf(relayed), name).toMatchObject({ code: "capability_denied" });
754 }
755 expect(yield* Ref.get(b.bearers)).toEqual([]);
756 }),
757 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
758);
759​
760it.effect("refuses a launch there above the link's access, naming the link", () =>
761 Effect.scoped(
762 Effect.gen(function* () {
763 const seen = yield* Ref.make<Seen>(nothingSeen);
764 const linkSession = yield* Ref.make("");
765 const b = yield* serveBox(seen, linkSession);
766 const a = yield* makeLaptop;
767 yield* linkTo(a.links, b, "auto");
768 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
769​
770 // A full-access agent here asks for more than the link allows there.
771 const launchAboveLink = a.call("thread:laptop-full", "t3_thread_launch", {
772 environmentId: box.environmentId,
773 projectId: boxProject,
774 title: "Run the suite there",
775 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
776 message: "Run the suite.",
777 runtimeMode: "full-access",
778 });
779 const { message } = failureOf(yield* launchAboveLink);
780 expect(message).toContain('"Box"');
781 expect(message).toContain("auto");
782 expect(message).toContain("full-access");
783 expect(message).not.toContain("parent mode");
784 expect((yield* Ref.get(seen)).launches).toEqual([]);
785​
786 // Once the link has expired, that is what the agent needs to hear.
787 yield* TestClock.adjust(Duration.days(31));
788 expect(failureOf(yield* launchAboveLink).message).toContain("expired");
789 }),
790 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
791);
792​
793const refusedRead = (message: string) =>
794 new OrchestratorMcpFailure({ code: "invalid_request", message });
795const beforePositionRefusal = refusedRead(
796 `Invalid parameters for tool 't3_thread_read': Unknown argument "beforePosition". Accepted arguments: limit, view.`,
797);
798​
799it("recognizes only a validation refusal of beforePosition", () => {
800 const cases: Array<[OrchestratorMcpFailure, boolean]> = [
801 [beforePositionRefusal, true],
802 [
803 refusedRead(
804 `Invalid parameters for tool 't3_thread_read': Unknown arguments "runLimit", "beforePosition". Accepted arguments: limit.`,
805 ),
806 true,
807 ],
808 [refusedRead(`Invalid parameters for tool 't3_thread_read': Unknown argument "limit".`), false],
809 // A thread id can carry the same words; only the refusal's code and prefix count.
810 [
811 new OrchestratorMcpFailure({
812 code: "thread_not_found",
813 message: `Thread Unknown argument "beforePosition". Accepted arguments: x. is no longer available.`,
814 }),
815 false,
816 ],
817 ];
818 for (const [failure, expected] of cases) {
819 expect(PeerForwarding.refusesBeforePosition(failure)).toBe(expected);
820 }
821});
822​
823it.effect("retries a newest-page read without its cursor when the peer refuses the cursor", () =>
824 Effect.gen(function* () {
825 const sent: Array<unknown> = [];
826 const olderPeer = (args: unknown): Effect.Effect<string, OrchestratorMcpFailure> => {
827 sent.push(args);
828 return "beforePosition" in (args as object)
829 ? Effect.fail(beforePositionRefusal)
830 : Effect.succeed("forward page");
831 };
832 const params = { threadId: "thread:box-auto", limit: 35 };
833 const newest = { ...params, beforePosition: Number.MAX_SAFE_INTEGER };
834​
835 const page = yield* PeerForwarding.readNewestOrRetry(olderPeer, newest, params);
836​
837 expect(page).toBe("forward page");
838 expect(sent).toEqual([newest, params]);
839 }),
840);