Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Give disposable execution scoped capabilities and reliable turn cleanup (#1696)

Regan Bellcd1176f2c0ea
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 4e87e9338..034d7612d 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -1253,7 +1253,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
turnContextBlocks.push(computerBlock);
if (!external && deps.scratchExec) {
systemPrompt +=
- '\n\nSelect a sandbox explicitly or use a stored default. The opt-in scratch box (scope:"scratch") is separate: same OS and tooling, org-global files only, no logins or tokens, wiped after the turn — prefer it for heavy self-contained runs that need no logins, workspace files, or follow-up; it keeps this computer responsive.';
+ '\n\nSelect a sandbox explicitly or use a stored default. The opt-in scratch box (scope:"scratch") is separate: same OS/tooling, read-only org-global files, this conversation\'s scoped Files/API capabilities, and credentials explicitly requested per execute call. Its local files are wiped after the turn, and resident workspace files and cached CLI logins are not restored. Use it for self-contained commands and API work; publish needed outputs to Files and verify success. Use scoped execution for existing workspace state or work that must continue locally.';
}
if (!external && deps.deploymentLayer?.hints.length) {
systemPrompt += `\n\n## Deployment tool hints\n${deps.deploymentLayer.hints.map((hint) => `- ${hint}`).join("\n")}`;
diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.ts
index 429b8bd97..81ef0004c 100644
--- a/src/core/orchestrator/sandboxes.ts
+++ b/src/core/orchestrator/sandboxes.ts
@@ -3,7 +3,7 @@ import { personalScope } from "../../types.ts";
import { intersectEgressPolicies } from "../../resolution/egress-policy.ts";
import { isOpenScopeMember } from "../../resolution/sharing-access.ts";
import type { GapPhase } from "../../sessions/session-store.ts";
-import { type SandboxHandle, supportsProcessSessions } from "../../sandbox/sandbox.ts";
+import { type SandboxHandle, supportsProcessSessions, SandboxProvisionCleanupError } from "../../sandbox/sandbox.ts";
import type { SandboxAccessPlan } from "../../sandbox/sandbox-resources.ts";
import { reconcileProcesses } from "../../processes/reconcile.ts";
import {
@@ -124,24 +124,52 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
provisionMs?: number;
materializeMs?: number;
} = { handle: null, pending: null, used: false };
- const scratchBox: { handle: SandboxHandle | null; provisionMs?: number } = { handle: null };
+ const scratchBox: { handle: SandboxHandle | null; pending: SandboxHandle | null; provisionMs?: number } = {
+ handle: null,
+ pending: null,
+ };
+ let scratchProvisionInFlight: Promise<SandboxHandle> | null = null;
+ const scratchKey = () => `turn:${session.id}:${transferId}`;
+ let scratchStartedAt: number | undefined;
+ let scratchReadyAt: number | undefined;
+ const recordScratchLifecycle = (
+ action: string,
+ handle?: SandboxHandle,
+ timing?: { releasedAt: number; cleanupMs: number },
+ ): void => {
+ deps.auditLog?.record({
+ at: Date.now(),
+ principalId: actor.id,
+ action: `sandbox.scratch.${action}`,
+ resource: scratchKey(),
+ scopeLabel: scopeId,
+ detail: JSON.stringify({
+ runId: input.runId,
+ sessionId: session.id,
+ backend: handle?.backend,
+ sandboxId: handle?.id,
+ startedAt: scratchStartedAt,
+ readyAt: scratchReadyAt,
+ provisionMs: scratchBox.provisionMs,
+ ...timing,
+ }),
+ });
+ };
const ownerAuthBox: { handle: SandboxHandle | null; pending: SandboxHandle | null; provisionMs?: number } = {
handle: null,
pending: null,
};
let ownerAuthProvisionInFlight: Promise<SandboxHandle> | null = null;
- const destroyOwnerAuthHandle = async (handle: SandboxHandle): Promise<void> => {
- let lastError: unknown;
+ const destroyEphemeralHandle = async (handle: SandboxHandle): Promise<void> => {
for (let attempt = 1; attempt <= 3; attempt++) {
try {
await deps.sandbox.teardown(handle, { destroy: true });
return;
- } catch (err) {
- lastError = err;
+ } catch {
if (attempt < 3) await sleep(50 * attempt);
}
}
- throw lastError;
+ throw new Error("Disposable sandbox destruction failed");
};
const scrubOwnerAuthHandle = async (handle: SandboxHandle): Promise<void> => {
if (!deps.keychain || !isolateOwnerKeychain) return;
@@ -181,7 +209,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
let provisionInFlight: Promise<SandboxHandle> | null = null;
const provision = (eager = false): Promise<SandboxHandle> => {
if (!eager) box.used = true;
- provisionInFlight ??= doProvision(eager ? () => {} : emitGapWork).catch((err) => {
+ provisionInFlight ??= doProvision(eager ? () => {} : emitGapWork, eager).catch((err) => {
provisionInFlight = null;
throw err;
});
@@ -291,7 +319,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
perf.credsMs += Date.now() - deviceFlowStart;
}
};
- const doProvision = async (emit: typeof emitGapWork): Promise<SandboxHandle> => {
+ const doProvision = async (emit: typeof emitGapWork, eager: boolean): Promise<SandboxHandle> => {
const provisionStart = Date.now();
if (input.externalSlack) {
const resource = await deps.sandboxResources?.resolve(memoryScopeId);
@@ -308,6 +336,22 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
box.pending = handle;
emit("provision", provisionStart, Date.now());
box.provisionMs = Date.now() - provisionStart;
+ deps.auditLog?.record({
+ at: Date.now(),
+ principalId: actor.id,
+ action: "sandbox.scoped.provision_ready",
+ resource: scratchKey(),
+ scopeLabel: scopeId,
+ detail: JSON.stringify({
+ runId: input.runId,
+ sessionId: session.id,
+ backend: handle.backend,
+ sandboxId: handle.id,
+ provisionMs: box.provisionMs,
+ coldStart: handle.coldStart,
+ eager,
+ }),
+ });
await prepareCredentials(handle, emit);
const dirCleanupStart = Date.now();
await prepareTurnFiles(handle);
@@ -486,22 +530,37 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
return provisioned;
};
- const provisionScratch = async (): Promise<SandboxHandle> => {
- if (scratchBox.handle) return scratchBox.handle;
- const provisionStart = Date.now();
- const handle = await deps.sandbox.provision(
- resolution.layers.filter((l) => l.mode === "ro" && l.mountPath === "global"),
- {
- egress: resolution.egress,
- ...(egressTokenForTurn ? { egressToken: egressTokenForTurn } : {}),
- scratch: { key: memoryScopeId },
- routeScopeId: memoryScopeId,
- ...(onSandboxStatus ? { onStatus: onSandboxStatus } : {}),
- },
- );
- scratchBox.provisionMs = Date.now() - provisionStart;
- scratchBox.handle = handle;
- return handle;
+ const provisionScratch = (): Promise<SandboxHandle> => {
+ if (scratchBox.pending)
+ return Promise.reject(new Error("Disposable sandbox initialization cleanup is still pending"));
+ if (scratchBox.handle) return Promise.resolve(scratchBox.handle);
+ scratchProvisionInFlight ??= (async () => {
+ const provisionStart = Date.now();
+ scratchStartedAt = provisionStart;
+ recordScratchLifecycle("provision_started");
+ const handle = await deps.sandbox.provision(
+ resolution.layers.filter((l) => l.mode === "ro" && l.mountPath === "global"),
+ {
+ env: connectorEnv,
+ egress: resolution.egress,
+ ...(egressTokenForTurn ? { egressToken: egressTokenForTurn } : {}),
+ scratch: { key: scratchKey() },
+ routeScopeId: memoryScopeId,
+ ...(onSandboxStatus ? { onStatus: onSandboxStatus } : {}),
+ },
+ );
+ scratchBox.provisionMs = Date.now() - provisionStart;
+ scratchBox.handle = handle;
+ scratchReadyAt = Date.now();
+ recordScratchLifecycle("provision_ready", handle);
+ return handle;
+ })().catch((error) => {
+ scratchProvisionInFlight = null;
+ if (error instanceof SandboxProvisionCleanupError) scratchBox.pending = error.handle;
+ recordScratchLifecycle("provision_failed", scratchBox.pending ?? undefined);
+ throw error;
+ });
+ return scratchProvisionInFlight;
};
const provisionOwnerAuth = ownerAuthAvailable
? async (): Promise<SandboxHandle> => {
@@ -561,6 +620,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
return handle;
})().catch(async (err) => {
ownerAuthProvisionInFlight = null;
+ if (err instanceof SandboxProvisionCleanupError) ownerAuthBox.pending = err.handle;
const pendingHandle = ownerAuthBox.pending;
if (pendingHandle) {
try {
@@ -576,7 +636,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
scrubErr,
);
});
- await destroyOwnerAuthHandle(pendingHandle);
+ await destroyEphemeralHandle(pendingHandle);
if (ownerAuthBox.pending === pendingHandle) ownerAuthBox.pending = null;
} catch (cleanupErr) {
deps.errors?.record(
@@ -658,6 +718,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
};
const reclaimBox = async (): Promise<void> => {
let ownerCleanupError: unknown;
+ let scratchCleanupError: unknown;
if (ownerAuthProvisionInFlight) await ownerAuthProvisionInFlight.catch(() => {});
ownerAuthProvisionInFlight = null;
const reachEntries = [...reachBoxes.entries()];
@@ -695,7 +756,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
scrubErr,
);
});
- await destroyOwnerAuthHandle(ownerHandle);
+ await destroyEphemeralHandle(ownerHandle);
ownerAuthBox.handle = null;
ownerAuthBox.pending = null;
} catch (err) {
@@ -712,11 +773,36 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
);
}
}
- const scratchHandle = scratchBox.handle;
- scratchBox.handle = null;
+ if (scratchProvisionInFlight) await scratchProvisionInFlight.catch(() => {});
+ scratchProvisionInFlight = null;
+ const scratchHandle = scratchBox.handle ?? scratchBox.pending;
if (scratchHandle) {
- await clearTurnFiles(scratchHandle);
- await deps.sandbox.teardown(scratchHandle).catch(() => {});
+ const cleanupStart = Date.now();
+ try {
+ await destroyEphemeralHandle(scratchHandle);
+ scratchBox.handle = null;
+ scratchBox.pending = null;
+ recordScratchLifecycle("released", scratchHandle, {
+ releasedAt: Date.now(),
+ cleanupMs: Date.now() - cleanupStart,
+ });
+ } catch {
+ scratchCleanupError = new Error("Disposable sandbox destruction failed");
+ recordScratchLifecycle("release_failed", scratchHandle, {
+ releasedAt: Date.now(),
+ cleanupMs: Date.now() - cleanupStart,
+ });
+ deps.errors?.record(
+ {
+ category: "sandbox",
+ code: "scratch_destroy_failed",
+ message: "Disposable sandbox destruction failed",
+ scopeLabel: scopeId,
+ sessionId: session.id,
+ },
+ scratchCleanupError,
+ );
+ }
}
await Promise.allSettled(resourcePending.values());
const released = new Set<string>();
@@ -751,6 +837,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
box.pending = null;
if (!handle) {
if (ownerCleanupError) throw ownerCleanupError;
+ if (scratchCleanupError) throw scratchCleanupError;
return;
}
await clearTurnFiles(handle);
@@ -768,6 +855,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
...(box.used ? {} : { homeUnchanged: true }),
});
if (ownerCleanupError) throw ownerCleanupError;
+ if (scratchCleanupError) throw scratchCleanupError;
};
return {
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 27b21f75f..8f04bd992 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -745,11 +745,11 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
const SCRATCH_DURABLE_ERROR =
'[error] a scratch box cannot be made durable yet — use scope:"scoped" for work that must survive future turns, or drop `durable`.';
const SCOPED_EPHEMERAL_ERROR =
- '[error] the scoped computer is always durable today — re-run with durable:true (or omit `durable`), or use scope:"scratch" for a run that leaves no trace.';
+ '[error] the scoped computer is always durable today — re-run with durable:true (or omit `durable`), or use scope:"scratch" for disposable local working files.';
const FILE_SEND_GUIDANCE =
"The files and apps tools use the default sandbox; execute and background can target sandbox_id. To send a file, write it to a workspace path and name that path to whichever tool sends: the surface `post` action's `files` when you have `post` (the only way there — a file needs a thread), otherwise `attach`, which rides it out with your reply. The tool result tells you what actually went. A background job can't deliver; have it write to the workspace and attach that from a live turn. ";
const DURABLE_PARAM_DESC =
- "Retain working state for later turns within provider recovery limits? Scoped retains working state; scratch and owner are invocation-only. Publish durable code to git and artifacts to Files.";
+ "Retain working state for later turns within provider recovery limits? Scoped retains working state; scratch lasts for the turn; owner is invocation-only. Publish durable code to git and artifacts to Files.";
const reachScopeDescription =
(scratchExec ? '"scoped" (default) | "scratch" | ' : '"scoped" (default) | ') +
@@ -759,7 +759,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
"Run a shell command and return its stdout/stderr/exit code. Pick where it runs with `scope`:\n" +
'- "scoped" (DEFAULT): this conversation\'s sandbox — its workspace files, turn-private inbox paths, shared-file handles, cached logins, and $AGENT_API_* tokens; working state is retained within provider recovery limits; publish durable code to git and artifacts to Files.\n' +
(scratchExec
- ? '- "scratch": a blank, instant box. Same OS/runtimes/CLIs, shared org files & skills at ./global (read-only), firewalled network — but NO logins, NO credentials or capability tokens, and NOTHING persists past this turn. Prefer it for heavy self-contained work (crunching fetched material, throwaway experiments, parallel or disk-hungry runs needing no workspace files) — it keeps the sandbox responsive; if the run needs logins, workspace files, or its writes must survive, use scope:"scoped".\n'
+ ? '- "scratch": a blank computer for this turn, with the same OS/tooling, read-only org-global files and skills, this conversation\'s scoped $AGENT_API_* capabilities (including Files), and only credentials explicitly requested for this execute call. It does not restore the resident workspace or cached CLI logins. Its local files are discarded after the turn. Use it for self-contained commands and API work, including credential-using work; publish any needed outputs to Files and verify success before finishing. Use scope:"scoped" when you need existing workspace files, installed state, cached logins, or local work that must continue later.\n'
: "") +
(ownerAuthExec
? "- \"owner\": available to the live speaker in Open shared conversations and to owner-authorized shared automation; this invocation-only auth box has org-global files plus the owner's credentials, no room workspace or $AGENT_API_* tokens, and is destroyed after the turn. Use for commands that need the owner's login without putting it on the shared computer.\n"
@@ -778,7 +778,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
? '- "owner": available to the live speaker in Open shared conversations and to owner-authorized shared automation; this invocation-only auth box has org-global files plus the owner\'s credentials, no shared workspace or $AGENT_API_* tokens, and is destroyed after the turn. Use it for credential-using commands without putting personal logins on the shared computer.\n'
: "") +
(scratchExec
- ? '- "scratch": a blank, instant box. Same OS/runtimes/CLIs, shared org files & skills at ./global (read-only), firewalled network — but NO logins, NO credentials or capability tokens ($AGENT_API_TOKEN etc. are absent), and NOTHING persists past this turn. Prefer it for heavy self-contained work — crunching or analyzing material you can fetch onto it, throwaway experiments, checks against public code, anything parallel or disk-hungry whose only product is the answer — because it keeps this conversation\'s computer responsive for everything else. Work on THIS conversation\'s workspace (its checkouts, uncommitted changes) and anything needing logins stays scoped; if a scratch run turns out to need those, re-run it with scope:"scoped".\n'
+ ? '- "scratch": a blank computer for this turn, with the same OS/tooling, read-only org-global files and skills, this conversation\'s scoped $AGENT_API_* capabilities (including Files), and only credentials explicitly requested for this execute call. It does not restore the resident workspace or cached CLI logins. Its local files are discarded after the turn. Use it for self-contained commands and API work, including credential-using work; publish any needed outputs to Files and verify success before finishing. Use scope:"scoped" when you need existing workspace files, installed state, cached logins, or local work that must continue later.\n'
: "") +
"`durable` defaults to true on scoped and false on invocation-only boxes; scoped cannot discard writes, and invocation-only boxes cannot be made durable.\n" +
FILE_SEND_GUIDANCE +
@@ -882,7 +882,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
],
{
description:
- 'Which computer runs this command: "scoped" (default — this conversation\'s sandbox: its working files and authorized logins; recovery depends on the provider) or "scratch" (blank, instant, credential-free, nothing persists — prefer for heavy self-contained runs needing no logins, workspace files, or follow-up).',
+ 'Which computer runs this command: "scoped" (default — this conversation\'s sandbox: its working files and authorized logins; recovery depends on the provider) or "scratch" (blank filesystem for this turn, scoped API capabilities and explicitly requested credentials; no resident workspace or cached logins).',
},
),
),
diff --git a/src/sandbox/agent37-sandbox.ts b/src/sandbox/agent37-sandbox.ts
index 68d6ce8ff..a53aebd61 100644
--- a/src/sandbox/agent37-sandbox.ts
+++ b/src/sandbox/agent37-sandbox.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { randomUUID } from "node:crypto";
import type { WorkspaceLayer } from "../types.ts";
import type { WorkspaceStore } from "../workspace/workspace-store.ts";
@@ -553,7 +554,7 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37San
return handle;
} catch (err) {
- await sandbox.teardown(handle).catch(swallowAs("agent37-sandbox: teardown after failed provision", undefined));
+ await cleanupFailedProvision(sandbox, handle);
throw err;
}
},
@@ -616,6 +617,7 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37San
activeScratch.delete(handle.id);
if (tdOpts?.destroy) await deleteInstance(handle.id);
else await deleteInstance(handle.id).catch(swallowAs("agent37-sandbox: scratch delete", undefined));
+ scratchKeyByName.delete(handle.id);
});
}
if (!tdOpts?.destroy) return;
diff --git a/src/sandbox/aws-sandbox.ts b/src/sandbox/aws-sandbox.ts
index d36cd6820..fb1a2df1b 100644
--- a/src/sandbox/aws-sandbox.ts
+++ b/src/sandbox/aws-sandbox.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { DeleteObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { orgId as configOrgId } from "../config.ts";
import type { WorkspaceLayer } from "../types.ts";
@@ -423,16 +424,6 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOpti
endpointById.set(id, body.endpoint);
const coldStart = body.coldStart;
- const prepared = await execRaw(
- id,
- `mkdir -p ${shq(WORKSPACE_DIR)} && ${ephemeralCredLinkScript(HOME_DIR, credentialPaths)}`,
- PREP_TIMEOUT_SEC,
- );
- if (prepared.code !== 0)
- throw new Error(
- `AWS sandbox credential setup failed: ${execFailureDetail(prepared, PREP_TIMEOUT_SEC).slice(0, 200)}`,
- );
-
const env = provOpts?.env && Object.keys(provOpts.env).length ? provOpts.env : undefined;
const handle: SandboxHandle = {
id,
@@ -443,20 +434,35 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOpti
...(env ? { env } : {}),
};
- await materializeRoLayers(
- workspace,
- layers,
- handle,
- {
- readFile: (h, rel) => sandbox.readFile(h, rel),
- writeFileBytes: (h, rel, data) => sandbox.writeFileBytes(h, rel, data),
- exec: (script, t) => execRaw(id, script, t),
- },
- { manifest: RO_LAYERS_MANIFEST, tar: RO_LAYERS_TAR, label: "aws" },
- );
-
activeByMicrovm.set(id, (activeByMicrovm.get(id) ?? 0) + 1);
- return handle;
+ try {
+ const prepared = await execRaw(
+ id,
+ `mkdir -p ${shq(WORKSPACE_DIR)} && ${ephemeralCredLinkScript(HOME_DIR, credentialPaths)}`,
+ PREP_TIMEOUT_SEC,
+ );
+ if (prepared.code !== 0)
+ throw new Error(
+ `AWS sandbox credential setup failed: ${execFailureDetail(prepared, PREP_TIMEOUT_SEC).slice(0, 200)}`,
+ );
+
+ await materializeRoLayers(
+ workspace,
+ layers,
+ handle,
+ {
+ readFile: (h, rel) => sandbox.readFile(h, rel),
+ writeFileBytes: (h, rel, data) => sandbox.writeFileBytes(h, rel, data),
+ exec: (script, t) => execRaw(id, script, t),
+ },
+ { manifest: RO_LAYERS_MANIFEST, tar: RO_LAYERS_TAR, label: "aws" },
+ );
+
+ return handle;
+ } catch (error) {
+ await cleanupFailedProvision(sandbox, handle);
+ throw error;
+ }
},
async run(handle, command, execOpts?: ExecOptions): Promise<ExecResult> {
diff --git a/src/sandbox/e2b-sandbox.ts b/src/sandbox/e2b-sandbox.ts
index bfdbe4c57..ef1c31db4 100644
--- a/src/sandbox/e2b-sandbox.ts
+++ b/src/sandbox/e2b-sandbox.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { randomUUID } from "node:crypto";
import type { WorkspaceLayer } from "../types.ts";
import type { WorkspaceStore } from "../workspace/workspace-store.ts";
@@ -264,6 +265,7 @@ export function createE2bSandbox(workspace: WorkspaceStore, opts: E2bSandboxOpti
async function withSession<T>(name: string, action: (session: E2bSession) => Promise<T>): Promise<T> {
const scratchKey = scratchKeyByName.get(name);
+ if (scratchKey === undefined && !scopeByName.has(name)) throw new Error("sandbox handle has been released");
const reviveScratch = async (): Promise<E2bSession> => {
const session = await client.create({ metadata: { name, scratch: "true" }, autoPause: false });
@@ -463,7 +465,7 @@ export function createE2bSandbox(workspace: WorkspaceStore, opts: E2bSandboxOpti
return handle;
} catch (err) {
- await sandbox.teardown(handle).catch(swallowAs("e2b-sandbox: teardown after failed provision", undefined));
+ await cleanupFailedProvision(sandbox, handle);
throw err;
}
},
@@ -622,8 +624,12 @@ export function createE2bSandbox(workspace: WorkspaceStore, opts: E2bSandboxOpti
}
activeScratch.delete(handle.id);
const session = sessionByName.get(handle.id);
+ if (session) {
+ if (tdOpts?.destroy) await session.kill();
+ else await session.kill().catch(swallowAs("e2b-sandbox: scratch kill", undefined));
+ }
sessionByName.delete(handle.id);
- if (session) await session.kill().catch(swallowAs("e2b-sandbox: scratch kill", undefined));
+ scratchKeyByName.delete(handle.id);
});
}
if (tdOpts?.destroy && !scopeByName.has(handle.id)) return;
diff --git a/src/sandbox/exec-sandbox-base.ts b/src/sandbox/exec-sandbox-base.ts
index 837a6368d..99b806b44 100644
--- a/src/sandbox/exec-sandbox-base.ts
+++ b/src/sandbox/exec-sandbox-base.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { randomUUID } from "node:crypto";
import type { WorkspaceLayer } from "../types.ts";
import type { WorkspaceStore } from "../workspace/workspace-store.ts";
@@ -79,7 +80,19 @@ export function createExecSandboxBase(deps: ExecSandboxBaseDeps): ExecSandboxBas
return provisionQueue(`scratch:${key}`, async () => {
scratchKeyByName.set(name, key);
const active = activeScratch.get(name) ?? 0;
- if (active === 0 && !deps.isProvisioned(name)) await deps.recreateScratch(name);
+ if (active === 0 && !deps.isProvisioned(name)) {
+ try {
+ await deps.recreateScratch(name);
+ } catch (error) {
+ deps.forgetInstance?.(name);
+ await cleanupFailedProvision(
+ { teardown: () => deps.deleteInstance(name) },
+ { id: name, rootDir: workspaceDir, scratch: true, backend: label },
+ );
+ scratchKeyByName.delete(name);
+ throw error;
+ }
+ }
activeScratch.set(name, active + 1);
return { name, coldStart: active === 0 };
});
@@ -115,6 +128,7 @@ export function createExecSandboxBase(deps: ExecSandboxBaseDeps): ExecSandboxBas
deps.forgetInstance?.(handle.id);
if (tdOpts?.destroy) await deps.deleteInstance(handle.id);
else await deps.deleteInstance(handle.id).catch(swallowAs(`${label}-sandbox: scratch delete`, undefined));
+ scratchKeyByName.delete(handle.id);
});
}
if (!tdOpts?.destroy) return;
@@ -192,7 +206,7 @@ export function createExecSandboxBase(deps: ExecSandboxBaseDeps): ExecSandboxBas
return handle;
} catch (err) {
- await teardown(handle).catch(swallowAs(`${label}-sandbox: teardown after failed provision`, undefined));
+ await cleanupFailedProvision({ teardown }, handle);
throw err;
}
}
diff --git a/src/sandbox/local-sandbox.ts b/src/sandbox/local-sandbox.ts
index 60ca308f6..895b2c570 100644
--- a/src/sandbox/local-sandbox.ts
+++ b/src/sandbox/local-sandbox.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { createHash, randomUUID } from "node:crypto";
import { orgId as configOrgId } from "../config.ts";
import { arch } from "node:os";
@@ -431,7 +432,7 @@ export function createLocalSandbox(workspace: WorkspaceStore, opts: LocalSandbox
return handle;
} catch (err) {
- await sandbox.teardown(handle).catch(swallowAs("local-sandbox: teardown after failed provision", undefined));
+ await cleanupFailedProvision(sandbox, handle);
throw err;
}
},
diff --git a/src/sandbox/modal-sandbox.ts b/src/sandbox/modal-sandbox.ts
index f9c10920b..5da5eed99 100644
--- a/src/sandbox/modal-sandbox.ts
+++ b/src/sandbox/modal-sandbox.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { randomUUID } from "node:crypto";
import type { WorkspaceLayer } from "../types.ts";
import type { WorkspaceStore } from "../workspace/workspace-store.ts";
@@ -405,6 +406,7 @@ export function createModalSandbox(workspace: WorkspaceStore, opts: ModalSandbox
async function withSessionUnlocked<T>(name: string, action: (session: ModalSession) => Promise<T>): Promise<T> {
const scratchKey = scratchKeyByName.get(name);
+ if (scratchKey === undefined && !scopeByName.has(name)) throw new Error("sandbox handle has been released");
const reviveScratch = async (): Promise<ModalSession> => {
const session = await client.create({ tags: tags("scratch") });
sessionByName.set(name, session);
@@ -744,7 +746,7 @@ export function createModalSandbox(workspace: WorkspaceStore, opts: ModalSandbox
return handle;
} catch (err) {
- await sandbox.teardown(handle).catch(swallowAs("modal-sandbox: teardown after failed provision", undefined));
+ await cleanupFailedProvision(sandbox, handle);
throw err;
}
},
@@ -903,8 +905,12 @@ export function createModalSandbox(workspace: WorkspaceStore, opts: ModalSandbox
}
activeScratch.delete(handle.id);
const session = sessionByName.get(handle.id);
+ if (session) {
+ if (tdOpts?.destroy) await session.terminate();
+ else await session.terminate().catch(swallowAs("modal-sandbox: scratch terminate", undefined));
+ }
sessionByName.delete(handle.id);
- if (session) await session.terminate().catch(swallowAs("modal-sandbox: scratch terminate", undefined));
+ scratchKeyByName.delete(handle.id);
});
}
if (tdOpts?.destroy && !scopeByName.has(handle.id)) return;
diff --git a/src/sandbox/porter-sandbox.ts b/src/sandbox/porter-sandbox.ts
index a3dd5e260..78cf4e721 100644
--- a/src/sandbox/porter-sandbox.ts
+++ b/src/sandbox/porter-sandbox.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { randomUUID } from "node:crypto";
import { NotFoundError } from "porter-sandbox";
import type { WorkspaceLayer } from "../types.ts";
@@ -333,7 +334,7 @@ export function createPorterSandbox(workspace: WorkspaceStore, opts: PorterSandb
return handle;
} catch (err) {
- await sandbox.teardown(handle).catch(swallowAs("porter-sandbox: teardown after failed provision", undefined));
+ await cleanupFailedProvision(sandbox, handle);
throw err;
}
},
@@ -435,9 +436,13 @@ export function createPorterSandbox(workspace: WorkspaceStore, opts: PorterSandb
if (e instanceof NotFoundError) return null;
throw e;
}));
- if (!target) return;
+ if (!target) {
+ scratchSlugByName.delete(handle.id);
+ return;
+ }
if (tdOpts?.destroy) await retirePorterBody(target, false);
else await retirePorterBody(target, false).catch(swallowAs("porter-sandbox: scratch terminate", undefined));
+ scratchSlugByName.delete(handle.id);
});
}
if (!tdOpts?.destroy) return;
diff --git a/src/sandbox/sandbox-routing.ts b/src/sandbox/sandbox-routing.ts
index e1580d3f4..76f1a428d 100644
--- a/src/sandbox/sandbox-routing.ts
+++ b/src/sandbox/sandbox-routing.ts
@@ -4,6 +4,7 @@ import type { DurableMap } from "../persistence/durable-map.ts";
import { swallow, swallowAs } from "../util/errors.ts";
import {
CapabilityUnsupportedError,
+ SandboxProvisionCleanupError,
supportsBlobStaging,
supportsProcessSessions,
type AgentComputerProfile,
@@ -182,7 +183,14 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
return { ...handle, backend: resource.backend, scopeId: resource.ownerScopeId, resourceId: resource.id };
}
const { name, sandbox } = await pick(scope);
- const handle = await sandbox.provision(layers, provOpts);
+ let handle: SandboxHandle;
+ try {
+ handle = await sandbox.provision(layers, provOpts);
+ } catch (error) {
+ if (error instanceof SandboxProvisionCleanupError)
+ throw new SandboxProvisionCleanupError({ ...error.handle, backend: name });
+ throw error;
+ }
const resourceId =
!provOpts?.scratch && scope ? await opts.resources?.recordLegacy(scope, name, handle) : undefined;
return { ...handle, backend: name, ...(scope ? { scopeId: scope } : {}), ...(resourceId ? { resourceId } : {}) };
diff --git a/src/sandbox/sandbox.ts b/src/sandbox/sandbox.ts
index 0229a3786..b2a6c8fe0 100644
--- a/src/sandbox/sandbox.ts
+++ b/src/sandbox/sandbox.ts
@@ -1,3 +1,4 @@
+import { swallow } from "../util/errors.ts";
import type { EgressPolicy, WorkspaceLayer } from "../types.ts";
export interface SandboxHandle {
@@ -13,6 +14,31 @@ export interface SandboxHandle {
scopeId?: string;
}
+export class SandboxProvisionCleanupError extends Error {
+ readonly handle: SandboxHandle;
+
+ constructor(handle: SandboxHandle) {
+ super("Disposable sandbox initialization cleanup failed");
+ this.name = "SandboxProvisionCleanupError";
+ this.handle = {
+ id: handle.id,
+ rootDir: handle.rootDir,
+ scratch: true,
+ ...(handle.backend ? { backend: handle.backend } : {}),
+ ...(handle.providerSandboxId ? { providerSandboxId: handle.providerSandboxId } : {}),
+ };
+ }
+}
+
+export async function cleanupFailedProvision(sandbox: Pick<Sandbox, "teardown">, handle: SandboxHandle): Promise<void> {
+ try {
+ await sandbox.teardown(handle, handle.scratch ? { destroy: true } : undefined);
+ } catch (error) {
+ if (handle.scratch) throw new SandboxProvisionCleanupError(handle);
+ swallow("sandbox: teardown after failed provision", error);
+ }
+}
+
export function hasParentPathSegment(path: string): boolean {
return path.split("/").includes("..");
}
diff --git a/src/sandbox/superserve-sandbox.ts b/src/sandbox/superserve-sandbox.ts
index 9f92109e0..1011de337 100644
--- a/src/sandbox/superserve-sandbox.ts
+++ b/src/sandbox/superserve-sandbox.ts
@@ -1,3 +1,4 @@
+import { cleanupFailedProvision } from "./sandbox.ts";
import { AsyncLocalStorage } from "node:async_hooks";
import { createHash, randomUUID } from "node:crypto";
import type { WorkspaceLayer } from "../types.ts";
@@ -622,10 +623,7 @@ export function createSuperserveSandbox(workspace: WorkspaceStore, opts: Superse
? provisionQueue(`scratch:${scratch.key}`, provisionAndPrepare)
: provisionQueue(scope, () => advisoryLock.withLock(lockKey(scope), provisionAndPrepare)));
} catch (err) {
- if (pendingHandle)
- await sandbox
- .teardown(pendingHandle)
- .catch(swallowAs("superserve-sandbox: teardown after failed provision", undefined));
+ if (pendingHandle) await cleanupFailedProvision(sandbox, pendingHandle);
throw err;
}
});
@@ -732,7 +730,10 @@ export function createSuperserveSandbox(workspace: WorkspaceStore, opts: Superse
}
activeScratch.delete(handle.id);
const live = liveByName.get(handle.id);
- if (!live) return;
+ if (!live) {
+ scratchKeyByName.delete(handle.id);
+ return;
+ }
try {
await live.session.kill();
} catch (err) {
@@ -740,6 +741,7 @@ export function createSuperserveSandbox(workspace: WorkspaceStore, opts: Superse
swallowAs("superserve-sandbox: scratch kill", undefined)(err);
}
dropLive(handle.id, live.session.id);
+ scratchKeyByName.delete(handle.id);
});
}
if (tdOpts?.destroy && !scopeByName.has(handle.id)) return;
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index 64a233808..4c8789b75 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -775,8 +775,8 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
const scratch = execOpts?.scratch === true;
const ownerAuth = execOpts?.ownerAuth === true;
const requestedCredentials = execOpts?.credentials ?? [];
- if (requestedCredentials.length && (scratch || execOpts?.reachTarget !== undefined || !writableScopeId)) {
- throw new Error("command credentials are available only on the scoped or owner computer");
+ if (requestedCredentials.length && (execOpts?.reachTarget !== undefined || !writableScopeId)) {
+ throw new Error("command credentials are available only on scoped, scratch, or owner computers");
}
const availableCredentials = new Map(
(
diff --git a/test/aws-role-cutover.test.ts b/test/aws-role-cutover.test.ts
index 612980a17..fd8f1d5d5 100644
--- a/test/aws-role-cutover.test.ts
+++ b/test/aws-role-cutover.test.ts
@@ -348,7 +348,12 @@ test("shared ACMECLI cutover isolates brokered STS without shrinking the existin
triggered: true,
ownerKeychainUnion: true,
}),
- /persistent control-plane deletion failure/,
+ (error: Error) => {
+ assert.equal(error.message, "Disposable sandbox destruction failed");
+ assert.equal(error.cause, undefined);
+ assert.ok(!error.stack?.includes("persistent control-plane deletion failure"));
+ return true;
+ },
);
built.sandbox.teardown = realTeardown;
assert.ok(stranded);
diff --git a/test/aws-sandbox.test.ts b/test/aws-sandbox.test.ts
index c98a17885..4aa470598 100644
--- a/test/aws-sandbox.test.ts
+++ b/test/aws-sandbox.test.ts
@@ -329,3 +329,25 @@ for (const writer of ["teardown", "reaper"] as const) {
await sb.destroyScope!(scope);
});
}
+
+test("failed overlapping preparation releases only its own sandbox lease", async () => {
+ const fake = installFakeMicrovm();
+ let failPreparation = false;
+ const sb = makeSandbox(fake, {
+ fetchImpl: (async (url: string | URL | Request, init?: RequestInit) => {
+ if (failPreparation && new URL(String(url)).pathname === "/exec") {
+ failPreparation = false;
+ throw new Error("injected preparation failure");
+ }
+ return fake.fetchImpl(url, init);
+ }) as typeof fetch,
+ });
+ const layers = rw(scopeId("personal", "overlapping-preparation"));
+ const first = await sb.provision(layers);
+ failPreparation = true;
+ await assert.rejects(sb.provision(layers), /injected preparation failure/);
+ assert.equal(fake.bodies.get(first.id)?.state, "RUNNING");
+ assert.equal(fake.s3store.size, 0);
+ await sb.teardown(first);
+ assert.equal(fake.bodies.get(first.id)?.state, "SUSPENDED");
+});
diff --git a/test/e2b-sandbox.test.ts b/test/e2b-sandbox.test.ts
index f78ff6b31..50e98b4fd 100644
--- a/test/e2b-sandbox.test.ts
+++ b/test/e2b-sandbox.test.ts
@@ -1,3 +1,4 @@
+import { SandboxProvisionCleanupError } from "../src/sandbox/sandbox.ts";
import { pollProcess } from "../src/sandbox/process-poll.ts";
import { test, after, beforeEach } from "node:test";
import { Readable } from "node:stream";
@@ -701,3 +702,64 @@ test("repeated destroy teardown never targets an unrelated default scope", async
assert.deepEqual(await store.get("default"), defaultRecord);
assert.equal(await store.get(scope), null);
});
+
+test("forced scratch destruction surfaces failure and retries the same live session", async () => {
+ let kills = 0;
+ const client = {
+ ...fake.client,
+ async create(opts: Parameters<typeof fake.client.create>[0]) {
+ const session = await fake.client.create(opts);
+ return {
+ ...session,
+ async kill() {
+ if (kills++ === 0) throw new Error("transient delete failure");
+ await session.kill();
+ },
+ };
+ },
+ };
+ const box = make({ client });
+ const handle = await box.provision(layers, { scratch: { key: "destroy-retry" } });
+ await assert.rejects(box.teardown(handle, { destroy: true }), /transient delete failure/);
+ await box.teardown(handle, { destroy: true });
+ assert.equal(kills, 2);
+});
+
+test("released scratch handles cannot recreate a persistent sandbox", async () => {
+ const handle = await sandbox.provision(layers, { scratch: { key: "released-handle" } });
+ await sandbox.teardown(handle, { destroy: true });
+ await assert.rejects(sandbox.run(handle, "true"), /handle has been released/);
+});
+
+test("failed scratch preparation retains the live session when rollback fails", async () => {
+ let kills = 0;
+ const box = make({
+ client: {
+ ...fake.client,
+ async create(opts: Parameters<typeof fake.client.create>[0]) {
+ const session = await fake.client.create(opts);
+ return {
+ ...session,
+ async runCommand() {
+ throw new Error("preparation failed");
+ },
+ async kill() {
+ if (kills++ === 0) throw new Error("sentinel-secret");
+ await session.kill();
+ },
+ };
+ },
+ },
+ });
+ let pending: import("../src/sandbox/sandbox.ts").SandboxHandle | undefined;
+ await assert.rejects(box.provision(layers, { scratch: { key: "failed-preparation" } }), (error: Error) => {
+ assert.ok(error instanceof SandboxProvisionCleanupError);
+ pending = error.handle;
+ assert.equal(error.cause, undefined);
+ assert.ok(!error.message.includes("sentinel-secret"));
+ return true;
+ });
+ assert.ok(pending);
+ await box.teardown(pending, { destroy: true });
+ assert.equal(kills, 2);
+});
diff --git a/test/execute-credential-preparation.test.ts b/test/execute-credential-preparation.test.ts
index ea830d5c9..9e6e1b99c 100644
--- a/test/execute-credential-preparation.test.ts
+++ b/test/execute-credential-preparation.test.ts
@@ -191,7 +191,7 @@ test("owner credentials cannot be requested on scoped or scratch workspaces", as
const selected = { ...credential(events, "owner"), scope: "owner" as const };
const { ctx, runs } = context(events, [selected], { provisionOwnerAuth: async () => handle });
await assert.rejects(ctx.execute("true", { credentials: ["owner"] }), /requires scope:owner/);
- await assert.rejects(ctx.execute("true", { credentials: ["owner"], scratch: true }), /only on the scoped/);
+ await assert.rejects(ctx.execute("true", { credentials: ["owner"], scratch: true }), /requires scope:owner/);
assert.deepEqual(events, []);
await ctx.execute("true", { credentials: ["owner"], ownerAuth: true });
assert.equal(runs.length, 1);
diff --git a/test/execute-scratch.test.ts b/test/execute-scratch.test.ts
index c0f1c02b4..49436763e 100644
--- a/test/execute-scratch.test.ts
+++ b/test/execute-scratch.test.ts
@@ -1,3 +1,4 @@
+import { SandboxProvisionCleanupError, cleanupFailedProvision } from "../src/sandbox/sandbox.ts";
import { execFileSync } from "node:child_process";
import { createTurnSandboxes, type TurnSandboxContext } from "../src/core/orchestrator/sandboxes.ts";
import { fakeSprites } from "./support/auto-fake-sprites.ts";
@@ -161,10 +162,12 @@ test("flag ON: the description advertises the routing policy truthfully", () =>
const [execute] = createAgentTools({ current: tc }, { scratchExec: true });
const desc = (execute as unknown as { description: string }).description;
assert.match(desc, /"scoped" \(DEFAULT\)/);
- assert.match(desc, /Prefer it for heavy self-contained work/);
- assert.match(desc, /NO logins, NO credentials/);
- assert.match(desc, /NOTHING persists/);
- assert.match(desc, /re-run it with scope:"scoped"/);
+ assert.match(desc, /Use it for self-contained commands and API work/);
+ assert.match(desc, /only credentials explicitly requested/);
+ assert.doesNotMatch(JSON.stringify(execute), /credential-free|blank, instant/);
+ assert.match(desc, /including Files/);
+ assert.match(desc, /local files are discarded after the turn/);
+ assert.match(desc, /Use scope:"scoped" when you need existing workspace files/);
assert.doesNotMatch((legacy as unknown as { description: string }).description, /scratch/i);
});
@@ -183,7 +186,7 @@ const dm = (text: string): TurnRequest => ({
text,
});
-test("a scratch turn runs on a separate volumeless box with NO capability tokens in its env", async () => {
+test("a scratch turn runs on a separate volumeless box with scoped capability tokens", async () => {
const { app } = freshApp({ signingSecret: "s3cret", apiBaseUrl: "https://core.test" });
const scoped = await app.turn(dm("!run printenv AGENT_API_TOKEN"));
@@ -195,7 +198,7 @@ test("a scratch turn runs on a separate volumeless box with NO capability tokens
const scratch = await app.turn(dm("!scratch printenv AGENT_API_TOKEN"));
assert.equal(scratch.status, "ok");
- assert.equal(scratch.reply, "(exit 1)", "the scratch box is credential-free — no capability token");
+ assert.equal(scratch.reply, "<redacted:credential>", "scoped capability tokens are usable but masked in output");
assert.ok(
fakeSprites.names().some((n) => n.startsWith("qm-personal-u1-")),
@@ -265,7 +268,7 @@ test("execute exposes only requested keychain environment values to one command"
assert.equal(scopedHandle.env, undefined, "command credentials never mutate SandboxHandle");
});
-test("execute rejects unavailable, conflicting, and scratch credential requests", async () => {
+test("execute rejects unavailable, conflicting, and reached credential requests", async () => {
const { ctx } = routingCtx({
commandCredentials: [
{ handle: "kc_one12345678", env: [{ key: "TOKEN", value: "one" }] },
@@ -279,8 +282,8 @@ test("execute rejects unavailable, conflicting, and scratch credential requests"
/conflicting environment key/,
);
await assert.rejects(
- ctx.execute("true", { scratch: true, credentials: ["kc_one12345678"] }),
- /scoped or owner computer/,
+ ctx.execute("true", { reachTarget: "#other", credentials: ["kc_one12345678"] }),
+ /scoped, scratch, or owner computers/,
);
});
@@ -530,3 +533,213 @@ test("scoped command wrappers preserve selected AWS credentials and clear unsele
);
assert.equal(result.stdout, "passed");
});
+
+test("scratch credentials are selected per command and masked before returning", async () => {
+ const environments: Array<Record<string, string> | undefined> = [];
+ const { ctx } = routingCtx({
+ provisionScratch: async () => ({ ...scratchHandle, env: { AGENT_API_TOKEN: "scope-capability" } }),
+ commandCredentials: [
+ { handle: "selected", env: [{ key: "TOKEN", value: "selected-secret" }] },
+ { handle: "unselected", env: [{ key: "OTHER_TOKEN", value: "other-secret" }] },
+ { handle: "owner", scope: "owner", env: [{ key: "OWNER_TOKEN", value: "owner-secret" }] },
+ ],
+ sandbox: {
+ async run(handle: SandboxHandle) {
+ environments.push(handle.env);
+ return { stdout: Object.values(handle.env ?? {}).join(" "), stderr: "", code: 0, timedOut: false };
+ },
+ } as unknown as Sandbox,
+ });
+ const result = await ctx.execute("env", { scratch: true, credentials: ["selected"] });
+ assert.equal(result.stdout, "<redacted:credential> <redacted:credential>");
+ assert.equal(environments[0]?.TOKEN, "selected-secret");
+ assert.equal(environments[0]?.OTHER_TOKEN, undefined);
+ await ctx.execute("env", { scratch: true });
+ assert.equal(environments[1]?.TOKEN, undefined);
+ await assert.rejects(ctx.execute("env", { scratch: true, credentials: ["owner"] }), /requires scope:owner/);
+});
+
+function turnBoxes(sandbox: Partial<Sandbox>, transferId = "turn-a") {
+ const events: import("../src/audit/audit-log.ts").AuditEvent[] = [];
+ const errors: unknown[] = [];
+ const boxes = createTurnSandboxes({
+ deps: {
+ sandbox,
+ auditLog: { record: (event: import("../src/audit/audit-log.ts").AuditEvent) => events.push(event) },
+ errors: { record: (...args: unknown[]) => errors.push(args) },
+ },
+ input: { runId: "run-1" },
+ actor: { id: "U1" },
+ session: { id: "session-1" },
+ transferId,
+ scopeId: scopeId("channel", "C1"),
+ memoryScopeId: scopeId("channel", "C1"),
+ connectorEnv: { AGENT_API_TOKEN: "scope-capability" },
+ credentialCutoverServices: [],
+ resolution: {
+ layers: [
+ { scopeId: scopeId("channel", "C1"), mode: "rw", mountPath: "" },
+ { scopeId: scopeId("org", "global"), mode: "ro", mountPath: "global" },
+ ],
+ },
+ } as unknown as TurnSandboxContext);
+ return { boxes, events, errors };
+}
+
+test("scratch provisioning is singleflight within a turn and isolated across turns", async () => {
+ const provisions: Parameters<Sandbox["provision"]>[] = [];
+ const releases: Parameters<Sandbox["teardown"]>[] = [];
+ const sandbox: Partial<Sandbox> = {
+ async provision(...args) {
+ provisions.push(args);
+ await Promise.resolve();
+ return { ...scratchHandle, id: args[1]!.scratch!.key, backend: "local" };
+ },
+ async teardown(...args) {
+ releases.push(args);
+ },
+ };
+ const first = turnBoxes(sandbox);
+ const second = turnBoxes(sandbox, "turn-b");
+ const [a, b, c] = await Promise.all([
+ first.boxes.provisionScratch(),
+ first.boxes.provisionScratch(),
+ second.boxes.provisionScratch(),
+ ]);
+ assert.equal(a, b);
+ assert.notEqual(a.id, c.id);
+ assert.equal(provisions.length, 2);
+ for (const [layers, opts] of provisions) {
+ assert.deepEqual(
+ layers.map((layer) => layer.mountPath),
+ ["global"],
+ );
+ assert.deepEqual(opts?.env, { AGENT_API_TOKEN: "scope-capability" });
+ }
+ await first.boxes.reclaimBox();
+ await second.boxes.reclaimBox();
+ assert.equal(releases.length, 2);
+ assert.ok(releases.every(([, opts]) => opts?.destroy === true));
+ assert.deepEqual(
+ first.events.map((event) => event.action),
+ ["sandbox.scratch.provision_started", "sandbox.scratch.provision_ready", "sandbox.scratch.released"],
+ );
+ assert.equal(new Set(first.events.map((event) => event.resource)).size, 1);
+ const detail = JSON.parse(first.events.at(-1)!.detail!);
+ assert.equal(detail.runId, "run-1");
+ assert.equal(detail.sessionId, "session-1");
+ assert.equal(detail.sandboxId, a.id);
+ assert.equal(detail.backend, "local");
+ assert.ok(detail.cleanupMs >= 0);
+ assert.ok(!JSON.stringify(first.events).includes("scope-capability"));
+});
+
+test("reclaim waits for in-flight scratch creation before destroying its handle", async () => {
+ const ready = Promise.withResolvers<SandboxHandle>();
+ const destroyed: string[] = [];
+ const { boxes } = turnBoxes({
+ provision: () => ready.promise,
+ async teardown(handle) {
+ destroyed.push(handle.id);
+ },
+ });
+ const provision = boxes.provisionScratch();
+ const reclaim = boxes.reclaimBox();
+ ready.resolve(scratchHandle);
+ await Promise.all([provision, reclaim]);
+ assert.deepEqual(destroyed, [scratchHandle.id]);
+ assert.equal(boxes.scratchBox.handle, null);
+});
+
+test("scratch destruction failures remain visible and retain the handle for retry", async () => {
+ let attempts = 0;
+ let fail = true;
+ const { boxes, events, errors } = turnBoxes({
+ async provision() {
+ return scratchHandle;
+ },
+ async teardown() {
+ attempts++;
+ if (fail) throw new Error("sentinel-secret");
+ },
+ });
+ await boxes.provisionScratch();
+ await assert.rejects(boxes.reclaimBox(), (error: Error) => {
+ assert.equal(error.message, "Disposable sandbox destruction failed");
+ assert.equal(error.cause, undefined);
+ assert.ok(!error.stack?.includes("sentinel-secret"));
+ return true;
+ });
+ assert.equal(attempts, 3);
+ assert.equal(boxes.scratchBox.handle, scratchHandle);
+ assert.equal(events.filter((event) => event.action === "sandbox.scratch.release_failed").length, 1);
+ assert.equal(events.filter((event) => event.action === "sandbox.scratch.released").length, 0);
+ assert.ok(!JSON.stringify({ events, errors }).includes("sentinel-secret"));
+ assert.equal(errors.length, 1);
+ fail = false;
+ await boxes.reclaimBox();
+ assert.equal(boxes.scratchBox.handle, null);
+});
+
+test("failed scratch provisioning is audited safely and can retry", async () => {
+ let attempts = 0;
+ const { boxes, events } = turnBoxes({
+ async provision() {
+ if (attempts++ === 0) throw new Error("sentinel-secret");
+ return scratchHandle;
+ },
+ async teardown() {},
+ });
+ await assert.rejects(boxes.provisionScratch(), /sentinel-secret/);
+ await boxes.provisionScratch();
+ await boxes.reclaimBox();
+ assert.deepEqual(
+ events.map((event) => event.action),
+ [
+ "sandbox.scratch.provision_started",
+ "sandbox.scratch.provision_failed",
+ "sandbox.scratch.provision_started",
+ "sandbox.scratch.provision_ready",
+ "sandbox.scratch.released",
+ ],
+ );
+ assert.ok(!JSON.stringify(events).includes("sentinel-secret"));
+});
+
+for (const recovers of [true, false]) {
+ test(`failed scratch initialization preserves safe cleanup identity; recovery=${recovers}`, async () => {
+ let destroys = 0;
+ const partial = { ...scratchHandle, backend: "local", env: { TOKEN: "sentinel-secret" } };
+ const sandbox: Partial<Sandbox> = {
+ async provision() {
+ await cleanupFailedProvision({ teardown: sandbox.teardown! }, partial);
+ throw new Error("initialization failed");
+ },
+ async teardown(handle, opts) {
+ assert.equal(handle.id, partial.id);
+ assert.equal(opts?.destroy, true);
+ if (destroys++ === 0 || !recovers) throw new Error("sentinel-secret");
+ },
+ };
+ const { boxes, events, errors } = turnBoxes(sandbox);
+ await assert.rejects(boxes.provisionScratch(), (error: Error) => {
+ assert.ok(error instanceof SandboxProvisionCleanupError);
+ assert.equal(error.handle.id, partial.id);
+ assert.equal(error.handle.env, undefined);
+ assert.equal(error.cause, undefined);
+ assert.ok(!JSON.stringify(error).includes("sentinel-secret"));
+ return true;
+ });
+ await assert.rejects(boxes.provisionScratch(), /cleanup is still pending/);
+ assert.equal(boxes.scratchBox.handle, null);
+ assert.equal(boxes.scratchBox.pending?.id, partial.id);
+ if (recovers) await boxes.reclaimBox();
+ else await assert.rejects(boxes.reclaimBox(), /Disposable sandbox destruction failed/);
+ const failure = events.find((event) => event.action === "sandbox.scratch.provision_failed")!;
+ assert.equal(JSON.parse(failure.detail!).sandboxId, partial.id);
+ assert.equal(JSON.parse(failure.detail!).backend, "local");
+ assert.equal(events.at(-1)?.action, `sandbox.scratch.${recovers ? "released" : "release_failed"}`);
+ assert.ok(!JSON.stringify({ events, errors }).includes("sentinel-secret"));
+ assert.equal(boxes.scratchBox.pending === null, recovers);
+ });
+}
diff --git a/test/modal-sandbox.test.ts b/test/modal-sandbox.test.ts
index aca31d2e4..37e8c7a6d 100644
--- a/test/modal-sandbox.test.ts
+++ b/test/modal-sandbox.test.ts
@@ -1144,3 +1144,18 @@ test("untracked scope sandboxes are terminated after a grace period while scratc
assert.deepEqual(running, new Set([tracked, scratch, foreign]));
assert.equal(running.has(orphan), false);
});
+
+test("forced scratch destruction surfaces failure and retries the same live session", async () => {
+ const handle = await sandbox.provision(layers, { scratch: { key: "destroy-retry" } });
+ fake.failTerminateOnce();
+ await assert.rejects(sandbox.teardown(handle, { destroy: true }));
+ assert.equal(fake.runningCount(), 1);
+ await sandbox.teardown(handle, { destroy: true });
+ assert.equal(fake.runningCount(), 0);
+});
+
+test("released scratch handles cannot recreate a persistent sandbox", async () => {
+ const handle = await sandbox.provision(layers, { scratch: { key: "released-handle" } });
+ await sandbox.teardown(handle, { destroy: true });
+ await assert.rejects(sandbox.run(handle, "true"), /handle has been released/);
+});
diff --git a/test/sandbox-routing.test.ts b/test/sandbox-routing.test.ts
index a493986e6..a34be28d1 100644
--- a/test/sandbox-routing.test.ts
+++ b/test/sandbox-routing.test.ts
@@ -1,3 +1,4 @@
+import { SandboxProvisionCleanupError } from "../src/sandbox/sandbox.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
import { createSandboxRouter, type SandboxRoute } from "../src/sandbox/sandbox-routing.ts";
@@ -371,3 +372,24 @@ for (const combined of [true, false]) {
assert.deepEqual(calls, combined ? ["combined:old:keep"] : ["remove:old", "list:keep"]);
});
}
+
+test("failed scratch initialization keeps its routed backend for cleanup", async () => {
+ const { router, sprites, seed } = build({ "personal:partial": { backend: "sprites" } });
+ await seed();
+ sprites.provision = async () => {
+ throw new SandboxProvisionCleanupError({ id: "partial", rootDir: "/workspace", scratch: true });
+ };
+ let pending: SandboxHandle | undefined;
+ await assert.rejects(
+ router.provision([], { scratch: { key: "turn" }, routeScopeId: "personal:partial" }),
+ (error: Error) => {
+ assert.ok(error instanceof SandboxProvisionCleanupError);
+ pending = error.handle;
+ assert.equal(pending.backend, "sprites");
+ return true;
+ },
+ );
+ assert.ok(pending);
+ await router.teardown(pending, { destroy: true });
+ assert.deepEqual(sprites.calls, ["teardown"]);
+});
diff --git a/test/sprites-sandbox.test.ts b/test/sprites-sandbox.test.ts
index 6eab4db5d..baad4eabb 100644
--- a/test/sprites-sandbox.test.ts
+++ b/test/sprites-sandbox.test.ts
@@ -1,3 +1,4 @@
+import { SandboxProvisionCleanupError } from "../src/sandbox/sandbox.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
import { createMemoryAdvisoryLock } from "../src/persistence/advisory-lock.ts";
import { pollProcess } from "../src/sandbox/process-poll.ts";
@@ -781,3 +782,28 @@ test("failed hydration and failed deletion remain pending across adapters withou
assert.equal(await b.readFile(restored, "ledger"), "saved");
assert.equal(await initializationStore.get(h.id), null);
});
+
+test("scratch allocation is deleted when resource initialization fails", async () => {
+ const box = make({ memoryMb: 4096 });
+ fake.failNext(400, { match: (call) => call.path.endsWith("/policy/resources") });
+ await assert.rejects(box.provision(layers, { scratch: { key: "partial-allocation" } }));
+ assert.ok(!fake.names().some((name) => name.includes("scratch")));
+});
+
+test("failed scratch initialization and deletion retain a safe retryable identity", async () => {
+ const box = make({ memoryMb: 4096 });
+ fake.failNext(400, { match: (call) => call.path.endsWith("/policy/resources") });
+ fake.failNext(400, { match: (call) => call.method === "DELETE" });
+ let pending: import("../src/sandbox/sandbox.ts").SandboxHandle | undefined;
+ await assert.rejects(box.provision(layers, { scratch: { key: "failed-rollback" } }), (error: Error) => {
+ assert.ok(error instanceof SandboxProvisionCleanupError);
+ pending = error.handle;
+ assert.equal(pending.backend, "sprites");
+ assert.ok(fake.names().includes(pending.id));
+ assert.equal(error.cause, undefined);
+ return true;
+ });
+ assert.ok(pending);
+ await box.teardown(pending, { destroy: true });
+ assert.ok(!fake.names().includes(pending.id));
+});