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