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