@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 746 lines 30.5 KB
Raw
1 import * as DocumentText from "../provider/DocumentText.ts";
2 import { NodeHttpServer } from "@effect/platform-node";
3 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import {
6 EnvironmentId,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadShell,
9 type SourceControlCloneRepositoryInput,
10 ProjectId,
11 ProviderInstanceId,
12 RunId,
13 ThreadId,
14 } from "@t3tools/contracts";
15 import { expect, it } from "@effect/vitest";
16 import * as Context from "effect/Context";
17 import * as Duration from "effect/Duration";
18 import * as Effect from "effect/Effect";
19 import * as Layer from "effect/Layer";
20 import * as Option from "effect/Option";
21 import * as Ref from "effect/Ref";
22 import * as TestClock from "effect/testing/TestClock";
23 import { McpSchema, McpServer } from "effect/ai";
24
25 import * as ServerConfig from "../config.ts";
26 import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
27 import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
28 import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
29 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
30 import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
31 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
32 import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
33 import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
34 import * as ProjectService from "../project/ProjectService.ts";
35 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
36 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
37 import * as SecretRequests from "../secrets/SecretRequests.ts";
38 import * as ServerSettings from "../serverSettings.ts";
39 import * as RemoteDelegation from "./RemoteDelegation.ts";
40 import * as McpHttpServer from "../mcp/McpHttpServer.ts";
41 import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
42 import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
43 import * as PeerForwarding from "./PeerForwarding.ts";
44 import * as PeerLinks from "./PeerLinks.ts";
45 import * as PeerLinkRequests from "./PeerLinkRequests.ts";
46 import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
47
48 const laptop = descriptorOf("environment-laptop", "Laptop");
49 const box = descriptorOf("environment-box", "Box");
50 const boxProject = ProjectId.make("project:box");
51 const boxThread = ThreadId.make("thread:box-auto");
52 const boxRun = RunId.make("run:box-auto");
53
54 /** What B's thread service was asked to do. */
55 interface 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 }
64 const 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. */
74 const 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 */
81 const 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. */
145 const 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. */
166 const 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 */
218 const 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
257 const 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 */
274 const 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
375 const 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
380 it.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
456 it.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
501 it.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
554 it.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 const failure = failureOf(refused);
597 expect(failure, name).toMatchObject({ code: "capability_denied" });
598 // The agent's thread is full access; what holds it is the link's access.
599 expect(failure.message, name).toContain("linked environment");
600 expect(failure.message, name).not.toContain("calling thread");
601 }
602 expect((yield* Ref.get(seen)).clones).toHaveLength(1);
603 expect((yield* Ref.get(seen)).projects).toHaveLength(1);
604 }),
605 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
606 );
607
608 it.effect("runs any tool that takes a linked environment there", () =>
609 Effect.scoped(
610 Effect.gen(function* () {
611 const seen = yield* Ref.make<Seen>(nothingSeen);
612 const linkSession = yield* Ref.make("");
613 const b = yield* serveBox(seen, linkSession);
614 const a = yield* makeLaptop;
615 yield* linkTo(a.links, b, "auto");
616 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
617
618 const there = yield* a.call("thread:laptop-full", "t3_thread_configure", {
619 environmentId: box.environmentId,
620 threadId: boxThread,
621 });
622 expect(there.structuredContent).toMatchObject({ threadId: boxThread, runtimeMode: "auto" });
623 const archived = yield* a.call("thread:laptop-full", "t3_thread_organize", {
624 environmentId: box.environmentId,
625 threadId: boxThread,
626 action: "archive",
627 });
628 expect(archived.isError).toBe(false);
629 expect((yield* Ref.get(seen)).stops).toEqual([`thread.archive ${boxThread}`]);
630
631 // This environment's own id keeps the call here.
632 const own = yield* a.call("thread:laptop-full", "t3_thread_configure", {
633 environmentId: laptop.environmentId,
634 });
635 expect(own.structuredContent).toMatchObject({
636 threadId: "thread:laptop-full",
637 runtimeMode: "full-access",
638 });
639 }),
640 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
641 );
642
643 it.effect("refuses what a linked environment cannot take before anything leaves", () =>
644 Effect.scoped(
645 Effect.gen(function* () {
646 const seen = yield* Ref.make<Seen>(nothingSeen);
647 const linkSession = yield* Ref.make("");
648 const b = yield* serveBox(seen, linkSession);
649 const a = yield* makeLaptop;
650 yield* linkTo(a.links, b, "auto");
651 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
652 yield* Ref.set(b.bearers, []);
653
654 const unknown = yield* a.call("thread:laptop-full", "t3_thread_read", {
655 environmentId: EnvironmentId.make("environment-elsewhere"),
656 threadId: boxThread,
657 });
658 expect(failureOf(unknown)).toMatchObject({ code: "invalid_request" });
659 expect(yield* Ref.get(b.bearers)).toEqual([]);
660
661 // The box sees only the link's credential, so one that may not control
662 // threads here may not reach them there either.
663 const previewOnly = new Set<McpInvocationContext.McpCapability>(["preview"]);
664 for (const [name, args] of [
665 ["t3_environment_links", {}],
666 ["t3_project_list", { environmentId: box.environmentId }],
667 ["t3_thread_list", { environmentId: box.environmentId, projectId: boxProject }],
668 ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
669 ["t3_thread_wait", { environmentId: box.environmentId, threadId: boxThread }],
670 [
671 "t3_thread_send",
672 { environmentId: box.environmentId, threadId: boxThread, message: "Carry on there." },
673 ],
674 [
675 "t3_thread_organize",
676 { environmentId: box.environmentId, threadId: boxThread, action: "archive" },
677 ],
678 [
679 "t3_thread_launch",
680 {
681 environmentId: box.environmentId,
682 projectId: boxProject,
683 title: "Start there",
684 modelSelection: { instanceId: "codex", model: "gpt-5" },
685 message: "Start there.",
686 },
687 ],
688 ] as const) {
689 const refused = yield* a.call("thread:laptop-full", name, args, previewOnly);
690 expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" });
691 }
692 expect(yield* Ref.get(b.bearers)).toEqual([]);
693
694 // Work a desk's link started here never uses this laptop's links: the
695 // box would see the laptop, not the desk, so its fence could not hold.
696 for (const [name, args] of [
697 ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
698 [
699 "t3_thread_send",
700 { environmentId: box.environmentId, threadId: boxThread, message: "From the desk." },
701 ],
702 [
703 "t3_thread_launch",
704 { environmentId: box.environmentId, projectId: boxProject, title: "x" },
705 ],
706 ] as const) {
707 const relayed = yield* a.call("thread:laptop-from-desk", name, args);
708 expect(failureOf(relayed), name).toMatchObject({ code: "capability_denied" });
709 }
710 expect(yield* Ref.get(b.bearers)).toEqual([]);
711 }),
712 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
713 );
714
715 it.effect("refuses a launch there above the link's access, naming the link", () =>
716 Effect.scoped(
717 Effect.gen(function* () {
718 const seen = yield* Ref.make<Seen>(nothingSeen);
719 const linkSession = yield* Ref.make("");
720 const b = yield* serveBox(seen, linkSession);
721 const a = yield* makeLaptop;
722 yield* linkTo(a.links, b, "auto");
723 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
724
725 // A full-access agent here asks for more than the link allows there.
726 const launchAboveLink = a.call("thread:laptop-full", "t3_thread_launch", {
727 environmentId: box.environmentId,
728 projectId: boxProject,
729 title: "Run the suite there",
730 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
731 message: "Run the suite.",
732 runtimeMode: "full-access",
733 });
734 const { message } = failureOf(yield* launchAboveLink);
735 expect(message).toContain('"Box"');
736 expect(message).toContain("auto");
737 expect(message).toContain("full-access");
738 expect(message).not.toContain("parent mode");
739 expect((yield* Ref.get(seen)).launches).toEqual([]);
740
741 // Once the link has expired, that is what the agent needs to hear.
742 yield* TestClock.adjust(Duration.days(31));
743 expect(failureOf(yield* launchAboveLink).message).toContain("expired");
744 }),
745 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
746 );