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