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

PeerForwarding.test.ts

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