From 141f76c78728201c33d5647795d571117fc31a63 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Wed, 11 Nov 2026 15:25:19 +0000 Subject: [PATCH 1/4] feat: let SubSandboxes start a sandbox for a parent that works on a sandbox A parent on a sandbox has no checkout on this machine, so start can take the repository and pushed branch its clone tracks instead of reading the host's checkout, and copies env files only from a real checkout. A caller name picks the words of a refusal, so an agent asking from a sandbox is not told about target.sandbox. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/sandbox/SubSandboxes.ts | 75 +++++++++++++++------ apps/server/src/sandbox/subSandboxPolicy.ts | 35 ++++++++-- 2 files changed, 86 insertions(+), 24 deletions(-) diff --git a/apps/server/src/sandbox/SubSandboxes.ts b/apps/server/src/sandbox/SubSandboxes.ts index 3a88811f45f22..1cda873d2963c 100644 --- a/apps/server/src/sandbox/SubSandboxes.ts +++ b/apps/server/src/sandbox/SubSandboxes.ts @@ -22,6 +22,7 @@ import { checkSubSandboxCapacity, resolveSubSandboxConfig, resolveSubSandboxSize, + type SubSandboxCaller, } from "./subSandboxPolicy.ts"; /** A subagent's sandbox, linked here and ready for its task. */ @@ -47,6 +48,19 @@ export class SubSandboxes extends Context.Service< /** The parent's checkout, whose repository and pushed branch the sandbox clones. */ readonly cwd: string; readonly size: string | undefined; + /** + * For a parent that works on a sandbox of its own, whose clone is there and not at `cwd`: + * the repository and pushed branch that clone tracks. `cwd` is then only the host + * project's folder, read for env files when it is a real checkout of the repository. + */ + readonly repository?: { + readonly remoteUrl: string; + readonly canonicalKey: string; + readonly baseRef: string | undefined; + readonly hostCheckout: boolean; + }; + /** Who asked, for the words of a refusal. `delegate_task` when absent. */ + readonly caller?: SubSandboxCaller; }) => Effect.Effect; /** Deletes a sandbox whose task never started. */ readonly discard: (instanceId: string) => Effect.Effect; @@ -61,8 +75,10 @@ export class SubSandboxes extends Context.Service< const failure = (code: OrchestratorMcpFailure["code"], message: string) => new OrchestratorMcpFailure({ code, message }); -const LINKED_ENVIRONMENTS_NEEDED = - "A subagent's sandbox runs its task as a linked environment, and Linked environments is off on this machine. Ask the user to turn it on in Settings → Labs, then try again, or run the task without target.sandbox."; +const linkedEnvironmentsNeeded = (caller: SubSandboxCaller) => + caller === "delegate_task" + ? "A subagent's sandbox runs its task as a linked environment, and Linked environments is off on this machine. Ask the user to turn it on in Settings → Labs, then try again, or run the task without target.sandbox." + : "A sub-sandbox runs its task as a linked environment of the user's computer, and Linked environments is off there. Ask the user to turn it on in T3 Code's Settings → Labs on their computer, then try again, or run the task here, on this sandbox."; /** The branch name a remote-tracking ref such as `origin/feature/x` points at. */ const branchOfUpstream = (upstreamRef: string | null) => { @@ -142,10 +158,32 @@ const make = Effect.gen(function* () { ), ); + /** The repository and pushed branch of the parent's checkout on this machine. */ + const checkoutSource = Effect.fn("SubSandboxes.checkoutSource")(function* (cwd: string) { + const identity = yield* repositoryIdentities.resolve(cwd); + const remoteUrl = identity?.locator.remoteUrl; + if (remoteUrl === undefined) { + return yield* failure( + "invalid_request", + "This thread's checkout has no git remote, so a sandbox has nothing to clone.", + ); + } + // The sandbox clones from GitHub, so it gets the parent's branch only once that is pushed. + const status = yield* git.statusDetailsLocal(cwd).pipe(Effect.orElseSucceed(() => null)); + return { + remoteUrl, + repositoryKey: identity?.canonicalKey.toLowerCase() ?? null, + baseRef: + status !== null && status.hasUpstream ? branchOfUpstream(status.upstreamRef) : undefined, + hostCheckout: true, + }; + }); + const start: SubSandboxes["Service"]["start"] = Effect.fn("SubSandboxes.start")( function* (input) { + const caller = input.caller ?? "delegate_task"; if (!(yield* peerLinks.enabled)) { - return yield* failure("invalid_request", LINKED_ENVIRONMENTS_NEEDED); + return yield* failure("invalid_request", linkedEnvironmentsNeeded(caller)); } const project = yield* projects.getById(input.projectId).pipe( Effect.map(Option.getOrUndefined), @@ -154,20 +192,15 @@ const make = Effect.gen(function* () { if (project === undefined) { return yield* failure("invalid_request", `Project ${input.projectId} was not found.`); } - const identity = yield* repositoryIdentities.resolve(input.cwd); - const remoteUrl = identity?.locator.remoteUrl; - if (remoteUrl === undefined) { - return yield* failure( - "invalid_request", - "This thread's checkout has no git remote, so a sandbox has nothing to clone.", - ); - } - // The sandbox clones from GitHub, so it gets the parent's branch only once that is pushed. - const status = yield* git - .statusDetailsLocal(input.cwd) - .pipe(Effect.orElseSucceed(() => null)); - const baseRef = - status !== null && status.hasUpstream ? branchOfUpstream(status.upstreamRef) : undefined; + const source = yield* input.repository === undefined + ? checkoutSource(input.cwd) + : Effect.succeed({ + remoteUrl: input.repository.remoteUrl, + repositoryKey: input.repository.canonicalKey.toLowerCase(), + baseRef: input.repository.baseRef, + hostCheckout: input.repository.hostCheckout, + }); + const { remoteUrl, baseRef } = source; const providers = yield* provisioner.providers; const instanceId = yield* random.uuidV4(); @@ -183,7 +216,7 @@ const make = Effect.gen(function* () { const resolved = resolveSubSandboxConfig({ parentThreadId: input.parentThreadId, projectId: input.projectId, - repositoryKey: identity?.canonicalKey.toLowerCase() ?? null, + repositoryKey: source.repositoryKey, records: listed, configs, }); @@ -195,6 +228,7 @@ const make = Effect.gen(function* () { parentThreadId: input.parentThreadId, records: listed, starting, + caller, }); if (full !== null) return yield* failure(full.code, full.message); const sized = resolveSubSandboxSize({ @@ -203,6 +237,7 @@ const make = Effect.gen(function* () { providers.providers.find((provider) => provider.kind === resolved.config.provider) ?.sizes ?? [], requested: input.size, + caller, }); if (sized._tag === "refused") { return yield* failure(sized.refusal.code, sized.refusal.message); @@ -224,7 +259,9 @@ const make = Effect.gen(function* () { title: project.title, remoteUrl, ...(baseRef === undefined ? {} : { baseRef }), - hostCopy: { projectId: project.id, workspaceRoot: project.workspaceRoot }, + ...(source.hostCheckout + ? { hostCopy: { projectId: project.id, workspaceRoot: project.workspaceRoot } } + : {}), }, }) .pipe( diff --git a/apps/server/src/sandbox/subSandboxPolicy.ts b/apps/server/src/sandbox/subSandboxPolicy.ts index b3d1b4786ff39..20b10f4121690 100644 --- a/apps/server/src/sandbox/subSandboxPolicy.ts +++ b/apps/server/src/sandbox/subSandboxPolicy.ts @@ -18,6 +18,27 @@ export interface SubSandboxRefusal { readonly message: string; } +/** + * Who asked: an agent here through `delegate_task`'s `target.sandbox`, or an agent on a sandbox + * through the helper T3 Code installs there (`sandbox_delegate`). Only the words differ. + */ +export type SubSandboxCaller = "delegate_task" | "sandbox"; + +const wordingFor = (caller: SubSandboxCaller) => + caller === "delegate_task" + ? { + runWithout: "Run the task without target.sandbox.", + runThisWithout: "run this one without target.sandbox", + runTaskWithout: "run this task without target.sandbox", + sizeParameter: "target.sandbox.size", + } + : { + runWithout: "Run the task here, on this sandbox.", + runThisWithout: "run this one here, on this sandbox", + runTaskWithout: "run this task here, on this sandbox", + sizeParameter: "size", + }; + const refuse = ( code: SubSandboxRefusal["code"], message: string, @@ -94,7 +115,9 @@ export const checkSubSandboxCapacity = (input: { readonly parentThreadId: ThreadId; readonly records: ReadonlyArray; readonly starting: ReadonlyMap; + readonly caller?: SubSandboxCaller; }): SubSandboxRefusal | null => { + const words = wordingFor(input.caller ?? "delegate_task"); const parents = new Map(input.starting); for (const record of input.records) { if (holdsPlace(record)) parents.set(record.instanceId, record.parentThreadId!); @@ -104,19 +127,19 @@ export const checkSubSandboxCapacity = (input: { if (limits.perThread === 0 || limits.total === 0) { return { code: "concurrency_full", - message: `The ${input.config.label} sandbox config does not let subagents start sandboxes. Run the task without target.sandbox.`, + message: `The ${input.config.label} sandbox config does not let subagents start sandboxes. ${words.runWithout}`, }; } if (forThread >= limits.perThread) { return { code: "concurrency_full", - message: `This thread already has ${forThread} subagent ${forThread === 1 ? "sandbox" : "sandboxes"} running, the most the ${input.config.label} config allows. Wait for one of those tasks to finish, or run this one without target.sandbox.`, + message: `This thread already has ${forThread} subagent ${forThread === 1 ? "sandbox" : "sandboxes"} running, the most the ${input.config.label} config allows. Wait for one of those tasks to finish, or ${words.runThisWithout}.`, }; } if (parents.size >= limits.total) { return { code: "concurrency_full", - message: `${parents.size} subagent sandboxes are already running on this machine, the most the ${input.config.label} config allows. Wait for one to finish, or run this task without target.sandbox.`, + message: `${parents.size} subagent sandboxes are already running on this machine, the most the ${input.config.label} config allows. Wait for one to finish, or ${words.runTaskWithout}.`, }; } return null; @@ -130,17 +153,19 @@ export const resolveSubSandboxSize = (input: { readonly config: SandboxEnvironmentConfig; readonly sizes: ReadonlyArray; readonly requested: string | undefined; + readonly caller?: SubSandboxCaller; }): | { readonly _tag: "size"; readonly size: string } | { readonly _tag: "refused"; readonly refusal: SubSandboxRefusal } => { const { config, sizes, requested } = input; + const words = wordingFor(input.caller ?? "delegate_task"); if (requested === undefined || requested === config.size) { return { _tag: "size", size: config.size }; } if (config.template !== undefined) { return refuse( "invalid_request", - `The ${config.label} config starts from the template ${config.template}, which decides the size. Omit target.sandbox.size.`, + `The ${config.label} config starts from the template ${config.template}, which decides the size. Omit ${words.sizeParameter}.`, ); } const base = sizes.findIndex((size) => size.id === config.size); @@ -148,7 +173,7 @@ export const resolveSubSandboxSize = (input: { if (!allowed.includes(requested)) { return refuse( "invalid_request", - `target.sandbox.size can be ${allowed.join(" or ")} (the ${config.label} config's size or one step up).`, + `${words.sizeParameter} can be ${allowed.join(" or ")} (the ${config.label} config's size or one step up).`, ); } return { _tag: "size", size: requested }; From 6467c5772539063b9efa3c19159a0f7ea9717f09 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Wed, 11 Nov 2026 15:25:39 +0000 Subject: [PATCH 2/4] feat: install a sub-sandbox helper on each chat's sandbox Sandboxes run the official T3 Code, so agents there get sandbox_delegate and sandbox_task_status from a small MCP server T3 Code installs: Node built-ins only, registered in Claude's MCP list like the servers a config copies. Requests and responses are files under ~/.t3/userdata/sub-sandbox, written by rename, and a request the host does not pick up within 45 s is withdrawn with a message to do the work locally. The launch installs it after T3 Code's skill, every resume of a chat's sandbox rewrites it before T3 starts, and a subagent's own sandbox never gets it. A failure is only a warning. The template scrub removes its folder with any pending requests. The provisioner can now run T3 Code's own scripts on a running sandbox for the host's poll. Co-Authored-By: Claude Opus 5.5 --- .../src/sandbox/SandboxProvisioner.test.ts | 128 ++++++ apps/server/src/sandbox/SandboxProvisioner.ts | 55 +++ .../src/sandbox/subSandboxHelper.test.ts | 342 ++++++++++++++ apps/server/src/sandbox/subSandboxHelper.ts | 419 ++++++++++++++++++ packages/contracts/src/sandbox.test.ts | 2 +- packages/contracts/src/sandbox.ts | 1 + 6 files changed, 946 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/sandbox/subSandboxHelper.test.ts create mode 100644 apps/server/src/sandbox/subSandboxHelper.ts diff --git a/apps/server/src/sandbox/SandboxProvisioner.test.ts b/apps/server/src/sandbox/SandboxProvisioner.test.ts index fd12fa24595a9..db150da368afd 100644 --- a/apps/server/src/sandbox/SandboxProvisioner.test.ts +++ b/apps/server/src/sandbox/SandboxProvisioner.test.ts @@ -3634,6 +3634,8 @@ describe("SandboxProvisioner lifecycle", () => { ]); expect(commands[0]).toContain("t3 service uninstall"); expect(commands[0]).toContain(`rm -rf "$HOME/.t3/userdata" "$HOME/.t3/environment-label"`); + // The sub-sandbox helper's queue goes, pending requests included, before T3's userdata. + expect(commands[0]).toContain(`rm -rf "$HOME/.t3/userdata/sub-sandbox"`); expect(commands[0]).not.toContain("pkill"); // Without its T3 identity the source could only come back as a different environment. expect(repository.byEnvironment(testEnvironmentId) !== undefined).toBe(false); @@ -5819,6 +5821,10 @@ describe("SandboxProvisioner per-thread launches", () => { }); expect(record?.threadId).toBeUndefined(); expect(record?.bridge).toBeUndefined(); + // A subagent's sandbox has no chat here to hold more tasks, so it never gets the helper. + expect(fake.commands.filter((command) => command.includes("userdata/sub-sandbox"))).toEqual( + [], + ); // The same clone and env files as a thread's launch, at the parent's pushed branch. const clone = fake.commands.find((command) => command.includes("https://github.com/octo/hello.git"), @@ -6718,6 +6724,128 @@ describe("SandboxProvisioner per-thread launches", () => { }, ); + const helperWarning = + "T3 Code's sub-sandbox helper could not be added, so agents on this sandbox cannot ask this computer for a sandbox of their own."; + const helperCommands = (fake: BoatFake) => + fake.commands.filter((command) => command.includes('dir="$HOME/.t3/userdata/sub-sandbox"')); + + it.effect("installs the sub-sandbox helper on a launched chat's sandbox", () => { + const fake = boatFake(); + const configs = memoryConfigs(); + return Effect.gen(function* () { + const provisioner = yield* SandboxProvisioner.SandboxProvisioner; + const { config } = yield* provisioner.saveConfig({ + config: configInput, + apiKey: "boat_test", + }); + yield* provisioner.launch({ configId: config.id, threadId, project }); + const done = yield* snapshotWhere(provisioner, (snapshot) => snapshot.phase === "done"); + const [installed, ...rest] = helperCommands(fake); + expect(rest).toEqual([]); + // Registered in Claude's MCP list, and named so a template save removes the entry. + expect(installed).toContain('"$HOME/.t3/mcp-servers.json" "$dir/mcp.mjs" t3-sub-sandbox'); + expect(installed).toContain('mv "$dir/mcp.mjs.tmp" "$dir/mcp.mjs"'); + // Not something the config asked for, so the step still reads as nothing to set up. + expect(stageOf(done, "tools")).toMatchObject({ status: "skipped" }); + expect(done.warnings).not.toContain(helperWarning); + }).pipe( + Effect.provide(provisionerLayer({}, memoryRepository().layer, { configs: configs.layer })), + Effect.provideService(HttpClient.HttpClient, fake.client), + ); + }); + + it.effect("only warns when the launch cannot install the sub-sandbox helper", () => { + const fake = boatFake({ failing: { text: "userdata/sub-sandbox", times: 1 } }); + const repository = memoryRepository(); + const configs = memoryConfigs(); + return Effect.gen(function* () { + const provisioner = yield* SandboxProvisioner.SandboxProvisioner; + const { config } = yield* provisioner.saveConfig({ + config: configInput, + apiKey: "boat_test", + }); + const { instanceId } = yield* provisioner.launch({ configId: config.id, threadId, project }); + const done = yield* snapshotWhere(provisioner, (snapshot) => snapshot.phase === "done"); + expect(done.warnings).toContain(helperWarning); + expect(stageOf(done, "tools")).toMatchObject({ status: "warning" }); + expect(repository.records.get(instanceId)?.state).toBe("running"); + expect(deletes(fake)).toEqual([]); + }).pipe( + Effect.provide(provisionerLayer({}, repository.layer, { configs: configs.layer })), + Effect.provideService(HttpClient.HttpClient, fake.client), + ); + }); + + it.effect( + "installs the sub-sandbox helper again on every resume of a chat's sandbox, before T3 starts, and only warns when it cannot", + () => { + const fake = boatFake({ failing: { text: "userdata/sub-sandbox", times: 1 } }); + const config: SandboxEnvironmentConfig = { + ...configInput, + id: "config-before-helper", + createdAt: "1970-01-01T00:00:00.000Z", + updatedAt: "1970-01-01T00:00:00.000Z", + }; + // A chat's sandbox made before T3 Code installed the helper, and a subagent's sandbox. + const older: SandboxRecord = { + instanceId: "before-helper", + environmentId: testEnvironmentId, + configId: config.id, + threadId, + provider: "boat", + sandboxId: boatSandboxId, + label: "hello on Boat small", + size: "small", + state: "stopped", + createdAt: "1970-01-01T00:00:00.000Z", + updatedAt: "1970-01-01T00:00:00.000Z", + httpBaseUrl: "https://boat.example/t3", + runningSince: null, + maxRunningMinutes: 480, + repoDir: "/home/boat/work/hello", + }; + const { threadId: _threadId, ...withoutThread } = older; + const subagents: SandboxRecord = { + ...withoutThread, + instanceId: "subagent-sandbox", + parentThreadId: threadId, + }; + const repository = memoryRepository([older, subagents]); + return Effect.gen(function* () { + const provisioner = yield* SandboxProvisioner.SandboxProvisioner; + // The first try fails: the sandbox still resumes, with a warning. + const failed = yield* provisioner.resume({ instanceId: "before-helper" }); + expect(failed.sandbox.state).toBe("running"); + expect(failed.warnings).toContain(helperWarning); + + yield* provisioner.stop({ instanceId: "before-helper" }); + fake.commands.length = 0; + const resumed = yield* provisioner.resume({ instanceId: "before-helper" }); + expect(resumed.warnings ?? []).not.toContain(helperWarning); + // Rewritten every time, so an older helper is replaced and Node's path stays current. + const [backfill, ...rest] = helperCommands(fake); + expect(rest).toEqual([]); + expect(fake.commands.indexOf(backfill!)).toBeLessThan( + fake.commands.findIndex((command) => command.includes("t3 serve")), + ); + + yield* provisioner.stop({ instanceId: "before-helper" }); + fake.commands.length = 0; + yield* provisioner.resume({ instanceId: "subagent-sandbox" }); + expect(helperCommands(fake)).toEqual([]); + }).pipe( + Effect.provide( + provisionerLayer( + { sandboxProviders: { boat: { apiKey: "boat_test" } } }, + repository.layer, + { configs: memoryConfigs([config]).layer }, + ), + ), + Effect.provideService(HttpClient.HttpClient, fake.client), + ); + }, + ); + it.effect("keeps the sandbox and revokes the key when the boat CLI cannot sign in", () => { const fake = boatFake({ failing: { text: "boat login", times: 1 } }); const repository = memoryRepository(); diff --git a/apps/server/src/sandbox/SandboxProvisioner.ts b/apps/server/src/sandbox/SandboxProvisioner.ts index a49cce104eefe..973c847f9958e 100644 --- a/apps/server/src/sandbox/SandboxProvisioner.ts +++ b/apps/server/src/sandbox/SandboxProvisioner.ts @@ -97,6 +97,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts"; import { type CliproxyHub, makeCliproxyApi } from "../usage/cliproxyApi.ts"; import * as SandboxHostAccess from "./SandboxHostAccess.ts"; +import { SUB_SANDBOX_HELPER_SCRUB, subSandboxHelperScript } from "./subSandboxHelper.ts"; import { CLAUDE_SETTINGS_SCRUB, claudeSettingsScript, @@ -287,6 +288,7 @@ while answering; do sleep 1 done ${KEEP_ALIVE_SCRUB} +${SUB_SANDBOX_HELPER_SCRUB} rm -rf "$HOME/.t3/userdata" "$HOME/.t3/environment-label" "$HOME/.t3/usage-host-id" ${CLAUDE_SETTINGS_SCRUB} ${GITHUB_LOGIN_SCRUB} @@ -490,6 +492,9 @@ const scriptHash = (script: string) => { // A minted Maple key also expires on its own, in case a revoke never reaches Maple. const MAPLE_KEY_SECONDS = 30 * 24 * 60 * 60; +const SUB_SANDBOX_HELPER_WARNING = + "T3 Code's sub-sandbox helper could not be added, so agents on this sandbox cannot ask this computer for a sandbox of their own."; + const SANDBOX_FILES_SKILL_WARNING = "T3 Code's t3-sandbox-files skill could not be added, so agents on this sandbox may keep files in /tmp, which a stop empties."; // A sandbox's GitHub token is replaced this long before it expires. @@ -613,6 +618,15 @@ export class SandboxProvisioner extends Context.Service< readonly checkWork: ( input: SandboxLifecycleInput, ) => Effect.Effect; + /** + * Runs one of T3 Code's own scripts on a running sandbox through its provider, as the poll for + * its agents' sub-sandbox requests does. Fails when the sandbox is gone or not running. + */ + readonly runScript: (input: { + readonly instanceId: string; + readonly script: SandboxScript; + readonly timeoutSeconds: number; + }) => Effect.Effect; readonly templates: ( input: SandboxTemplatesInput, ) => Effect.Effect; @@ -2992,6 +3006,15 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`, steps += 1; yield* fail(SANDBOX_FILES_SKILL_WARNING); } + // A chat's agents can ask this host for sandboxes of their own; a subagent's sandbox has no + // chat on this host to hold their tasks, so it never gets the helper. Only a failure shows. + if (machine.record().parentThreadId === undefined) { + const helperWritten = yield* machine.run(subSandboxHelperScript(), 60).pipe(Effect.exit); + if (Exit.isFailure(helperWritten)) { + steps += 1; + yield* fail(SUB_SANDBOX_HELPER_WARNING); + } + } return { steps, failed }; }); @@ -3808,6 +3831,20 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`, } satisfies SandboxCheckWorkResult; }); + const runScript: SandboxProvisioner["Service"]["runScript"] = Effect.fn( + "SandboxProvisioner.runScript", + )(function* (input) { + const found = yield* records.get(input.instanceId).pipe(Effect.orDie); + if (Option.isNone(found) || found.value.state !== "running") { + return yield* new SandboxProviderError({ + provider: Option.isNone(found) ? "boat" : found.value.provider, + stage: "start", + detail: "The sandbox is not running.", + }); + } + return yield* runOnRecord(found.value)(input.script, input.timeoutSeconds); + }); + // A sandbox made before keep-alive has no idle window of its own, so its config's applies. const keepAliveSettingsOf = Effect.fn("SandboxProvisioner.keepAliveSettingsOf")(function* ( record: SandboxRecord, @@ -4056,6 +4093,22 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`, Effect.as(null), Effect.orElseSucceed(() => SANDBOX_FILES_SKILL_WARNING), ); + // Every resume rewrites the sub-sandbox helper, so one made before it existed gets it and an + // older copy is replaced, again before T3 starts. Only a chat's sandbox has it. + const helper = + record.threadId === undefined || record.parentThreadId !== undefined + ? null + : yield* onHttp( + driver.execute({ + config, + sandboxId: record.sandboxId, + timeoutSeconds: SANDBOX_RESUME_STEP_SECONDS.subSandboxHelper, + ...subSandboxHelperScript(), + }), + ).pipe( + Effect.as(null), + Effect.orElseSucceed(() => SUB_SANDBOX_HELPER_WARNING), + ); yield* onHttp( driver.execute({ config, @@ -4136,6 +4189,7 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`, rejoined.warning, kept.warning, skill, + helper, github.warning, bridged.warning, ].filter((warning): warning is string => warning !== null); @@ -4682,6 +4736,7 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`, stop, resume, checkWork, + runScript, templates, saveTemplate, deleteTemplate, diff --git a/apps/server/src/sandbox/subSandboxHelper.test.ts b/apps/server/src/sandbox/subSandboxHelper.test.ts new file mode 100644 index 0000000000000..928f45953fa0e --- /dev/null +++ b/apps/server/src/sandbox/subSandboxHelper.test.ts @@ -0,0 +1,342 @@ +// @effect-diagnostics nodeBuiltinImport:off - drives the helper and its scripts as subprocesses in a temp HOME. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; + +import type { SandboxScript } from "./sandboxSetup.ts"; +import { + parseSubSandboxPoll, + SUB_SANDBOX_HELPER_SCRUB, + SUB_SANDBOX_HELPER_SOURCE, + SUB_SANDBOX_POLL_SCRIPT, + subSandboxHelperScript, + subSandboxRespondScript, +} from "./subSandboxHelper.ts"; + +// Everything runs in a throwaway HOME with this machine's sh and node, as it would on a sandbox, +// with a script's secrets in its environment the way drivers pass them. +let home = ""; +const dir = () => NodePath.join(home, ".t3/userdata/sub-sandbox"); +const at = (...parts: Array) => NodePath.join(dir(), ...parts); + +beforeEach(() => { + home = NodeFS.realpathSync(NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sub-sandbox-"))); +}); +afterEach(() => { + NodeFS.rmSync(home, { recursive: true, force: true }); +}); + +const sh = (script: string | SandboxScript) => { + const { command, secrets } = typeof script === "string" ? { command: script } : script; + const result = NodeChildProcess.spawnSync("sh", ["-c", command], { + cwd: home, + env: { PATH: process.env.PATH, HOME: home, ...secrets }, + encoding: "utf8", + }); + return { stdout: result.stdout, stderr: result.stderr, status: result.status }; +}; + +const readJson = (file: string) => JSON.parse(NodeFS.readFileSync(file, "utf8")); +const listed = (folder: string) => + NodeFS.existsSync(at(folder)) ? NodeFS.readdirSync(at(folder)).toSorted() : []; +/** Resolves once `file` exists, on its folder's change events. */ +const appears = (file: string) => + new Promise((resolve) => { + NodeFS.mkdirSync(NodePath.dirname(file), { recursive: true }); + const watcher = NodeFS.watch(NodePath.dirname(file), () => { + if (!NodeFS.existsSync(file)) return; + watcher.close(); + resolve(); + }); + if (NodeFS.existsSync(file)) { + watcher.close(); + resolve(); + } + }); + +interface RpcMessage { + readonly id: number; + readonly result: { + readonly content: ReadonlyArray<{ readonly text: string }>; + readonly isError?: boolean; + readonly tools: ReadonlyArray<{ readonly name: string; readonly description: string }>; + readonly serverInfo: { readonly name: string }; + }; +} + +/** Runs the helper as Claude would, over stdio, and returns a JSON-RPC caller. */ +const startHelper = () => { + NodeFS.mkdirSync(dir(), { recursive: true }); + NodeFS.writeFileSync(at("mcp.mjs"), SUB_SANDBOX_HELPER_SOURCE); + const child = NodeChildProcess.spawn(process.execPath, [at("mcp.mjs")], { + cwd: home, + env: { + PATH: process.env.PATH, + HOME: home, + T3CODE_THREAD_ID: "thread-on-sandbox", + T3_SUB_SANDBOX_POLL_MS: "50", + T3_SUB_SANDBOX_ACK_SECONDS: "4", + T3_SUB_SANDBOX_STALE_ACK_SECONDS: "1", + }, + }); + let buffered = ""; + const waiting = new Map void>(); + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + buffered += chunk; + let newline = buffered.indexOf("\n"); + while (newline >= 0) { + const message = JSON.parse(buffered.slice(0, newline)) as RpcMessage; + buffered = buffered.slice(newline + 1); + waiting.get(message.id)?.(message); + newline = buffered.indexOf("\n"); + } + }); + let next = 0; + const request = (method: string, params?: unknown) => + new Promise((resolve) => { + next += 1; + waiting.set(next, resolve); + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: next, method, params })}\n`); + }); + const call = async (name: string, args: unknown) => { + const message = await request("tools/call", { name, arguments: args }); + return { text: message.result.content[0]!.text, isError: message.result.isError === true }; + }; + return { request, call, stop: () => child.kill() }; +}; + +const TERMINAL = ["completed", "failed", "cancelled"]; + +/** What the host's response write leaves for the helper. */ +const respond = (id: string, status: string, extra: Record = {}) => + sh( + subSandboxRespondScript( + id, + { version: 1, id, status, message: `${status} message`, updatedAt: "now", ...extra }, + TERMINAL.includes(status), + ), + ); + +describe("sub-sandbox helper", () => { + it("lists its two tools with short descriptions", async () => { + const helper = startHelper(); + try { + const initialized = await helper.request("initialize", { protocolVersion: "2025-06-18" }); + expect(initialized.result.serverInfo.name).toBe("t3-sub-sandbox"); + const { result } = await helper.request("tools/list"); + expect(result.tools.map((tool) => tool.name)).toEqual([ + "sandbox_delegate", + "sandbox_task_status", + ]); + for (const tool of result.tools) expect(tool.description.length).toBeLessThan(450); + expect(result.tools[0]!.description).toContain("CPU, RAM and disk"); + } finally { + helper.stop(); + } + }); + + it("writes a request with the caller's thread, then withdraws it and says to work here when the host does not answer", async () => { + const helper = startHelper(); + try { + const answer = await helper.call("sandbox_delegate", { + task: "Run the whole test suite", + size: "large", + requestId: "req-1", + }); + expect(answer.isError).toBe(true); + expect(answer.text).toContain("did not pick up request req-1"); + expect(answer.text).toContain("may be asleep or offline"); + expect(answer.text).toContain("Run this work here, on this sandbox"); + // Withdrawn, so a host that wakes later never starts it; nothing half-written is left. + expect(listed("requests")).toEqual([]); + expect(listed("withdrawn")).toEqual(["req-1.json"]); + expect(readJson(at("withdrawn", "req-1.json"))).toMatchObject({ + version: 1, + id: "req-1", + task: "Run the whole test suite", + size: "large", + threadId: "thread-on-sandbox", + cwd: home, + }); + const status = await helper.call("sandbox_task_status", { id: "req-1" }); + expect(status.text).toContain("status: withdrawn"); + // The same id is not asked again. + const again = await helper.call("sandbox_delegate", { task: "x", requestId: "req-1" }); + expect(again.text).toContain("Ask again with a new requestId"); + } finally { + helper.stop(); + } + }); + + it("answers with the host's response, once per id, and hands back the result", async () => { + const helper = startHelper(); + // A host that polled lately gets the full wait. + sh(SUB_SANDBOX_POLL_SCRIPT); + try { + const written = appears(at("requests", "req-2.json")); + const asked = helper.call("sandbox_delegate", { task: "Build it", requestId: "req-2" }); + await written; + // The host's poll claims it and answers. + expect(parseSubSandboxPoll(sh(SUB_SANDBOX_POLL_SCRIPT).stdout)?.requests).toMatchObject([ + { id: "req-2" }, + ]); + respond("req-2", "queued"); + const answer = await asked; + expect(answer.isError).toBe(false); + expect(answer.text).toContain("Request req-2 is queued"); + expect(answer.text).toContain("status: queued"); + + // Asking again with the same id returns the same request and writes nothing new. + const again = await helper.call("sandbox_delegate", { task: "Build it", requestId: "req-2" }); + expect(again.text).toContain("status: queued"); + expect(listed("requests")).toEqual([]); + expect(listed("claimed")).toEqual(["req-2.json"]); + + // A status call waits for the next change, and the result comes with the last one. + const waited = helper.call("sandbox_task_status", { id: "req-2", waitSeconds: 10 }); + respond("req-2", "completed", { + result: + "All 812 tests passed.\n\n[Sub-sandbox] Its sandbox held no unpushed work and was deleted.", + subSandbox: { label: "app subagent on Boat", sandboxId: "bx_sub", environmentId: "env" }, + }); + const done = await waited; + expect(done.text).toContain("Request req-2 completed."); + expect(done.text).toContain("All 812 tests passed."); + expect(done.text).toContain("was deleted"); + expect(done.text).toContain("app subagent on Boat (bx_sub)"); + expect(done.text).toContain("status: completed"); + expect(listed("done")).toEqual(["req-2.json"]); + } finally { + helper.stop(); + } + }); + + it("refuses a request it cannot pass on", async () => { + const helper = startHelper(); + try { + expect((await helper.call("sandbox_delegate", { task: " " })).isError).toBe(true); + expect((await helper.call("sandbox_delegate", { task: "x", size: "a b" })).isError).toBe( + true, + ); + expect( + (await helper.call("sandbox_delegate", { task: "x", requestId: "../x" })).isError, + ).toBe(true); + expect((await helper.call("sandbox_task_status", { id: "nope" })).text).toContain( + "No request nope", + ); + expect(listed("requests")).toEqual([]); + } finally { + helper.stop(); + } + }); +}); + +describe("subSandboxHelperScript", () => { + it("writes the helper and registers it in Claude's MCP list next to the user's servers", () => { + NodeFS.writeFileSync( + NodePath.join(home, ".claude.json"), + JSON.stringify({ mcpServers: { mine: { command: "mine" } }, theme: "dark" }), + ); + const script = subSandboxHelperScript(); + expect(script.command).not.toContain(Buffer.from(SUB_SANDBOX_HELPER_SOURCE).toString("base64")); + expect(sh(script).status).toBe(0); + // A resume runs it again; nothing doubles. + expect(sh(script).status).toBe(0); + expect(NodeFS.readFileSync(at("mcp.mjs"), "utf8")).toBe(SUB_SANDBOX_HELPER_SOURCE); + const config = readJson(NodePath.join(home, ".claude.json")); + expect(config.theme).toBe("dark"); + expect(config.mcpServers.mine).toEqual({ command: "mine" }); + expect(config.mcpServers["t3-sub-sandbox"]).toMatchObject({ + type: "stdio", + args: [at("mcp.mjs")], + }); + expect(NodePath.isAbsolute(config.mcpServers["t3-sub-sandbox"].command)).toBe(true); + // Named among the servers T3 wrote, so a template save removes the entry. + expect(readJson(NodePath.join(home, ".t3/mcp-servers.json"))).toEqual(["t3-sub-sandbox"]); + for (const folder of ["requests", "claimed", "responses", "withdrawn", "done"]) { + expect(NodeFS.existsSync(at(folder))).toBe(true); + } + }); + + it("fails without Node and writes nothing", () => { + const script = subSandboxHelperScript(); + const result = NodeChildProcess.spawnSync("/bin/sh", ["-c", script.command], { + cwd: home, + env: { PATH: "/usr/bin:/bin", HOME: home, ...script.secrets }, + encoding: "utf8", + }); + // Only meaningful where this machine's Node is not in the system folders. + if ( + NodeChildProcess.spawnSync("/bin/sh", ["-c", "PATH=/usr/bin:/bin command -v node"]).status === + 0 + ) + return; + expect(result.status).toBe(3); + expect(NodeFS.existsSync(at("mcp.mjs"))).toBe(false); + }); +}); + +describe("sub-sandbox poll", () => { + const request = (id: string) => + NodeFS.writeFileSync( + at("requests", `${id}.json`), + JSON.stringify({ version: 1, id, task: id }), + ); + + it("says when the helper is not there", () => { + expect(parseSubSandboxPoll(sh(SUB_SANDBOX_POLL_SCRIPT).stdout)).toEqual({ + installed: false, + requests: [], + open: [], + }); + }); + + it("claims new requests once, then lists them as open until the last response", () => { + expect(sh(subSandboxHelperScript()).status).toBe(0); + request("a"); + request("b"); + const first = parseSubSandboxPoll(sh(SUB_SANDBOX_POLL_SCRIPT).stdout)!; + expect(first.requests.map((entry) => entry.id)).toEqual(["a", "b"]); + expect(JSON.parse(first.requests[0]!.json)).toMatchObject({ id: "a", task: "a" }); + expect(listed("requests")).toEqual([]); + expect(listed("claimed")).toEqual(["a.json", "b.json"]); + expect(Number(NodeFS.readFileSync(at("host-seen"), "utf8"))).toBeGreaterThan(0); + + respond("a", "running", { taskId: "task-a" }); + const second = parseSubSandboxPoll(sh(SUB_SANDBOX_POLL_SCRIPT).stdout)!; + expect(second.requests.map((entry) => entry.id)).toEqual(["b"]); + expect(second.open.map((entry) => entry.id)).toEqual(["a"]); + expect(JSON.parse(second.open[0]!.json)).toMatchObject({ status: "running", taskId: "task-a" }); + + respond("a", "completed", { result: "done" }); + respond("b", "failed", { code: "concurrency_full" }); + expect(parseSubSandboxPoll(sh(SUB_SANDBOX_POLL_SCRIPT).stdout)).toEqual({ + installed: true, + requests: [], + open: [], + }); + expect(listed("done")).toEqual(["a.json", "b.json"]); + expect(readJson(at("responses", "b.json"))).toMatchObject({ code: "concurrency_full" }); + // Written by rename, so no temp file is ever left for the helper to read. + expect(listed("responses")).toEqual(["a.json", "b.json"]); + }); + + it("reads a cut-off poll as nothing", () => { + expect(parseSubSandboxPoll("T3_SUB_REQUEST a e30=\n")).toBeNull(); + }); + + it("refuses a response id it would put in a path", () => { + expect(() => subSandboxRespondScript("../x", {}, false)).toThrow(); + }); + + it("goes with a template save, pending requests included", () => { + expect(sh(subSandboxHelperScript()).status).toBe(0); + request("pending"); + expect(sh(SUB_SANDBOX_HELPER_SCRUB).status).toBe(0); + expect(NodeFS.existsSync(dir())).toBe(false); + }); +}); diff --git a/apps/server/src/sandbox/subSandboxHelper.ts b/apps/server/src/sandbox/subSandboxHelper.ts new file mode 100644 index 0000000000000..a32e7640022e5 --- /dev/null +++ b/apps/server/src/sandbox/subSandboxHelper.ts @@ -0,0 +1,419 @@ +// The MCP helper T3 Code installs on a chat's sandbox, which runs the official T3 Code: requests +// and answers are files under ~/.t3/userdata/sub-sandbox that the host reads and writes with the +// provider's exec. Each side writes by rename, and the poll claims a request by moving it, so a +// withdrawn one never starts. The layout is in docs/internals/sandbox-environments.md. + +import { shellQuote } from "./SandboxProvider.ts"; +import type { SandboxScript } from "./sandboxSetup.ts"; + +const SUB_SANDBOX_DIR = "$HOME/.t3/userdata/sub-sandbox"; + +/** The helper's name in Claude's MCP list, so its tools are `mcp__t3-sub-sandbox__…`. */ +const SUB_SANDBOX_MCP_NAME = "t3-sub-sandbox"; + +/** A request id: what the helper makes, and all the host accepts before using one in a path. */ +export const SUB_SANDBOX_REQUEST_ID = /^[A-Za-z0-9_-]{1,64}$/u; + +const base64 = (value: string) => Buffer.from(value, "utf8").toString("base64"); + +/** + * The helper itself: Node built-ins only, no install step. Written without template literals so + * it can live in this one. + */ +export const SUB_SANDBOX_HELPER_SOURCE = String.raw`// T3 Code sub-sandbox helper. Installed and kept up to date by T3 Code on the user's computer. +import { execFile } from "node:child_process"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const number = (value, fallback) => { + const parsed = Number(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; +}; +const dir = process.env.T3_SUB_SANDBOX_DIR || path.join(os.homedir(), ".t3", "userdata", "sub-sandbox"); +const ACK_SECONDS = number(process.env.T3_SUB_SANDBOX_ACK_SECONDS, 45); +// A host that has not polled for a while is most likely asleep; it gets a shorter wait. +const STALE_ACK_SECONDS = number(process.env.T3_SUB_SANDBOX_STALE_ACK_SECONDS, 20); +const HOST_STALE_SECONDS = 180; +const POLL_MS = number(process.env.T3_SUB_SANDBOX_POLL_MS, 1000); +// Every call stays well under the minute some MCP clients give a tool. +const MAX_WAIT_SECONDS = 30; +const LATE_SECONDS = 10; +const MAX_TASK_LENGTH = 60000; +const ID = /^[A-Za-z0-9_-]{1,64}$/; +const SIZE = /^[A-Za-z0-9._-]{1,64}$/; +const TERMINAL = new Set(["completed", "failed", "cancelled"]); +const folder = (name) => path.join(dir, name); +const fileOf = (name, id) => path.join(folder(name), id + ".json"); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +const writeAtomic = (file, value) => { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const temp = path.join(path.dirname(file), "." + path.basename(file) + "." + process.pid + ".tmp"); + fs.writeFileSync(temp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 }); + fs.renameSync(temp, file); +}; +const readJson = (file) => { + try { + return JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + return null; + } +}; +const exists = (file) => fs.existsSync(file); +const where = (id) => { + if (exists(fileOf("responses", id))) return "responded"; + if (exists(fileOf("withdrawn", id))) return "withdrawn"; + if (exists(fileOf("claimed", id)) || exists(fileOf("done", id))) return "claimed"; + if (exists(fileOf("requests", id))) return "requested"; + return null; +}; +const hostSeenSecondsAgo = () => { + let seen = NaN; + try { + seen = Number(fs.readFileSync(path.join(dir, "host-seen"), "utf8").trim()); + } catch {} + return Number.isFinite(seen) && seen > 0 ? Math.max(0, Math.round(Date.now() / 1000 - seen)) : null; +}; +const run = (command, args, options) => + new Promise((resolve) => { + const env = { ...process.env, PATH: path.join(os.homedir(), ".local", "bin") + ":" + (process.env.PATH || "") }; + execFile(command, args, { timeout: 15000, maxBuffer: 4 * 1024 * 1024, env, ...options }, (error, stdout) => + resolve(error ? null : String(stdout)), + ); + }); + +// What the host needs to start the subagent like the caller: its thread, model and pushed branch. +const callerContext = async () => { + const threadId = process.env.T3CODE_THREAD_ID || undefined; + const cwd = process.cwd(); + const upstream = ((await run("git", ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], { cwd })) || "").trim(); + let model; + if (threadId) { + const shown = await run("t3", ["thread", "show", threadId, "--json", "--messages", "0"], { cwd }); + try { + const thread = JSON.parse(shown || "null")?.thread; + if (typeof thread?.providerInstanceId === "string" && typeof thread?.model === "string") { + model = { instanceId: thread.providerInstanceId, model: thread.model }; + } + } catch {} + } + return { + ...(threadId ? { threadId } : {}), + cwd, + ...(upstream && !upstream.includes(" ") ? { upstream } : {}), + ...(model ? { model } : {}), + }; +}; + +const STATUS_WORDS = { + queued: "is queued on the user's computer", + starting_sandbox: "is starting a new sandbox, which takes a few minutes", + running: "is running on its sandbox", + completed: "completed", + failed: "failed", + cancelled: "was cancelled", +}; +const describe = (id, response) => { + const lines = ["Request " + id + " " + (STATUS_WORDS[response.status] || response.status) + "."]; + if (response.message) lines.push(response.message); + if (response.subSandbox?.label) lines.push("Sandbox: " + response.subSandbox.label + (response.subSandbox.sandboxId ? " (" + response.subSandbox.sandboxId + ")" : "") + "."); + if (typeof response.result === "string" && response.result.trim() !== "") lines.push("", "Result:", response.result); + if (!TERMINAL.has(response.status)) lines.push("", "Check again with sandbox_task_status (waitSeconds up to 30)."); + lines.push("", "status: " + response.status); + return lines.join("\n"); +}; +const text = (value, isError = false) => ({ content: [{ type: "text", text: value }], ...(isError ? { isError: true } : {}) }); +const notAnswering = (id, seconds) => + text( + "Not started: T3 Code on the user's computer did not pick up request " + id + " within " + seconds + + " seconds. That computer holds the sandbox configs and keys, so it must be awake and running T3 Code, and it may be asleep or offline. Nothing was started and the request was withdrawn. Run this work here, on this sandbox, instead.", + true, + ); + +const waitFor = async (seconds, done) => { + const deadline = Date.now() + seconds * 1000; + while (Date.now() < deadline) { + const value = done(); + if (value) return value; + await sleep(POLL_MS); + } + return done(); +}; + +const delegate = async (args) => { + const task = typeof args?.task === "string" ? args.task.trim() : ""; + if (task === "") return text("Pass task: the full brief for the subagent.", true); + if (task.length > MAX_TASK_LENGTH) return text("task is too long (at most " + MAX_TASK_LENGTH + " characters).", true); + const size = typeof args?.size === "string" && args.size.trim() !== "" ? args.size.trim() : undefined; + if (size !== undefined && !SIZE.test(size)) return text("size is a machine size id such as large.", true); + const asked = typeof args?.requestId === "string" && args.requestId.trim() !== "" ? args.requestId.trim() : undefined; + if (asked !== undefined && !ID.test(asked)) return text("requestId takes letters, digits, - and _ (at most 64).", true); + const id = asked || "sr_" + crypto.randomBytes(8).toString("hex"); + const found = where(id); + if (found === "responded") return text(describe(id, readJson(fileOf("responses", id)) || { status: "queued" })); + if (found === "withdrawn") return text("Request " + id + " was withdrawn because the user's computer did not answer. Ask again with a new requestId.", true); + if (found === null) { + writeAtomic(fileOf("requests", id), { + version: 1, + id, + task, + ...(size ? { size } : {}), + ...(await callerContext()), + createdAt: new Date().toISOString(), + }); + } + const seen = hostSeenSecondsAgo(); + const seconds = seen !== null && seen <= HOST_STALE_SECONDS ? ACK_SECONDS : STALE_ACK_SECONDS; + const answered = await waitFor(seconds, () => readJson(fileOf("responses", id))); + if (answered) return text(describe(id, answered)); + try { + fs.mkdirSync(folder("withdrawn"), { recursive: true, mode: 0o700 }); + fs.renameSync(fileOf("requests", id), fileOf("withdrawn", id)); + return notAnswering(id, seconds); + } catch {} + // The host took it just now. + const late = await waitFor(LATE_SECONDS, () => readJson(fileOf("responses", id))); + return late + ? text(describe(id, late)) + : text("Request " + id + " was picked up by the user's computer. Check it with sandbox_task_status.\n\nstatus: queued"); +}; + +const status = async (args) => { + const id = typeof args?.id === "string" ? args.id.trim() : ""; + if (!ID.test(id)) return text("Pass id: the request id sandbox_delegate returned.", true); + const wait = Math.min(MAX_WAIT_SECONDS, Math.max(0, Number(args?.waitSeconds) || 0)); + const first = exists(fileOf("responses", id)) ? fs.readFileSync(fileOf("responses", id), "utf8") : null; + const firstStatus = first === null ? null : readJson(fileOf("responses", id))?.status; + if (wait > 0 && !TERMINAL.has(firstStatus)) { + await waitFor(wait, () => { + try { + return fs.readFileSync(fileOf("responses", id), "utf8") !== first; + } catch { + return where(id) === "withdrawn"; + } + }); + } + const response = readJson(fileOf("responses", id)); + if (response) return text(describe(id, response)); + const found = where(id); + if (found === null) return text("No request " + id + " on this sandbox.", true); + if (found === "withdrawn") return text("Request " + id + " was withdrawn: the user's computer did not pick it up, and nothing was started.\n\nstatus: withdrawn"); + const seen = hostSeenSecondsAgo(); + return text( + "Request " + id + " is waiting for the user's computer" + (found === "claimed" ? ", which picked it up." : " to pick it up") + + (seen === null ? "" : " (last heard from " + seen + " s ago)") + ".\n\nstatus: waiting", + ); +}; + +const TOOLS = [ + { + name: "sandbox_delegate", + description: + "Run a task as a subagent on a new sandbox with its own CPU, RAM and disk. Use it when this sandbox is too small: heavy or parallel builds, large test runs, more memory or disk. The subagent starts from a fresh clone at your pushed branch, so push first. Needs the user's computer awake; if it does not answer, do the work here. Returns a request id for sandbox_task_status.", + inputSchema: { + type: "object", + properties: { + task: { type: "string", description: "Full brief for the subagent: what to do and what to report back." }, + size: { type: "string", description: "Machine size id, at most one step above this sandbox's. Omit for the same size." }, + requestId: { type: "string", description: "Your own id; asking again with it never starts a second sandbox." }, + }, + required: ["task"], + additionalProperties: false, + }, + }, + { + name: "sandbox_task_status", + description: "Status of a sandbox_delegate request, and its result once it ends. waitSeconds (max 30) waits for a change.", + inputSchema: { + type: "object", + properties: { id: { type: "string" }, waitSeconds: { type: "number" } }, + required: ["id"], + additionalProperties: false, + }, + }, +]; + +const send = (message) => process.stdout.write(JSON.stringify(message) + "\n"); +const handle = async (message) => { + const { id, method, params } = message; + if (id === undefined || id === null) return; + if (method === "initialize") { + return send({ + jsonrpc: "2.0", + id, + result: { + protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18", + capabilities: { tools: {} }, + serverInfo: { name: "t3-sub-sandbox", version: "1" }, + }, + }); + } + if (method === "ping") return send({ jsonrpc: "2.0", id, result: {} }); + if (method === "tools/list") return send({ jsonrpc: "2.0", id, result: { tools: TOOLS } }); + if (method === "tools/call") { + const name = params?.name; + const call = name === "sandbox_delegate" ? delegate : name === "sandbox_task_status" ? status : null; + if (call === null) return send({ jsonrpc: "2.0", id, error: { code: -32602, message: "Unknown tool " + name } }); + try { + return send({ jsonrpc: "2.0", id, result: await call(params?.arguments ?? {}) }); + } catch (error) { + return send({ jsonrpc: "2.0", id, result: text("The helper failed: " + (error?.message || error), true) }); + } + } + return send({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found" } }); +}; + +let buffered = ""; +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (chunk) => { + buffered += chunk; + let newline; + while ((newline = buffered.indexOf("\n")) >= 0) { + const line = buffered.slice(0, newline).trim(); + buffered = buffered.slice(newline + 1); + if (line === "") continue; + let message; + try { + message = JSON.parse(line); + } catch { + send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); + continue; + } + void handle(message); + } +}); +process.stdin.on("end", () => process.exit(0)); +`; + +/** + * Writes the helper and registers it in Claude's user-scope MCP list with the Node that ran the + * install, so a resume refreshes both. The name is added to the list of servers T3 wrote, so a + * template save removes the entry. Exits 3 without Node, which the MCP entry would need too. + */ +export const subSandboxHelperScript = (): SandboxScript => ({ + // Kept out of the command text only for its size. + secrets: { T3_SUB_SANDBOX_HELPER: base64(SUB_SANDBOX_HELPER_SOURCE) }, + command: `set -eu +umask 077 +export PATH="$HOME/.local/bin:$PATH" +if ! command -v node >/dev/null 2>&1; then + unset T3_SUB_SANDBOX_HELPER + echo "Node is not installed." >&2 + exit 3 +fi +dir="${SUB_SANDBOX_DIR}" +mkdir -p "$dir/requests" "$dir/claimed" "$dir/responses" "$dir/withdrawn" "$dir/done" +printf '%s' "$T3_SUB_SANDBOX_HELPER" | base64 -d >"$dir/mcp.mjs.tmp" +unset T3_SUB_SANDBOX_HELPER +mv "$dir/mcp.mjs.tmp" "$dir/mcp.mjs" +node -e ' +const fs = require("node:fs"); +const [file, written, helper, name] = process.argv.slice(1); +let config = {}; +try { + config = JSON.parse(fs.readFileSync(file, "utf8")); +} catch (error) { + if (error.code !== "ENOENT") throw new Error(".claude.json is not valid JSON"); +} +if (config === null || typeof config !== "object" || Array.isArray(config)) { + throw new Error(".claude.json is not an object"); +} +const current = config.mcpServers !== null && typeof config.mcpServers === "object" ? config.mcpServers : {}; +config.mcpServers = { ...current, [name]: { type: "stdio", command: process.execPath, args: [helper] } }; +fs.writeFileSync(file + ".t3-tmp", JSON.stringify(config, null, 2) + "\\n", { mode: 0o600 }); +fs.renameSync(file + ".t3-tmp", file); +let names = []; +try { names = JSON.parse(fs.readFileSync(written, "utf8")); } catch {} +fs.writeFileSync(written, JSON.stringify([...new Set([...names, name])]) + "\\n", { mode: 0o600 }); +' "\${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json" "$HOME/.t3/mcp-servers.json" "$dir/mcp.mjs" ${SUB_SANDBOX_MCP_NAME}`, +}); + +const POLL_PREFIX = "T3_SUB_"; + +/** + * The host's poll: says it was here, claims every new request by moving it to `claimed/`, and + * prints each claimed request without a response (new) or with one (open, for after a restart). + * Prints `T3_SUB_NONE` when the helper is not installed. + */ +export const SUB_SANDBOX_POLL_SCRIPT = `dir="${SUB_SANDBOX_DIR}" +if [ ! -f "$dir/mcp.mjs" ]; then + echo ${POLL_PREFIX}NONE + exit 0 +fi +date +%s >"$dir/.host-seen.tmp" && mv "$dir/.host-seen.tmp" "$dir/host-seen" +mkdir -p "$dir/claimed" +for f in "$dir"/requests/*.json; do + [ -f "$f" ] || continue + mv "$f" "$dir/claimed/" 2>/dev/null || true +done +for f in "$dir"/claimed/*.json; do + [ -f "$f" ] || continue + id="$(basename "$f" .json)" + if [ -f "$dir/responses/$id.json" ]; then + printf '${POLL_PREFIX}OPEN %s %s\\n' "$id" "$(base64 <"$dir/responses/$id.json" | tr -d '\\n')" + else + printf '${POLL_PREFIX}REQUEST %s %s\\n' "$id" "$(base64 <"$f" | tr -d '\\n')" + fi +done +echo ${POLL_PREFIX}END +exit 0`; + +export interface SubSandboxPoll { + /** False when the sandbox has no helper, as one made before it existed. */ + readonly installed: boolean; + /** Claimed requests with no response yet, as their JSON text. */ + readonly requests: ReadonlyArray<{ readonly id: string; readonly json: string }>; + /** Claimed requests that have a response, as that response's JSON text. */ + readonly open: ReadonlyArray<{ readonly id: string; readonly json: string }>; +} + +/** What the poll printed, or null when it did not finish (cut-off output reads as nothing). */ +export const parseSubSandboxPoll = (stdout: string): SubSandboxPoll | null => { + const lines = stdout.split("\n").map((line) => line.trim()); + if (lines.includes(`${POLL_PREFIX}NONE`)) return { installed: false, requests: [], open: [] }; + if (!lines.includes(`${POLL_PREFIX}END`)) return null; + const requests: Array<{ id: string; json: string }> = []; + const open: Array<{ id: string; json: string }> = []; + for (const line of lines) { + const match = /^T3_SUB_(REQUEST|OPEN) (\S+) ([A-Za-z0-9+/=]*)$/u.exec(line); + if (match === null || !SUB_SANDBOX_REQUEST_ID.test(match[2]!)) continue; + const entry = { id: match[2]!, json: Buffer.from(match[3]!, "base64").toString("utf8") }; + (match[1] === "REQUEST" ? requests : open).push(entry); + } + return { installed: true, requests, open }; +}; + +/** + * Writes one response for the helper to read, atomically; the last one also moves the request to + * `done/`, so later polls skip it. The response rides in `secrets` only for its size. + */ +export const subSandboxRespondScript = ( + id: string, + response: unknown, + final: boolean, +): SandboxScript => { + if (!SUB_SANDBOX_REQUEST_ID.test(id)) throw new Error(`Invalid sub-sandbox request id: ${id}`); + const quoted = shellQuote(id); + return { + secrets: { T3_SUB_RESPONSE: base64(`${JSON.stringify(response, null, 2)}\n`) }, + command: `set -eu +umask 077 +dir="${SUB_SANDBOX_DIR}" +mkdir -p "$dir/responses" +printf '%s' "$T3_SUB_RESPONSE" | base64 -d >"$dir/responses/.${id}.json.tmp" +unset T3_SUB_RESPONSE +mv "$dir/responses/.${id}.json.tmp" "$dir/responses/"${quoted}.json${ + final + ? ` +mkdir -p "$dir/done" +if [ -f "$dir/claimed/"${quoted}.json ]; then mv "$dir/claimed/"${quoted}.json "$dir/done/"; fi` + : "" + }`, + }; +}; + +// Run before a template save, before T3's userdata is removed: a copy must not inherit the helper's +// queue or a pending request. Its MCP entry goes with the other servers T3 wrote. +export const SUB_SANDBOX_HELPER_SCRUB = `rm -rf "${SUB_SANDBOX_DIR}"`; diff --git a/packages/contracts/src/sandbox.test.ts b/packages/contracts/src/sandbox.test.ts index 00c55e5024d10..153b58ea19234 100644 --- a/packages/contracts/src/sandbox.test.ts +++ b/packages/contracts/src/sandbox.test.ts @@ -198,7 +198,7 @@ describe("isSandboxHostProjectRoot", () => { describe("SANDBOX_RESUME_WAIT_SECONDS", () => { it("outlasts every resume step at its limit, the T3 start the slowest Boat resume adds", () => { - expect(SANDBOX_RESUME_WAIT_SECONDS).toBe(15 * 60 + 30); + expect(SANDBOX_RESUME_WAIT_SECONDS).toBe(16 * 60); const steps = Object.values(SANDBOX_RESUME_STEP_SECONDS); expect(SANDBOX_RESUME_WAIT_SECONDS).toBeGreaterThan( steps.reduce((sum: number, step) => sum + step, 0), diff --git a/packages/contracts/src/sandbox.ts b/packages/contracts/src/sandbox.ts index 9975c544dbccd..fbea98d57965e 100644 --- a/packages/contracts/src/sandbox.ts +++ b/packages/contracts/src/sandbox.ts @@ -261,6 +261,7 @@ export const SANDBOX_RESUME_STEP_SECONDS = { tailnetRejoin: 420, t3Start: 180, agentSkill: 30, + subSandboxHelper: 30, } as const; /** From fdde953a30d20ff79b1c642f64ea31dffe51b4dd Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Wed, 11 Nov 2026 15:26:08 +0000 Subject: [PATCH 3/4] feat: start sub-sandboxes that agents on a sandbox ask for The host polls each running chat sandbox for helper requests with one provider exec: every 15 s while the chat runs a turn here or has a request open, every 60 s otherwise, and once per running stretch where the helper is missing. Each request starts through SubSandboxes and RemoteDelegation on behalf of the chat's thread here, so the same config, limits, sizes and end-of-task checkWork apply, and every status, refusal and result is written back. Nothing starts before the first answer lands, and a restart recovers open requests from their responses without starting any twice. Co-Authored-By: Claude Opus 5.5 --- .../src/sandbox/SubSandboxRequests.test.ts | 552 +++++++++++++++++ apps/server/src/sandbox/SubSandboxRequests.ts | 575 ++++++++++++++++++ apps/server/src/server.ts | 7 + packages/sandbox-bridge/src/bridge.ts | 3 +- 4 files changed, 1136 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/sandbox/SubSandboxRequests.test.ts create mode 100644 apps/server/src/sandbox/SubSandboxRequests.ts diff --git a/apps/server/src/sandbox/SubSandboxRequests.test.ts b/apps/server/src/sandbox/SubSandboxRequests.test.ts new file mode 100644 index 0000000000000..70bceb85538a4 --- /dev/null +++ b/apps/server/src/sandbox/SubSandboxRequests.test.ts @@ -0,0 +1,552 @@ +// @effect-diagnostics nodeBuiltinImport:off - the sandbox is a temp HOME the real scripts run in with sh. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { assert, describe, it } from "@effect/vitest"; +import { + EnvironmentId, + NodeId, + ProjectId, + ProviderInstanceId, + RunId, + type SandboxEnvironmentConfig, + SandboxProviderError, + type SandboxRecord, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { TestClock } from "effect/testing"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as SandboxProvisioner from "./SandboxProvisioner.ts"; +import * as SubSandboxes from "./SubSandboxes.ts"; +import * as SubSandboxRequests from "./SubSandboxRequests.ts"; + +// The sandbox's side is a throwaway HOME the real poll and response scripts run in with sh, as a +// provider's exec would; everything on this host past the scripts is a fake. + +const chatThreadId = ThreadId.make("thread:sandbox-chat"); +const hostProjectId = ProjectId.make("project:host-placeholder"); +const subEnvironmentId = EnvironmentId.make("environment:sub"); +const subProjectId = ProjectId.make("project:on-sub"); +const bridgeInstance = ProviderInstanceId.make("sandboxes"); +const taskId = NodeId.make("node:sub-task"); + +const SHELL_PATH = process.env.PATH; + +const config: SandboxEnvironmentConfig = { + id: "config-boat", + label: "Boat", + provider: "boat", + size: "small", + passGithubToken: false, + joinTailnet: false, + access: "public", + envFiles: {}, + idleMinutes: 30, + maxRunningMinutes: 480, + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:00:00.000Z", +}; + +const chatRecord = (overrides: Partial = {}): SandboxRecord => ({ + instanceId: "chat", + environmentId: EnvironmentId.make("environment:chat"), + configId: config.id, + threadId: chatThreadId, + provider: "boat", + sandboxId: "bx_chat", + label: "app on Boat", + size: "small", + state: "running", + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:00:00.000Z", + httpBaseUrl: "https://bx-chat.example", + runningSince: "2026-11-01T00:00:00.000Z", + maxRunningMinutes: 480, + repoDir: "/home/boat/work/app", + repository: "acme/app", + hostProjectId, + ...overrides, +}); + +const subRecord = (instanceId: string): SandboxRecord => { + const { threadId: _threadId, hostProjectId: _project, ...rest } = chatRecord(); + return { + ...rest, + instanceId, + parentThreadId: chatThreadId, + environmentId: subEnvironmentId, + sandboxId: `bx_${instanceId}`, + label: "app subagent on Boat", + sandboxProjectId: subProjectId, + }; +}; + +interface Fakes { + readonly home: string; + records: Array; + configs: Array; + linkedEnvironments: boolean; + /** The chat's runs on this host: one running turn the bridge relays, unless emptied. */ + runs: Array; + /** The delegated task on the chat's thread here, once recorded. */ + task: { status: string; result: string | null } | null; + /** Response writes that fail before one goes through, as on a sandbox that stopped. */ + failWrites: number; + readonly scripts: Array; + readonly created: Array< + Parameters[0] + >; + readonly delegated: Array<{ + readonly scope: Parameters[0]; + readonly input: Parameters[1]; + }>; +} + +const makeFakes = (overrides: Partial = {}): Fakes => ({ + home: NodeFS.realpathSync(NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sub-requests-"))), + records: [chatRecord()], + configs: [config], + linkedEnvironments: true, + runs: [ + { + id: RunId.make("run:chat"), + status: "running", + rootNodeId: NodeId.make("node:chat"), + providerInstanceId: bridgeInstance, + ordinal: 3, + }, + ], + task: null, + failWrites: 0, + scripts: [], + created: [], + delegated: [], + ...overrides, +}); + +const queue = (fakes: Fakes, ...parts: Array) => + NodePath.join(fakes.home, ".t3/userdata/sub-sandbox", ...parts); + +/** What the helper leaves on the sandbox: itself, and a request. */ +const installHelper = (fakes: Fakes) => { + for (const folder of ["requests", "claimed", "responses", "withdrawn", "done"]) { + NodeFS.mkdirSync(queue(fakes, folder), { recursive: true }); + } + NodeFS.writeFileSync(queue(fakes, "mcp.mjs"), "// helper"); +}; +const ask = (fakes: Fakes, id: string, extra: Record = {}) => + NodeFS.writeFileSync( + queue(fakes, "requests", `${id}.json`), + JSON.stringify({ + version: 1, + id, + task: "Run the full build and its tests", + threadId: "thread:on-sandbox", + cwd: "/home/boat/work/app", + upstream: "origin/feature/fast", + model: { instanceId: "claudeAgent", model: "claude-sonnet-5-5" }, + ...extra, + }), + ); +const responseOf = (fakes: Fakes, id: string) => { + const file = queue(fakes, "responses", `${id}.json`); + return NodeFS.existsSync(file) ? JSON.parse(NodeFS.readFileSync(file, "utf8")) : undefined; +}; +const polls = (fakes: Fakes) => + fakes.scripts.filter((script) => script.includes("T3_SUB_END")).length; + +const layerFor = (fakes: Fakes) => + SubSandboxRequests.layer.pipe( + Layer.provideMerge(SubSandboxes.layer), + Layer.provide( + Layer.mergeAll( + NodeCrypto.layer, + Layer.mock(SandboxProvisioner.SandboxProvisioner)({ + list: Effect.sync(() => ({ sandboxes: [...fakes.records], orphans: [] })), + configs: Effect.sync(() => ({ configs: [...fakes.configs] })), + providers: Effect.succeed({ + providers: [ + { + kind: "boat", + sizes: [ + { id: "small", label: "Small", detail: "" }, + { id: "default", label: "Default", detail: "" }, + { id: "large", label: "Large", detail: "" }, + ], + }, + ], + } as never), + createSubSandbox: (input) => + Effect.sync(() => { + fakes.created.push(input); + fakes.records.push(subRecord(input.instanceId)); + return { + instanceId: input.instanceId, + provider: "boat" as const, + sandboxId: `bx_${input.instanceId}`, + environmentId: subEnvironmentId, + label: "app subagent on Boat", + httpBaseUrl: "https://bx-sub.example", + pairingCode: "PAIR-CODE", + setup: { claude: "ready", github: "ready", tailscale: "skipped", warnings: [] }, + }; + }), + delete: ({ instanceId }) => + Effect.sync(() => { + fakes.records = fakes.records.filter((record) => record.instanceId !== instanceId); + return { warnings: [] }; + }), + runScript: ({ script }) => + Effect.suspend(() => { + fakes.scripts.push(script.command); + if (script.command.includes("T3_SUB_RESPONSE") && fakes.failWrites > 0) { + fakes.failWrites -= 1; + return Effect.fail( + new SandboxProviderError({ provider: "boat", stage: "start", detail: "down" }), + ); + } + const ran = NodeChildProcess.spawnSync("sh", ["-c", script.command], { + env: { PATH: SHELL_PATH, HOME: fakes.home, ...script.secrets }, + encoding: "utf8", + }); + return Effect.succeed({ + exitCode: ran.status ?? 1, + stdout: ran.stdout, + stderr: ran.stderr, + }); + }), + }), + Layer.mock(PeerLinks.PeerLinks)({ + enabled: Effect.sync(() => fakes.linkedEnvironments), + link: () => Effect.succeed({} as never), + unlink: () => Effect.succeed(true), + }), + Layer.mock(ProjectService.ProjectService)({ + // The chat's host project is the placeholder folder a sandbox chat gets, no checkout. + getById: () => + Effect.succeedSome({ + id: hostProjectId, + title: "app", + workspaceRoot: "/home/me/.t3/sandbox-projects/acme/app", + } as never), + }), + // A parent on a sandbox has no checkout here to read. + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ + resolve: () => Effect.die("read a checkout on the host"), + }), + Layer.mock(GitVcsDriver.GitVcsDriver)({ + statusDetailsLocal: () => Effect.die("read a checkout on the host"), + }), + Layer.mock(RemoteDelegation.RemoteDelegation)({ + delegate: (scope, input) => + Effect.sync(() => { + fakes.delegated.push({ scope, input }); + fakes.task = { status: "running", result: null }; + return { taskId }; + }), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (_threadId, fields) => + Effect.sync( + () => + ({ + thread: { id: chatThreadId, projectId: hostProjectId, title: "app" }, + runs: fakes.runs, + subagents: + (fields as ReadonlyArray).includes("subagents") && fakes.task !== null + ? [{ id: taskId, ...fakes.task }] + : [], + }) as never, + ), + }), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("environment:host")), + }), + ), + ), + ); + +/** Lets the request a tick forked finish; every fake answers at once. */ +const settle = Effect.gen(function* () { + for (let index = 0; index < 200; index += 1) yield* Effect.yieldNow; +}); + +const tick = SubSandboxRequests.SubSandboxRequests.pipe( + Effect.flatMap((requests) => requests.tick), + Effect.andThen(settle), +); + +const cleanUp = (fakes: Fakes) => + Effect.sync(() => NodeFS.rmSync(fakes.home, { recursive: true, force: true })); + +describe("SubSandboxRequests", () => { + it.effect( + "starts a request's task on a new sandbox for the sandbox's chat, once, and writes each status back", + () => { + const fakes = makeFakes(); + installHelper(fakes); + ask(fakes, "req-1", { size: "default" }); + return Effect.gen(function* () { + yield* tick; + // The same config, limits and size rules as delegate_task's target.sandbox. + assert.equal(fakes.created.length, 1); + const created = fakes.created[0]!; + assert.equal(created.config.id, config.id); + assert.equal(created.parentThreadId, chatThreadId); + assert.equal(created.size, "default"); + // The sandbox's clone, at its pushed branch; no env files from a placeholder folder. + assert.deepEqual(created.project, { + id: hostProjectId, + title: "app", + remoteUrl: "https://github.com/acme/app.git", + baseRef: "feature/fast", + }); + // Recorded on the chat's thread here, on its running turn, with the model it runs. + assert.equal(fakes.delegated.length, 1); + const { scope, input } = fakes.delegated[0]!; + assert.equal(scope.thread.threadId, chatThreadId); + assert.equal(scope.thread.providerInstanceId, bridgeInstance); + assert.equal(input.task, "Run the full build and its tests"); + assert.equal(input.mode, "wait"); + assert.equal(input.clientRequestId, "sub-sandbox-request:req-1"); + assert.deepEqual(input.target, { + environmentId: subEnvironmentId, + projectId: subProjectId, + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-5-5", + }); + assert.deepInclude(responseOf(fakes, "req-1"), { + status: "running", + taskId, + subSandbox: { + label: "app subagent on Boat", + sandboxId: `bx_${fakes.created[0]!.instanceId}`, + environmentId: subEnvironmentId, + }, + }); + + // Later polls never start it again. + yield* TestClock.adjust("15 seconds"); + yield* tick; + yield* TestClock.adjust("15 seconds"); + yield* tick; + assert.equal(fakes.created.length, 1); + assert.equal(fakes.delegated.length, 1); + assert.equal(responseOf(fakes, "req-1").status, "running"); + + // Its result, with where the sub-sandbox's work went, goes back with the last status. + fakes.task = { + status: "completed", + result: + "Build green.\n\n[Sub-sandbox] Its sandbox held no unpushed work and was deleted.", + }; + yield* tick; + assert.deepInclude(responseOf(fakes, "req-1"), { + status: "completed", + result: + "Build green.\n\n[Sub-sandbox] Its sandbox held no unpushed work and was deleted.", + }); + assert.isTrue(NodeFS.existsSync(queue(fakes, "done", "req-1.json"))); + assert.isFalse(NodeFS.existsSync(queue(fakes, "claimed", "req-1.json"))); + }).pipe(Effect.provide(layerFor(fakes)), Effect.ensuring(cleanUp(fakes))); + }, + ); + + it.effect("starts nothing until the sandbox has its first answer", () => { + const fakes = makeFakes({ failWrites: 1 }); + installHelper(fakes); + ask(fakes, "req-1"); + return Effect.gen(function* () { + yield* tick; + assert.equal(fakes.created.length, 0); + assert.isUndefined(responseOf(fakes, "req-1")); + // Still claimed without an answer, so the next poll offers it again. + yield* TestClock.adjust("15 seconds"); + yield* tick; + assert.equal(fakes.created.length, 1); + assert.equal(responseOf(fakes, "req-1").status, "running"); + }).pipe(Effect.provide(layerFor(fakes)), Effect.ensuring(cleanUp(fakes))); + }); + + describe("refusals reach the sandbox", () => { + const refused = (fakes: Fakes, id = "req-1") => + Effect.gen(function* () { + installHelper(fakes); + ask(fakes, id); + yield* tick; + assert.equal(fakes.created.length, 0); + assert.equal(fakes.delegated.length, 0); + const response = responseOf(fakes, id); + assert.equal(response.status, "failed"); + assert.isTrue(NodeFS.existsSync(queue(fakes, "done", `${id}.json`))); + return response as { readonly code: string; readonly message: string }; + }).pipe(Effect.provide(layerFor(fakes)), Effect.ensuring(cleanUp(fakes))); + + it.effect("when the chat already has as many sub-sandboxes as its config allows", () => { + const fakes = makeFakes(); + fakes.records.push(subRecord("one"), subRecord("two")); + return Effect.gen(function* () { + const response = yield* refused(fakes); + assert.equal(response.code, "concurrency_full"); + assert.include(response.message, "the most the Boat config allows"); + assert.include(response.message, "here, on this sandbox"); + assert.notInclude(response.message, "target.sandbox"); + }); + }); + + it.effect("when the config allows none", () => { + const fakes = makeFakes({ + configs: [{ ...config, subSandboxes: { perThread: 0, total: 0 } }], + }); + return Effect.gen(function* () { + const response = yield* refused(fakes); + assert.equal(response.code, "concurrency_full"); + assert.include(response.message, "does not let subagents start sandboxes"); + }); + }); + + it.effect("when Linked environments is off", () => { + const fakes = makeFakes({ linkedEnvironments: false }); + return Effect.gen(function* () { + const response = yield* refused(fakes); + assert.equal(response.code, "invalid_request"); + assert.include(response.message, "Settings → Labs"); + }); + }); + + it.effect("when the sandbox's config is gone", () => { + const fakes = makeFakes({ configs: [] }); + return Effect.gen(function* () { + const response = yield* refused(fakes); + assert.equal(response.code, "invalid_request"); + assert.include(response.message, "config no longer exists"); + }); + }); + + it.effect("when the chat runs no turn on this host", () => { + const fakes = makeFakes({ runs: [] }); + return Effect.gen(function* () { + const response = yield* refused(fakes); + assert.equal(response.code, "parent_not_active"); + assert.include(response.message, "Run this work here, on this sandbox"); + }); + }); + + it.effect("when it asks for more than one size up", () => { + const fakes = makeFakes(); + return Effect.gen(function* () { + installHelper(fakes); + ask(fakes, "req-1", { size: "large" }); + yield* tick; + const response = responseOf(fakes, "req-1"); + assert.equal(response.status, "failed"); + assert.include(response.message, "size can be small or default"); + }).pipe(Effect.provide(layerFor(fakes)), Effect.ensuring(cleanUp(fakes))); + }); + }); + + it.effect("picks up where it left off after a restart without running a request twice", () => { + const fakes = makeFakes(); + installHelper(fakes); + ask(fakes, "req-1"); + // Picked up before a restart, but the server stopped while starting its sandbox. + NodeFS.writeFileSync( + queue(fakes, "claimed", "req-2.json"), + JSON.stringify({ version: 1, id: "req-2", task: "Lint" }), + ); + NodeFS.writeFileSync( + queue(fakes, "responses", "req-2.json"), + JSON.stringify({ + version: 1, + id: "req-2", + status: "starting_sandbox", + message: "", + updatedAt: "", + }), + ); + return Effect.gen(function* () { + yield* tick.pipe(Effect.provide(layerFor(fakes))); + assert.equal(fakes.created.length, 1); + assert.equal(responseOf(fakes, "req-1").status, "running"); + const interrupted = responseOf(fakes, "req-2"); + assert.equal(interrupted.status, "failed"); + assert.include(interrupted.message, "restarted while it was starting this sandbox"); + + // A new server finds req-1 open with its task, and follows it to the end. + yield* Effect.gen(function* () { + yield* tick; + yield* TestClock.adjust("15 seconds"); + yield* tick; + assert.equal(fakes.created.length, 1); + assert.equal(fakes.delegated.length, 1); + fakes.task = { status: "failed", result: "Out of disk." }; + yield* tick; + assert.deepInclude(responseOf(fakes, "req-1"), { + status: "failed", + result: "Out of disk.", + }); + }).pipe(Effect.provide(layerFor(fakes))); + }).pipe(Effect.ensuring(cleanUp(fakes))); + }); + + it.effect("polls a working chat's sandbox every 15 s and an idle one every 60 s", () => { + const fakes = makeFakes({ runs: [] }); + installHelper(fakes); + return Effect.gen(function* () { + yield* tick; + assert.equal(polls(fakes), 1); + for (let second = 5; second < 60; second += 5) { + yield* TestClock.adjust("5 seconds"); + yield* tick; + } + assert.equal(polls(fakes), 1); + yield* TestClock.adjust("5 seconds"); + yield* tick; + assert.equal(polls(fakes), 2); + + // A turn on the chat is when its agents can ask. + fakes.runs = makeFakes().runs; + for (let second = 0; second < 60; second += 5) { + yield* TestClock.adjust("5 seconds"); + yield* tick; + } + assert.equal(polls(fakes), 6); + + // A stopped sandbox, and a subagent's own, are never polled. + fakes.records = [chatRecord({ state: "stopped", runningSince: null }), subRecord("sub")]; + for (let second = 0; second < 60; second += 5) { + yield* TestClock.adjust("5 seconds"); + yield* tick; + } + assert.equal(polls(fakes), 6); + }).pipe(Effect.provide(layerFor(fakes)), Effect.ensuring(cleanUp(fakes))); + }); + + it.effect("polls a sandbox without the helper once per running stretch", () => { + const fakes = makeFakes(); + return Effect.gen(function* () { + yield* tick; + for (let second = 0; second < 120; second += 5) { + yield* TestClock.adjust("5 seconds"); + yield* tick; + } + assert.equal(fakes.scripts.length, 1); + // A resume may have added it. + fakes.records = [chatRecord({ runningSince: "2026-11-02T00:00:00.000Z" })]; + yield* tick; + assert.equal(fakes.scripts.length, 2); + }).pipe(Effect.provide(layerFor(fakes)), Effect.ensuring(cleanUp(fakes))); + }); +}); diff --git a/apps/server/src/sandbox/SubSandboxRequests.ts b/apps/server/src/sandbox/SubSandboxRequests.ts new file mode 100644 index 0000000000000..72230dafc6fd4 --- /dev/null +++ b/apps/server/src/sandbox/SubSandboxRequests.ts @@ -0,0 +1,575 @@ +import { + isSandboxHostProjectRoot, + type NodeId, + type OrchestrationV2Subagent, + ProviderInstanceId, + type SandboxRecord, + type ThreadId, +} from "@t3tools/contracts"; +import { CLAUDE_FALLBACK_MODEL } from "@t3tools/sandbox-bridge"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as SandboxProvisioner from "./SandboxProvisioner.ts"; +import { + parseSubSandboxPoll, + SUB_SANDBOX_POLL_SCRIPT, + SUB_SANDBOX_REQUEST_ID, + subSandboxRespondScript, +} from "./subSandboxHelper.ts"; +import * as SubSandboxes from "./SubSandboxes.ts"; + +/** + * Requests from agents on a sandbox (`sandbox_delegate`), started as `delegate_task` with + * `target.sandbox` would, for the sandbox's chat. One exec per poll: every 15 s while the chat runs + * a turn here or has a request open or recent, else every 60 s; never while stopped. + */ +export class SubSandboxRequests extends Context.Service< + SubSandboxRequests, + { + /** One pass: polls the sandboxes that are due and writes what changed. Tests step it. */ + readonly tick: Effect.Effect; + /** Ticks every few seconds for as long as the server runs. */ + readonly start: () => Effect.Effect; + } +>()("t3/sandbox/SubSandboxRequests") {} + +/** How often a sandbox whose agents are working, or that has requests, is polled. */ +const ACTIVE_POLL_SECONDS = 15; +/** How often any other running sandbox with the helper is polled. */ +const IDLE_POLL_SECONDS = 60; +/** A sandbox stays on the active cadence this long after a request. */ +const RECENT_REQUEST_SECONDS = 300; +const TICK_SECONDS = 5; +const POLL_TIMEOUT_SECONDS = 30; +const WRITE_TIMEOUT_SECONDS = 30; +/** The longest result written back; the agent reads the rest in the chat on the computer. */ +const MAX_RESULT_LENGTH = 50_000; + +const SubSandboxRequestFile = Schema.Struct({ + id: Schema.String, + task: Schema.String, + size: Schema.optional(Schema.String), + threadId: Schema.optional(Schema.String), + cwd: Schema.optional(Schema.String), + upstream: Schema.optional(Schema.String), + model: Schema.optional(Schema.Struct({ instanceId: Schema.String, model: Schema.String })), +}); +const decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(SubSandboxRequestFile)); + +export const SubSandboxResponseStatus = Schema.Literals([ + "queued", + "starting_sandbox", + "running", + "completed", + "failed", + "cancelled", +]); +export type SubSandboxResponseStatus = typeof SubSandboxResponseStatus.Type; + +/** What the helper reads from `responses/.json`. */ +export const SubSandboxResponse = Schema.Struct({ + version: Schema.Literal(1), + id: Schema.String, + status: SubSandboxResponseStatus, + message: Schema.String, + updatedAt: Schema.String, + /** Why it was refused, as `delegate_task` would say: `concurrency_full`, `invalid_request`… */ + code: Schema.optional(Schema.String), + /** The task on the sandbox chat's thread on this host, once it is recorded. */ + taskId: Schema.optional(Schema.String), + subSandbox: Schema.optional( + Schema.Struct({ label: Schema.String, sandboxId: Schema.String, environmentId: Schema.String }), + ), + /** The subagent's last reply, with where its sandbox's work went. */ + result: Schema.optional(Schema.String), +}); +export type SubSandboxResponse = typeof SubSandboxResponse.Type; +const decodeResponse = Schema.decodeUnknownOption(Schema.fromJsonString(SubSandboxResponse)); + +const TERMINAL: ReadonlySet = new Set([ + "completed", + "failed", + "cancelled", +]); + +const NO_TURN_HERE = + "Not started: T3 Code on the user's computer records a sub-sandbox's task on this chat's running turn, and it sees none there. That happens when a turn did not go through T3 Code on the computer or phone. Run this work here, on this sandbox."; +const INTERRUPTED = + "T3 Code on the user's computer restarted while it was starting this sandbox, so it does not know whether one was made. Nothing will run for this request; ask again with a new id. If a sandbox from it shows under Settings → Connections → Sandboxes, delete it there."; + +/** A branch name `git clone --branch` takes from a tracking ref such as `origin/feature/x`. */ +const branchOf = (upstream: string | undefined) => { + if (upstream === undefined) return undefined; + const slash = upstream.indexOf("/"); + const branch = slash < 0 ? "" : upstream.slice(slash + 1); + return /^[A-Za-z0-9._/-]{1,200}$/u.test(branch) && + !branch.includes("..") && + !branch.startsWith("-") + ? branch + : undefined; +}; + +const statusOfTask = (task: OrchestrationV2Subagent): SubSandboxResponseStatus => + task.status === "completed" ? "completed" : task.status === "cancelled" ? "cancelled" : "failed"; + +const clip = (text: string) => + text.length <= MAX_RESULT_LENGTH + ? text + : `${text.slice(0, MAX_RESULT_LENGTH)}\n\n[Cut at ${MAX_RESULT_LENGTH} characters. The whole result is in the chat's task on the user's computer.]`; + +interface OpenRequest { + readonly id: string; + readonly parentThreadId: ThreadId; + status: SubSandboxResponseStatus; + taskId: NodeId | undefined; + subSandbox: SubSandboxResponse["subSandbox"]; + /** Being started; its handler writes its statuses, not the tick. */ + starting: boolean; + /** The newest response the sandbox has not taken yet, as when it stopped meanwhile. */ + unwritten: SubSandboxResponse | null; +} + +interface Watched { + lastPolledAt: number | null; + lastRequestAt: number | null; + /** The running stretch a poll found no helper in; the next stretch polls again. */ + noHelperIn: string | null; + polling: boolean; + readonly open: Map; +} + +const make = Effect.gen(function* () { + const provisioner = yield* SandboxProvisioner.SandboxProvisioner; + const subSandboxes = yield* SubSandboxes.SubSandboxes; + const remoteDelegation = yield* RemoteDelegation.RemoteDelegation; + const threads = yield* ThreadManagement.ThreadManagementService; + const projects = yield* ProjectService.ProjectService; + const hereId = yield* ServerEnvironment.ServerEnvironment.pipe( + Effect.flatMap((environment) => environment.getEnvironmentId), + ); + // Requests being started live as long as this service, so shutting down stops them. + const scope = yield* Scope.Scope; + const watched = new Map(); + + const nowIso = DateTime.now.pipe(Effect.map(DateTime.formatIso)); + + const watchOf = (instanceId: string) => { + const existing = watched.get(instanceId); + if (existing !== undefined) return existing; + const created: Watched = { + lastPolledAt: null, + lastRequestAt: null, + noHelperIn: null, + polling: false, + open: new Map(), + }; + watched.set(instanceId, created); + return created; + }; + + const response = ( + request: Pick, + status: SubSandboxResponseStatus, + message: string, + extra: { readonly code?: string; readonly result?: string } = {}, + ) => + nowIso.pipe( + Effect.map((updatedAt): SubSandboxResponse => ({ + version: 1, + id: request.id, + status, + message, + updatedAt, + ...(extra.code === undefined ? {} : { code: extra.code }), + ...(request.taskId === undefined ? {} : { taskId: request.taskId }), + ...(request.subSandbox === undefined ? {} : { subSandbox: request.subSandbox }), + ...(extra.result === undefined ? {} : { result: clip(extra.result) }), + })), + ); + + /** Writes `next` on the sandbox, or keeps it for the next tick when that fails. */ + const write = (record: SandboxRecord, request: OpenRequest, next: SubSandboxResponse) => + provisioner + .runScript({ + instanceId: record.instanceId, + script: subSandboxRespondScript(request.id, next, TERMINAL.has(next.status)), + timeoutSeconds: WRITE_TIMEOUT_SECONDS, + }) + .pipe( + Effect.map((result) => result.exitCode === 0), + Effect.orElseSucceed(() => false), + Effect.map((written) => { + request.status = next.status; + request.unwritten = written ? null : next; + if (written && TERMINAL.has(next.status)) { + watchOf(record.instanceId).open.delete(request.id); + } + return written; + }), + ); + + const refuse = (record: SandboxRecord, request: OpenRequest, message: string, code: string) => + response(request, "failed", message, { code }).pipe( + Effect.flatMap((next) => write(record, request, next)), + Effect.asVoid, + ); + + /** + * Starts one request's task: on behalf of the sandbox's chat, whose thread on this host is the + * parent, through the same sandbox config, limits and sizes as `delegate_task`'s `target.sandbox`. + */ + const handle = Effect.fn("SubSandboxRequests.handle")(function* ( + record: SandboxRecord, + request: OpenRequest, + json: string, + ) { + const decoded = decodeRequest(json); + if (Option.isNone(decoded) || decoded.value.task.trim() === "") { + return yield* refuse( + record, + request, + "Not started: the request could not be read.", + "invalid_request", + ); + } + const asked = decoded.value; + const parent = yield* threads + .getThreadRecords(request.parentThreadId, ["runs"]) + .pipe(Effect.option); + if (Option.isNone(parent)) { + return yield* refuse(record, request, NO_TURN_HERE, "parent_not_active"); + } + const parentRun = parent.value.runs + .filter(ThreadManagement.isActiveRun) + .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + if (parentRun === undefined || parentRun.rootNodeId === null) { + return yield* refuse(record, request, NO_TURN_HERE, "parent_not_active"); + } + if (record.repository === undefined) { + return yield* refuse( + record, + request, + "Not started: T3 Code on the user's computer does not know which repository this sandbox cloned.", + "invalid_request", + ); + } + yield* write( + record, + request, + yield* response( + request, + "starting_sandbox", + "T3 Code on the user's computer is starting a sandbox for it.", + ), + ); + const projectId = parent.value.thread.projectId; + const project = yield* projects.getById(projectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + const workspaceRoot = project?.workspaceRoot ?? ""; + const started = yield* subSandboxes + .start({ + parentThreadId: request.parentThreadId, + projectId, + cwd: workspaceRoot, + size: asked.size, + repository: { + remoteUrl: `https://github.com/${record.repository}.git`, + canonicalKey: `github.com/${record.repository}`, + baseRef: branchOf(asked.upstream), + // Env files come from the host's own checkout, never from a placeholder folder. + hostCheckout: workspaceRoot !== "" && !isSandboxHostProjectRoot(workspaceRoot), + }, + caller: "sandbox", + }) + .pipe(Effect.result); + if (started._tag === "Failure") { + return yield* refuse( + record, + request, + `Not started: ${started.failure.message}`, + started.failure.code, + ); + } + const sub = started.success; + const model = asked.model ?? CLAUDE_FALLBACK_MODEL; + const threadScope: McpInvocationContext.McpThreadInvocationScope = { + environmentId: hereId, + requestNamespace: `sub-sandbox-request:${record.instanceId}`, + thread: { + threadId: request.parentThreadId, + providerSessionId: `sub-sandbox-request:${record.instanceId}`, + providerInstanceId: parentRun.providerInstanceId, + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 0, + }; + const delegated = yield* remoteDelegation + .delegate(threadScope, { + task: asked.task.trim(), + // A result reaching a turn still running is read through sandbox_task_status; one that + // arrives after the turn ended wakes the chat, as a local delegated task would. + mode: "wait", + clientRequestId: `sub-sandbox-request:${request.id}`, + target: { + environmentId: sub.environmentId, + ...(sub.projectId === undefined ? {} : { projectId: sub.projectId }), + providerInstanceId: ProviderInstanceId.make(model.instanceId), + model: model.model, + }, + }) + .pipe(Effect.result); + if (delegated._tag === "Failure") { + yield* subSandboxes.discard(sub.instanceId); + return yield* refuse( + record, + request, + `Not started: the sandbox started, but its task could not: ${delegated.failure.message} The sandbox was deleted.`, + delegated.failure.code, + ); + } + const made = yield* provisioner.list.pipe( + Effect.map((listed) => + listed.sandboxes.find((candidate) => candidate.instanceId === sub.instanceId), + ), + Effect.orElseSucceed(() => undefined), + ); + request.taskId = delegated.success.taskId; + request.subSandbox = { + label: made?.label ?? "a new sandbox", + sandboxId: made?.sandboxId ?? "", + environmentId: sub.environmentId, + }; + yield* write( + record, + request, + yield* response( + request, + "running", + "The subagent is working on its own sandbox. It shows under this chat on the user's computer.", + ), + ); + }); + + /** A task this side recorded: its result, once it has one, goes back to the sandbox. */ + const follow = Effect.fn("SubSandboxRequests.follow")(function* ( + record: SandboxRecord, + request: OpenRequest, + ) { + if (request.taskId === undefined) return; + const task = yield* threads + .getThreadRecords(request.parentThreadId, ["subagents"], { subagentIds: [request.taskId] }) + .pipe( + Effect.map(({ subagents }) => subagents[0]), + Effect.orElseSucceed(() => undefined), + ); + if (task === undefined || task.result === null) return; + const status = statusOfTask(task); + yield* write( + record, + request, + yield* response( + request, + status, + status === "completed" + ? "The subagent finished." + : status === "cancelled" + ? "The task was cancelled on the user's computer." + : "The subagent's task ended without finishing.", + { result: task.result }, + ), + ); + }); + + /** A request this server has not tracked since it started: picked up before a restart. */ + const recover = Effect.fn("SubSandboxRequests.recover")(function* ( + record: SandboxRecord, + watch: Watched, + id: string, + json: string, + ) { + const previous = decodeResponse(json); + const request: OpenRequest = { + id, + parentThreadId: record.threadId!, + status: Option.isSome(previous) ? previous.value.status : "queued", + taskId: + Option.isSome(previous) && previous.value.taskId !== undefined + ? (previous.value.taskId as NodeId) + : undefined, + subSandbox: Option.isSome(previous) ? previous.value.subSandbox : undefined, + starting: false, + unwritten: null, + }; + watch.open.set(id, request); + // Already answered: only moving it to done/ was missed. + if (Option.isSome(previous) && TERMINAL.has(previous.value.status)) { + return yield* write(record, request, previous.value); + } + // It never reached a task, so whatever started it is gone; it is never started twice. + if (request.taskId === undefined) { + return yield* write( + record, + request, + yield* response(request, "failed", INTERRUPTED, { code: "orchestration_error" }), + ); + } + return true; + }); + + const poll = Effect.fn("SubSandboxRequests.poll")(function* ( + record: SandboxRecord, + watch: Watched, + now: number, + ) { + watch.lastPolledAt = now; + const result = yield* provisioner + .runScript({ + instanceId: record.instanceId, + script: { command: SUB_SANDBOX_POLL_SCRIPT }, + timeoutSeconds: POLL_TIMEOUT_SECONDS, + }) + .pipe(Effect.option); + if (Option.isNone(result)) return; + const polled = parseSubSandboxPoll(result.value.stdout); + if (polled === null) return; + if (!polled.installed) { + watch.noHelperIn = record.runningSince; + return; + } + for (const open of polled.open) { + if (!watch.open.has(open.id)) yield* recover(record, watch, open.id, open.json); + } + for (const asked of polled.requests) { + if (watch.open.has(asked.id) || !SUB_SANDBOX_REQUEST_ID.test(asked.id)) continue; + watch.lastRequestAt = now; + const request: OpenRequest = { + id: asked.id, + parentThreadId: record.threadId!, + status: "queued", + taskId: undefined, + subSandbox: undefined, + starting: true, + unwritten: null, + }; + watch.open.set(asked.id, request); + // Nothing starts until the sandbox has the first answer: a request whose first answer + // never landed is offered again by the next poll, and one that has it is never started + // twice, a restart included (see `recover`). + const queued = yield* write( + record, + request, + yield* response(request, "queued", "T3 Code on the user's computer picked it up."), + ); + if (!queued) { + watch.open.delete(asked.id); + continue; + } + yield* handle(record, request, asked.json).pipe( + Effect.catchCause((cause) => + Effect.logWarning("sub-sandbox request failed", { id: asked.id, cause }).pipe( + Effect.andThen( + refuse( + record, + request, + "Not started: T3 Code on the user's computer hit an error starting it.", + "orchestration_error", + ), + ), + ), + ), + Effect.ensuring( + Effect.sync(() => { + request.starting = false; + }), + ), + Effect.forkIn(scope), + ); + } + }); + + /** Whether the chat runs a turn on this host, which is when its agents can ask. */ + const chatIsWorking = (threadId: ThreadId) => + threads.getThreadRecords(threadId, ["runs"]).pipe( + Effect.map(({ runs }) => runs.some(ThreadManagement.isActiveRun)), + Effect.orElseSucceed(() => false), + ); + + const visit = Effect.fn("SubSandboxRequests.visit")(function* ( + record: SandboxRecord, + now: number, + ) { + const watch = watchOf(record.instanceId); + for (const request of watch.open.values()) { + if (request.starting) continue; + if (request.unwritten !== null) { + yield* write(record, request, request.unwritten); + } else { + yield* follow(record, request); + } + } + if (watch.polling || watch.noHelperIn === record.runningSince) return; + const recent = + watch.lastRequestAt !== null && now - watch.lastRequestAt < RECENT_REQUEST_SECONDS * 1000; + const active = watch.open.size > 0 || recent || (yield* chatIsWorking(record.threadId!)); + const every = (active ? ACTIVE_POLL_SECONDS : IDLE_POLL_SECONDS) * 1000; + // A tick's own delay is not held against the next poll. + if (watch.lastPolledAt !== null && now - watch.lastPolledAt < every - 1000) return; + watch.polling = true; + yield* poll(record, watch, now).pipe( + Effect.ensuring( + Effect.sync(() => { + watch.polling = false; + }), + ), + ); + }); + + const tick: SubSandboxRequests["Service"]["tick"] = Effect.gen(function* () { + const listed = yield* provisioner.list.pipe(Effect.option); + if (Option.isNone(listed)) return; + const live = new Set(listed.value.sandboxes.map((record) => record.instanceId)); + for (const instanceId of watched.keys()) { + if (!live.has(instanceId)) watched.delete(instanceId); + } + const now = yield* Clock.currentTimeMillis; + // A chat's sandbox only: a subagent's sandbox has no chat on this host to hold more tasks. + const due = listed.value.sandboxes.filter( + (record) => + record.state === "running" && + record.resumingSince === undefined && + record.threadId !== undefined && + record.parentThreadId === undefined && + record.environmentId !== null, + ); + yield* Effect.forEach(due, (record) => visit(record, now), { + concurrency: 4, + discard: true, + }); + }).pipe( + Effect.catchCause((cause) => Effect.logWarning("sub-sandbox requests tick failed", { cause })), + ); + + const start: SubSandboxRequests["Service"]["start"] = () => + forkParked(tick.pipe(Effect.repeat(Schedule.spaced(`${TICK_SECONDS} seconds`)), Effect.asVoid)); + + return SubSandboxRequests.of({ tick, start }); +}); + +export const layer = Layer.effect(SubSandboxRequests, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9e99eeca76c49..192bc0d871cac 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -85,6 +85,7 @@ import * as McpHttpServer from "./mcp/McpHttpServer.ts"; import * as PeerForwarding from "./peer/PeerForwarding.ts"; import * as RemoteDelegation from "./peer/RemoteDelegation.ts"; import * as SubSandboxes from "./sandbox/SubSandboxes.ts"; +import * as SubSandboxRequests from "./sandbox/SubSandboxRequests.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PeerMcpClient from "./peer/PeerMcpClient.ts"; @@ -820,10 +821,16 @@ const layerMakeRoutes = Layer.mergeAll( Layer.effectDiscard( RemoteDelegation.RemoteDelegation.pipe(Effect.flatMap((remote) => remote.start())), ), + // Picks up what agents on this machine's sandboxes ask for through the helper installed there. + Layer.effectDiscard( + SubSandboxRequests.SubSandboxRequests.pipe(Effect.flatMap((requests) => requests.start())), + ), ).pipe( Layer.provide( PullRequestReviewGuideService.layer.pipe(Layer.provide(PullRequestReviewGuides.layer)), ), + // Sub-sandbox requests from agents on sandboxes, started through the two layers below. + Layer.provide(SubSandboxRequests.layer), // delegate_task to a linked environment, from /mcp and the follower above. Layer.provide(RemoteDelegation.layer.pipe(Layer.provide(ProjectionStoreV2.layer))), // Sandboxes delegate_task starts for subagents, linked like any environment and ended with diff --git a/packages/sandbox-bridge/src/bridge.ts b/packages/sandbox-bridge/src/bridge.ts index fc2d61ebdae74..cb9c65d136ebb 100644 --- a/packages/sandbox-bridge/src/bridge.ts +++ b/packages/sandbox-bridge/src/bridge.ts @@ -282,7 +282,8 @@ export const sandboxSelectionFor = ( return sameSelection(next, sandbox) ? null : next; }; -const CLAUDE_FALLBACK_MODEL: ModelSelection = { +/** What a sandbox thread runs on when nothing names its model. */ +export const CLAUDE_FALLBACK_MODEL: ModelSelection = { instanceId: "claudeAgent", model: "claude-opus-5-5", } as ModelSelection; From c3ce360bcf3b65eef0ee757a8a6e5897203c6f21 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Wed, 11 Nov 2026 15:26:29 +0000 Subject: [PATCH 4/4] docs: explain how agents on a sandbox ask for a sub-sandbox Co-Authored-By: Claude Opus 5.5 --- docs/internals/sandbox-environments.md | 56 +++++++++++++++++++++++++- docs/user/remote-access.md | 24 ++++++++++- 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/docs/internals/sandbox-environments.md b/docs/internals/sandbox-environments.md index c5b73ecdf0c29..b564f575f62d3 100644 --- a/docs/internals/sandbox-environments.md +++ b/docs/internals/sandbox-environments.md @@ -428,11 +428,65 @@ without pairing with the sandbox. - **Placeholder projects.** A project whose root `isSandboxHostProjectRoot` matches gets no git status, scripts, open-in, files or terminal in the web app. - **Stopped sandbox.** A run starting on a `sandboxes` thread whose sandbox is stopped makes the - host resume it. Meanwhile the bridge retries for `SANDBOX_RESUME_WAIT_SECONDS` (15½ minutes: + host resume it. Meanwhile the bridge retries for `SANDBOX_RESUME_WAIT_SECONDS` (16 minutes: every step of a resume at its limit, `SANDBOX_RESUME_STEP_SECONDS`, plus a minute), showing "Starting sandbox bx_…", then says the sandbox is not answering. Messages sent meanwhile queue behind that run on the host, so they go out after it whether or not a client stays open. +## Sub-sandboxes + +`delegate_task` with `target.sandbox` starts the child on a sandbox of its own +([`SubSandboxes.ts`](../../apps/server/src/sandbox/SubSandboxes.ts), rules in +[`subSandboxPolicy.ts`](../../apps/server/src/sandbox/subSandboxPolicy.ts)): the parent's sandbox +config or the project's, a place held within the config's `subSandboxes` limits, `createSubSandbox`, +a peer link, and `RemoteDelegation.delegate`. When the task ends, `settle` runs `checkWork` and +deletes the sandbox when it is clean, else stops and keeps it. + +Agents on a sandbox reach the same path through a helper the host installs, since the sandbox runs +the official T3 Code ([`subSandboxHelper.ts`](../../apps/server/src/sandbox/subSandboxHelper.ts), +[`SubSandboxRequests.ts`](../../apps/server/src/sandbox/SubSandboxRequests.ts)). + +- **The helper** is a stdio MCP server, `~/.t3/userdata/sub-sandbox/mcp.mjs`, using only Node + built-ins. Node is what the fork already needs to register MCP servers in Claude's + `~/.claude.json`, where it is registered as `t3-sub-sandbox` with the absolute path of the Node + that installed it. The name goes in `~/.t3/mcp-servers.json`, so `MCP_SERVERS_SCRUB` removes it. + The official `t3` binary is a Node single executable and gives no `node` of its own. Claude + hands its environment, `T3CODE_THREAD_ID` included, to the MCP servers it spawns. The helper + sends that id, its working directory, the upstream branch there and the thread's model, read + with `t3 thread show --json`. +- **Files.** `requests/.json` is written by the helper with a temp file and a rename. The + host's poll claims each request by moving it to `claimed/`. A helper that gets no response + within its wait (45 seconds, or 20 when `host-seen` is over 3 minutes old; every call stays + under 60 seconds, which some MCP clients allow a tool) moves the request to + `withdrawn/` instead. Each rename has one winner, so a withdrawn request never starts. + `responses/.json` is written by the host, also with a temp file and a rename. Its statuses + are `queued`, `starting_sandbox`, `running` (with `taskId` and the sub-sandbox), + `completed`/`failed`/`cancelled` (with `result`, or `code` for a refusal). The last one moves + the request to `done/`. +- **Host poll.** `SubSandboxRequests` ticks every 5 seconds and runs `SUB_SANDBOX_POLL_SCRIPT` + through `SandboxProvisioner.runScript` (`driver.execute`). It polls a running chat sandbox + (`threadId` set, no `parentThreadId`, not resuming) every 15 seconds while the chat's thread + here has an active run, a request is open, or one came in the last 5 minutes. Otherwise it polls + every 60 seconds. A sandbox whose poll finds no helper is not polled again until its next + running stretch. The bridge's bearer cannot be used instead: it has only `orchestration:*` + scopes, and the official server's file RPCs need `filesystem:*`. +- **Handling.** A new request gets `queued` written first, and nothing starts until that write + lands. The parent is the chat's thread here (`SandboxRecord.threadId`, the bridge's mirror), + with its latest active run, since `RemoteDelegation` records tasks on a running turn. The + sandbox's clone comes from `record.repository` at the request's upstream branch. Env files are + copied only when the host project is a real checkout. The scope acts as that thread, on the + run's provider instance (`sandboxes`). The child runs on the request's model, or the bridge's + Claude fallback, with `mode: "wait"`, so a result is not delivered again to a turn that is + still running. +- **Restarts.** In-flight state lives in memory and on the sandbox. A claimed request that already + has a response is recovered from that response. With a `taskId` it is followed until the task + has a result. Without one, the server stopped while starting its sandbox, so it is failed and + never started again. +- **Install.** `setUpTools` writes the helper after T3 Code's skill on every launch except a + subagent's sandbox. Every resume of a chat sandbox rewrites it before T3 starts + (`SANDBOX_RESUME_STEP_SECONDS.subSandboxHelper`). A failure is a warning. The template scrub + removes the folder (`SUB_SANDBOX_HELPER_SCRUB`) before T3's userdata goes. + ## Lifecycle and hard limits Every machine gets a row in `sandbox_instances` (see diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index c2d05ebf5d3da..231197ae503b3 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -309,7 +309,29 @@ environments** has to be on under **Settings → Labs**; the agent says so when unpushed commits. A clean one is deleted. One with work, or one it could not check, is stopped and kept, and the task's result says which sandbox and folder hold the work. - In the Sandboxes list they sit under the thread that delegated their tasks. -- An agent running on a sandbox cannot start one yet: the sandbox runs the official T3 Code. + +Agents on a sandbox can ask too. The sandbox runs the official T3 Code, whose `delegate_task` has no +`target.sandbox`, so T3 Code installs a small helper there that gives Claude two tools: +`sandbox_delegate` asks for a sandbox and `sandbox_task_status` reports on it. The request goes to +this machine, which starts the sandbox the same way: from the same config, within the same limits +and sizes, and ended the same way when the task is done. The task shows under the sandbox's chat +on this machine. + +- **This machine must be awake** and running T3 Code, since it holds the configs and provider + keys. It checks each running sandbox for requests every 15 seconds while that sandbox's chat + works, and every minute otherwise. When nothing picks a request up within about 45 seconds, the + helper withdraws it and tells the agent to do the work on its own sandbox. +- The request is recorded on the chat's running turn on this machine, so it works when the + conversation goes through T3 Code here or on your phone. Each request has an id, and asking + again with the same id never starts a second sandbox. A result is passed back to the agent when + it asks for the status, and a result that arrives after its turn has ended starts a new turn, + as a subagent's result does here. +- Refusals reach the agent with the reason: a limit reached (`concurrency_full`), **Linked + environments** off, no config to start from, or a size too large. A config whose limits are 0 + still gets the helper, and every request from it is refused with that reason. +- Sandboxes get the helper when they start, and older sandboxes get it when they resume. A + subagent's own sandbox does not get it. The helper is for Claude; other agents on a sandbox do + not see it. Saving a template removes it, with any pending requests. ### Templates