Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Retire legacy sandbox provider routing (#2019)

Regan Bell1ea79127ea97
diff --git a/cli/src/config.ts b/cli/src/config.ts
index fff93fd0d..28d7bab4f 100644
--- a/cli/src/config.ts
+++ b/cli/src/config.ts
@@ -708,10 +708,7 @@ function validate(raw: unknown, path: string): QmConfig {
`${path}: "env.core.SANDBOX_BACKEND" is blank — name the backend core should run, or remove the key; every target forwards env.core verbatim, so a blank value leaves core with no backend`,
);
}
- if (
- (effectiveSandboxBackend({ env, sandbox }) === "superserve" || scopeUsesSuperserve(env.core)) &&
- !env.core?.SUPERSERVE_TEMPLATE?.trim()
- ) {
+ if (effectiveSandboxBackend({ env, sandbox }) === "superserve" && !env.core?.SUPERSERVE_TEMPLATE?.trim()) {
throw new CliError(
`${path}: the superserve sandbox backend requires env.core.SUPERSERVE_TEMPLATE (the ready qm-agent-<release> template); core refuses to start without it`,
);
@@ -979,30 +976,11 @@ export function validatePortalTrust(config: QmConfig, path = "config", secrets?:
}
}
-function scopeUsesSuperserve(core: Record<string, string> | undefined): boolean {
- try {
- const scopes: unknown = JSON.parse(core?.SANDBOX_SCOPE_BACKENDS || "{}");
- return Boolean(
- scopes &&
- typeof scopes === "object" &&
- !Array.isArray(scopes) &&
- Object.values(scopes).some((value) => typeof value === "string" && value.trim() === "superserve"),
- );
- } catch {
- return false;
- }
-}
-
export function requiresAwsMicrovmImage(config: QmConfig): boolean {
if (config.target !== "aws") return false;
const core = config.env.core;
if ((core?.DEPLOY_PROVIDER?.trim() || "aws") === "aws") return true;
- if ((core?.SANDBOX_BACKEND?.trim() || config.sandbox?.backend || "aws") === "aws") return true;
- const scopes: unknown = JSON.parse(core?.SANDBOX_SCOPE_BACKENDS || "{}");
- if (!scopes || typeof scopes !== "object" || Array.isArray(scopes)) {
- throw new CliError("SANDBOX_SCOPE_BACKENDS must be an object");
- }
- return Object.values(scopes).some((value) => typeof value === "string" && value.trim() === "aws");
+ return (core?.SANDBOX_BACKEND?.trim() || config.sandbox?.backend || "aws") === "aws";
}
function validateAwsFrontDoor(config: QmConfig, path: string): void {
diff --git a/cli/src/secrets.ts b/cli/src/secrets.ts
index 77fe6ca6c..c02dc5c7d 100644
--- a/cli/src/secrets.ts
+++ b/cli/src/secrets.ts
@@ -541,11 +541,7 @@ function conditionMatches(config: QmConfig, condition: SecretCondition): boolean
config.env.core?.SANDBOX_BACKEND ??
config.sandbox?.backend ??
targetEnvDefault(config, "core", "SANDBOX_BACKEND");
- if (backend?.trim() === condition.backend) return true;
- const scopes: unknown = JSON.parse(config.env.core?.SANDBOX_SCOPE_BACKENDS || "{}");
- if (!scopes || typeof scopes !== "object" || Array.isArray(scopes))
- throw new Error("SANDBOX_SCOPE_BACKENDS must be an object");
- return Object.values(scopes).some((value) => typeof value === "string" && value.trim() === condition.backend);
+ return backend?.trim() === condition.backend;
}
if (condition.kind === "service-enabled") return config.services.includes(condition.service);
if (condition.kind === "service-absent") return !config.services.includes(condition.service);
@@ -775,8 +771,7 @@ function requiresOtherEmailTransport(config: QmConfig, condition: SecretConditio
function conditionClause(condition: SecretCondition): string {
if (condition.kind === "background-work-control") return "aws.backgroundWorkControl is enabled";
- if (condition.kind === "sandbox-backend")
- return `SANDBOX_BACKEND or SANDBOX_SCOPE_BACKENDS selects ${condition.backend}`;
+ if (condition.kind === "sandbox-backend") return `SANDBOX_BACKEND selects ${condition.backend}`;
if (condition.kind === "service-enabled") return `the ${condition.service} service is enabled`;
if (condition.kind === "service-absent") return `the ${condition.service} service is not enabled`;
if (condition.kind === "all") return condition.conditions.map(conditionClause).join(" and ");
diff --git a/cli/test/config.test.ts b/cli/test/config.test.ts
index 63cfb91a2..42ada5796 100644
--- a/cli/test/config.test.ts
+++ b/cli/test/config.test.ts
@@ -623,8 +623,7 @@ test("AWS validates release labels, unique coordinates, Fargate sizes, and owned
},
},
({ path }) => {
- if (scopeBackend === "aws") assert.throws(() => loadConfigAt(path), /AWS_DEPLOY_IMAGE/);
- else assert.equal(loadConfigAt(path).config.env.core?.DEPLOY_PROVIDER, "fly");
+ assert.equal(loadConfigAt(path).config.env.core?.DEPLOY_PROVIDER, "fly");
},
);
}
@@ -970,20 +969,6 @@ test("superserve backend requires the agent template in env.core", () => {
sandbox: { backend: "local" },
env: { core: { SANDBOX_SCOPE_BACKENDS: JSON.stringify({ personal: "superserve" }) } },
},
- ({ path }) => {
- assert.throws(() => loadConfigAt(path), /superserve sandbox backend requires env.core.SUPERSERVE_TEMPLATE/);
- },
- );
- withConfig(
- {
- sandbox: { backend: "local" },
- env: {
- core: {
- SANDBOX_SCOPE_BACKENDS: JSON.stringify({ personal: "superserve" }),
- SUPERSERVE_TEMPLATE: "qm-agent-1.0.0",
- },
- },
- },
({ path }) => assert.doesNotThrow(() => loadConfigAt(path)),
);
});
diff --git a/cli/test/secrets.test.ts b/cli/test/secrets.test.ts
index 4ad6bf114..be6ba20ea 100644
--- a/cli/test/secrets.test.ts
+++ b/cli/test/secrets.test.ts
@@ -402,22 +402,17 @@ test("combined auth rejects two source secrets for the same environment name", (
);
});
-test("scope-selected providers require both Modal and Sprites credentials", () => {
+test("the retired SANDBOX_SCOPE_BACKENDS map no longer requires provider credentials", () => {
const config = makeConfig({
- env: { core: { SANDBOX_BACKEND: "sprites", SANDBOX_SCOPE_BACKENDS: '{"personal":"modal","channel":"sprites"}' } },
+ env: {
+ core: { SANDBOX_BACKEND: "sprites", SANDBOX_SCOPE_BACKENDS: '{"personal":"modal","channel":"superserve"}' },
+ },
});
const required = computedSecrets(config)
.filter((secret) => secret.required)
.map((secret) => secret.name);
- for (const name of ["SPRITES_TOKEN", "MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"])
- assert.ok(required.includes(name), name);
-});
-
-test("a scope routed to superserve requires its API key even when it is not the primary backend", () => {
- const config = makeConfig({
- env: { core: { SANDBOX_BACKEND: "local", SANDBOX_SCOPE_BACKENDS: '{"channel":"superserve"}' } },
- });
- assert.equal(secretByName(config, "SUPERSERVE_API_KEY").required, true);
+ assert.ok(required.includes("SPRITES_TOKEN"));
+ for (const name of ["MODAL_TOKEN_ID", "SUPERSERVE_API_KEY"]) assert.ok(!required.includes(name), name);
});
test("shared Fly publishing requires private peers only when selected", () => {
diff --git a/docs/sandbox-resources.md b/docs/sandbox-resources.md
index 46f00b12c..a91132e03 100644
--- a/docs/sandbox-resources.md
+++ b/docs/sandbox-resources.md
@@ -2,9 +2,9 @@
A sandbox is an independently recorded resource with an owning scope, provider, backing identity, and lifecycle state. Creating a sandbox provisions a blank machine without copying files or changing a default. Setting a default changes routing only. Background jobs retain the target on which they started.
-Before activation, agents have `execute`, `background`, and `sandbox` with `status` and `restart`. With `SANDBOX_RESOURCES_ENABLED=true`, a single `sandbox` tool replaces the advertised `execute` and `background` tools and provides management, command execution, and process control. `list` returns the available providers and supported actions. Unsupported provider operations fail explicitly. Files publication is separate from sandbox management.
+Sandbox resources are always on. A single `sandbox` tool provides management, command execution, and process control. `list` returns the available providers and supported actions. Unsupported provider operations fail explicitly. Files publication is separate from sandbox management.
-`sandbox` actions `exec` and `start_process` accept `sandbox_id`. Without a target, execution requires the scope's stored default after activation. `set_default` accepts an ID or null; null clears the default. A new scope has no default. Retiring a sandbox requires clearing its default and stopping its jobs first. Retirement is available only for providers with direct scope deletion. It never provisions or restores a machine. Once retirement begins, execution stays blocked; interrupted or failed cleanup remains visible and can be retried. Retirement deletes its working state, so durable outputs should be published to Files or git beforehand.
+`sandbox` actions `exec` and `start_process` accept `sandbox_id`. Without a target, execution requires the scope's stored default. `set_default` accepts an ID or null; null clears the default. A new scope has no default. Retiring a sandbox requires clearing its default and stopping its jobs first. Retirement is available only for providers with direct scope deletion. It never provisions or restores a machine. Once retirement begins, execution stays blocked; interrupted or failed cleanup remains visible and can be retried. Retirement deletes its working state, so durable outputs should be published to Files or git beforehand.
In Isolated posture, agent inventory and operations stay in the current owning scope. In Open posture, authenticated human turns and owner-authorized scheduled turns can also target the acting person's personal sandboxes and Open shared sandboxes where they are a current member. Access is rechecked for each operation; changing conversations does not transfer ownership or grant other participants personal access. Cross-context execution uses the target's existing workspace without copying the calling conversation's credentials, files, or capability tokens onto it. Defaults remain local to their owning scope. Cross-context commands must satisfy both the calling conversation's and target sandbox's command policies. Network access is narrowed to satisfy both egress policies. Provider-native recovery status includes its own expiry; a sandbox record is not an indefinite backup guarantee.
@@ -30,12 +30,14 @@ Process actions also accept optional `purpose` for approval context. Unrelated f
Execution and process handlers retain their existing approval and output-screening paths. Strict sandbox approvals are scoped to each action (`tool:sandbox:exec`, for example); an older broad `tool:sandbox` grant does not authorize newly exposed command or process actions. Transcript entries identify the actual `sandbox` action. Files publication, application deployment, and file read/write remain separate capabilities; unsupported resize and clone actions are not advertised.
-## Staged activation
+## Upgrade and rollback
-The feature defaults off. Deploy this reader-compatible version to every core and worker and retain a compatible rollback release before enabling it. Drain pre-feature cores and their in-flight work before activation. Compatible readers coordinate legacy record publication and migrations with the activation lock; ordinary provider provisioning remains concurrent. An older binary cannot be made safe by a lock introduced in a newer binary.
+Resources and explicit defaults are always enabled. At startup, a one-time, locked import adopts old routing entries, known session scopes, and provider records. It preserves existing defaults (including an explicit null), resource IDs, and original backing identities. It makes no provider calls or disk copies. Inferred resources start unverified; the completion marker is written last, so an interrupted import can be retried. Before writing adoption state, the import refuses any newly selected default whose provider is not configured, naming the affected scope and provider. Installations with the existing `explicit-defaults` marker have already completed this import.
-On activation, startup completes a durable, locked backfill before accepting new work. It preserves explicit defaults, existing routing, session scopes, provider records, and original backing identities. It makes no provider calls or disk copies. Inferred resources start unverified. The activation marker is written last, so an interrupted backfill can be retried. Legacy provisioning selected before activation may complete afterward: its inventory publication fills only a missing default and preserves an explicit selection or null. Legacy migrations complete before backfill or are refused after activation.
+The old routing table is retained only as upgrade input. It is never read when selecting a computer, and there are no routing-table write or migration endpoints. `SANDBOX_SCOPE_BACKENDS` is accepted only to interpret old bindings during the import; remove it afterwards. `SANDBOX_RESOURCES_ENABLED` no longer changes behavior.
-The activation marker is permanent: after it exists, a missing default means no default even when the feature flag is turned off again. Turning the flag off restores the legacy `execute` and `background` tool names and hides new management operations; it does not restore implicit computer creation or move running jobs. Rollback must use a reader-compatible release.
+Before upgrading from a release without resource-aware readers, drain its cores and workers. Rollback must use a resource-aware release that honors the permanent completion marker. A missing default after import means no default, not permission to recreate an old scoped computer.
-Agent-facing migration is retired. Existing operator migration refuses scopes with managed defaults. Provision, verify on the named target, then select a default explicitly when moving work between providers; copying files is optional.
+Scoped commands require an explicit target or selected default. Disposable scratch and owner-auth computers use the selected computer's provider without reusing its disk or resource identity; with no selection they use the installation provider, without creating a default. An unavailable selected provider fails explicitly rather than substituting another provider.
+
+To move work between providers, create a computer, restore the required work from git or Files, verify it, and select it as the new default. Selection does not copy files or migrate running jobs.
diff --git a/docs/superserve.md b/docs/superserve.md
index dc4d9f767..68f4ae640 100644
--- a/docs/superserve.md
+++ b/docs/superserve.md
@@ -34,9 +34,8 @@ key through the CLI's secret configuration:
}
```
-`env.core.SANDBOX_BACKEND` overrides `sandbox.backend`. To select Superserve for
-individual scope kinds, use `SANDBOX_SCOPE_BACKENDS`; the same key, template, and
-database requirements apply.
+`env.core.SANDBOX_BACKEND` overrides `sandbox.backend`. Agents and admins select Superserve per
+scope by creating a Superserve sandbox and setting it as the default.
For local development, export the key and template and run
`npm run dev-instance -- --sandbox superserve`.
diff --git a/docs/swarms.md b/docs/swarms.md
index cc6a8e497..16d955b7c 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -9,8 +9,7 @@ with a `Swarm worker` title. Worker transcripts remain read-only for ordinary me
## Deployment
Use Postgres for production (`DATABASE_URL`, `SESSION_STORE=postgres`, and
-`RUN_STORE=postgres`) and enable the existing sandbox inventory with
-`SANDBOX_RESOURCES_ENABLED=true`. Configure a sandbox backend with its required
+`RUN_STORE=postgres`) (sandbox resources are always on). Configure a sandbox backend with its required
credentials and deployment-specific settings. Workers use the provider of the scope's selected computer, or the deployment default when none is selected. An initial
`backend` override chooses another configured provider that supports creation and
retirement. That choice is stored once; later default changes never move workers
diff --git a/docs/upgrading-runtime.md b/docs/upgrading-runtime.md
index 4b7e18913..e381dad14 100644
--- a/docs/upgrading-runtime.md
+++ b/docs/upgrading-runtime.md
@@ -15,16 +15,17 @@ available until the new revision has passed operational checks.
- `SANDBOX_SECONDARY_BACKEND` is retired. `SANDBOX_BACKEND` selects the primary
backend; additional configured backends become available through their
credentials and backend settings. Remove the old secondary setting.
-- `SANDBOX_SCOPE_BACKENDS` optionally maps scope kinds to their default providers,
- for example `{"personal":"modal","channel":"sprites"}`. Unlisted kinds use
- `SANDBOX_BACKEND`. Explicit per-scope routes and selected sandbox resources
- retain precedence. Configure credentials for every selected backend; the CLI
- includes them in deployment secret requirements. Use distinct provider app/name
- prefixes for deployments sharing a provider account.
- Changing this setting does not migrate existing workspaces. Record existing
- providers as explicit routes before changing defaults, then migrate and verify
- each workspace through the sandbox migration workflow. Retain its original
- provider until migration completes.
+- The `sandbox_routing` table, `SANDBOX_RESOURCES_ENABLED`, and the sandbox
+ migration endpoints and agent action are retired. Sandbox resources are always
+ on; scoped execution uses the selected sandbox resource. Disposable computers use
+ that resource's provider, or the installation provider when no resource is selected. On upgrade,
+ existing routes and `SANDBOX_SCOPE_BACKENDS` mappings are imported once as
+ sandbox records so existing computers are preserved; afterwards
+ `SANDBOX_SCOPE_BACKENDS` has no runtime effect. To move a scope to another
+ provider, create a sandbox there, copy durable work via git or Files, and set
+ it as the default. Keep credentials and provider settings for all legacy mappings
+ until the import completes; an unconfigured provider needed by the import stops
+ startup before any adoption state is written.
- Reach-denied Slack notifications are retired. Consult the audit log for denied
requests.
diff --git a/src/api/deps.ts b/src/api/deps.ts
index 6557d0e47..c4b7d3d87 100644
--- a/src/api/deps.ts
+++ b/src/api/deps.ts
@@ -43,7 +43,6 @@ import type { RunSignalStore } from "../runs/run-signal-store.ts";
import type { WorkspaceStore } from "../workspace/workspace-store.ts";
import type { FileArtifactStore } from "../files/file-artifact-store.ts";
import type { MemoryService } from "../memory/memory-service.ts";
-import type { SandboxMigrationRunner } from "../sandbox/sandbox-migration-runner.ts";
import type { EgressEnforcement, Sandbox } from "../sandbox/sandbox.ts";
import type { EnvironmentStore } from "../environments/environment-store.ts";
import type { Scheduler } from "../cron/scheduler.ts";
@@ -166,7 +165,6 @@ export interface ServerDeps {
egressDeclaredEnforcement?: EgressEnforcement;
egressEnforcement?: EgressEnforcement;
egressControlPlaneConfigured?: boolean;
- sandboxMigration?: SandboxMigrationRunner;
sandboxResources?: SandboxResources;
sandbox?: Sandbox;
advisoryLock?: AdvisoryLock;
diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.ts
index da8d407e2..179b82297 100644
--- a/src/api/routes/admin.ts
+++ b/src/api/routes/admin.ts
@@ -21,7 +21,7 @@ import {
putAdminCronRuntime,
} from "./admin/artifacts.ts";
import { getAdminMemory, listMemoryScopes, putAdminMemory } from "./admin/memory.ts";
-import { listSandboxRoutes, migrateSandboxScope, manageSandboxResources } from "./admin/sandbox.ts";
+import { manageSandboxResources } from "./admin/sandbox.ts";
import {
createAdminGrant,
getUserDetail,
@@ -151,8 +151,6 @@ const routes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "PUT", path: "/v1/admin/memory", auth: "either", handle: putAdminMemory },
{ method: "GET", path: "/v1/admin/sandboxes/:scopeId", auth: "either", handle: manageSandboxResources },
{ method: "POST", path: "/v1/admin/sandboxes/:scopeId", auth: "either", handle: manageSandboxResources },
- { method: "GET", path: "/v1/admin/sandbox-routes", auth: "either", handle: listSandboxRoutes },
- { method: "POST", path: "/v1/admin/sandbox-routes/:scopeId/migrate", auth: "either", handle: migrateSandboxScope },
{ method: "GET", path: "/v1/admin/users", auth: "either", handle: listUsers },
{ method: "GET", path: "/v1/admin/directory", auth: "either", handle: searchDirectory },
{ method: "GET", path: "/v1/admin/keychain", auth: "either", handle: listKeychainStatus },
diff --git a/src/api/routes/admin/sandbox.ts b/src/api/routes/admin/sandbox.ts
index edafd8ff5..480a738b7 100644
--- a/src/api/routes/admin/sandbox.ts
+++ b/src/api/routes/admin/sandbox.ts
@@ -1,91 +1,8 @@
-import { parseScopeId, type ScopeId } from "../../../types.ts";
import { errMessage } from "../../../util/errors.ts";
-import type { SandboxBackendName } from "../../../sandbox/sandbox-routing.ts";
import { sendJson } from "../../http.ts";
import { audit, authorizeAdmin, orgScope } from "../shared.ts";
import { type ApiCtx } from "../route.ts";
-export async function listSandboxRoutes(ctx: ApiCtx): Promise<void> {
- const { res, deps } = ctx;
- const actor = await authorizeAdmin(ctx, orgScope(deps));
- if (!actor) return;
- const runner = deps.sandboxMigration;
- if (!runner)
- return sendJson(res, 404, { error: "not_supported", message: "sandbox routing is not wired on this deployment" });
- audit(deps, {
- principalId: actor.id,
- action: "sandbox_routes.read",
- resource: "sandbox_routes",
- scopeLabel: orgScope(deps),
- });
- const routes = await runner.listRoutes();
- return sendJson(res, 200, {
- defaultBackend: runner.defaultBackend,
- scopeDefaults: runner.scopeDefaults ?? {},
- availableBackends: runner.availableBackends(),
- routes: routes.map(([scopeId, r]) => ({ scopeId, ...r })),
- });
-}
-
-export async function migrateSandboxScope(ctx: ApiCtx): Promise<void> {
- const { res, deps, body, params } = ctx;
- const actor = await authorizeAdmin(ctx, orgScope(deps));
- if (!actor) return;
- const runner = deps.sandboxMigration;
- if (!runner)
- return sendJson(res, 404, { error: "not_supported", message: "sandbox routing is not wired on this deployment" });
- const scopeId = params.scopeId! as ScopeId;
- if (parseScopeId(scopeId).kind === null) {
- return sendJson(res, 400, { error: "bad_request", message: "scopeId is not a valid scope id" });
- }
- const b = (body ?? {}) as Record<string, unknown>;
- const to = typeof b.to === "string" ? (b.to as SandboxBackendName) : undefined;
- const reason = typeof b.reason === "string" ? b.reason : undefined;
- const force = b.force === true;
- const copyTimeoutSec =
- typeof b.copyTimeoutSec === "number" && Number.isFinite(b.copyTimeoutSec)
- ? Math.min(7200, Math.max(60, Math.floor(b.copyTimeoutSec)))
- : undefined;
- const strategy = b.strategy === "snapshot" ? ("snapshot" as const) : undefined;
- const resumeBlobId =
- strategy === "snapshot" && typeof b.resumeBlobId === "string" && /^[0-9a-f]{32}$/.test(b.resumeBlobId)
- ? b.resumeBlobId
- : undefined;
- if (!to || !runner.availableBackends().includes(to)) {
- return sendJson(res, 400, {
- error: "bad_request",
- message: `to must be one of: ${runner.availableBackends().join(", ")}`,
- });
- }
- try {
- if ((await deps.sandboxResources?.resolve(scopeId)) !== undefined)
- throw new Error("this scope uses sandbox resources; change its default independently");
- const result = await runner.migrateScope(scopeId, to, reason, {
- force,
- ...(copyTimeoutSec !== undefined ? { copyTimeoutSec } : {}),
- ...(strategy ? { strategy } : {}),
- ...(resumeBlobId ? { resumeBlobId } : {}),
- });
- audit(deps, {
- principalId: actor.id,
- action: "sandbox_routes.migrate",
- resource:
- `${result.from}->${result.to} sha=${result.sha.slice(0, 12)}` +
- (result.capabilitiesLost.length ? ` lost=${result.capabilitiesLost.join("; ")}` : ""),
- scopeLabel: scopeId,
- });
- return sendJson(res, 200, result);
- } catch (err) {
- audit(deps, {
- principalId: actor.id,
- action: "sandbox_routes.migrate_failed",
- resource: errMessage(err).slice(0, 200),
- scopeLabel: scopeId,
- });
- return sendJson(res, 409, { error: "migration_failed", message: errMessage(err) });
- }
-}
-
export async function manageSandboxResources(ctx: ApiCtx): Promise<void> {
const actor = await authorizeAdmin(ctx, orgScope(ctx.deps));
if (!actor) return;
diff --git a/src/config.ts b/src/config.ts
index d2c3da769..60597cf04 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -2,7 +2,7 @@ import type { ExternalSlackPolicies } from "./resolution/external-slack.ts";
import { isStrongSigningSecret } from "./auth/source-auth.ts";
import { parseSandboxCapabilityTtlMs } from "./auth/capability-token.ts";
import { parseScopeId } from "./types.ts";
-import type { SandboxScopeDefaults } from "./sandbox/sandbox-routing.ts";
+import type { LegacySandboxScopeDefaults } from "./sandbox/sandbox-resource-upgrade.ts";
import { existsSync, readdirSync } from "node:fs";
import {
parseProviderBaseUrl,
@@ -71,9 +71,8 @@ export interface Config {
databaseDirectPoolMax?: number;
harness: "mock" | "pi" | "opencode" | "codex" | "claude";
securityPosture: SecurityPosture;
- sandboxResourcesEnabled: boolean;
sharingPosture: SharingPosture;
- sandboxScopeDefaults?: SandboxScopeDefaults;
+ legacySandboxScopeDefaults?: LegacySandboxScopeDefaults;
sandboxBackend: "aws" | "local" | "sprites" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37" | "superserve";
sandboxSecondaryBackend?:
"aws" | "local" | "sprites" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37" | "superserve";
@@ -1269,7 +1268,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
);
}
const sandboxBackend = sandboxBackendEnvStrict(env.SANDBOX_BACKEND);
- const sandboxScopeDefaults: SandboxScopeDefaults = {};
+ const legacySandboxScopeDefaults: LegacySandboxScopeDefaults = {};
if (env.SANDBOX_SCOPE_BACKENDS) {
const values: unknown = JSON.parse(env.SANDBOX_SCOPE_BACKENDS);
if (!values || typeof values !== "object" || Array.isArray(values))
@@ -1278,11 +1277,10 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
const parsed = parseScopeId(kind + ":scope").kind;
if (!parsed || parsed !== kind || typeof value !== "string" || !value.trim())
throw new Error("Invalid SANDBOX_SCOPE_BACKENDS entry: " + kind);
- sandboxScopeDefaults[parsed] = sandboxBackendEnvStrict(value, "SANDBOX_SCOPE_BACKENDS." + kind);
+ legacySandboxScopeDefaults[parsed] = sandboxBackendEnvStrict(value, "SANDBOX_SCOPE_BACKENDS." + kind);
}
}
- const superserveSelected =
- sandboxBackend === "superserve" || Object.values(sandboxScopeDefaults).includes("superserve");
+ const superserveSelected = sandboxBackend === "superserve";
if (superserveSelected && !env.SUPERSERVE_TEMPLATE?.trim()) {
throw new Error(
"SANDBOX_BACKEND=superserve requires SUPERSERVE_TEMPLATE, the ready qm-agent-<release> template that carries the agent toolchain.",
@@ -1477,8 +1475,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
? { securityScreenProxy: { provider: proxyProvider!, endpoint: proxyEndpoint!, token: proxyToken! } }
: {}),
sandboxBackend,
- sandboxScopeDefaults,
- sandboxResourcesEnabled: boolEnvStrict("SANDBOX_RESOURCES_ENABLED", env.SANDBOX_RESOURCES_ENABLED) ?? false,
+ legacySandboxScopeDefaults,
deployProvider,
...(env.EGRESS_SERVICE_HOSTS
? {
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 1ffa8f857..6fa534371 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -2768,7 +2768,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const baseTools = createToolContext({
sandbox: deps.sandbox,
sandboxResources: turnSandboxResources,
- ...(deps.sandboxMigration ? { sandboxMigration: deps.sandboxMigration, invalidateProvision } : {}),
+ invalidateProvision,
provision,
provisionScratch,
provisionResource,
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index 38081885b..ed6deaa73 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -25,7 +25,6 @@ import type { SessionSyscallsFactory } from "../../sessions/session-syscalls.ts"
import type { DeliveryStore } from "../../delivery/delivery-store.ts";
import type { WorkspaceStore } from "../../workspace/workspace-store.ts";
import type { Sandbox } from "../../sandbox/sandbox.ts";
-import type { SandboxMigrationRunner } from "../../sandbox/sandbox-migration-runner.ts";
import type { ProcessRegistry } from "../../processes/process-registry.ts";
import type { MonitorStore } from "../../monitors/monitor-store.ts";
import type { CronStore } from "../../cron/cron-store.ts";
@@ -129,7 +128,6 @@ export interface OrchestratorDeps {
workspace: WorkspaceStore;
files: FileArtifactStore;
sandbox: Sandbox;
- sandboxMigration?: SandboxMigrationRunner;
sandboxResources?: SandboxResources;
modelGateway: ModelGateway;
auditLog: AuditLog;
diff --git a/src/deployment/secret-schema.ts b/src/deployment/secret-schema.ts
index d2006368d..4c2f34383 100644
--- a/src/deployment/secret-schema.ts
+++ b/src/deployment/secret-schema.ts
@@ -58,11 +58,7 @@ export const CORE_SECRET_SPECS: readonly RuntimeSecretSpec[] = [
];
function sandboxBackendSelected(env: NodeJS.ProcessEnv, backend: string): boolean {
- if (env.SANDBOX_BACKEND?.trim() === backend) return true;
- const scopes: unknown = JSON.parse(env.SANDBOX_SCOPE_BACKENDS || "{}");
- if (!scopes || typeof scopes !== "object" || Array.isArray(scopes))
- throw new Error("SANDBOX_SCOPE_BACKENDS must be an object");
- return Object.values(scopes).some((value) => typeof value === "string" && value.trim() === backend);
+ return env.SANDBOX_BACKEND?.trim() === backend;
}
const GATE_PREDICATES: Readonly<Record<SecretGate, (env: NodeJS.ProcessEnv) => boolean>> = {
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 203602a02..9ca724cf9 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -345,7 +345,7 @@ export type CoreToolOptions = Omit<
export function coreToolOptions(config: Config): CoreToolOptions {
return {
- sandboxResources: config.sandboxResourcesEnabled,
+ sandboxResources: true,
scratchExec: config.scratchExecEnabled,
// Availability is checked per turn; Open can be enabled without restarting the harness.
ownerAuthExec: true,
diff --git a/src/sandbox/e2b-sandbox.ts b/src/sandbox/e2b-sandbox.ts
index 08b45c02d..9b310414b 100644
--- a/src/sandbox/e2b-sandbox.ts
+++ b/src/sandbox/e2b-sandbox.ts
@@ -5,7 +5,6 @@ import type { WorkspaceStore } from "../workspace/workspace-store.ts";
import type { DurableMap } from "../persistence/durable-map.ts";
import { createMemoryMap } from "../persistence/durable-map.ts";
import { createKeyedQueue } from "../util/async.ts";
-import { collectBlob } from "../persistence/blob-transfer.ts";
import { swallowAs, errMessage } from "../util/errors.ts";
import { shq } from "../util/shell.ts";
import { nonInteractiveShellPrefix, DROPPED_PROXY_ENV, forceThroughProxyEnv } from "./sandbox-env.ts";
@@ -58,7 +57,6 @@ const WORKSPACE_BASENAME = "workspace";
const RO_LAYERS_TAR = ".ro-layers.tar";
const RO_LAYERS_MANIFEST = ".ro-layers.manifest";
const HOME_TAR = `${HOME_DIR}/.qm-home.tar`;
-const IN_MEMORY_ADOPT_MAX_BYTES = 256 * 1024 * 1024;
const SNAPSHOT_PRUNE = HOME_SNAPSHOT_PRUNE;
const DEFAULT_KEEP_WARM_SEC = 3600;
@@ -509,38 +507,6 @@ export function createE2bSandbox(workspace: WorkspaceStore, opts: E2bSandboxOpti
exportFiles: execExport.exportFiles,
- async adoptHomeSnapshot(scopeId: string, blobId: string): Promise<void> {
- const blobTransfer = opts.blobTransfer;
- if (!blobTransfer) throw new Error("e2b adoptHomeSnapshot: no blob transfer store wired");
- const ref = blobTransfer.s3Ref?.(blobId);
- if (ref && snapshots.adoptFromS3) {
- await snapshots.adoptFromS3(scopeId, ref);
- } else {
- const blob = await blobTransfer.open(blobId);
- if (!blob) throw new Error(`e2b adoptHomeSnapshot: blob ${blobId} not found`);
- if (blob.sizeBytes > IN_MEMORY_ADOPT_MAX_BYTES) {
- blob.stream.destroy();
- throw new Error(
- `e2b adoptHomeSnapshot: blob is ${blob.sizeBytes} bytes; adopting over ${IN_MEMORY_ADOPT_MAX_BYTES} needs S3-backed blob and snapshot stores`,
- );
- }
- await snapshots.put(scopeId, await collectBlob(blob.stream));
- }
- const name = sandboxScopeName(prefix, scopeId);
- return provisionQueue(scopeId, async () => {
- const session = sessionByName.get(name);
- sessionByName.delete(name);
- const stored = await store.get(scopeId);
- const killGone = (e: unknown): void => {
- if (!(e instanceof E2bSandboxGoneError)) throw e;
- };
- if (session) await session.kill().catch(killGone);
- else if (stored) await client.kill(stored.sandboxId).catch(killGone);
- await store.delete(scopeId);
- await forgetSnapshot(stored?.recoverySnapshotId);
- });
- },
-
async persistHomeSnapshot(scopeId: string): Promise<void> {
const name = sandboxScopeName(prefix, scopeId);
scopeByName.set(name, scopeId);
diff --git a/src/sandbox/home-snapshot.ts b/src/sandbox/home-snapshot.ts
index 449e3bf83..7441d3f46 100644
--- a/src/sandbox/home-snapshot.ts
+++ b/src/sandbox/home-snapshot.ts
@@ -2,13 +2,10 @@ import { basename } from "node:path/posix";
import {
AbortMultipartUploadCommand,
CompleteMultipartUploadCommand,
- CopyObjectCommand,
CreateMultipartUploadCommand,
GetObjectCommand,
- HeadObjectCommand,
PutObjectCommand,
UploadPartCommand,
- UploadPartCopyCommand,
} from "@aws-sdk/client-s3";
import { shq } from "../util/shell.ts";
import { swallowAs } from "../util/errors.ts";
@@ -64,7 +61,6 @@ export interface HomeSnapshotStore {
open(scope: string): Promise<StoredSnapshot | null>;
put(scope: string, data: Uint8Array): Promise<void>;
createUpload(scope: string): Promise<SnapshotUpload>;
- adoptFromS3?(scope: string, ref: { bucket: string; key: string }): Promise<void>;
}
export class SnapshotTooLargeError extends Error {
@@ -159,54 +155,9 @@ export function createS3SnapshotStore(opts: S3SnapshotStoreOptions): HomeSnapsho
abort,
};
},
- async adoptFromS3(scope, ref): Promise<void> {
- const head = (await s3.send(new HeadObjectCommand({ Bucket: ref.bucket, Key: ref.key }))) as {
- ContentLength?: number;
- };
- const size = head.ContentLength ?? 0;
- const Key = keyFor(scope);
- const source = `/${ref.bucket}/${encodeURIComponent(ref.key)}`;
- if (size <= SINGLE_COPY_MAX_BYTES) {
- await s3.send(new CopyObjectCommand({ Bucket, Key, CopySource: source }));
- return;
- }
- const started = (await s3.send(new CreateMultipartUploadCommand({ Bucket, Key }))) as { UploadId?: string };
- const uploadId = started.UploadId!;
- try {
- const parts: Array<{ ETag: string; PartNumber: number }> = [];
- for (let offset = 0, part = 1; offset < size; offset += COPY_PART_BYTES, part++) {
- const end = Math.min(offset + COPY_PART_BYTES, size) - 1;
- const copied = (await s3.send(
- new UploadPartCopyCommand({
- Bucket,
- Key,
- UploadId: uploadId,
- PartNumber: part,
- CopySource: source,
- CopySourceRange: `bytes=${offset}-${end}`,
- }),
- )) as { CopyPartResult?: { ETag?: string } };
- parts.push({ ETag: copied.CopyPartResult!.ETag!, PartNumber: part });
- }
- await s3.send(
- new CompleteMultipartUploadCommand({
- Bucket,
- Key,
- UploadId: uploadId,
- MultipartUpload: { Parts: parts },
- }),
- );
- } catch (e) {
- await s3.send(new AbortMultipartUploadCommand({ Bucket, Key, UploadId: uploadId })).catch(() => {});
- throw e;
- }
- },
};
}
-const SINGLE_COPY_MAX_BYTES = 4_500_000_000;
-const COPY_PART_BYTES = 1_000_000_000;
-
export interface HomeSnapshotSessionIo<S> {
runCommand(
session: S,
diff --git a/src/sandbox/modal-sandbox.ts b/src/sandbox/modal-sandbox.ts
index 5da5eed99..66c08abfc 100644
--- a/src/sandbox/modal-sandbox.ts
+++ b/src/sandbox/modal-sandbox.ts
@@ -7,7 +7,6 @@ import type { DurableMap } from "../persistence/durable-map.ts";
import { createMemoryMap } from "../persistence/durable-map.ts";
import { orgId as configOrgId } from "../config.ts";
import { createKeyedQueue } from "../util/async.ts";
-import { collectBlob } from "../persistence/blob-transfer.ts";
import { swallowAs, errMessage } from "../util/errors.ts";
import { shq } from "../util/shell.ts";
import { nonInteractiveShellPrefix, DROPPED_PROXY_ENV, forceThroughProxyEnv } from "./sandbox-env.ts";
@@ -56,7 +55,6 @@ const RO_LAYERS_TAR = ".ro-layers.tar";
const RO_LAYERS_MANIFEST = ".ro-layers.manifest";
const HOME_TAR = `${HOME_DIR}/.qm-home.tar`;
const HYDRATED_MARKER = `${HOME_DIR}/.qm-hydrated`;
-const IN_MEMORY_ADOPT_MAX_BYTES = 256 * 1024 * 1024;
const ACTIVITY_TOUCH_INTERVAL_MS = 10 * 60_000;
const swallowGone = (error: unknown): void => {
if (!(error instanceof ModalSandboxGoneError)) throw error;
@@ -786,34 +784,6 @@ export function createModalSandbox(workspace: WorkspaceStore, opts: ModalSandbox
exportFiles: execExport.exportFiles,
- async adoptHomeSnapshot(scopeId: string, blobId: string): Promise<void> {
- const blobTransfer = opts.blobTransfer;
- if (!blobTransfer) throw new Error("modal adoptHomeSnapshot: no blob transfer store wired");
- const ref = blobTransfer.s3Ref?.(blobId);
- if (ref && snapshots.adoptFromS3) {
- await snapshots.adoptFromS3(scopeId, ref);
- } else {
- const blob = await blobTransfer.open(blobId);
- if (!blob) throw new Error(`modal adoptHomeSnapshot: blob ${blobId} not found`);
- if (blob.sizeBytes > IN_MEMORY_ADOPT_MAX_BYTES) {
- blob.stream.destroy();
- throw new Error(
- `modal adoptHomeSnapshot: blob is ${blob.sizeBytes} bytes; adopting over ${IN_MEMORY_ADOPT_MAX_BYTES} needs S3-backed blob and snapshot stores`,
- );
- }
- await snapshots.put(scopeId, await collectBlob(blob.stream));
- }
- const name = sandboxScopeName(prefix, scopeId);
- return provisionQueue(scopeId, async () => {
- const session = sessionByName.get(name);
- sessionByName.delete(name);
- const stored = await store.get(scopeId);
- if (session) await session.terminate().catch(swallowGone);
- else if (stored) await client.terminate(stored.sandboxId).catch(swallowGone);
- await store.delete(scopeId);
- });
- },
-
async persistHomeSnapshot(scopeId: string): Promise<void> {
const name = sandboxScopeName(prefix, scopeId);
scopeByName.set(name, scopeId);
diff --git a/src/sandbox/sandbox-migrate.ts b/src/sandbox/sandbox-migrate.ts
deleted file mode 100644
index d1c0c19fa..000000000
--- a/src/sandbox/sandbox-migrate.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { posix } from "node:path";
-import { shq } from "../util/shell.ts";
-import { supportsBlobStaging, type Sandbox, type SandboxHandle } from "./sandbox.ts";
-import { posixJoin } from "./exec-file-ops.ts";
-
-export function translateScript(toHome: string, fromHome: string): string {
- const H = shq(toHome);
- const FROM = fromHome.replace(/\/+$/, "");
- const pat = FROM.replace(/[.[\]*^$\\#]/g, "\\$&");
- const sub = toHome.replace(/[&\\#]/g, "\\$&");
- const rewriteTargets = [`${H}/.gitconfig`, `${H}/.config`, `${H}/.bashrc`, `${H}/.profile`];
- const rewrite = (f: string) =>
- `t=$(mktemp) && sed "s#${pat}\\([^A-Za-z0-9_.-]\\)#${sub}\\1#g; s#${pat}\\$#${sub}#" ${f} > "$t" && mv "$t" ${f}`;
- return [
- `for t in ${rewriteTargets.join(" ")}; do`,
- ` [ -e "$t" ] && grep -rIl ${shq(FROM)} "$t" 2>/dev/null | while IFS= read -r f; do`,
- ` ${rewrite('"$f"')} || true`,
- ` done`,
- `done`,
- `find ${H} -maxdepth 4 -path '*/.git/config' -type f 2>/dev/null | while IFS= read -r f; do`,
- ` grep -Iq ${shq(FROM)} "$f" 2>/dev/null && { ${rewrite('"$f"')}; } || true`,
- `done`,
- `find ${H} -name pyvenv.cfg -type f 2>/dev/null | while IFS= read -r cfg; do`,
- ` rm -rf "$(dirname "$cfg")" 2>/dev/null || true`,
- `done`,
- `true`,
- ].join("\n");
-}
-
-export interface CopyHomeResult {
- bytes: number;
- sha: string;
- sourceFiles: number;
- destFiles: number;
-}
-
-export interface PackedHome {
- tarPath: string;
- tarRel: string;
- sha: string;
- bytes: number;
- sourceFiles: number;
-}
-
-const HOME_TAR_PREFIX = ".home-";
-
-export async function packHome(
- fromSandbox: Sandbox,
- fromHandle: SandboxHandle,
- fromHome: string,
- timeoutMs: number,
-): Promise<PackedHome> {
- const tarRel = `${HOME_TAR_PREFIX}${randomUUID()}.tgz`;
- const tarPath = posixJoin(fromHandle.rootDir, tarRel);
- const H = shq(fromHome);
- const P = shq(tarPath);
- const packed = await fromSandbox.run(
- fromHandle,
- `cd ${H} && tar czf ${P} --exclude=${shq(`./${posix.relative(fromHome, fromHandle.rootDir)}/${HOME_TAR_PREFIX}*.tgz`)} . 2>/dev/null; rc=$?; [ "$rc" -le 1 ] || exit "$rc"; sha256sum ${P} | cut -d' ' -f1 && wc -c < ${P} && find . -type f ! -name ${shq(`${HOME_TAR_PREFIX}*.tgz`)} | wc -l`,
- { timeoutMs },
- );
- if (packed.code !== 0) {
- await fromSandbox.run(fromHandle, `rm -f ${P}`, { timeoutMs: 30_000 }).catch(() => {});
- throw new Error(`packHome: source tar failed (${packed.code}): ${(packed.stderr || packed.stdout).slice(0, 200)}`);
- }
- const [shaLine = "", sizeLine = "", filesLine = ""] = packed.stdout.trim().split("\n");
- const sha = shaLine.trim();
- const bytes = Number.parseInt(sizeLine.trim(), 10);
- const sourceFiles = Number.parseInt(filesLine.trim(), 10);
- if (!/^[0-9a-f]{64}$/.test(sha) || !Number.isFinite(bytes) || !Number.isFinite(sourceFiles)) {
- throw new Error(`packHome: unreadable source manifest: ${packed.stdout.slice(0, 200)}`);
- }
- return { tarPath, tarRel, sha, bytes, sourceFiles };
-}
-
-export interface CopyHomeArgs {
- fromSandbox: Sandbox;
- fromHandle: SandboxHandle;
- fromHome: string;
- toSandbox: Sandbox;
- toHandle: SandboxHandle;
- toHome: string;
- timeoutSec?: number;
-}
-
-export async function copyHome(args: CopyHomeArgs): Promise<CopyHomeResult> {
- const { fromSandbox, fromHandle, fromHome, toSandbox, toHandle, toHome } = args;
- const timeoutMs = (args.timeoutSec ?? 900) * 1000;
- const T = shq(toHome);
- const { tarPath, tarRel, sha, bytes, sourceFiles } = await packHome(fromSandbox, fromHandle, fromHome, timeoutMs);
- const toTarPath = posixJoin(toHandle.rootDir, tarRel);
- try {
- return await transferHome();
- } finally {
- await Promise.all([
- fromSandbox.run(fromHandle, `rm -f ${shq(tarPath)}`, { timeoutMs: 30_000 }).catch(() => {}),
- toSandbox.run(toHandle, `rm -f ${shq(toTarPath)}`, { timeoutMs: 30_000 }).catch(() => {}),
- ]);
- }
-
- async function transferHome(): Promise<CopyHomeResult> {
- if (supportsBlobStaging(fromSandbox) && supportsBlobStaging(toSandbox)) {
- const stageOpts = { timeoutSec: timeoutMs / 1000 };
- const blobId = await fromSandbox.stageOut(fromHandle, tarRel, stageOpts);
- await toSandbox.stageIn(toHandle, tarRel, blobId, stageOpts);
- } else {
- const tarBytes = await fromSandbox.readFileBytes(fromHandle, tarRel);
- if (!tarBytes) throw new Error("copyHome: source tar vanished before read");
- await toSandbox.writeFileBytes(toHandle, tarRel, tarBytes);
- }
-
- const extracted = await toSandbox.run(
- toHandle,
- `dsha=$(sha256sum ${shq(toTarPath)} | cut -d' ' -f1); [ "$dsha" = ${shq(sha)} ] || { echo "sha-mismatch:$dsha"; exit 3; }; mkdir -p ${T} && cd ${T} && tar xzf ${shq(toTarPath)} 2>/dev/null && find . -type f ! -name ${shq(`${HOME_TAR_PREFIX}*.tgz`)} | wc -l`,
- { timeoutMs },
- );
- if (extracted.code !== 0) {
- throw new Error(
- `copyHome: dest verify/extract failed (${extracted.code}): ${(extracted.stderr || extracted.stdout).slice(0, 200)}`,
- );
- }
- const destFiles = Number.parseInt(extracted.stdout.trim().split("\n").pop() ?? "", 10);
-
- if (fromHome !== toHome) {
- const t = await toSandbox.run(toHandle, translateScript(toHome, fromHome), { timeoutMs: 120_000 });
- if (t.code !== 0)
- throw new Error(`copyHome: translation failed (${t.code}): ${(t.stderr || t.stdout).slice(0, 200)}`);
- }
-
- return { bytes, sha, sourceFiles, destFiles };
- }
-}
diff --git a/src/sandbox/sandbox-migration-runner.ts b/src/sandbox/sandbox-migration-runner.ts
deleted file mode 100644
index 8227758c4..000000000
--- a/src/sandbox/sandbox-migration-runner.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import type { DurableMap } from "../persistence/durable-map.ts";
-import type { AdvisoryLock } from "../persistence/advisory-lock.ts";
-import { sleep } from "../util/async.ts";
-import { swallowAs } from "../util/errors.ts";
-import { shq } from "../util/shell.ts";
-import { copyHome, packHome, translateScript, type CopyHomeResult } from "./sandbox-migrate.ts";
-import {
- sandboxDefaultForScope,
- type SandboxScopeDefaults,
- type SandboxBackendName,
- type SandboxRoute,
-} from "./sandbox-routing.ts";
-import {
- capabilitiesLostMovingTo,
- supportsBlobStaging,
- type ProvisionOptions,
- type Sandbox,
- type SandboxHandle,
-} from "./sandbox.ts";
-import type { WorkspaceLayer } from "../types.ts";
-
-export interface SandboxMigrationOptions {
- backends: Partial<Record<SandboxBackendName, Sandbox>>;
- routes: DurableMap<SandboxRoute>;
- defaultBackend: SandboxBackendName;
- scopeDefaults?: SandboxScopeDefaults;
- advisoryLock?: AdvisoryLock;
- provisionOptions?: (scopeId: string) => Promise<ProvisionOptions>;
- settleMs?: number;
- withLegacyMutation?: <T>(scopeId: string, action: () => Promise<T>) => Promise<T>;
- hasLiveWork?: (scopeId: string) => Promise<boolean>;
-}
-
-interface MigrateScopeResult extends CopyHomeResult {
- scopeId: string;
- from: SandboxBackendName;
- to: SandboxBackendName;
- resynced: boolean;
- capabilitiesLost: string[];
-}
-
-interface MigrateScopeOptions {
- force?: boolean;
- copyTimeoutSec?: number;
- strategy?: "copy" | "snapshot";
- resumeBlobId?: string;
-}
-
-export interface SandboxMigrationRunner {
- migrateScope(
- scopeId: string,
- to: SandboxBackendName,
- reason?: string,
- opts?: MigrateScopeOptions,
- ): Promise<MigrateScopeResult>;
- listRoutes(): Promise<Array<[string, SandboxRoute]>>;
- availableBackends(): SandboxBackendName[];
- defaultBackend: SandboxBackendName;
- scopeDefaults?: SandboxScopeDefaults;
-}
-
-const scopeLayers = (scopeId: string): WorkspaceLayer[] => [
- { scopeId: scopeId as WorkspaceLayer["scopeId"], mountPath: "/", mode: "rw" },
-];
-
-export function createSandboxMigrationRunner(opts: SandboxMigrationOptions): SandboxMigrationRunner {
- const { backends, routes, defaultBackend } = opts;
-
- async function migrate(
- scopeId: string,
- to: SandboxBackendName,
- reason?: string,
- migrateOpts?: MigrateScopeOptions,
- ): Promise<MigrateScopeResult> {
- const toSandbox = backends[to];
- if (!toSandbox) throw new Error(`cannot migrate to ${to}: that backend is not constructed on this deployment`);
- const route = await routes.get(scopeId);
- const from = route?.backend ?? sandboxDefaultForScope(scopeId, defaultBackend, opts.scopeDefaults);
- if (from === to) throw new Error(`scope is already on ${to}`);
- const fromSandbox = backends[from];
- if (!fromSandbox) throw new Error(`scope lives on ${from}, which is not constructed on this deployment`);
- if (route?.pinned)
- throw new Error(`scope is pinned to ${from}${route.reason ? ` (${route.reason})` : ""}; unpin before migrating`);
- if (opts.hasLiveWork && (await opts.hasLiveWork(scopeId))) {
- throw new Error("scope has live background work; wait for it to finish or stop it before migrating");
- }
- const capabilitiesLost = capabilitiesLostMovingTo(fromSandbox, toSandbox);
- if (capabilitiesLost.length && !migrateOpts?.force) {
- throw new Error(
- `cannot migrate to ${to}: it has no ${capabilitiesLost.join(", no ")}, which the scope has on ${from} today. ` +
- `Migrate with force to accept the loss.`,
- );
- }
- if (migrateOpts?.strategy === "snapshot") {
- if (!supportsBlobStaging(fromSandbox))
- throw new Error(`snapshot migration needs blob staging on ${from}, which is not wired`);
- if (!toSandbox.adoptHomeSnapshot)
- throw new Error(`snapshot migration needs ${to} to support adopting home snapshots`);
- }
- const provOpts = (await opts.provisionOptions?.(scopeId)) ?? {};
- const fromHandle = await fromSandbox.provision(scopeLayers(scopeId), provOpts);
- const fromHome = fromHandle.homeDir ?? fromSandbox.profile.spec?.homeDir ?? "/root";
- const timeoutMs = (migrateOpts?.copyTimeoutSec ?? 900) * 1000;
- const startedAtIso = new Date().toISOString();
-
- const snapshotPass = async (resumeBlobId?: string): Promise<CopyHomeResult> => {
- let blobId: string;
- let manifest = { bytes: 0, sha: "resumed", sourceFiles: 0 };
- if (resumeBlobId) {
- blobId = resumeBlobId;
- } else {
- const packed = await packHome(fromSandbox, fromHandle, fromHome, timeoutMs);
- manifest = { bytes: packed.bytes, sha: packed.sha, sourceFiles: packed.sourceFiles };
- try {
- blobId = await (fromSandbox as Sandbox & Required<Pick<Sandbox, "stageOut">>).stageOut(
- fromHandle,
- packed.tarRel,
- { timeoutSec: timeoutMs / 1000 },
- );
- } finally {
- await fromSandbox.run(fromHandle, `rm -f ${shq(packed.tarPath)}`, { timeoutMs: 30_000 }).catch(() => {});
- }
- }
- await toSandbox.adoptHomeSnapshot!(scopeId, blobId);
- const toHandle = await toSandbox.provision(scopeLayers(scopeId), provOpts);
- const toHome = toHandle.homeDir ?? toSandbox.profile.spec?.homeDir ?? "/root";
- let verified = false;
- try {
- if (toHandle.coldStart) {
- throw new Error("snapshot migration: the target provisioned cold — the adopted snapshot never hydrated");
- }
- const counted = await toSandbox.run(toHandle, `find ${shq(toHome)} -type f | wc -l`, { timeoutMs });
- const destFiles = Number.parseInt(counted.stdout.trim(), 10);
- if (counted.code !== 0 || !Number.isFinite(destFiles) || destFiles < Math.max(1, manifest.sourceFiles)) {
- throw new Error(
- `snapshot migration: hydrated home has ${counted.stdout.trim().slice(0, 40)} files, expected at least ${Math.max(1, manifest.sourceFiles)}`,
- );
- }
- if (fromHome !== toHome) {
- const t = await toSandbox.run(toHandle, translateScript(toHome, fromHome), { timeoutMs });
- if (t.code !== 0)
- throw new Error(
- `snapshot migration: translation failed (${t.code}): ${(t.stderr || t.stdout).slice(0, 200)}`,
- );
- }
- await toSandbox.persistHomeSnapshot?.(scopeId);
- verified = true;
- return { bytes: manifest.bytes, sha: manifest.sha, sourceFiles: manifest.sourceFiles, destFiles };
- } finally {
- if (verified) {
- await toSandbox.teardown(toHandle);
- } else {
- await toSandbox
- .teardown(toHandle, { destroy: true })
- .catch(swallowAs("sandbox-migration: destroy unverified target", undefined));
- }
- }
- };
-
- if (migrateOpts?.strategy === "snapshot") {
- let copied = await snapshotPass(migrateOpts.resumeBlobId);
- let resynced = false;
- const changed = migrateOpts.resumeBlobId
- ? { stdout: "" }
- : await fromSandbox.run(
- fromHandle,
- `find ${shq(fromHome)} -type f -newermt ${shq(startedAtIso)} 2>/dev/null | head -1`,
- { timeoutMs: 60_000 },
- );
- if (changed.stdout.trim() !== "") {
- copied = await snapshotPass();
- resynced = true;
- }
- await routes.put(scopeId, {
- backend: to,
- migratedAt: new Date().toISOString(),
- migrationSha: copied.sha,
- ...(reason ? { reason } : {}),
- ...(capabilitiesLost.length ? { capabilitiesLost } : {}),
- });
- await park(fromSandbox, fromHandle);
- return { scopeId, from, to, resynced, capabilitiesLost, ...copied };
- }
-
- const toHandle = await toSandbox.provision(scopeLayers(scopeId), provOpts);
- const toHome = toHandle.homeDir ?? toSandbox.profile.spec?.homeDir ?? "/root";
- const copyArgs = {
- fromSandbox,
- fromHandle,
- fromHome,
- toSandbox,
- toHandle,
- toHome,
- ...(migrateOpts?.copyTimeoutSec ? { timeoutSec: migrateOpts.copyTimeoutSec } : {}),
- };
- let copied = await copyHome(copyArgs);
- const routeRow = (): SandboxRoute => ({
- backend: to,
- migratedAt: new Date().toISOString(),
- migrationSha: copied.sha,
- ...(reason ? { reason } : {}),
- ...(capabilitiesLost.length ? { capabilitiesLost } : {}),
- });
- await routes.put(scopeId, routeRow());
- if (opts.settleMs) await sleep(opts.settleMs);
- let resynced = false;
- const changed = await fromSandbox.run(
- fromHandle,
- `find ${shq(fromHome)} -type f -newermt ${shq(startedAtIso)} 2>/dev/null | head -1`,
- { timeoutMs: 60_000 },
- );
- if (changed.stdout.trim() !== "") {
- copied = await copyHome(copyArgs);
- await routes.put(scopeId, routeRow());
- resynced = true;
- }
- await Promise.all([park(fromSandbox, fromHandle), park(toSandbox, toHandle)]);
- return { scopeId, from, to, resynced, capabilitiesLost, ...copied };
- }
-
- const park = (s: Sandbox, h: SandboxHandle) => s.teardown(h).catch(() => {});
-
- return {
- migrateScope: (scopeId, to, reason?, migrateOpts?) => {
- const run = () =>
- opts.advisoryLock
- ? opts.advisoryLock.withLock(`sandbox-migration:${scopeId}`, () => migrate(scopeId, to, reason, migrateOpts))
- : migrate(scopeId, to, reason, migrateOpts);
- return opts.withLegacyMutation ? opts.withLegacyMutation(scopeId, run) : run();
- },
- listRoutes: () => routes.entries(),
- availableBackends: () =>
- Object.entries(backends)
- .filter(([, s]) => !!s)
- .map(([n]) => n as SandboxBackendName),
- defaultBackend,
- scopeDefaults: opts.scopeDefaults,
- };
-}
diff --git a/src/sandbox/sandbox-resource-upgrade.ts b/src/sandbox/sandbox-resource-upgrade.ts
new file mode 100644
index 000000000..a1027c998
--- /dev/null
+++ b/src/sandbox/sandbox-resource-upgrade.ts
@@ -0,0 +1,115 @@
+import { createHash } from "node:crypto";
+import type { DurableMap } from "../persistence/durable-map.ts";
+import type { AdvisoryLock } from "../persistence/advisory-lock.ts";
+import { parseScopeId, type ScopeKind } from "../types.ts";
+import type { SandboxBackendName } from "./sandbox-routing.ts";
+import type { AgentComputerSpec } from "./sandbox.ts";
+import type { SandboxDefault, SandboxResource } from "./sandbox-resources.ts";
+
+export interface SandboxResourceUpgradeMarker {
+ activatedAt: string;
+}
+
+export interface LegacySandboxBinding {
+ scopeId: string;
+ backend: SandboxBackendName;
+ machineId?: string;
+}
+
+export type LegacySandboxScopeDefaults = Partial<Record<ScopeKind, SandboxBackendName>>;
+
+export interface LegacyRoute {
+ backend: SandboxBackendName;
+}
+
+export function legacySandboxBackendForScope(
+ scope: string,
+ fallback: SandboxBackendName,
+ defaults?: LegacySandboxScopeDefaults,
+): SandboxBackendName {
+ const kind = parseScopeId(scope).kind;
+ return (kind && defaults?.[kind]) || fallback;
+}
+
+export const legacySandboxId = (scopeId: string, backend: SandboxBackendName): string =>
+ `legacy-${createHash("sha256").update(`${backend}:${scopeId}`).digest("hex").slice(0, 24)}`;
+
+export async function upgradeLegacySandboxes(opts: {
+ availableBackends: readonly SandboxBackendName[];
+ records: DurableMap<SandboxResource>;
+ defaults: DurableMap<SandboxDefault>;
+ marker: DurableMap<SandboxResourceUpgradeMarker>;
+ lock: AdvisoryLock;
+ routes?: () => Promise<Array<[string, LegacyRoute]>>;
+ legacyScopes?: () => Promise<string[]>;
+ legacySandboxes?: () => Promise<LegacySandboxBinding[]>;
+ legacyBackend: (scopeId: string) => SandboxBackendName;
+ specFor?: (backend: SandboxBackendName) => AgentComputerSpec | undefined;
+}): Promise<void> {
+ const done = async (): Promise<boolean> => (await opts.marker.get("explicit-defaults")) !== null;
+ if (await done()) return;
+ await opts.lock.withLock("sandbox-resources:activation", async () => {
+ if (await done()) return;
+ const [existing, defaults, routes, knownScopes, bindings] = await Promise.all([
+ opts.records.all(),
+ opts.defaults.entries(),
+ opts.routes?.() ?? [],
+ opts.legacyScopes?.() ?? [],
+ opts.legacySandboxes?.() ?? [],
+ ]);
+ const managed = new Set(existing.filter((record) => !record.legacy).map((record) => record.backingScopeId));
+ const valid = (scope: string): boolean => !!parseScopeId(scope).kind && !managed.has(scope);
+ const routed = new Map(routes);
+ const backendFor = (scope: string): SandboxBackendName => routed.get(scope)?.backend ?? opts.legacyBackend(scope);
+ const scopes = new Set(
+ [
+ ...knownScopes,
+ ...routed.keys(),
+ ...bindings.map((binding) => binding.scopeId),
+ ...existing.map((record) => record.ownerScopeId),
+ ].filter(valid),
+ );
+ const selected = new Map(defaults);
+ const retired = new Set(existing.filter((record) => record.state === "retired").map((record) => record.id));
+ for (const scope of scopes) {
+ const backend = backendFor(scope);
+ if (
+ !selected.has(scope) &&
+ !retired.has(legacySandboxId(scope, backend)) &&
+ !opts.availableBackends.includes(backend)
+ )
+ throw new Error(
+ `cannot import legacy computer for ${scope}: backend ${backend} is not configured; restore that provider before upgrading`,
+ );
+ }
+ const candidates = new Map<string, LegacySandboxBinding>();
+ for (const binding of bindings)
+ if (valid(binding.scopeId)) candidates.set(legacySandboxId(binding.scopeId, binding.backend), binding);
+ for (const scope of scopes) {
+ const id = legacySandboxId(scope, backendFor(scope));
+ if (!candidates.has(id)) candidates.set(id, { scopeId: scope, backend: backendFor(scope) });
+ }
+ for (const [id, binding] of candidates) {
+ const spec = opts.specFor?.(binding.backend);
+ await opts.records.putIfAbsent(id, {
+ id,
+ backend: binding.backend,
+ ownerScopeId: binding.scopeId as SandboxResource["ownerScopeId"],
+ backingScopeId: binding.scopeId,
+ name: "Existing scoped computer",
+ createdBy: "system",
+ createdAt: new Date().toISOString(),
+ legacy: true,
+ state: "unverified",
+ ...(binding.machineId ? { machineId: binding.machineId } : {}),
+ ...(spec ? { spec } : {}),
+ });
+ }
+ for (const scope of scopes) {
+ const id = legacySandboxId(scope, backendFor(scope));
+ const record = await opts.records.get(id);
+ await opts.defaults.putIfAbsent(scope, { sandboxId: record?.state === "retired" ? null : id });
+ }
+ await opts.marker.put("explicit-defaults", { activatedAt: new Date().toISOString() });
+ });
+}
diff --git a/src/sandbox/sandbox-resources.ts b/src/sandbox/sandbox-resources.ts
index 1555e7c30..1b5bebbc9 100644
--- a/src/sandbox/sandbox-resources.ts
+++ b/src/sandbox/sandbox-resources.ts
@@ -1,15 +1,10 @@
import { withLiveTurnMembership } from "../resolution/scope-membership.ts";
-import { randomUUID, createHash } from "node:crypto";
+import { randomUUID } from "node:crypto";
import type { DurableMap } from "../persistence/durable-map.ts";
import type { AdvisoryLock } from "../persistence/advisory-lock.ts";
import { parseScopeId, type CommandPolicy, type EgressPolicy, type ScopeId } from "../types.ts";
-import {
- sandboxDefaultForScope,
- type SandboxScopeDefaults,
- type SandboxBackendName,
- type SandboxRoute,
-} from "./sandbox-routing.ts";
-import type { Sandbox, SandboxHandle, AgentComputerSpec, ProvisionOptions, ComputerStatus } from "./sandbox.ts";
+import type { SandboxBackendName } from "./sandbox-routing.ts";
+import type { Sandbox, AgentComputerSpec, ProvisionOptions, ComputerStatus } from "./sandbox.ts";
export interface SandboxResource {
id: string;
@@ -41,16 +36,6 @@ export interface SandboxDefault {
sandboxId: string | null;
}
-export interface SandboxResourceRollout {
- activatedAt: string;
-}
-
-export interface LegacySandboxBinding {
- scopeId: string;
- backend: SandboxBackendName;
- machineId?: string;
-}
-
export interface SandboxResources {
forTurn(turn: { actorId: string; scopeId: ScopeId; isCurrent: () => Promise<boolean> }): SandboxResources;
initialize(): Promise<void>;
@@ -76,101 +61,31 @@ export interface SandboxResources {
retire(actorId: string, id: string): Promise<void>;
use<T>(id: string, action: () => Promise<T>, exclusive?: boolean): Promise<T>;
setDefault(actorId: string, scopeId: ScopeId, id: string | null): Promise<void>;
- resolve(scopeId: ScopeId): Promise<SandboxResource | null | undefined>;
+ resolve(scopeId: ScopeId): Promise<SandboxResource | null>;
get(id: string): Promise<SandboxResource>;
- defaultBackend(scopeId?: string): SandboxBackendName;
- withLegacyMutation<T>(scopeId: string, action: () => Promise<T>): Promise<T>;
- recordLegacy(scopeId: string, backend: SandboxBackendName, handle: SandboxHandle): Promise<string>;
+ defaultBackend(): SandboxBackendName;
}
export function createSandboxResources(opts: {
- enabled: boolean;
- rollout: DurableMap<SandboxResourceRollout>;
- legacyScopes?: () => Promise<string[]>;
- legacySandboxes?: () => Promise<LegacySandboxBinding[]>;
+ upgrade?: () => Promise<void>;
records: DurableMap<SandboxResource>;
defaults: DurableMap<SandboxDefault>;
- routes: DurableMap<SandboxRoute>;
backends: Partial<Record<SandboxBackendName, Sandbox>>;
defaultBackend: SandboxBackendName;
- scopeDefaults?: SandboxScopeDefaults;
provisionOptions?: (scopeId: string) => Promise<ProvisionOptions>;
beforeDefaultChange?: (scopeId: string) => Promise<void>;
beforeRetire?: (record: SandboxResource) => Promise<void>;
lock: AdvisoryLock;
canUseScope(actorId: string, scopeId: ScopeId): Promise<boolean>;
}): SandboxResources {
- const legacyId = (scopeId: string, backend: SandboxBackendName): string =>
- `legacy-${createHash("sha256").update(`${backend}:${scopeId}`).digest("hex").slice(0, 24)}`;
- let activated = false;
- const isActivated = async (): Promise<boolean> => {
- if (!activated) activated = (await opts.rollout.get("explicit-defaults")) !== null;
- return activated;
- };
+ let upgraded: Promise<void> | undefined;
const initialize = async (): Promise<void> => {
- if (await isActivated()) return;
- if (!opts.enabled) return;
- await opts.lock.withLock("sandbox-resources:activation", async () => {
- if (await isActivated()) return;
- const [existing, routes, knownScopes, bindings] = await Promise.all([
- opts.records.all(),
- opts.routes.entries(),
- opts.legacyScopes?.() ?? [],
- opts.legacySandboxes?.() ?? [],
- ]);
- const managedScopes = new Set(existing.filter((record) => !record.legacy).map((record) => record.backingScopeId));
- const valid = (scope: string): boolean => !!parseScopeId(scope).kind && !managedScopes.has(scope);
- const routeBackends = new Map(routes.map(([scope, route]) => [scope, route.backend]));
- const scopes = new Set(
- [
- ...knownScopes,
- ...routes.map(([scope]) => scope),
- ...bindings.map((binding) => binding.scopeId),
- ...existing.map((record) => record.ownerScopeId),
- ].filter(valid),
- );
- const candidates = new Map<string, LegacySandboxBinding>();
- for (const binding of bindings) {
- if (valid(binding.scopeId)) candidates.set(legacyId(binding.scopeId, binding.backend), binding);
- }
- for (const scope of scopes) {
- const backend =
- routeBackends.get(scope) ?? sandboxDefaultForScope(scope, opts.defaultBackend, opts.scopeDefaults);
- const id = legacyId(scope, backend);
- if (!candidates.has(id)) candidates.set(id, { scopeId: scope, backend });
- }
- for (const [id, binding] of candidates) {
- await opts.records.putIfAbsent(id, {
- id,
- backend: binding.backend,
- ownerScopeId: binding.scopeId,
- backingScopeId: binding.scopeId,
- name: "Existing scoped computer",
- createdBy: "system",
- createdAt: new Date().toISOString(),
- legacy: true,
- state: "unverified",
- ...(binding.machineId ? { machineId: binding.machineId } : {}),
- ...(opts.backends[binding.backend]?.profile.spec
- ? { spec: opts.backends[binding.backend]!.profile.spec }
- : {}),
- });
- }
- for (const scope of scopes) {
- const id = legacyId(
- scope,
- routeBackends.get(scope) ?? sandboxDefaultForScope(scope, opts.defaultBackend, opts.scopeDefaults),
- );
- const record = await opts.records.get(id);
- await opts.defaults.putIfAbsent(scope, { sandboxId: record?.state === "retired" ? null : id });
- }
- await opts.rollout.put("explicit-defaults", { activatedAt: new Date().toISOString() });
- activated = true;
+ if (!opts.upgrade) return;
+ upgraded ??= opts.upgrade().catch((error: unknown) => {
+ upgraded = undefined;
+ throw error;
});
- };
- const requireEnabled = async (): Promise<void> => {
- if (!opts.enabled) throw new Error("sandbox management is disabled until the resource rollout is enabled");
- await initialize();
+ await upgraded;
};
const actionsFor = (backend: Sandbox | undefined): string[] => {
if (!backend) return [];
@@ -200,24 +115,6 @@ export function createSandboxResources(opts: {
return action();
});
};
- const recordLegacy = async (scopeId: string, backend: SandboxBackendName, handle: SandboxHandle): Promise<string> => {
- const id = legacyId(scopeId, backend);
- await opts.records.putIfAbsent(id, {
- id,
- backend,
- ownerScopeId: scopeId,
- backingScopeId: scopeId,
- name: "Existing scoped computer",
- createdBy: "system",
- createdAt: new Date().toISOString(),
- legacy: true,
- state: "ready",
- machineId: handle.id,
- spec: opts.backends[backend]?.profile.spec,
- });
- if (await isActivated()) await opts.defaults.putIfAbsent(scopeId, { sandboxId: id });
- return id;
- };
return {
forTurn: (turn) =>
createSandboxResources({
@@ -225,24 +122,12 @@ export function createSandboxResources(opts: {
canUseScope: async (actorId, scopeId) =>
withLiveTurnMembership(opts.canUseScope, { ...turn, verified: await turn.isCurrent() })(actorId, scopeId),
}),
- defaultBackend: (scopeId) => sandboxDefaultForScope(scopeId, opts.defaultBackend, opts.scopeDefaults),
+ defaultBackend: () => opts.defaultBackend,
initialize,
get,
- recordLegacy: (scopeId, backend, handle) =>
- opts.lock.withLock("sandbox-resources:activation", () => recordLegacy(scopeId, backend, handle)),
- async withLegacyMutation(scopeId, action) {
- await initialize();
- return opts.lock.withLock("sandbox-resources:activation", async () => {
- if ((await isActivated()) || (await opts.defaults.get(scopeId)))
- throw new Error(
- "sandbox migration is retired for explicit defaults; create a sandbox and set its default instead",
- );
- return action();
- });
- },
use,
async retire(actorId, id) {
- await requireEnabled();
+ await initialize();
const record = await get(id);
await authorize(actorId, record.ownerScopeId);
await opts.lock.withLock(`sandbox-resource:${id}`, () =>
@@ -250,10 +135,7 @@ export function createSandboxResources(opts: {
const current = await get(id);
if (current.state === "retired" && !current.cleanupPending && !current.error) return;
const selected = await opts.defaults.get(current.ownerScopeId);
- const legacyBackend =
- (await opts.routes.get(current.ownerScopeId))?.backend ??
- sandboxDefaultForScope(current.ownerScopeId, opts.defaultBackend, opts.scopeDefaults);
- if (selected?.sandboxId === id || (!selected && current.legacy && current.backend === legacyBackend))
+ if (selected?.sandboxId === id)
throw new Error("unset or change this scope's default before retiring its computer");
await opts.beforeRetire?.(current);
const backend = opts.backends[current.backend];
@@ -283,7 +165,7 @@ export function createSandboxResources(opts: {
return use(id, () => backend.computerStatus!(record.backingScopeId));
},
async restart(actorId, id) {
- await requireEnabled();
+ await initialize();
const record = await get(id);
if (record.state === "retired") throw new Error("sandbox has been retired");
await authorize(actorId, record.ownerScopeId);
@@ -294,8 +176,7 @@ export function createSandboxResources(opts: {
async resolve(scopeId) {
await initialize();
const route = await opts.defaults.get(scopeId);
- if (!route) return (await isActivated()) ? null : undefined;
- return route.sandboxId === null ? null : get(route.sandboxId);
+ return route?.sandboxId ? get(route.sandboxId) : null;
},
async list(actorId, scopeId) {
await authorize(actorId, scopeId);
@@ -325,7 +206,7 @@ export function createSandboxResources(opts: {
};
},
async create(actorId, scopeId, backend, name, reservationId) {
- await requireEnabled();
+ await initialize();
await authorize(actorId, scopeId);
if (!Object.hasOwn(opts.backends, backend) || !opts.backends[backend as SandboxBackendName])
throw new Error(`sandbox backend unavailable: ${backend}`);
@@ -376,7 +257,7 @@ export function createSandboxResources(opts: {
});
},
async setDefault(actorId, scopeId, id) {
- await requireEnabled();
+ await initialize();
await authorize(actorId, scopeId);
await opts.lock.withLock(`sandbox-default:${scopeId}`, async () => {
if (id !== null) {
diff --git a/src/sandbox/sandbox-routing.ts b/src/sandbox/sandbox-routing.ts
index 9ef52c6da..4960a78bd 100644
--- a/src/sandbox/sandbox-routing.ts
+++ b/src/sandbox/sandbox-routing.ts
@@ -1,6 +1,5 @@
import type { SandboxResources } from "./sandbox-resources.ts";
-import { parseScopeId, type ScopeKind, type WorkspaceLayer } from "../types.ts";
-import type { DurableMap } from "../persistence/durable-map.ts";
+import type { WorkspaceLayer } from "../types.ts";
import { swallow, swallowAs } from "../util/errors.ts";
import {
CapabilityUnsupportedError,
@@ -20,8 +19,6 @@ import {
export type SandboxBackendName =
"sprites" | "aws" | "local" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37" | "superserve";
-export type SandboxScopeDefaults = Partial<Record<ScopeKind, SandboxBackendName>>;
-
export class NoDefaultSandboxError extends Error {
constructor() {
super(
@@ -30,65 +27,26 @@ export class NoDefaultSandboxError extends Error {
}
}
-export function sandboxDefaultForScope(
- scope: string | undefined,
- fallback: SandboxBackendName,
- defaults?: SandboxScopeDefaults,
-): SandboxBackendName {
- const kind = scope ? parseScopeId(scope).kind : null;
- return (kind && defaults?.[kind]) || fallback;
-}
-
-export interface SandboxRoute {
- backend: SandboxBackendName;
- migratedAt?: string;
- migrationSha?: string;
- capabilitiesLost?: string[];
- pinned?: boolean;
- reason?: string;
-}
-
export interface RoutingSandboxOptions {
backends: Partial<Record<SandboxBackendName, Sandbox>>;
- routes: DurableMap<SandboxRoute>;
defaultBackend: SandboxBackendName;
- scopeDefaults?: SandboxScopeDefaults;
- resources?: SandboxResources;
+ resources: SandboxResources;
onError?: (e: { category: string; code: string; message: string; scopeLabel?: string }) => void;
}
-export const ROUTE_CACHE_TTL_MS = 15_000;
-
export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
- const { backends, routes, defaultBackend } = opts;
+ const { backends, resources, defaultBackend } = opts;
const fallback = ((): Sandbox => {
const s = backends[defaultBackend];
if (!s) throw new Error(`sandbox router: default backend ${defaultBackend} is not constructed`);
return s;
})();
- const routeCache = new Map<string, { route: SandboxRoute | null; at: number }>();
- async function routeFor(scopeId: string): Promise<SandboxRoute | null> {
- const hit = routeCache.get(scopeId);
- if (hit && Date.now() - hit.at < ROUTE_CACHE_TTL_MS) return hit.route;
- const route = (await routes.get(scopeId)) ?? null;
- routeCache.set(scopeId, { route, at: Date.now() });
- return route;
- }
-
- async function pick(scopeId: string): Promise<{ name: SandboxBackendName; sandbox: Sandbox }> {
- const route = await routeFor(scopeId);
- const name = route?.backend ?? sandboxDefaultForScope(scopeId, defaultBackend, opts.scopeDefaults);
+ const backendFor = (name: SandboxBackendName): Sandbox => {
const sandbox = backends[name];
- if (sandbox) return { name, sandbox };
- opts.onError?.({
- category: "sandbox_routing",
- code: "backend_unavailable",
- message: `scope routed to ${name} but that backend is not constructed here; refusing a substitute computer`,
- scopeLabel: scopeId,
- });
- throw new Error(`sandbox backend unavailable: ${name}; refusing to use a substitute computer`);
- }
+ if (!sandbox) throw new Error(`sandbox backend unavailable: ${name}; refusing to use a substitute computer`);
+ return sandbox;
+ };
const forHandle = (handle: SandboxHandle): Sandbox => {
if (!handle.backend) return fallback;
@@ -98,29 +56,12 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
};
const useHandle = <T>(handle: SandboxHandle, action: () => Promise<T>): Promise<T> =>
- handle.resourceId && opts.resources ? opts.resources.use(handle.resourceId, action) : action();
+ handle.resourceId ? resources.use(handle.resourceId, action) : action();
- async function computerTarget(scopeId: string): Promise<{ sandbox: Sandbox; scopeId: string; resourceId?: string }> {
- const resource = await opts.resources?.resolve(scopeId);
- if (resource === null) throw new NoDefaultSandboxError();
- if (resource) {
- const sandbox = backends[resource.backend];
- if (!sandbox) throw new Error(`sandbox backend unavailable: ${resource.backend}`);
- return { sandbox, scopeId: resource.backingScopeId, resourceId: resource.id };
- }
- return { sandbox: await pickStrict(scopeId), scopeId };
- }
-
- async function pickStrict(scopeId: string): Promise<Sandbox> {
- const route = await routeFor(scopeId);
- const name = route?.backend ?? sandboxDefaultForScope(scopeId, defaultBackend, opts.scopeDefaults);
- const sandbox = backends[name];
- if (!sandbox) {
- throw new Error(
- `scope ${scopeId} is routed to ${name}, which is not constructed here — refusing to act on a substitute computer`,
- );
- }
- return sandbox;
+ async function computerTarget(scopeId: string) {
+ const resource = await resources.resolve(scopeId);
+ if (!resource) throw new NoDefaultSandboxError();
+ return { sandbox: backendFor(resource.backend), scopeId: resource.backingScopeId, resourceId: resource.id };
}
const reportedGaps = new Set<string>();
@@ -155,45 +96,33 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
profile: fallback.profile,
async profileFor(scopeId: string, sandboxId?: string): Promise<AgentComputerProfile> {
- const resource = sandboxId ? await opts.resources?.get(sandboxId) : await opts.resources?.resolve(scopeId);
- if (sandboxId && !resource) throw new Error("sandbox inventory unavailable");
- if (resource) {
- const sandbox = backends[resource.backend];
- if (!sandbox) throw new Error(`sandbox backend unavailable: ${resource.backend}`);
- return sandbox.profile;
- }
- if (resource === null) return fallback.profile;
- return (await pick(scopeId)).sandbox.profile;
+ const resource = sandboxId ? await resources.get(sandboxId) : await resources.resolve(scopeId);
+ return resource ? backendFor(resource.backend).profile : fallback.profile;
},
async provision(layers: WorkspaceLayer[], provOpts?: ProvisionOptions): Promise<SandboxHandle> {
const scope = provOpts?.routeScopeId ?? writableScope(layers);
- let resource;
- if (provOpts?.sandboxId) resource = await opts.resources?.get(provOpts.sandboxId);
- else if (!provOpts?.scratch) resource = await opts.resources?.resolve(scope);
- if (provOpts?.sandboxId && !resource) throw new Error("sandbox inventory unavailable");
- if (resource === null) throw new NoDefaultSandboxError();
- if (resource) {
- const sandbox = backends[resource.backend];
- if (!sandbox) throw new Error(`sandbox backend unavailable: ${resource.backend}`);
- const routedLayers = layers.map((layer) =>
- layer.mode === "rw" ? { ...layer, scopeId: resource.backingScopeId } : layer,
- );
- const handle = await opts.resources!.use(resource.id, () => sandbox.provision(routedLayers, provOpts), true);
- return { ...handle, backend: resource.backend, scopeId: resource.ownerScopeId, resourceId: resource.id };
- }
- const { name, sandbox } = await pick(scope);
- 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 resource = provOpts?.sandboxId ? await resources.get(provOpts.sandboxId) : await resources.resolve(scope);
+ const backend = resource?.backend ?? defaultBackend;
+ const sandbox = backendFor(backend);
+ const provision = async (targetLayers: WorkspaceLayer[]) => {
+ try {
+ return await sandbox.provision(targetLayers, provOpts);
+ } catch (error) {
+ if (error instanceof SandboxProvisionCleanupError) error.handle.backend = backend;
+ throw error;
+ }
+ };
+ if (provOpts?.scratch) {
+ const handle = await provision(layers);
+ return { ...handle, backend, scopeId: scope };
}
- const resourceId =
- !provOpts?.scratch && scope ? await opts.resources?.recordLegacy(scope, name, handle) : undefined;
- return { ...handle, backend: name, ...(scope ? { scopeId: scope } : {}), ...(resourceId ? { resourceId } : {}) };
+ if (!resource) throw new NoDefaultSandboxError();
+ const routedLayers = layers.map((layer) =>
+ layer.mode === "rw" ? { ...layer, scopeId: resource.backingScopeId } : layer,
+ );
+ const handle = await resources.use(resource.id, () => provision(routedLayers), true);
+ return { ...handle, backend: resource.backend, scopeId: resource.ownerScopeId, resourceId: resource.id };
},
run(handle, command, execOpts?: ExecOptions): Promise<ExecResult> {
@@ -231,12 +160,8 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
},
teardown(handle, tdOpts?: TeardownOptions): Promise<void> {
const action = () => forHandle(handle).teardown(handle, tdOpts);
- return handle.resourceId && opts.resources
- ? opts.resources.use(
- handle.resourceId,
- action,
- !!tdOpts?.destroy || !!forHandle(handle).profile.parksOnTeardown,
- )
+ return handle.resourceId
+ ? resources.use(handle.resourceId, action, !!tdOpts?.destroy || !!forHandle(handle).profile.parksOnTeardown)
: action();
},
@@ -300,7 +225,7 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
computerStatus: async (scopeId: string) => {
const target = await computerTarget(scopeId);
const action = () => requireCap(target.sandbox, "computerStatus", scopeId).computerStatus(target.scopeId);
- return target.resourceId && opts.resources ? opts.resources.use(target.resourceId, action) : action();
+ return resources.use(target.resourceId, action);
},
}
: {}),
@@ -309,7 +234,7 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
restartComputer: async (scopeId: string) => {
const target = await computerTarget(scopeId);
const action = () => requireCap(target.sandbox, "restartComputer", scopeId).restartComputer(target.scopeId);
- return target.resourceId && opts.resources ? opts.resources.use(target.resourceId, action, true) : action();
+ return resources.use(target.resourceId, action, true);
},
}
: {}),
diff --git a/src/sandbox/sandbox.ts b/src/sandbox/sandbox.ts
index a3f2a7798..86ab65136 100644
--- a/src/sandbox/sandbox.ts
+++ b/src/sandbox/sandbox.ts
@@ -238,7 +238,6 @@ export interface Sandbox {
writeStdin?(handle: SandboxHandle, processId: string, data: string): Promise<void>;
signalProcess?(handle: SandboxHandle, processId: string, signal: string): Promise<void>;
listProcesses?(handle: SandboxHandle): Promise<ProcessSession[]>;
- adoptHomeSnapshot?(scopeId: string, blobId: string): Promise<void>;
persistHomeSnapshot?(scopeId: string): Promise<void>;
computerStatus?(scopeId: string): Promise<ComputerStatus>;
restartComputer?(scopeId: string): Promise<void>;
@@ -291,20 +290,3 @@ export function supportsProcessSessions(sandbox: Sandbox): sandbox is ProcessSan
typeof sandbox.listProcesses === "function"
);
}
-
-const SANDBOX_CAPABILITIES: ReadonlyArray<{ label: string; supported: (s: Sandbox) => boolean }> = [
- { label: "process sessions (background work, dev servers)", supported: supportsProcessSessions },
- { label: "home export (publish, resident-auth capture)", supported: supportsAgentComputerExport },
-];
-
-const ENFORCEMENT_RANK: Record<EgressEnforcement, number> = { none: 0, ip_port: 1, domain: 2 };
-
-export function capabilitiesLostMovingTo(from: Sandbox, to: Sandbox): string[] {
- const lost = SANDBOX_CAPABILITIES.filter((c) => c.supported(from) && !c.supported(to)).map((c) => c.label);
- const fromEgress = from.profile.egressEnforcement ?? "none";
- const toEgress = to.profile.egressEnforcement ?? "none";
- if (ENFORCEMENT_RANK[toEgress] < ENFORCEMENT_RANK[fromEgress]) {
- lost.push(`egress enforcement (${fromEgress} on the source, ${toEgress} on the target)`);
- }
- return lost;
-}
diff --git a/src/swarms/swarm-service.ts b/src/swarms/swarm-service.ts
index 5a784136c..0661b5b99 100644
--- a/src/swarms/swarm-service.ts
+++ b/src/swarms/swarm-service.ts
@@ -298,7 +298,7 @@ export function createSwarmService(deps: {
const source = run.request;
const inventory = await deps.sandboxes.list(auth.actorId, session.scopeId);
const selected = inventory.sandboxes.find((box) => box.id === inventory.defaultSandboxId);
- const requested = backend ?? selected?.backend ?? deps.sandboxes.defaultBackend(session.scopeId);
+ const requested = backend ?? selected?.backend ?? deps.sandboxes.defaultBackend();
const provider = inventory.providers.find((item) => item.name === requested);
if (!provider || !provider.actions.includes("create") || !provider.actions.includes("retire"))
throw new Error("sandbox backend must support creating and retiring workers");
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index e2c991889..35034e637 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -11,8 +11,6 @@ import { join } from "node:path";
import { interpolateSplitEnv } from "../deployment/deployment-layer.ts";
import type { CredentialPathSpec } from "../credentials/resident-paths.ts";
import type { ComputerStatus, ExecResult, Sandbox, SandboxHandle } from "../sandbox/sandbox.ts";
-import { ROUTE_CACHE_TTL_MS, type SandboxBackendName } from "../sandbox/sandbox-routing.ts";
-import type { SandboxMigrationRunner } from "../sandbox/sandbox-migration-runner.ts";
import { CapabilityUnsupportedError, hasParentPathSegment, supportsAgentComputerExport } from "../sandbox/sandbox.ts";
import type {
ApprovalGrantModes,
@@ -226,7 +224,6 @@ export interface ToolContext extends SurfaceToolDeps {
): Promise<unknown>;
computerStatus(sandboxId?: string): Promise<ComputerStatus>;
restartComputer(sandboxId?: string): Promise<void>;
- migrateComputer(to: string): Promise<{ from: string; to: string }>;
read(path: string, signal?: AbortSignal): Promise<ReadResult>;
skill(name: string, opts?: { path?: string; sandboxId?: string; signal?: AbortSignal }): Promise<SkillResult>;
write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult>;
@@ -474,10 +471,8 @@ export interface ToolContextDeps {
grantedHandles: GrantedHandle[];
context?: TurnContext;
sharedMaterializeDir?: string;
- sandboxMigration?: SandboxMigrationRunner;
sandboxResources?: SandboxResources;
invalidateProvision?: () => void;
- migrateSettleMs?: number;
workspace: WorkspaceStore;
deploy: DeployService;
acl: AclStore;
@@ -722,60 +717,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
if (!writableScopeId) throw new Error("this turn has no scoped computer to restart");
await deps.sandbox.restartComputer(writableScopeId);
},
- async migrateComputer(to: string): Promise<{ from: string; to: string }> {
- if (writableScopeId && (await deps.sandboxResources?.resolve(writableScopeId)) !== undefined)
- throw new Error("this scope uses sandbox resources; create a sandbox and change its default independently");
- const runner = deps.sandboxMigration;
- if (!runner) throw new Error("computer migration is not available on this deployment");
- if (!writableScopeId) throw new Error("this turn has no scoped computer to migrate");
- const available = runner.availableBackends();
- if (!(available as string[]).includes(to)) {
- throw new Error(
- `${JSON.stringify(to)} is not an available backend here — choose one of: ${available.join(", ")}`,
- );
- }
- const approvalCommand = `computer:"migrate" to:"${to}"`;
- const approvalKey = `computer-migrate:${to}`;
- if (!deps.authorizeCommand(approvalCommand, approvalKey)) {
- throw new NeedsApproval(
- approvalCommand,
- `moving this computer to ${to} re-homes its files onto a different provider and can take several minutes`,
- "approval",
- undefined,
- approvalKey,
- );
- }
- try {
- const result = await runner.migrateScope(writableScopeId, to as SandboxBackendName, "agent-requested", {
- copyTimeoutSec: 1800,
- });
- deps.auditLog?.record({
- at: Date.now(),
- principalId: deps.createdBy,
- action: "sandbox_routes.migrate",
- resource: `${result.from}->${result.to} sha=${result.sha.slice(0, 12)}`,
- scopeLabel: writableScopeId,
- });
- await new Promise((res) => setTimeout(res, deps.migrateSettleMs ?? ROUTE_CACHE_TTL_MS));
- deps.invalidateProvision?.();
- return { from: result.from, to: result.to };
- } catch (err) {
- deps.auditLog?.record({
- at: Date.now(),
- principalId: deps.createdBy,
- action: "sandbox_routes.migrate_failed",
- resource: errMessage(err).slice(0, 200),
- scopeLabel: writableScopeId,
- });
- throw new Error(
- errMessage(err).replace(
- "Migrate with force to accept the loss.",
- "An operator can force this from the admin console.",
- ),
- { cause: err },
- );
- }
- },
async execute(
command: string,
execOpts?: {
diff --git a/src/wiring.ts b/src/wiring.ts
index 2b8af52e2..10a4fcc02 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -45,7 +45,6 @@ import {
type SandboxResource,
type SandboxDefault,
type SandboxResources,
- type SandboxResourceRollout,
} from "./sandbox/sandbox-resources.ts";
import { createModelVerifier, type ModelVerifier } from "./model/model-verification.ts";
import type { probeModel } from "./harness/pi-harness.ts";
@@ -235,13 +234,12 @@ import { createS3SnapshotStore } from "./sandbox/home-snapshot.ts";
import { createModalSandbox, type StoredModalSandbox } from "./sandbox/modal-sandbox.ts";
import { createSdkModalClient } from "./sandbox/modal-client.ts";
import { createPorterSandbox } from "./sandbox/porter-sandbox.ts";
+import { createSandboxRouter, type SandboxBackendName } from "./sandbox/sandbox-routing.ts";
import {
- createSandboxRouter,
- ROUTE_CACHE_TTL_MS,
- type SandboxBackendName,
- type SandboxRoute,
-} from "./sandbox/sandbox-routing.ts";
-import { createSandboxMigrationRunner, type SandboxMigrationRunner } from "./sandbox/sandbox-migration-runner.ts";
+ upgradeLegacySandboxes,
+ legacySandboxBackendForScope,
+ type LegacyRoute,
+} from "./sandbox/sandbox-resource-upgrade.ts";
import { effectiveEgressEnforcement, type Sandbox } from "./sandbox/sandbox.ts";
import { withOperatorTokenFallback } from "./credentials/connector-token.ts";
import {
@@ -540,7 +538,6 @@ export interface BuiltApp {
memory: MemoryService;
sandbox: Sandbox;
advisoryLock: AdvisoryLock;
- sandboxMigration: SandboxMigrationRunner;
sandboxResources: SandboxResources;
blobTransfer: BlobTransferStore;
files: FileArtifactStore;
@@ -1094,38 +1091,47 @@ export function buildApp(
for (const name of Object.keys(buildBackend) as Array<Config["sandboxBackend"]>) {
if (name !== config.sandboxBackend && enabledBackends.has(name)) sandboxBackends[name] = buildBackend[name]();
}
- for (const backend of Object.values(config.sandboxScopeDefaults ?? {})) {
- if (backend && !sandboxBackends[backend]) throw new Error(`Scope sandbox backend ${backend} is not configured`);
- }
- const sandboxRoutes = artifactMap<SandboxRoute>("sandbox_routing");
+ const sandboxRecords = artifactMap<SandboxResource>("sandbox_resources");
+ const sandboxDefaults = artifactMap<SandboxDefault>("sandbox_defaults");
const sandboxResources = createSandboxResources({
- enabled: config.sandboxResourcesEnabled,
- rollout: artifactMap<SandboxResourceRollout>("sandbox_resource_rollout"),
- legacyScopes: async () => (await sessions.distinctScopes()).map((scope) => scope.scopeId),
- legacySandboxes: async () => {
- const [e2b, modal, aws, superserve] = await Promise.all([
- e2bBodies.entries(),
- modalBodies.entries(),
- awsBodies.entries(),
- superserveBodies.entries(),
- ]);
- return [
- ...e2b.map(([scopeId, body]) => ({ scopeId, backend: "e2b" as const, machineId: body.sandboxId })),
- ...modal.map(([scopeId, body]) => ({ scopeId, backend: "modal" as const, machineId: body.sandboxId })),
- ...aws.map(([scopeId, body]) => ({ scopeId, backend: "aws" as const, machineId: body.microvmId })),
- ...superserve.map(([scopeId, body]) => ({
- scopeId,
- backend: "superserve" as const,
- machineId: body.sandboxId,
- })),
- ];
- },
- records: artifactMap<SandboxResource>("sandbox_resources"),
- defaults: artifactMap<SandboxDefault>("sandbox_defaults"),
- routes: sandboxRoutes,
+ records: sandboxRecords,
+ defaults: sandboxDefaults,
+ upgrade: () =>
+ upgradeLegacySandboxes({
+ availableBackends: Object.keys(sandboxBackends) as SandboxBackendName[],
+ records: sandboxRecords,
+ defaults: sandboxDefaults,
+ marker: artifactMap<{ activatedAt: string }>("sandbox_resource_rollout"),
+ routes: () => artifactMap<LegacyRoute>("sandbox_routing").entries(),
+ lock: advisoryLock,
+ legacyBackend: (scope) =>
+ legacySandboxBackendForScope(scope, config.sandboxBackend, config.legacySandboxScopeDefaults),
+ specFor: (backend) => sandboxBackends[backend]?.profile.spec,
+ legacyScopes: async () => [
+ ...(await sessions.distinctScopes()).map((scope) => scope.scopeId),
+ ...(await environments.list()).map((environment) => environment.id),
+ ],
+ legacySandboxes: async () => {
+ const [e2b, modal, aws, superserve] = await Promise.all([
+ e2bBodies.entries(),
+ modalBodies.entries(),
+ awsBodies.entries(),
+ superserveBodies.entries(),
+ ]);
+ return [
+ ...e2b.map(([scopeId, body]) => ({ scopeId, backend: "e2b" as const, machineId: body.sandboxId })),
+ ...modal.map(([scopeId, body]) => ({ scopeId, backend: "modal" as const, machineId: body.sandboxId })),
+ ...aws.map(([scopeId, body]) => ({ scopeId, backend: "aws" as const, machineId: body.microvmId })),
+ ...superserve.map(([scopeId, body]) => ({
+ scopeId,
+ backend: "superserve" as const,
+ machineId: body.sandboxId,
+ })),
+ ];
+ },
+ }),
backends: sandboxBackends,
defaultBackend: config.sandboxBackend,
- scopeDefaults: config.sandboxScopeDefaults,
lock: advisoryLock,
beforeRetire: async (record) => {
if (
@@ -1162,37 +1168,9 @@ export function buildApp(
const sandbox: Sandbox = createSandboxRouter({
resources: sandboxResources,
backends: sandboxBackends,
- routes: sandboxRoutes,
defaultBackend: config.sandboxBackend,
- scopeDefaults: config.sandboxScopeDefaults,
onError: sandboxOnError,
});
- const sandboxMigration = createSandboxMigrationRunner({
- backends: sandboxBackends,
- routes: sandboxRoutes,
- defaultBackend: config.sandboxBackend,
- scopeDefaults: config.sandboxScopeDefaults,
- advisoryLock,
- settleMs: ROUTE_CACHE_TTL_MS,
- provisionOptions: async (scopeId) => {
- const egressSecret = config.capabilitySecret ?? config.signingSecret;
- if (!egressSecret) return {};
- const egressToken = await mintCapabilityToken(
- {
- actorId: "system:sandbox-migration",
- scopeId: scopeId as ScopeId,
- aud: EGRESS_PROXY_AUD,
- egress: egressClaimAllowingControlPlane({ allowedHosts: [] }, config.apiBaseUrl ?? "", true),
- exp: Date.now() + CAPABILITY_TTL_MS,
- },
- egressSecret,
- config.capabilityTokenCompression,
- );
- return { egressToken };
- },
- withLegacyMutation: (scope, action) => sandboxResources.withLegacyMutation(scope, action),
- hasLiveWork: async (scope) => !!processes && (await processes.liveByScope(scope)).length > 0,
- });
const secretSource =
config.secretsBackend === "aws"
? createLayeredSecretSource(
@@ -1939,7 +1917,6 @@ export function buildApp(
workspace,
files,
sandbox,
- sandboxMigration,
sandboxResources,
swarms,
connectorTokens,
@@ -2870,7 +2847,6 @@ export function buildApp(
...(askResolution ? { fireAskResolution: askResolution } : {}),
...(dropResolution ? { fireDropResolution: dropResolution } : {}),
sandbox,
- sandboxMigration,
sandboxResources,
advisoryLock,
blobTransfer,
@@ -3048,7 +3024,6 @@ export function serverDeps(
sessionShares: built.sessionShares,
sessionShareBytes: built.sessionShareBytes,
environments: built.environments,
- sandboxMigration: built.sandboxMigration,
sandboxResources: built.sandboxResources,
};
}
diff --git a/test/admin-agent-capability.test.ts b/test/admin-agent-capability.test.ts
index 1ca9fb5c1..93a20aeda 100644
--- a/test/admin-agent-capability.test.ts
+++ b/test/admin-agent-capability.test.ts
@@ -1,4 +1,5 @@
import "./support/auto-fake-sprites.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -584,6 +585,7 @@ for (const [name, input, expected] of [
test(`orchestrator-issued ${name} token reaches the HTTP admin gate with the right authority`, async () => {
const s = start();
try {
+ await selectDefaultSandbox(s.built, "admin-alice", "channel:C1");
let cap: string | undefined;
const provision = s.built.sandbox.provision.bind(s.built.sandbox);
s.built.sandbox.provision = (layers, opts) => {
diff --git a/test/admin-metrics.test.ts b/test/admin-metrics.test.ts
index ca1840e12..87c13f536 100644
--- a/test/admin-metrics.test.ts
+++ b/test/admin-metrics.test.ts
@@ -1,4 +1,5 @@
import "./support/auto-fake-sprites.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -98,6 +99,7 @@ test("metrics: turn anatomy splits no-sandbox (Trace A) from sandbox (Trace B) t
text: "hello there",
};
assert.equal((await s.built.app.turn(chat)).status, "ok");
+ await selectDefaultSandbox(s.built, "U2", "personal:U2");
const tool: TurnRequest = {
surface: "test",
actor: { externalId: "U2" },
diff --git a/test/admin-sandbox-migrate.test.ts b/test/admin-sandbox-migrate.test.ts
deleted file mode 100644
index 043325f3b..000000000
--- a/test/admin-sandbox-migrate.test.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join, dirname } from "node:path";
-import type { AddressInfo } from "node:net";
-import { createInsecureTestServer } from "../src/api/server.ts";
-import { buildApp } from "../src/wiring.ts";
-import { createSandboxMigrationRunner } from "../src/sandbox/sandbox-migration-runner.ts";
-import { createMemoryMap } from "../src/persistence/durable-map.ts";
-import type { SandboxRoute } from "../src/sandbox/sandbox-routing.ts";
-import type { Sandbox, SandboxHandle, ExecResult } from "../src/sandbox/sandbox.ts";
-import { testConfig } from "./support/test-config.ts";
-
-function hostBackend(name: string, homeDir: string): Sandbox {
- mkdirSync(homeDir, { recursive: true });
- const rootDir = join(homeDir, "workspace");
- mkdirSync(rootDir, { recursive: true });
- const resolve = (rel: string) => join(rootDir, rel);
- return {
- profile: { backend: name, writablePersistence: "resident_disk", processSessions: false },
- async provision(): Promise<SandboxHandle> {
- return { id: `${name}-box`, rootDir, homeDir };
- },
- async run(_h: SandboxHandle, command: string): Promise<ExecResult> {
- const r = spawnSync("sh", ["-c", command], {
- encoding: "utf8",
- maxBuffer: 64 * 1024 * 1024,
- env: { PATH: process.env.PATH ?? "" },
- });
- return { stdout: r.stdout ?? "", stderr: r.stderr ?? "", code: r.status ?? -1, timedOut: false };
- },
- async readFileBytes(_h: SandboxHandle, rel: string): Promise<Uint8Array | null> {
- const p = resolve(rel);
- return existsSync(p) ? readFileSync(p) : null;
- },
- async writeFileBytes(_h: SandboxHandle, rel: string, data: Uint8Array): Promise<void> {
- const p = resolve(rel);
- mkdirSync(dirname(p), { recursive: true });
- writeFileSync(p, data);
- },
- async teardown(): Promise<void> {},
- async readFile() {
- return null;
- },
- async writeFile() {},
- async listDir() {
- return [];
- },
- async removeDir() {},
- } as unknown as Sandbox;
-}
-
-function start(root: string) {
- const fat = hostBackend("aws", join(root, "aws-home"));
- const thin = hostBackend("sprites", join(root, "sprites-home"));
- (fat as { exportFiles?: unknown }).exportFiles = async () => [];
- const routes = createMemoryMap<SandboxRoute>();
- const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "admin-migrate-")) }));
- const server = createInsecureTestServer(built.app, {
- admin: built.admin,
- sessions: built.sessions,
- auditLog: built.auditLog,
- workspace: built.workspace,
- sandboxMigration: createSandboxMigrationRunner({
- backends: { aws: fat, sprites: thin },
- routes,
- defaultBackend: "aws",
- }),
- });
- server.listen(0);
- const base = `http://localhost:${(server.address() as AddressInfo).port}`;
- return { base, built, routes, close: () => new Promise<void>((r) => server.close(() => r())) };
-}
-
-const ALICE = { "x-admin-actor": "admin-alice@default-org", "content-type": "application/json" };
-const migrate = (base: string, scopeId: string, body: unknown, headers: Record<string, string> = ALICE) =>
- fetch(`${base}/v1/admin/sandbox-routes/${encodeURIComponent(scopeId)}/migrate`, {
- method: "POST",
- headers,
- body: JSON.stringify(body),
- });
-
-test("copyTimeoutSec stretches the copy budget through to the guest execs, clamped to sane bounds", async () => {
- const root = mkdtempSync(join(tmpdir(), "admin-migrate-timeout-"));
- const fat = hostBackend("aws", join(root, "aws-home"));
- const thin = hostBackend("sprites", join(root, "sprites-home"));
- (fat as { exportFiles?: unknown }).exportFiles = async () => [];
- const timeouts: number[] = [];
- const origRun = fat.run.bind(fat);
- fat.run = async (h, command, opts) => {
- if (opts?.timeoutMs) timeouts.push(opts.timeoutMs);
- return origRun(h, command, opts);
- };
- const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "admin-migrate-")) }));
- const server = createInsecureTestServer(built.app, {
- admin: built.admin,
- sessions: built.sessions,
- auditLog: built.auditLog,
- workspace: built.workspace,
- sandboxMigration: createSandboxMigrationRunner({
- backends: { aws: fat, sprites: thin },
- routes: createMemoryMap<SandboxRoute>(),
- defaultBackend: "aws",
- }),
- });
- server.listen(0);
- const base = `http://localhost:${(server.address() as AddressInfo).port}`;
- try {
- const res = await migrate(base, "personal:U9", { to: "sprites", force: true, copyTimeoutSec: 999_999 });
- assert.equal(res.status, 200);
- assert.ok(
- timeouts.includes(7200 * 1000),
- `an oversized request is clamped to the 7200s ceiling and still reaches the copy execs (saw: ${timeouts.join(",")})`,
- );
- assert.ok(!timeouts.includes(900 * 1000), "the default budget is replaced, not merely accompanied");
- } finally {
- await new Promise<void>((r) => server.close(() => r()));
- }
-});
-
-test("the migrate endpoint refuses a capability-losing move, then records what force gave up", async () => {
- const root = mkdtempSync(join(tmpdir(), "admin-migrate-e2e-"));
- const s = start(root);
- try {
- writeFileSync(join(root, "aws-home", "notes.txt"), "hello\n");
-
- const refused = await migrate(s.base, "personal:yna", { to: "sprites" });
- assert.equal(refused.status, 409);
- const refusedBody = (await refused.json()) as { error: string; message: string };
- assert.equal(refusedBody.error, "migration_failed");
- assert.match(refusedBody.message, /home export \(publish, resident-auth capture\)/);
- assert.match(refusedBody.message, /force/);
- assert.equal(await s.routes.get("personal:yna"), null, "a refused migration leaves the scope where it was");
- assert.ok(
- (await s.built.auditLog.events()).some((e) => e.action === "sandbox_routes.migrate_failed"),
- "the refusal is audited",
- );
-
- const forced = await migrate(s.base, "personal:yna", { to: "sprites", reason: "canary", force: true });
- assert.equal(forced.status, 200);
- const body = (await forced.json()) as { to: string; capabilitiesLost: string[]; sha: string };
- assert.equal(body.to, "sprites");
- assert.deepEqual(body.capabilitiesLost, ["home export (publish, resident-auth capture)"]);
-
- assert.equal(readFileSync(join(root, "sprites-home", "notes.txt"), "utf8"), "hello\n");
- const route = await s.routes.get("personal:yna");
- assert.equal(route?.backend, "sprites");
- assert.equal(route?.reason, "canary");
- assert.deepEqual(route?.capabilitiesLost, ["home export (publish, resident-auth capture)"]);
-
- const migrated = (await s.built.auditLog.events()).find((e) => e.action === "sandbox_routes.migrate");
- assert.ok(migrated, "the migration is audited");
- assert.match(migrated.resource ?? "", /lost=home export/);
- assert.equal(migrated.scopeLabel, "personal:yna");
- } finally {
- await s.close();
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("migrating a scope is org-admin only", async () => {
- const root = mkdtempSync(join(tmpdir(), "admin-migrate-authz-"));
- const s = start(root);
- try {
- const r = await migrate(
- s.base,
- "personal:yna",
- { to: "sprites", force: true },
- {
- "x-admin-actor": "stranger@default-org",
- "content-type": "application/json",
- },
- );
- assert.ok(r.status === 401 || r.status === 403, `expected a refusal, got ${r.status}`);
- assert.equal(await s.routes.get("personal:yna"), null, "a rejected caller cannot move a scope");
- } finally {
- await s.close();
- rmSync(root, { recursive: true, force: true });
- }
-});
diff --git a/test/advisory-lock.test.ts b/test/advisory-lock.test.ts
index 784c47275..1299bb4d3 100644
--- a/test/advisory-lock.test.ts
+++ b/test/advisory-lock.test.ts
@@ -1,11 +1,6 @@
-import {
- createSandboxResources,
- type SandboxResource,
- type SandboxDefault,
- type SandboxResourceRollout,
-} from "../src/sandbox/sandbox-resources.ts";
-import type { SandboxRoute } from "../src/sandbox/sandbox-routing.ts";
-import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import type { SandboxResource, SandboxDefault } from "../src/sandbox/sandbox-resources.ts";
+import { upgradeLegacySandboxes, type SandboxResourceUpgradeMarker } from "../src/sandbox/sandbox-resource-upgrade.ts";
+import { createPostgresMap } from "../src/persistence/durable-map.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
import { createPgPool } from "../src/persistence/pg-pool.ts";
@@ -134,55 +129,64 @@ test("pg mutex: waiting beyond timeoutMs throws a clear error", { skip }, async
}
});
-test("pg sandbox activation fences publication from a separate compatible reader", { skip }, async () => {
+test("pg sandbox upgrade runs once across cores and never overwrites a newer default", { skip }, async () => {
const pgA = createPgPool(URL!);
const pgB = createPgPool(URL!);
const release = Promise.withResolvers<string[]>();
try {
- const options = {
- enabled: false,
- rollout: createMemoryMap<SandboxResourceRollout>(),
- records: createMemoryMap<SandboxResource>(),
- defaults: createMemoryMap<SandboxDefault>(),
- routes: createMemoryMap<SandboxRoute>(),
- backends: {},
- defaultBackend: "local" as const,
- canUseScope: async () => true,
- };
+ const maps = (pg: typeof pgA) => ({
+ availableBackends: ["local"] as const,
+ records: createPostgresMap<SandboxResource>(pg, "upgrade_sandbox_records"),
+ defaults: createPostgresMap<SandboxDefault>(pg, "upgrade_sandbox_defaults"),
+ marker: createPostgresMap<SandboxResourceUpgradeMarker>(pg, "upgrade_sandbox_marker"),
+ legacyBackend: () => "local" as const,
+ });
+ const shared = maps(pgA);
+ const other = maps(pgB);
+ await shared.defaults.put("personal:cleared", { sandboxId: null });
const entered = Promise.withResolvers<void>();
- const reader = createSandboxResources({ ...options, lock: createPostgresAdvisoryLock(pgB, { pollMs: 10 }) });
- const active = createSandboxResources({
- ...options,
- enabled: true,
+ let calls = 0;
+ const first = upgradeLegacySandboxes({
+ ...shared,
lock: createPostgresAdvisoryLock(pgA, { pollMs: 10 }),
legacyScopes: () => {
+ calls++;
entered.resolve();
return release.promise;
},
});
- const activation = active.initialize();
await entered.promise;
- const publication = reader.recordLegacy("personal:late", "local", { id: "late", rootDir: "/workspace" });
- release.resolve([]);
- await activation;
- const id = await publication;
- assert.equal((await reader.resolve("personal:late"))?.id, id);
- assert.deepEqual(await options.defaults.get("personal:late"), { sandboxId: id });
- let changed = false;
- await assert.rejects(
- reader.withLegacyMutation("personal:late", async () => {
- changed = true;
- }),
- /retired/,
- );
- assert.equal(changed, false);
+ const second = upgradeLegacySandboxes({
+ ...other,
+ lock: createPostgresAdvisoryLock(pgB, { pollMs: 10 }),
+ legacyScopes: async () => {
+ calls++;
+ return ["personal:late"];
+ },
+ });
+ await shared.defaults.put("personal:old", { sandboxId: "newer" });
+ release.resolve(["personal:old", "personal:cleared", "personal:adopted"]);
+ await Promise.all([first, second]);
+ assert.equal(calls, 1);
+ assert.deepEqual(await shared.defaults.get("personal:old"), { sandboxId: "newer" });
+ assert.equal(await shared.defaults.get("personal:late"), null);
+ assert.deepEqual(await other.defaults.get("personal:cleared"), { sandboxId: null });
+ const adopted = await other.defaults.get("personal:adopted");
+ assert.ok(adopted?.sandboxId);
+ assert.equal((await other.records.get(adopted.sandboxId))?.backingScopeId, "personal:adopted");
+ await upgradeLegacySandboxes({
+ ...other,
+ lock: createPostgresAdvisoryLock(pgB),
+ routes: async () => {
+ throw new Error("completed upgrades must never read legacy routing again");
+ },
+ });
} finally {
release.resolve([]);
await pgA.close();
await pgB.close();
}
});
-
test(
"pg shared sandbox use overlaps across cores and excludes lifecycle mutations",
{ skip, timeout: 10000 },
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index 54702218e..870938181 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -24,9 +24,6 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["execute
};
},
async restartComputer() {},
- async migrateComputer(): Promise<{ from: string; to: string }> {
- throw new Error("computer migration is not available on this deployment");
- },
async computerStatus() {
return { machine: "healthy", guestResponsive: true };
},
diff --git a/test/aws-role-cutover.test.ts b/test/aws-role-cutover.test.ts
index fd8f1d5d5..64ca0ac44 100644
--- a/test/aws-role-cutover.test.ts
+++ b/test/aws-role-cutover.test.ts
@@ -10,6 +10,7 @@ import { scopeId } from "../src/types.ts";
import { installGlobalFakeSprites, type FakeSprites } from "./support/fake-sprites.ts";
import { testConfig } from "./support/test-config.ts";
import { createAwsRoleBroker } from "../src/auth/aws-role-broker.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
let ff: FakeSprites;
before(() => {
@@ -110,6 +111,7 @@ test("shared ACMECLI cutover isolates brokered STS without shrinking the existin
const bob = { externalId: "BOB" };
const alice = { externalId: "ALICE" };
const room = scopeId("channel", "C-owner-auth");
+ await selectDefaultSandbox(built, "BOB", room);
const conversation = {
kind: "channel" as const,
threadRef: "ch:C-owner-auth:cron",
@@ -414,6 +416,7 @@ test("cutover policy retains legacy files only in prefer-ephemeral mode", async
},
);
const room = scopeId("channel", "C-acmecli-fallback");
+ await selectDefaultSandbox(built, actor.externalId, room);
await built.keychain!.save({
ownerId: room,
service: "acmecli",
@@ -513,6 +516,7 @@ test("a nonlegacy policy never places brokered STS on a shared room", async () =
},
);
const room = scopeId("channel", "C-acmecli-flag-off");
+ await selectDefaultSandbox(built, actor.externalId, room);
await built.keychain!.save({
ownerId: room,
service: "acmecli",
diff --git a/test/browser-model.test.ts b/test/browser-model.test.ts
index 0673fb424..37c9c950e 100644
--- a/test/browser-model.test.ts
+++ b/test/browser-model.test.ts
@@ -1,4 +1,5 @@
import "./support/auto-fake-sprites.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
import { createServer as httpServer } from "node:http";
@@ -138,6 +139,7 @@ test("gateway deployment provisions a browser token without exposing the company
},
});
const built = buildApp(config, { modelCredentialFetch: async () => new Response("unavailable", { status: 503 }) });
+ await selectDefaultSandbox(built, "U1", "personal:U1");
let captured: ProvisionOptions | undefined;
const provision = built.sandbox.provision.bind(built.sandbox);
built.sandbox.provision = (layers, opts) => {
@@ -175,6 +177,7 @@ test("gateway browsing never selects a direct provider when callback signing or
},
});
const built = buildApp(config, { modelCredentialFetch: async () => new Response("unavailable", { status: 503 }) });
+ await selectDefaultSandbox(built, "U1", "personal:U1");
let captured: ProvisionOptions | undefined;
const provision = built.sandbox.provision.bind(built.sandbox);
built.sandbox.provision = (layers, opts) => {
@@ -234,6 +237,7 @@ test("company browsing without a gateway uses current deployment credentials and
const server = createServer(built.app, serverDeps(config, built));
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
t.after(() => new Promise<void>((resolve) => server.close(() => resolve())));
+ await selectDefaultSandbox(built, "U1", "personal:U1");
let captured: ProvisionOptions | undefined;
const provision = built.sandbox.provision.bind(built.sandbox);
built.sandbox.provision = (layers, opts) => {
diff --git a/test/command-policy-route.test.ts b/test/command-policy-route.test.ts
index 5ff5e8c2a..acc469f5e 100644
--- a/test/command-policy-route.test.ts
+++ b/test/command-policy-route.test.ts
@@ -1,4 +1,5 @@
import "./support/auto-fake-sprites.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -34,6 +35,7 @@ const putPolicy = (base: string, b: unknown) =>
test("a pending approval survives a surface restart: GET /v1/approvals/:id returns a replayable request", async () => {
const srv = start();
try {
+ await selectDefaultSandbox(srv.built, "U1", "personal:U1");
const command = "git push --force origin main";
const turn = {
surface: "slack",
diff --git a/test/config.test.ts b/test/config.test.ts
index e1312ff50..ec54f2292 100644
--- a/test/config.test.ts
+++ b/test/config.test.ts
@@ -498,15 +498,14 @@ test("SANDBOX_BACKEND: unset defaults to local (dev only); the retired secondary
),
"a stray key without a template must not enable the secondary backend",
);
- assert.throws(
+ assert.doesNotThrow(
() =>
loadConfig({
SANDBOX_BACKEND: "local",
SANDBOX_SCOPE_BACKENDS: '{"channel":"superserve"}',
SUPERSERVE_API_KEY: "ss_live_k",
}),
- /SUPERSERVE_TEMPLATE/,
- "a scope routed to superserve needs the template even when it is not the primary backend",
+ "upgrade-only provider settings do not require live credentials or templates",
);
assert.doesNotThrow(() =>
loadConfig({
@@ -886,16 +885,6 @@ test("direct Files initiation defaults off and requires explicit activation", ()
assert.throws(() => loadConfig({ FILES_DIRECT_UPLOADS_ENABLED: "maybe" }));
});
-test("sandbox resource rollout requires explicit activation", () => {
- assert.equal(loadConfig({ ...productionEnv }).sandboxResourcesEnabled, false);
- for (const value of ["true", "on", "1"])
- assert.equal(loadConfig({ ...productionEnv, SANDBOX_RESOURCES_ENABLED: value }).sandboxResourcesEnabled, true);
- assert.throws(
- () => loadConfig({ ...productionEnv, SANDBOX_RESOURCES_ENABLED: "enable" }),
- /not a recognized boolean/,
- );
-});
-
test("suggestion generation defaults on and can be explicitly disabled", () => {
assert.equal(loadConfig({}).suggestedActivitiesEnabled, true);
assert.equal(loadConfig({ SUGGESTED_ACTIVITIES_ENABLED: "true" }).suggestedActivitiesEnabled, true);
@@ -903,7 +892,7 @@ test("suggestion generation defaults on and can be explicitly disabled", () => {
assert.throws(() => loadConfig({ SUGGESTED_ACTIVITIES_ENABLED: "maybe" }));
});
-test("sandbox scope defaults parse exact scope kinds and reject malformed mappings", () => {
+test("legacy sandbox scope defaults are parsed for upgrade", () => {
const credentials = {
SPRITES_TOKEN: "unit-test-sprites",
MODAL_TOKEN_ID: "unit-test-modal-id",
@@ -911,7 +900,7 @@ test("sandbox scope defaults parse exact scope kinds and reject malformed mappin
};
assert.deepEqual(
loadConfig({ ...credentials, SANDBOX_SCOPE_BACKENDS: '{"personal":"modal","channel":"sprites"}' })
- .sandboxScopeDefaults,
+ .legacySandboxScopeDefaults,
{ personal: "modal", channel: "sprites" },
);
for (const value of [
diff --git a/test/connector-invariants.test.ts b/test/connector-invariants.test.ts
index 60ffb14a5..d4265a043 100644
--- a/test/connector-invariants.test.ts
+++ b/test/connector-invariants.test.ts
@@ -15,6 +15,7 @@ import type { ConnectorTokenStore } from "../src/credentials/keychain.ts";
import type { TurnRequest } from "../src/types.ts";
import { fakeSprites } from "./support/auto-fake-sprites.ts";
import { testConfig } from "./support/test-config.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
const CATALOG_HOSTS = Object.values(PROVIDERS).flatMap((p) => p.hosts);
@@ -172,6 +173,7 @@ function turn(kind: "dm" | "channel", text: string): TurnRequest {
test("F1/F3 — a live DM receives only its requested connector; a channel receives none", async () => {
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "floor-")) }));
+ await selectDefaultSandbox(built, "U1", "personal:U1", "channel:C1");
await built.connectorTokens.setConnectorToken("gmail.googleapis.com", "U1", { accessToken: "u1-gmail" });
const key = envKey("gmail.googleapis.com");
const absent = `!run test -z "$${key}" && echo absent`;
@@ -198,6 +200,7 @@ function wake(text: string, readOnly: boolean): TurnRequest {
for (const surface of ["cron", "loop"]) {
test(`personal ${surface} selects owner credentials without grants`, async () => {
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "wake-conn-")) }));
+ await selectDefaultSandbox(built, "U1", "personal:U1");
await built.connectorTokens.setConnectorToken("gmail.googleapis.com", "U1", { accessToken: "u1-gmail" });
const saved = await built.keychain!.save({
ownerId: "U1",
@@ -254,6 +257,7 @@ for (const bulkInventory of [false, true])
const built = buildApp(
testConfig({ dataDir: mkdtempSync(join(tmpdir(), "connector-accounts-")), maxAttempts: 1 }),
);
+ await selectDefaultSandbox(built, "U1", "personal:U1");
if (!bulkInventory) delete built.connectorTokens.listConnectorsByOwners;
const host = "gmail.googleapis.com";
await built.connectorTokens.setConnectorToken(
@@ -315,6 +319,7 @@ test("operator fallback forwards metadata without reading secret values", async
test("explicit default OAuth accounts remain discoverable through bulk metadata", async () => {
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "default-account-")), maxAttempts: 1 }));
+ await selectDefaultSandbox(built, "U1", "personal:U1");
const host = "gmail.googleapis.com";
await built.connectorTokens.setConnectorToken(
host,
@@ -340,6 +345,7 @@ for (const mixedOAuth of [false, true, "expired-default"] as const)
for (const value of [undefined, "operator-fallback-token"]) {
test(`configured operator fallback is lazy with mixedOAuth=${mixedOAuth} and available=${value !== undefined}`, async () => {
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "fallback-catalog-")), maxAttempts: 1 }));
+ await selectDefaultSandbox(built, "U1", "personal:U1");
const host = "gmail.googleapis.com";
if (mixedOAuth === true)
await built.connectorTokens.setConnectorToken(host, "U1", { accessToken: "personal-token" }, "personal");
diff --git a/test/device-flow-persist.test.ts b/test/device-flow-persist.test.ts
index cc24893f0..0095bc082 100644
--- a/test/device-flow-persist.test.ts
+++ b/test/device-flow-persist.test.ts
@@ -20,6 +20,7 @@ import {
import { scopeId, type TurnRequest } from "../src/types.ts";
import { installGlobalFakeSprites, type FakeSprites } from "./support/fake-sprites.ts";
import { testConfig } from "./support/test-config.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
let ff: FakeSprites;
before(() => {
@@ -415,13 +416,15 @@ test("ACMECLI quarantine removes the canonical root even with no record or a sta
);
});
-function freshApp() {
- return buildApp(
+async function freshApp() {
+ const built = buildApp(
testConfig({
dataDir: mkdtempSync(join(tmpdir(), "dfp-app-")),
signingSecret: "device-flow-test-secret",
}),
);
+ await selectDefaultSandbox(built, "U1", scopeId("personal", "U1"), scopeId("channel", "C1"));
+ return built;
}
const actor = { externalId: "U1" };
@@ -440,7 +443,7 @@ function channel(text: string): TurnRequest {
}
test("a DM turn auto-captures a device-flow login under the PERSON, and a fresh machine gets it back", async () => {
- const { app, keychain } = freshApp();
+ const { app, keychain } = await freshApp();
const res = await app.turn(
dm("!run mkdir -p ~/.config/gh && printf 'oauth_token: gho_E2E' > ~/.config/gh/hosts.yml && echo done"),
);
@@ -458,7 +461,7 @@ test("a DM turn auto-captures a device-flow login under the PERSON, and a fresh
});
test("a login performed on a shared channel box is keyed to the SCOPE, like its workspace", async () => {
- const { app, keychain } = freshApp();
+ const { app, keychain } = await freshApp();
const res = await app.turn(
channel("!run mkdir -p ~/.config/glab && printf 'token: glpat_CH' > ~/.config/glab/config.yml && echo done"),
);
@@ -470,7 +473,7 @@ test("a login performed on a shared channel box is keyed to the SCOPE, like its
});
test("a capture failure is logged as an error event and does NOT fail the turn", async () => {
- const { app, keychain, errors } = freshApp();
+ const { app, keychain, errors } = await freshApp();
const realSave = keychain!.save.bind(keychain!);
keychain!.save = async () => {
throw new Error("injected keychain outage");
@@ -500,6 +503,7 @@ test("removing platform credential vending preserves stored quarantine on person
const request = shared ? channel("!run echo ready") : dm("!run echo ready");
const ownerId = shared ? scopeId("channel", "C1") : "U1";
const targetScope = shared ? scopeId("channel", "C1") : scopeId("personal", "U1");
+ await selectDefaultSandbox(built, "U1", targetScope);
await built.keychain!.save({
ownerId,
service: "acmecli",
@@ -1100,6 +1104,7 @@ test("removed layer tools retain quarantine, capture exclusion and reset-to-lega
const request = shared ? channel("!run echo ready") : dm("!run echo ready");
const ownerId = shared ? scopeId("channel", "C1") : "U1";
const targetScope = shared ? scopeId("channel", "C1") : scopeId("personal", "U1");
+ await selectDefaultSandbox(built, "U1", targetScope);
await built.keychain!.save({
ownerId,
service: "retired",
diff --git a/test/e2b-sandbox.test.ts b/test/e2b-sandbox.test.ts
index 50e98b4fd..c3f6e4d50 100644
--- a/test/e2b-sandbox.test.ts
+++ b/test/e2b-sandbox.test.ts
@@ -1,7 +1,6 @@
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";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -305,26 +304,6 @@ test("a failing snapshot store fails the fallback provision instead of cold-star
assert.equal(await s.readFile(b, "precious.txt"), "irreplaceable\n", "snapshot survives the outage");
});
-test("adoptHomeSnapshot promotes a staged blob to the snapshot store and resets the scope's sandbox", async () => {
- const { makeTar } = await import("../src/sandbox/tar.ts");
- const blobs = createMemoryBlobTransferStore();
- const s = make({ blobTransfer: blobs, capabilitySecret: "blob-secret", apiBaseUrl: "http://core.internal:8080" });
-
- const a = await s.provision(layers);
- await s.writeFile(a, "old.txt", "stale sprite-era sandbox\n");
- await s.teardown(a, { keepWarm: true });
-
- const tar = await makeTar([{ path: "migrated.txt", data: Buffer.from("came from sprites\n") }]);
- const { blobId } = await blobs.put(Readable.from([Buffer.from(tar)]));
- assert.ok(s.adoptHomeSnapshot);
- await s.adoptHomeSnapshot!(scope, blobId);
-
- const b = await s.provision(layers);
- const migrated = await s.run(b, "cat ~/migrated.txt");
- assert.equal(migrated.stdout, "came from sprites\n", "hydrates from the adopted snapshot");
- assert.notEqual((await s.run(b, "cat ~/old.txt")).code, 0, "the pre-adopt sandbox was discarded, not reused");
-});
-
test("blob staging is advertised only when the channel is actually wired", async () => {
assert.equal(
supportsBlobStaging(make()),
diff --git a/test/execute-env-credentials.test.ts b/test/execute-env-credentials.test.ts
index 0c1d043de..07431793f 100644
--- a/test/execute-env-credentials.test.ts
+++ b/test/execute-env-credentials.test.ts
@@ -8,6 +8,7 @@ import { scopeId } from "../src/types.ts";
import { installGlobalFakeSprites, type FakeSprites } from "./support/fake-sprites.ts";
import { testConfig } from "./support/test-config.ts";
import { createAwsRoleBroker } from "../src/auth/aws-role-broker.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
let ff: FakeSprites;
before(() => {
@@ -126,6 +127,8 @@ test("legacy role broker vends only for explicitly selected scoped execution", a
},
},
);
+ const owner = scopeId("personal", actor.externalId);
+ await selectDefaultSandbox(built, actor.externalId, owner);
const conversation = { kind: "dm" as const, threadRef: "dm:legacy-selected", audience: [actor] };
const run = (text: string) => built.app.turn({ surface: "slack", actor, conversation, text });
assert.equal((await run('!run test -z "${AWS_ACCESS_KEY_ID-}" && echo absent')).reply, "absent");
diff --git a/test/execute-scratch.test.ts b/test/execute-scratch.test.ts
index 49436763e..7d81f11f1 100644
--- a/test/execute-scratch.test.ts
+++ b/test/execute-scratch.test.ts
@@ -171,12 +171,15 @@ test("flag ON: the description advertises the routing policy truthfully", () =>
assert.doesNotMatch((legacy as unknown as { description: string }).description, /scratch/i);
});
-function freshApp(extra: Partial<Config> = {}) {
+async function freshApp(extra: Partial<Config> = {}) {
const config = testConfig({
dataDir: mkdtempSync(join(tmpdir(), "ap-scratch-")),
...extra,
});
- return buildApp(config);
+ const built = buildApp(config);
+ const computer = await built.sandboxResources.create("U1", "personal:U1", "sprites", "scoped");
+ await built.sandboxResources.setDefault("U1", "personal:U1", computer.id);
+ return built;
}
const dm = (text: string): TurnRequest => ({
@@ -187,7 +190,7 @@ const dm = (text: string): TurnRequest => ({
});
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 { app } = await freshApp({ signingSecret: "s3cret", apiBaseUrl: "https://core.test" });
const scoped = await app.turn(dm("!run printenv AGENT_API_TOKEN"));
assert.equal(scoped.status, "ok");
@@ -201,7 +204,7 @@ test("a scratch turn runs on a separate volumeless box with scoped capability to
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-")),
+ fakeSprites.names().some((n) => n.startsWith("qm-sandbox-")),
"the scoped box is the scope's durable sprite",
);
assert.ok(
@@ -215,7 +218,7 @@ test("a scratch turn runs on a separate volumeless box with scoped capability to
});
test("nothing on the scratch box survives the turn", async () => {
- const { app } = freshApp();
+ const { app } = await freshApp();
const first = await app.turn(dm('!scratch sh -c "echo leak > leak.txt && cat leak.txt"'));
assert.equal(first.reply, "leak");
const second = await app.turn(dm('!scratch sh -c "cat leak.txt 2>/dev/null; echo clean"'));
@@ -223,7 +226,7 @@ test("nothing on the scratch box survives the turn", async () => {
});
test("a deliverable has to live on the scoped computer — the scratch box can't be attached from", async () => {
- const { app } = freshApp();
+ const { app } = await freshApp();
const made = await app.turn(dm('!scratch sh -c "printf hello > from-scratch.txt && echo made"'));
assert.equal(made.reply, "made");
const res = await app.turn(dm("!attach from-scratch.txt"));
@@ -232,7 +235,7 @@ test("a deliverable has to live on the scoped computer — the scratch box can't
});
test("a scratch-only turn still reclaims its box (reset + suspend) when the turn ends", async () => {
- const { app, sandbox } = freshApp();
+ const { app, sandbox } = await freshApp();
let toreDown = 0;
const realTeardown = sandbox.teardown.bind(sandbox);
sandbox.teardown = async (handle, opts) => {
@@ -296,77 +299,6 @@ test("execute schema lists exact command credential handles", async () => {
assert.deepEqual(seen.at(-1)?.opts, { credentials: ["kc_github12345"] });
});
-test("migrateComputer gates on approval, validates the target, bounds the copy, and settles routing", async () => {
- const migrated: Array<{ scope: string; to: string; reason?: string; opts?: unknown }> = [];
- const audited: string[] = [];
- let invalidated = 0;
- const runner = {
- migrateScope: async (scope: string, to: string, reason?: string, opts?: unknown) => {
- migrated.push({ scope, to, ...(reason ? { reason } : {}), opts });
- return {
- scopeId: scope,
- from: "e2b",
- to,
- resynced: false,
- capabilitiesLost: [],
- bytes: 1,
- sha: "shashasha1234",
- sourceFiles: 1,
- };
- },
- listRoutes: async () => [],
- availableBackends: () => ["e2b", "modal"],
- defaultBackend: "e2b",
- };
- const base = {
- sandboxMigration: runner as never,
- migrateSettleMs: 0,
- invalidateProvision: () => {
- invalidated++;
- },
- auditLog: { record: (e: { action: string }) => audited.push(e.action) } as never,
- };
-
- const unapproved = routingCtx(base);
- await assert.rejects(unapproved.ctx.migrateComputer("modal"), (e: Error) => e.name === "NeedsApproval");
-
- const { ctx } = routingCtx({ ...base, authorizeCommand: (c: string) => c === 'computer:"migrate" to:"modal"' });
- await assert.rejects(ctx.migrateComputer("sprites"), /not an available backend here.*e2b, modal/);
- const moved = await ctx.migrateComputer("modal");
- assert.deepEqual(moved, { from: "e2b", to: "modal" });
- assert.deepEqual(migrated, [
- { scope: scopeId("personal", "U1"), to: "modal", reason: "agent-requested", opts: { copyTimeoutSec: 1800 } },
- ]);
- assert.equal(invalidated, 1, "the turn's provision memo is cleared so the next command lands on the new box");
- assert.deepEqual(audited, ["sandbox_routes.migrate"]);
-});
-
-test("migrateComputer rewords the operator-only force refusal and audits failures", async () => {
- const audited: string[] = [];
- const runner = {
- migrateScope: async () => {
- throw new Error("cannot migrate to sprites: it has no process sessions. Migrate with force to accept the loss.");
- },
- listRoutes: async () => [],
- availableBackends: () => ["e2b", "sprites"],
- defaultBackend: "e2b",
- };
- const { ctx } = routingCtx({
- sandboxMigration: runner as never,
- migrateSettleMs: 0,
- authorizeCommand: () => true,
- auditLog: { record: (e: { action: string }) => audited.push(e.action) } as never,
- });
- await assert.rejects(ctx.migrateComputer("sprites"), /An operator can force this from the admin console\./);
- await assert.rejects(ctx.migrateComputer("sprites"), (e: Error) => !/Migrate with force/.test(e.message));
- assert.deepEqual(audited, ["sandbox_routes.migrate_failed", "sandbox_routes.migrate_failed"]);
-});
-
-test("migrateComputer without a wired runner fails loudly", async () => {
- const { ctx } = routingCtx({ authorizeCommand: () => true });
- await assert.rejects(ctx.migrateComputer("modal"), /not available on this deployment/);
-});
-
test("execute masks credential output before model delivery, screening, and transcript logging", async () => {
const secret = "execution-secret-123456";
const emitted: unknown[] = [];
diff --git a/test/keychain-ask.test.ts b/test/keychain-ask.test.ts
index bdfa2ff2d..ec9d0d024 100644
--- a/test/keychain-ask.test.ts
+++ b/test/keychain-ask.test.ts
@@ -34,6 +34,7 @@ import { mintCapabilityToken, CAPABILITY_TTL_MS, type CapabilityClaims } from ".
import { scopeId, type TurnRequest, type TurnResult } from "../src/types.ts";
import { fakeSprites } from "./support/auto-fake-sprites.ts";
import { testConfig } from "./support/test-config.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
const KEY = deriveConnectorKey("keychain-ask-test-key");
const SECRET = "keychain-ask-route-secret".repeat(3);
@@ -1225,6 +1226,7 @@ test("turn e2e: trigger-fired turns mint `triggered` into the capability token;
return null;
};
+ await selectDefaultSandbox(built, "U_ALICE", "channel:C9");
let mark = fakeSprites.execScripts().length;
const turn = (triggered: boolean): TurnRequest =>
({
diff --git a/test/keychain.test.ts b/test/keychain.test.ts
index aa6559614..af744371c 100644
--- a/test/keychain.test.ts
+++ b/test/keychain.test.ts
@@ -26,6 +26,7 @@ import { mintCapabilityToken, CAPABILITY_TTL_MS, type CapabilityClaims } from ".
import { scopeId, type TurnRequest } from "../src/types.ts";
import { fakeSprites } from "./support/auto-fake-sprites.ts";
import { testConfig } from "./support/test-config.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
const KEY = deriveConnectorKey("keychain-test-key");
@@ -1512,6 +1513,7 @@ test("turn e2e: prompt lists exact handles and keychain env credentials are neve
assert.match(sys.reply ?? "", /Alice \(U_OWNER\): github/);
assert.match(sys.reply ?? "", /no grant for this conversation/);
assert.ok(!(sys.reply ?? "").includes("ghp_e2e"), "prompt never carries the secret");
+ await selectDefaultSandbox(built, "U_ASKER", "channel:C1");
let mark = fakeSprites.execScripts().length;
assert.equal((await built.app.turn(channelTurn("!run true", "U_ASKER", audience))).status, "ok");
@@ -1533,6 +1535,7 @@ test("turn e2e: prompt lists exact handles and keychain env credentials are neve
assert.match(sys2.reply ?? "", /STANDING grant .*use my gh here for repo work/);
assert.match(sys2.reply ?? "", new RegExp(`kc_${cred.id.slice(0, 12)}`));
+ await selectDefaultSandbox(built, "U_OWNER", "personal:U_OWNER");
mark = fakeSprites.execScripts().length;
const dm: TurnRequest = {
surface: "test",
diff --git a/test/live-slack/local-provider.ts b/test/live-slack/local-provider.ts
index 10527505d..2759aa31b 100644
--- a/test/live-slack/local-provider.ts
+++ b/test/live-slack/local-provider.ts
@@ -22,7 +22,7 @@ async function main(): Promise<void> {
runStore: "memory",
harness: "pi",
sandboxBackend: "local",
- sandboxResourcesEnabled: true,
+
backgroundWorkEnabled: false,
turnWallClockMs: 180_000,
localSandbox: { ...config.localSandbox, coreContainer: process.env.QM_CORE_CONTAINER },
diff --git a/test/loop-execution.test.ts b/test/loop-execution.test.ts
index b1d56332b..ebd0d96f7 100644
--- a/test/loop-execution.test.ts
+++ b/test/loop-execution.test.ts
@@ -11,6 +11,8 @@ import { testConfig } from "./support/test-config.ts";
for (const checkResult of ["passed", "failed", "missing"] as const) {
test(`loop intake executes with granted credentials and ${checkResult} checks gate held outputs`, async () => {
const built = buildApp(testConfig());
+ const computer = await built.sandboxResources.create("U1", "personal:U1", "sprites", "default");
+ await built.sandboxResources.setDefault("U1", "personal:U1", computer.id);
const org = scopeId("org", "default-org");
await built.serviceCreds.setServiceCredential(org, {
slug: "error-source",
diff --git a/test/modal-sandbox.test.ts b/test/modal-sandbox.test.ts
index 37e8c7a6d..b1fe5113e 100644
--- a/test/modal-sandbox.test.ts
+++ b/test/modal-sandbox.test.ts
@@ -415,27 +415,6 @@ test("stageIn pulls a blob into the guest atomically (temp then mv)", async () =
assert.match(script, /curl -fsS/, "-f so an HTTP error fails loudly instead of writing the error body");
});
-test("adoptHomeSnapshot promotes a staged blob to the snapshot store and resets the scope's sandbox", async () => {
- const { Readable } = await import("node:stream");
- const { makeTar } = await import("../src/sandbox/tar.ts");
- const blobs = createMemoryBlobTransferStore();
- const s = make({ blobTransfer: blobs, capabilitySecret: "blob-secret", apiBaseUrl: "http://core.internal:8080" });
-
- const a = await s.provision(layers);
- await s.writeFile(a, "old.txt", "stale e2b-era sandbox\n");
- await s.teardown(a, { keepWarm: true });
-
- const tar = await makeTar([{ path: "migrated.txt", data: Buffer.from("came from e2b\n") }]);
- const { blobId } = await blobs.put(Readable.from([Buffer.from(tar)]));
- assert.ok(s.adoptHomeSnapshot);
- await s.adoptHomeSnapshot!(scope, blobId);
-
- const b = await s.provision(layers);
- const migrated = await s.run(b, "cat ~/migrated.txt");
- assert.equal(migrated.stdout, "came from e2b\n", "hydrates from the adopted snapshot");
- assert.notEqual((await s.run(b, "cat ~/old.txt")).code, 0, "the pre-adopt sandbox was discarded, not reused");
-});
-
test("persistHomeSnapshot writes the live home to the snapshot store on demand", async () => {
const store = createMemoryMap<StoredModalSandbox>();
const counting = instrumentedSnapshotStore();
diff --git a/test/open-continuity-http.test.ts b/test/open-continuity-http.test.ts
index db3042d24..97f5cbe3f 100644
--- a/test/open-continuity-http.test.ts
+++ b/test/open-continuity-http.test.ts
@@ -49,7 +49,7 @@ const SECRET = "synthetic-continuity-http-signing-key";
const members = ["alice", "bob"].map((id) => ({ id, type: "internal" as const }));
async function fixture(t: TestContext) {
- const b = buildApp(testConfig({ signingSecret: SECRET, sandboxResourcesEnabled: true, memoryCapture: "off" }));
+ const b = buildApp(testConfig({ signingSecret: SECRET, memoryCapture: "off" }));
await b.config.hydrate?.();
await b.identity.hydrate();
await b.deploymentLayerReady;
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index dac8a5888..90331bfc1 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -4,7 +4,7 @@ import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { buildApp } from "../src/wiring.ts";
+import { buildApp as buildAppRaw } from "../src/wiring.ts";
import { scopeId, type TurnRequest } from "../src/types.ts";
import { TEST_CAPABILITY_SECRET, testConfig } from "./support/test-config.ts";
import { runNowSettled } from "./support/settle.ts";
@@ -26,6 +26,43 @@ import { createDirectoryStore } from "../src/directory/directory-store.ts";
import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
+const noDefaultSandbox = new WeakSet<object>();
+function requestScope(req: TurnRequest): string | null {
+ const c = req.conversation;
+ if (c.kind === "dm") return `personal:${req.actor.externalId}`;
+ if ((c.kind === "channel" || c.kind === "group") && c.channelRef) return `${c.kind}:${c.channelRef}`;
+ return null;
+}
+async function selectComputer(built: ReturnType<typeof buildAppRaw>, actorId: string, scope: ScopeId) {
+ const asSpeaker = built.sandboxResources.forTurn({ actorId, scopeId: scope, isCurrent: async () => true });
+ const computer = await asSpeaker.create(actorId, scope, built.sandboxResources.defaultBackend());
+ await asSpeaker.setDefault(actorId, scope, computer.id);
+ return computer;
+}
+function buildApp(...args: Parameters<typeof buildAppRaw>): ReturnType<typeof buildAppRaw> {
+ const built = buildAppRaw(...args);
+ const ready = new Map<string, Promise<void>>();
+ const ensure = (actorId: string, scope: string) => {
+ let p = ready.get(scope);
+ if (!p) {
+ p = (async () => {
+ if (noDefaultSandbox.has(built)) return;
+ if (await built.sandboxResources.resolve(scope as ScopeId)) return;
+ await selectComputer(built, actorId, scope as ScopeId);
+ })();
+ ready.set(scope, p);
+ }
+ return p;
+ };
+ const turn = built.app.turn.bind(built.app);
+ built.app.turn = async (req, ...rest) => {
+ const scope = requestScope(req);
+ if (scope) await ensure(req.actor.externalId, scope);
+ return turn(req, ...rest);
+ };
+ return built;
+}
+
function freshApp(overrides: Partial<Config> = {}, securityScreener?: SecurityScreener) {
const config = testConfig({
dataDir: mkdtempSync(join(tmpdir(), "ap-")),
@@ -1726,7 +1763,9 @@ test("turn-private transfer files are removed after staging", async () => {
});
test("a later turn removes same-conversation and expired transfer files", async () => {
- const { app, sandbox } = freshApp();
+ const built = freshApp();
+ const { app, sandbox } = built;
+ await selectComputer(built, "U1", scopeId("personal", "U1"));
const handle = await sandbox.provision([{ scopeId: scopeId("personal", "U1"), mountPath: "", mode: "rw" }]);
const sessionDir = `${TURN_FILES_DIR}/${hashId(["dm:U1:t1"], 24)}`;
await sandbox.writeFile(handle, `${sessionDir}/abandoned/inbox/stale.bin`, "stale");
@@ -3832,7 +3871,8 @@ test("environments: an unattached scope provisions through its own scope (today'
const config = testConfig({
dataDir: mkdtempSync(join(tmpdir(), "ap-")),
});
- const { app, sandbox } = buildApp(config);
+ const built = buildApp(config);
+ const { app, sandbox } = built;
const realProvision = sandbox.provision.bind(sandbox);
let rwScope: string | undefined;
sandbox.provision = (layers, opts) => {
@@ -3844,6 +3884,7 @@ test("environments: an unattached scope provisions through its own scope (today'
assert.equal(before.status, "ok");
assert.equal(rwScope, scopeId("personal", "U1"), "no attachment ⇒ provision through the scope itself");
+ await selectComputer(built, "U-shared", scopeId("personal", "U-shared"));
const env = await app.createEnvironment({ scopeId: scopeId("personal", "U-shared"), name: "prod", actorId: "U1" });
await app.attachScope({ scopeId: scopeId("personal", "U1"), environmentId: env.id, actorId: "U1" });
@@ -4184,7 +4225,9 @@ test("Auto screens oversize external output in chunks, so an injection buried pa
});
test("activated resource defaults preserve an existing computer and stop eager provisioning after unset", async () => {
- const built = freshApp({ sandboxResourcesEnabled: true, eagerProvisionEnabled: true });
+ const built = freshApp({ eagerProvisionEnabled: true });
+ noDefaultSandbox.add(built);
+ await selectComputer(built, "U1", scopeId("personal", "U1"));
await built.sessions.getOrCreateByThread("dm:U1:t1", "dm", "personal:U1");
await built.sandboxResources.initialize();
const boxes = spyProvisioning(built.sandbox);
@@ -4249,6 +4292,7 @@ for (const combined of [true, false]) {
test(`turn cleanup retains recent and malformed paths and removes stale files (combined=${combined})`, async () => {
const built = freshApp();
if (!combined) built.sandbox.removeDirAndList = undefined;
+ await selectComputer(built, "U1", scopeId("personal", "U1"));
const handle = await built.sandbox.provision([{ scopeId: scopeId("personal", "U1"), mountPath: "", mode: "rw" }]);
const old = `.agent-turn/owner/${(Date.now() - 48 * 3600_000).toString(36)}-nonce/file`;
const recent = `.agent-turn/owner/${Date.now().toString(36)}-nonce/file`;
diff --git a/test/pi-harness-oneshot.test.ts b/test/pi-harness-oneshot.test.ts
index 39ff1e28a..44b698963 100644
--- a/test/pi-harness-oneshot.test.ts
+++ b/test/pi-harness-oneshot.test.ts
@@ -128,7 +128,7 @@ test("piHarnessConfigOptions maps every Config knob the harness consumes, field
},
piCaptureRequests: false,
piSystemCacheSplit: true,
- sandboxResourcesEnabled: true,
+
scratchExecEnabled: true,
reachExecEnabled: true,
signingSecret: "sek",
diff --git a/test/reach-files.test.ts b/test/reach-files.test.ts
index 91c8cf40a..48572039a 100644
--- a/test/reach-files.test.ts
+++ b/test/reach-files.test.ts
@@ -12,6 +12,7 @@ import { reachEnqueue } from "../src/reach/reach.ts";
import { scopeId } from "../src/types.ts";
import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../src/auth/capability-token.ts";
import { testConfig } from "./support/test-config.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
const SECRET = "reach-files-secret".repeat(3);
@@ -50,6 +51,7 @@ describe("POST /v1/reach with files", () => {
{ principalId: "U-carol", displayName: "Carol", type: "internal" },
{ principalId: "U-alice", displayName: "Alice", type: "internal" },
]);
+ await selectDefaultSandbox(built, "U-carol", scopeId("personal", "U-carol"));
server = createServer(built.app, {
signingSecret: SECRET,
sandbox: built.sandbox,
diff --git a/test/run-tool-entries.test.ts b/test/run-tool-entries.test.ts
index 5cc2cb473..689f1ba9c 100644
--- a/test/run-tool-entries.test.ts
+++ b/test/run-tool-entries.test.ts
@@ -1,4 +1,5 @@
import "./support/auto-fake-sprites.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -35,6 +36,7 @@ test("a run's tool entries are read from the session tape, bounded by its turn a
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "run-tools-")) }));
built.runtime.start();
try {
+ await selectDefaultSandbox(built, "U1", "personal:U1");
const first = await built.app.turn(dm("!run echo hi"));
const run = await settled(built, first.runId!);
const second = await built.app.turn(dm("plain follow-up"));
@@ -59,6 +61,7 @@ test("a run's tool entries include rounds after a mid-run goal prompt and stop a
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "run-tools-goal-")) }));
built.runtime.start();
try {
+ await selectDefaultSandbox(built, "U1", "personal:U1");
const first = await built.app.turn(dm("!run echo hi"));
const run = await settled(built, first.runId!);
const session = (await built.sessions.getByThread(run.sessionId))!;
@@ -111,6 +114,7 @@ test("each tool entry nudges the run stream once it is durable", async () => {
return appended;
};
try {
+ await selectDefaultSandbox(built, "U1", "personal:U1");
const turn = await built.app.turn(dm("!run echo hi"));
const unsubscribe = built.app.subscribeRun(turn.runId!, (event) => {
if (event.kind === "refresh") log.push("refresh");
diff --git a/test/sandbox-migrate.test.ts b/test/sandbox-migrate.test.ts
deleted file mode 100644
index 9ec948247..000000000
--- a/test/sandbox-migrate.test.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join, dirname } from "node:path";
-import { copyHome } from "../src/sandbox/sandbox-migrate.ts";
-import { posixJoin } from "../src/sandbox/exec-file-ops.ts";
-import type { Sandbox, SandboxHandle, ExecResult } from "../src/sandbox/sandbox.ts";
-
-function hostSandbox(homeDir: string): { sandbox: Sandbox; handle: SandboxHandle } {
- mkdirSync(homeDir, { recursive: true });
- const rootDir = join(homeDir, "workspace");
- mkdirSync(rootDir, { recursive: true });
- const resolve = (rel: string) => posixJoin(rootDir, rel);
- const sandbox: Partial<Sandbox> = {
- async run(_h, command): Promise<ExecResult> {
- const r = spawnSync("sh", ["-c", command], {
- encoding: "utf8",
- maxBuffer: 64 * 1024 * 1024,
- env: { PATH: process.env.PATH ?? "" },
- });
- return {
- stdout: r.stdout ?? "",
- stderr: r.stderr ?? "",
- code: r.status ?? (r.signal ? 137 : -1),
- timedOut: false,
- };
- },
- async readFileBytes(_h, rel): Promise<Uint8Array | null> {
- const p = resolve(rel);
- return existsSync(p) ? readFileSync(p) : null;
- },
- async writeFileBytes(_h, rel, data): Promise<void> {
- const p = resolve(rel);
- mkdirSync(dirname(p), { recursive: true });
- writeFileSync(p, data);
- },
- };
- return { sandbox: sandbox as Sandbox, handle: { id: homeDir, rootDir } };
-}
-
-test("copyHome moves $HOME, sha-verifies, rewrites paths, and nukes venvs", async () => {
- const root = mkdtempSync(join(tmpdir(), "copyhome-"));
- const fromHome = join(root, "src");
- const toHome = join(root, "dst");
- const src = hostSandbox(fromHome);
- const dst = hostSandbox(toHome);
- try {
- writeFileSync(join(fromHome, "notes.txt"), "hello\n");
- mkdirSync(join(fromHome, ".config"), { recursive: true });
- writeFileSync(join(fromHome, ".config", "app.conf"), `workdir=${fromHome}/workspace\n`);
- writeFileSync(join(fromHome, ".bashrc"), `export HOME_ALIAS=${fromHome}\nkeep=${fromHome}fs/data\n`);
- const venv = join(fromHome, "workspace", "venv");
- mkdirSync(join(venv, "bin"), { recursive: true });
- writeFileSync(join(venv, "pyvenv.cfg"), "home = /usr/bin\n");
- writeFileSync(join(venv, "bin", "python"), `#!${fromHome}/workspace/venv/bin/python3\n`);
-
- const res = await copyHome({
- fromSandbox: src.sandbox,
- fromHandle: src.handle,
- fromHome,
- toSandbox: dst.sandbox,
- toHandle: dst.handle,
- toHome,
- });
-
- assert.match(res.sha, /^[0-9a-f]{64}$/);
- assert.ok(res.sourceFiles >= 3);
- assert.equal(readFileSync(join(toHome, "notes.txt"), "utf8"), "hello\n");
- assert.equal(readFileSync(join(toHome, ".config", "app.conf"), "utf8"), `workdir=${toHome}/workspace\n`);
- assert.equal(
- readFileSync(join(toHome, ".bashrc"), "utf8"),
- `export HOME_ALIAS=${toHome}\nkeep=${fromHome}fs/data\n`,
- );
- assert.ok(!existsSync(join(toHome, "workspace", "venv")), "venv should be nuked");
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("a tar that warns about files changing mid-read (exit 1) still copies — the resync pass covers deltas", async () => {
- const root = mkdtempSync(join(tmpdir(), "copyhome-warn-"));
- const fromHome = join(root, "src");
- const toHome = join(root, "dst");
- const shims = join(root, "shims");
- mkdirSync(shims, { recursive: true });
- const realTar = spawnSync("sh", ["-c", "command -v tar"], { encoding: "utf8" }).stdout.trim();
- writeFileSync(join(shims, "tar"), `#!/bin/sh\n"${realTar}" "$@"\nexit 1\n`, { mode: 0o755 });
- const src = hostSandbox(fromHome);
- const origRun = src.sandbox.run.bind(src.sandbox);
- src.sandbox.run = (h, command, opts) =>
- origRun(h, command.includes("tar czf") ? `PATH="${shims}:$PATH"; ${command}` : command, opts);
- const dst = hostSandbox(toHome);
- try {
- writeFileSync(join(fromHome, "notes.txt"), "busy home\n");
- const res = await copyHome({
- fromSandbox: src.sandbox,
- fromHandle: src.handle,
- fromHome,
- toSandbox: dst.sandbox,
- toHandle: dst.handle,
- toHome,
- });
- assert.match(res.sha, /^[0-9a-f]{64}$/);
- assert.equal(readFileSync(join(toHome, "notes.txt"), "utf8"), "busy home\n");
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("copyHome never mutates the source", async () => {
- const root = mkdtempSync(join(tmpdir(), "copyhome-src-"));
- const fromHome = join(root, "src");
- const toHome = join(root, "dst");
- const src = hostSandbox(fromHome);
- const dst = hostSandbox(toHome);
- try {
- mkdirSync(join(fromHome, ".config"));
- writeFileSync(join(fromHome, ".config", "app.conf"), `workdir=${fromHome}/x\n`);
- await copyHome({
- fromSandbox: src.sandbox,
- fromHandle: src.handle,
- fromHome,
- toSandbox: dst.sandbox,
- toHandle: dst.handle,
- toHome,
- });
- assert.equal(readFileSync(join(fromHome, ".config", "app.conf"), "utf8"), `workdir=${fromHome}/x\n`);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("copyHome throws on a corrupt transfer instead of leaving a truncated $HOME", async () => {
- const root = mkdtempSync(join(tmpdir(), "copyhome-corrupt-"));
- const fromHome = join(root, "src");
- const toHome = join(root, "dst");
- const src = hostSandbox(fromHome);
- const dst = hostSandbox(toHome);
- writeFileSync(join(fromHome, "big.txt"), "x".repeat(5000));
- const corrupt: Sandbox = {
- ...dst.sandbox,
- async writeFileBytes(h, rel, data) {
- const bad = Buffer.from(data);
- bad[0] = bad[0]! ^ 0xff;
- return dst.sandbox.writeFileBytes(h, rel, bad);
- },
- };
- try {
- await assert.rejects(
- copyHome({
- fromSandbox: src.sandbox,
- fromHandle: src.handle,
- fromHome,
- toSandbox: corrupt,
- toHandle: dst.handle,
- toHome,
- }),
- /sha-mismatch|verify\/extract failed/,
- );
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
diff --git a/test/sandbox-migration-runner.test.ts b/test/sandbox-migration-runner.test.ts
deleted file mode 100644
index d865bbb14..000000000
--- a/test/sandbox-migration-runner.test.ts
+++ /dev/null
@@ -1,432 +0,0 @@
-import {
- createSandboxResources,
- type SandboxResource,
- type SandboxDefault,
- type SandboxResourceRollout,
-} from "../src/sandbox/sandbox-resources.ts";
-import { createMemoryAdvisoryLock } from "../src/persistence/advisory-lock.ts";
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, utimesSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join, dirname } from "node:path";
-import { createSandboxMigrationRunner } from "../src/sandbox/sandbox-migration-runner.ts";
-import { createMemoryMap } from "../src/persistence/durable-map.ts";
-import type { SandboxRoute } from "../src/sandbox/sandbox-routing.ts";
-import { posixJoin } from "../src/sandbox/exec-file-ops.ts";
-import type { Sandbox, SandboxHandle, ExecResult } from "../src/sandbox/sandbox.ts";
-
-function hostBackend(name: string, homeDir: string): Sandbox & { tornDown: number } {
- mkdirSync(homeDir, { recursive: true });
- const rootDir = join(homeDir, "workspace");
- mkdirSync(rootDir, { recursive: true });
- const resolve = (rel: string) => posixJoin(rootDir, rel);
- const s = {
- tornDown: 0,
- profile: { backend: name, writablePersistence: "resident_disk" as const, processSessions: false },
- async provision(): Promise<SandboxHandle> {
- return { id: `${name}-box`, rootDir, homeDir };
- },
- async run(_h: SandboxHandle, command: string): Promise<ExecResult> {
- const r = spawnSync("sh", ["-c", command], {
- encoding: "utf8",
- maxBuffer: 64 * 1024 * 1024,
- env: { PATH: process.env.PATH ?? "" },
- });
- return {
- stdout: r.stdout ?? "",
- stderr: r.stderr ?? "",
- code: r.status ?? (r.signal ? 137 : -1),
- timedOut: false,
- };
- },
- async readFileBytes(_h: SandboxHandle, rel: string): Promise<Uint8Array | null> {
- const p = resolve(rel);
- return existsSync(p) ? readFileSync(p) : null;
- },
- async writeFileBytes(_h: SandboxHandle, rel: string, data: Uint8Array): Promise<void> {
- const p = resolve(rel);
- mkdirSync(dirname(p), { recursive: true });
- writeFileSync(p, data);
- },
- async teardown(): Promise<void> {
- s.tornDown++;
- },
- async readFile() {
- return null;
- },
- async writeFile() {},
- async listDir() {
- return [];
- },
- async removeDir() {},
- };
- return s as unknown as Sandbox & { tornDown: number };
-}
-
-function build(root: string) {
- const aws = hostBackend("aws", join(root, "aws-home"));
- const sprites = hostBackend("sprites", join(root, "sprites-home"));
- const routes = createMemoryMap<SandboxRoute>();
- return { aws, sprites, routes };
-}
-
-test("migrateScope copies $HOME, flips the route only after a verified copy, and parks both boxes", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-runner-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "hello\n");
- const runner = createSandboxMigrationRunner({ backends: { aws, sprites }, routes, defaultBackend: "aws" });
- const res = await runner.migrateScope("personal:alice", "sprites", "canary");
- assert.equal(res.from, "aws");
- assert.equal(res.to, "sprites");
- assert.match(res.sha, /^[0-9a-f]{64}$/);
- assert.equal(readFileSync(join(root, "sprites-home", "notes.txt"), "utf8"), "hello\n");
- const route = await routes.get("personal:alice");
- assert.equal(route?.backend, "sprites");
- assert.equal(route?.migrationSha, res.sha);
- assert.equal(route?.reason, "canary");
- assert.equal(aws.tornDown, 1);
- assert.equal(sprites.tornDown, 1);
- const back = await runner.migrateScope("personal:alice", "aws");
- assert.equal(back.from, "sprites");
- assert.equal((await routes.get("personal:alice"))?.backend, "aws");
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("snapshot strategy exports once, adopts into the target's snapshot store, and flips only after a hydrated home verifies", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-snap-"));
- try {
- const { aws: src, routes } = build(root);
- const notes = join(root, "aws-home", "notes.txt");
- writeFileSync(notes, "hello snapshot\n");
- utimesSync(notes, new Date(0), new Date(0));
- const blobs = new Map<string, Buffer>();
- const adopted: string[] = [];
- (src as unknown as { stageOut: Sandbox["stageOut"]; importFiles: unknown; stageIn: unknown }).stageOut = async (
- h,
- rel,
- ) => {
- const bytes = await src.readFileBytes(h, rel);
- if (!bytes) throw new Error("no tar");
- const id = `blob-${blobs.size + 1}`;
- blobs.set(id, Buffer.from(bytes));
- return id;
- };
- (src as unknown as { stageIn: unknown }).stageIn = async () => {};
- (src as unknown as { importFiles: unknown }).importFiles = async () => {};
-
- const dstHome = join(root, "e2b-home");
- const dst = hostBackend("e2b", dstHome);
- let hydratePending: Buffer | null = null;
- (dst as unknown as { adoptHomeSnapshot: Sandbox["adoptHomeSnapshot"] }).adoptHomeSnapshot = async (
- scope,
- blobId,
- ) => {
- adopted.push(`${scope}:${blobId}`);
- hydratePending = blobs.get(blobId) ?? null;
- if (!hydratePending) throw new Error("unknown blob");
- };
- const origProvision = dst.provision.bind(dst);
- dst.provision = async (layers, opts) => {
- const h = await origProvision(layers, opts);
- if (hydratePending) {
- const tarFile = join(dstHome, ".hydrate.tgz");
- writeFileSync(tarFile, hydratePending);
- hydratePending = null;
- spawnSync("sh", ["-c", `cd ${dstHome} && tar xzf .hydrate.tgz && rm -f .hydrate.tgz`], { encoding: "utf8" });
- }
- return h;
- };
-
- const runner = createSandboxMigrationRunner({ backends: { aws: src, e2b: dst }, routes, defaultBackend: "aws" });
- const res = await runner.migrateScope("personal:alice", "e2b", "snapshot cutover", {
- force: true,
- strategy: "snapshot",
- });
- assert.equal(res.to, "e2b");
- assert.match(res.sha, /^[0-9a-f]{64}$/);
- assert.ok(res.destFiles >= 1);
- assert.equal(adopted.length, 1);
- assert.equal(res.resynced, false);
- assert.equal(readFileSync(join(dstHome, "notes.txt"), "utf8"), "hello snapshot\n");
- assert.equal((await routes.get("personal:alice"))?.backend, "e2b");
- assert.equal(existsSync(join(root, "aws-home", "notes.txt")), true, "source untouched");
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("snapshot strategy resumes from an already-exported blob without repacking the source", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-snap-resume-"));
- try {
- const { aws: src, routes } = build(root);
- let packs = 0;
- const origRun = src.run.bind(src);
- src.run = async (h, command, opts) => {
- if (command.includes("tar czf")) packs++;
- return origRun(h, command, opts);
- };
- (src as unknown as { stageOut: unknown }).stageOut = async () => {
- throw new Error("stageOut must not run on resume");
- };
- (src as unknown as { stageIn: unknown }).stageIn = async () => {};
- (src as unknown as { importFiles: unknown }).importFiles = async () => {};
-
- const dstHome = join(root, "e2b-home");
- const dst = hostBackend("e2b", dstHome);
- const adopted: string[] = [];
- (dst as unknown as { adoptHomeSnapshot: Sandbox["adoptHomeSnapshot"] }).adoptHomeSnapshot = async (
- scope,
- blobId,
- ) => {
- adopted.push(blobId);
- writeFileSync(join(dstHome, "restored.txt"), "from resumed blob\n");
- };
-
- const runner = createSandboxMigrationRunner({ backends: { aws: src, e2b: dst }, routes, defaultBackend: "aws" });
- const res = await runner.migrateScope("personal:alice", "e2b", "resume", {
- force: true,
- strategy: "snapshot",
- resumeBlobId: "ab".repeat(16),
- });
- assert.equal(packs, 0, "no source pack on resume");
- assert.deepEqual(adopted, ["ab".repeat(16)]);
- assert.equal(res.sha, "resumed");
- assert.equal(res.resynced, false, "resume never resyncs from the live source");
- assert.equal((await routes.get("personal:alice"))?.backend, "e2b");
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("snapshot strategy refuses when the target cannot adopt snapshots", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-snap-refuse-"));
- try {
- const { aws: src, sprites: dst, routes } = build(root);
- (src as unknown as { stageOut: unknown }).stageOut = async () => "blob-x";
- (src as unknown as { stageIn: unknown }).stageIn = async () => {};
- (src as unknown as { importFiles: unknown }).importFiles = async () => {};
- const runner = createSandboxMigrationRunner({
- backends: { aws: src, sprites: dst },
- routes,
- defaultBackend: "aws",
- });
- await assert.rejects(
- runner.migrateScope("personal:alice", "sprites", undefined, { force: true, strategy: "snapshot" }),
- /adopting home snapshots/,
- );
- assert.equal(await routes.get("personal:alice"), null);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("migrateScope refuses: same backend, pinned scope, live work, unconstructed target", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-refuse-"));
- try {
- const { aws, sprites, routes } = build(root);
- const busy = new Set<string>();
- const runner = createSandboxMigrationRunner({
- backends: { aws, sprites },
- routes,
- defaultBackend: "aws",
- hasLiveWork: async (scopeId) => busy.has(scopeId),
- });
- await assert.rejects(runner.migrateScope("personal:a", "aws"), /already on aws/);
- await assert.rejects(runner.migrateScope("personal:a", "local"), /not constructed/);
- await routes.put("personal:pinned", { backend: "aws", pinned: true, reason: "big box" });
- await assert.rejects(runner.migrateScope("personal:pinned", "sprites"), /pinned/);
- busy.add("personal:busy");
- await assert.rejects(runner.migrateScope("personal:busy", "sprites"), /live background work/);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("migrateScope refuses a target that carries fewer capabilities, unless forced", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-caps-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "hello\n");
- const awsWithBackup: Sandbox = {
- ...aws,
- async exportFiles() {
- return [];
- },
- };
- const runner = createSandboxMigrationRunner({
- backends: { aws: awsWithBackup, sprites },
- routes,
- defaultBackend: "aws",
- });
-
- await assert.rejects(runner.migrateScope("personal:alice", "sprites"), /home export/);
- assert.equal(await routes.get("personal:alice"), null, "a refused migration must not flip the route");
-
- const forced = await runner.migrateScope("personal:alice", "sprites", "canary", { force: true });
- assert.deepEqual(forced.capabilitiesLost, ["home export (publish, resident-auth capture)"]);
- const route = await routes.get("personal:alice");
- assert.equal(route?.backend, "sprites");
- assert.deepEqual(route?.capabilitiesLost, ["home export (publish, resident-auth capture)"]);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("a resync after the settle window keeps the durable record of what was lost", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-resync-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "hello\n");
- const awsWithBackup: Sandbox = {
- ...aws,
- async exportFiles() {
- return [];
- },
- async run(h, command, o) {
- if (command.includes("-newermt")) return { stdout: "notes.txt\n", stderr: "", code: 0, timedOut: false };
- return aws.run(h, command, o);
- },
- };
- const runner = createSandboxMigrationRunner({
- backends: { aws: awsWithBackup, sprites },
- routes,
- defaultBackend: "aws",
- });
- const res = await runner.migrateScope("personal:alice", "sprites", "canary", { force: true });
- assert.equal(res.resynced, true, "the test must actually exercise the resync write");
- assert.deepEqual((await routes.get("personal:alice"))?.capabilitiesLost, [
- "home export (publish, resident-auth capture)",
- ]);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("migrateScope refuses a target that enforces less egress", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-egress-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "hello\n");
- const confined: Sandbox = { ...aws, profile: { ...aws.profile, egressEnforcement: "domain" } };
- const open: Sandbox = { ...sprites, profile: { ...sprites.profile, egressEnforcement: "none" } };
- const runner = createSandboxMigrationRunner({
- backends: { aws: confined, sprites: open },
- routes,
- defaultBackend: "aws",
- });
- await assert.rejects(runner.migrateScope("personal:alice", "sprites"), /egress enforcement/);
- await routes.put("personal:bob", { backend: "sprites" });
- writeFileSync(join(root, "sprites-home", "notes.txt"), "hello\n");
- const res = await runner.migrateScope("personal:bob", "aws");
- assert.deepEqual(res.capabilitiesLost, []);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("migrateScope reports no loss when the substrates carry the same capabilities", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-caps-equal-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "hello\n");
- const runner = createSandboxMigrationRunner({ backends: { aws, sprites }, routes, defaultBackend: "aws" });
- const res = await runner.migrateScope("personal:alice", "sprites");
- assert.deepEqual(res.capabilitiesLost, []);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("a failed copy leaves the route untouched", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-fail-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "hello\n");
- const corrupt: Sandbox = {
- ...sprites,
- async writeFileBytes(h, rel, data) {
- const bad = Buffer.from(data);
- bad[0] = bad[0]! ^ 0xff;
- return sprites.writeFileBytes(h, rel, bad);
- },
- };
- const runner = createSandboxMigrationRunner({ backends: { aws, sprites: corrupt }, routes, defaultBackend: "aws" });
- await assert.rejects(runner.migrateScope("personal:alice", "sprites"), /sha-mismatch|verify\/extract failed/);
- assert.equal(await routes.get("personal:alice"), null);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("activation cannot pass a running migration before its final route and teardown", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-activation-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "preserve me\n");
- const lock = createMemoryAdvisoryLock();
- const rollout = createMemoryMap<SandboxResourceRollout>();
- const options = {
- enabled: false,
- rollout,
- records: createMemoryMap<SandboxResource>(),
- defaults: createMemoryMap<SandboxDefault>(),
- routes,
- backends: { aws, sprites },
- defaultBackend: "aws" as const,
- lock,
- canUseScope: async () => true,
- };
- const reader = createSandboxResources(options);
- const activating = createSandboxResources({ ...options, enabled: true });
- const parked = Promise.withResolvers<void>();
- const release = Promise.withResolvers<void>();
- aws.teardown = async () => {
- parked.resolve();
- await release.promise;
- };
- const runner = createSandboxMigrationRunner({
- backends: { aws, sprites },
- routes,
- defaultBackend: "aws",
- advisoryLock: lock,
- withLegacyMutation: (scope, action) => reader.withLegacyMutation(scope, action),
- });
- const migration = runner.migrateScope("personal:alice", "sprites");
- await parked.promise;
- const activation = activating.initialize();
- assert.equal(await rollout.get("explicit-defaults"), null);
- release.resolve();
- await Promise.all([migration, activation]);
- assert.equal((await activating.resolve("personal:alice"))?.backend, "sprites");
- assert.equal(readFileSync(join(root, "sprites-home", "notes.txt"), "utf8"), "preserve me\n");
- await assert.rejects(runner.migrateScope("personal:alice", "aws"), /retired/);
- assert.equal((await routes.get("personal:alice"))?.backend, "sprites");
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
-
-test("migration reads the scope default as its source before installing an explicit route", async () => {
- const root = mkdtempSync(join(tmpdir(), "mig-scope-default-"));
- try {
- const { aws, sprites, routes } = build(root);
- writeFileSync(join(root, "aws-home", "notes.txt"), "scope default data\n");
- const runner = createSandboxMigrationRunner({
- backends: { aws, sprites },
- routes,
- defaultBackend: "sprites",
- scopeDefaults: { personal: "aws" },
- });
- const result = await runner.migrateScope("personal:alice", "sprites", "scope policy migration");
- assert.equal(result.from, "aws");
- assert.equal(readFileSync(join(root, "sprites-home", "notes.txt"), "utf8"), "scope default data\n");
- assert.equal((await routes.get("personal:alice"))?.backend, "sprites");
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
-});
diff --git a/test/sandbox-resources.test.ts b/test/sandbox-resources.test.ts
index 3263195de..40ca24dba 100644
--- a/test/sandbox-resources.test.ts
+++ b/test/sandbox-resources.test.ts
@@ -5,13 +5,15 @@ import { createDeviceFlowCutoverStore } from "../src/credentials/device-flow-cut
import { createTurnSandboxes, type TurnSandboxContext } from "../src/core/orchestrator/sandboxes.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
+import { createSandboxResources, type SandboxResource, type SandboxDefault } from "../src/sandbox/sandbox-resources.ts";
+import { createSandboxRouter } from "../src/sandbox/sandbox-routing.ts";
import {
- createSandboxResources,
- type SandboxResource,
- type SandboxDefault,
- type SandboxResourceRollout,
-} from "../src/sandbox/sandbox-resources.ts";
-import { createSandboxRouter, type SandboxRoute } from "../src/sandbox/sandbox-routing.ts";
+ upgradeLegacySandboxes,
+ legacySandboxBackendForScope,
+ legacySandboxId,
+ type LegacyRoute,
+ type SandboxResourceUpgradeMarker,
+} from "../src/sandbox/sandbox-resource-upgrade.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
import { createMemoryAdvisoryLock } from "../src/persistence/advisory-lock.ts";
import type { Sandbox } from "../src/sandbox/sandbox.ts";
@@ -19,8 +21,8 @@ import type { Sandbox } from "../src/sandbox/sandbox.ts";
function fixture(configure?: (backend: Sandbox) => void, legacyScopes = ["personal:alice"]) {
const records = createMemoryMap<SandboxResource>();
const defaults = createMemoryMap<SandboxDefault>();
- const routes = createMemoryMap<SandboxRoute>();
- const rollout = createMemoryMap<SandboxResourceRollout>();
+ const routes = createMemoryMap<LegacyRoute>();
+ const marker = createMemoryMap<SandboxResourceUpgradeMarker>();
const disks = new Map<string, Map<string, string>>();
const provisioned: string[] = [];
const backend: Sandbox = {
@@ -60,23 +62,35 @@ function fixture(configure?: (backend: Sandbox) => void, legacyScopes = ["person
},
};
configure?.(backend);
+ const lock = createMemoryAdvisoryLock();
+ const upgrade =
+ (overrides: Partial<Parameters<typeof upgradeLegacySandboxes>[0]> = {}) =>
+ () =>
+ upgradeLegacySandboxes({
+ availableBackends: ["local"],
+ records,
+ defaults,
+ marker,
+ lock,
+ routes: () => routes.entries(),
+ legacyScopes: async () => legacyScopes,
+ legacyBackend: () => "local",
+ ...overrides,
+ });
const options = {
- enabled: true,
- rollout,
- legacyScopes: async () => legacyScopes,
+ upgrade: upgrade(),
records,
defaults,
- routes,
backends: { local: backend },
defaultBackend: "local",
- lock: createMemoryAdvisoryLock(),
+ lock,
canUseScope: async (actor: string, scope: string) =>
actor === "admin" || scope === `personal:${actor}` || (actor === "alice" && scope === "channel:team"),
} satisfies Parameters<typeof createSandboxResources>[0];
const resources = createSandboxResources(options);
- const router = createSandboxRouter({ routes, backends: { local: backend }, defaultBackend: "local", resources });
+ const router = createSandboxRouter({ backends: { local: backend }, defaultBackend: "local", resources });
const layers = [{ scopeId: "personal:alice", mode: "rw" as const, mountPath: "/" }];
- return { records, defaults, routes, resources, router, provisioned, layers, backend, options, rollout };
+ return { records, defaults, routes, resources, router, provisioned, layers, backend, options, marker, upgrade };
}
test("blank sandbox identities coexist and default changes never copy files or redirect existing handles", async () => {
@@ -103,11 +117,11 @@ test("blank sandbox identities coexist and default changes never copy files or r
});
test("explicit sandbox profiles follow selected storage rather than the parent's default provider", async () => {
- const { backend, options, routes } = fixture();
+ const { backend, options } = fixture();
const modal: Sandbox = { ...backend, profile: { ...backend.profile, backend: "modal" } };
const backends = { local: backend, modal };
const resources = createSandboxResources({ ...options, backends });
- const router = createSandboxRouter({ backends, routes, defaultBackend: "local", resources });
+ const router = createSandboxRouter({ backends, defaultBackend: "local", resources });
const worker = await resources.create("alice", "personal:alice", "modal", "Worker");
assert.equal((await router.profileFor!("personal:alice")).backend, "local");
assert.equal((await router.profileFor!("personal:alice", worker.id)).backend, "modal");
@@ -132,16 +146,17 @@ test("unset defaults remain unset durably while explicit execution remains usabl
});
test("legacy adoption is deterministic and reconnects the existing backing identity", async () => {
- const { resources, router, layers, records } = fixture();
- const old = await router.provision(layers);
- await router.writeFile(old, "file", "keep");
+ const { resources, router, layers, records, backend } = fixture();
+ const old = await backend.provision(layers);
+ await backend.writeFile(old, "file", "keep");
const lists = await Promise.all(Array.from({ length: 8 }, () => resources.list("alice", "personal:alice")));
const id = lists[0]!.defaultSandboxId!;
+ assert.equal(id, legacySandboxId("personal:alice", "local"));
assert.ok(lists.every((list) => list.defaultSandboxId === id));
assert.equal((await records.all()).length, 1);
- await resources.setDefault("alice", "personal:alice", id);
+ assert.equal((await records.get(id))?.backingScopeId, "personal:alice");
const adopted = await router.provision(layers);
- assert.equal(adopted.id, old.id);
+ assert.equal(adopted.resourceId, id);
assert.equal(await router.readFile(adopted, "file"), "keep");
});
@@ -471,31 +486,8 @@ for (const shared of [false, true])
}
});
-test("disabled readers honor explicit defaults and refuse management without activating", async () => {
- const { options, defaults, records, backend, routes, rollout, layers, provisioned } = fixture(undefined, []);
- const resources = createSandboxResources({ ...options, enabled: false });
- const router = createSandboxRouter({ backends: { local: backend }, defaultBackend: "local", routes, resources });
- assert.equal(await resources.resolve("personal:alice"), undefined);
- const old = await router.provision(layers);
- assert.equal(old.id, "personal:alice");
- assert.equal(await rollout.get("explicit-defaults"), null);
- const record = (await records.all())[0]!;
- await defaults.put("personal:alice", { sandboxId: record.id });
- assert.equal((await resources.resolve("personal:alice"))?.id, record.id);
- await defaults.put("personal:alice", { sandboxId: null });
- await assert.rejects(router.provision(layers), /no default sandbox/);
- for (const action of [
- () => resources.create("alice", "personal:alice", "local"),
- () => resources.setDefault("alice", "personal:alice", record.id),
- () => resources.restart("alice", record.id),
- () => resources.retire("alice", record.id),
- ])
- await assert.rejects(action(), /management is disabled/);
- assert.deepEqual(provisioned, ["personal:alice"]);
-});
-
test("activation preserves routes, cold identities and explicit nulls without calling a provider", async () => {
- const { options, records, defaults, routes, rollout, provisioned } = fixture(undefined, []);
+ const { options, records, defaults, routes, marker, provisioned, upgrade } = fixture(undefined, []);
await routes.put("personal:routed", { backend: "modal" });
await defaults.put("personal:unset", { sandboxId: null });
const managed: SandboxResource = {
@@ -513,12 +505,15 @@ test("activation preserves routes, cold identities and explicit nulls without ca
await defaults.put(managed.ownerScopeId, { sandboxId: managed.id });
const resources = createSandboxResources({
...options,
- legacyScopes: async () => ["personal:old-session", "personal:unset"],
- legacySandboxes: async () => [
- { scopeId: "personal:routed", backend: "modal", machineId: "sb-old" },
- { scopeId: "personal:routed", backend: "e2b", machineId: "e2b-cold" },
- { scopeId: "sandbox-managed", backend: "local", machineId: "managed-machine" },
- ],
+ upgrade: upgrade({
+ availableBackends: ["local", "modal"],
+ legacyScopes: async () => ["personal:old-session", "personal:unset"],
+ legacySandboxes: async () => [
+ { scopeId: "personal:routed", backend: "modal", machineId: "sb-old" },
+ { scopeId: "personal:routed", backend: "e2b", machineId: "e2b-cold" },
+ { scopeId: "sandbox-managed", backend: "local", machineId: "managed-machine" },
+ ],
+ }),
});
const routed = await resources.resolve("personal:routed");
assert.equal(routed?.backend, "modal");
@@ -529,23 +524,21 @@ test("activation preserves routes, cold identities and explicit nulls without ca
assert.equal(await resources.resolve("personal:unset"), null);
assert.equal((await resources.resolve(managed.ownerScopeId))?.id, "managed");
assert.equal(await resources.resolve("personal:new-after-activation"), null);
- assert.ok(await rollout.get("explicit-defaults"));
+ assert.ok(await marker.get("explicit-defaults"));
const inventory = await resources.list("admin", "personal:routed");
assert.ok(inventory.sandboxes.some((r) => r.backend === "e2b" && r.machineId === "e2b-cold"));
assert.ok(!inventory.sandboxes.some((r) => r.legacy && r.backingScopeId === "sandbox-managed"));
assert.deepEqual(inventory.sandboxes.find((r) => r.id === routed!.id)?.availableActions, []);
assert.deepEqual(provisioned, []);
assert.equal((await routes.get("personal:routed"))?.backend, "modal");
- const rollbackReader = createSandboxResources({ ...options, enabled: false });
- assert.equal(await rollbackReader.resolve("personal:new-after-activation"), null);
- assert.equal((await rollbackReader.resolve("personal:routed"))?.id, routed?.id);
+ await routes.put("personal:later", { backend: "local" });
+ const restarted = createSandboxResources(options);
+ assert.equal(await restarted.resolve("personal:later"), null);
+ assert.equal((await restarted.resolve("personal:routed"))?.id, routed?.id);
});
test("activation retries partial durable writes without losing defaults or creating machines", async () => {
- const { options, defaults, rollout, records, provisioned } = fixture(undefined, [
- "personal:first",
- "personal:second",
- ]);
+ const { options, defaults, marker, records, provisioned } = fixture(undefined, ["personal:first", "personal:second"]);
const put = defaults.putIfAbsent;
let fail = true;
defaults.putIfAbsent = async (id, value) => {
@@ -554,7 +547,7 @@ test("activation retries partial durable writes without losing defaults or creat
};
const resources = createSandboxResources(options);
await assert.rejects(resources.resolve("personal:first"), /database interrupted/);
- assert.equal(await rollout.get("explicit-defaults"), null);
+ assert.equal(await marker.get("explicit-defaults"), null);
const first = await defaults.get("personal:first");
await defaults.put("personal:first", { sandboxId: null });
fail = false;
@@ -562,7 +555,7 @@ test("activation retries partial durable writes without losing defaults or creat
assert.ok(first?.sandboxId);
assert.equal(await resources.resolve("personal:first"), null);
assert.equal((await records.all()).length, 2);
- assert.ok(await rollout.get("explicit-defaults"));
+ assert.ok(await marker.get("explicit-defaults"));
assert.deepEqual(provisioned, []);
});
@@ -578,84 +571,6 @@ test("boot activation freezes legacy scope adoption before a new session arrives
assert.deepEqual(provisioned, []);
});
-test("activation and a compatible reader publish a late legacy computer without losing its default", async () => {
- const { options, defaults, records } = fixture(undefined, []);
- const enumerating = Promise.withResolvers<void>();
- const resume = Promise.withResolvers<string[]>();
- const active = createSandboxResources({
- ...options,
- legacyScopes: () => {
- enumerating.resolve();
- return resume.promise;
- },
- });
- const reader = createSandboxResources({ ...options, enabled: false });
- const activation = active.initialize();
- await enumerating.promise;
- const publication = reader.recordLegacy("personal:late", "local", { id: "late-machine", rootDir: "/workspace" });
- resume.resolve([]);
- await activation;
- const id = await publication;
- assert.deepEqual(await defaults.get("personal:late"), { sandboxId: id });
- assert.equal((await reader.resolve("personal:late"))?.id, id);
- assert.equal((await records.get(id))?.machineId, "late-machine");
- await defaults.put("personal:cleared", { sandboxId: null });
- await reader.recordLegacy("personal:cleared", "local", { id: "in-flight", rootDir: "/workspace" });
- assert.equal(await reader.resolve("personal:cleared"), null);
-});
-
-test("activation waits for a compatible legacy route mutation and rejects later mutations", async () => {
- const { options, routes } = fixture(undefined, []);
- const reader = createSandboxResources({ ...options, enabled: false });
- const active = createSandboxResources(options);
- const entered = Promise.withResolvers<void>();
- const resume = Promise.withResolvers<void>();
- const mutation = reader.withLegacyMutation("personal:moving", async () => {
- entered.resolve();
- await resume.promise;
- await routes.put("personal:moving", { backend: "modal" });
- });
- await entered.promise;
- const activation = active.initialize();
- resume.resolve();
- await Promise.all([mutation, activation]);
- assert.equal((await active.resolve("personal:moving"))?.backend, "modal");
- let changed = false;
- await assert.rejects(
- reader.withLegacyMutation("personal:moving", async () => {
- changed = true;
- }),
- /retired/,
- );
- assert.equal(changed, false);
-});
-
-test("a legacy migration queued behind activation fails before its action runs", async () => {
- const { options } = fixture(undefined, []);
- const entered = Promise.withResolvers<void>();
- const resume = Promise.withResolvers<string[]>();
- const active = createSandboxResources({
- ...options,
- legacyScopes: () => {
- entered.resolve();
- return resume.promise;
- },
- });
- const reader = createSandboxResources({ ...options, enabled: false });
- const activation = active.initialize();
- await entered.promise;
- let changed = false;
- const rejected = assert.rejects(
- reader.withLegacyMutation("personal:late", async () => {
- changed = true;
- }),
- /retired/,
- );
- resume.resolve([]);
- await Promise.all([activation, rejected]);
- assert.equal(changed, false);
-});
-
test("retirement deletes an inferred missing computer without provisioning, status or restore", async () => {
const { resources, backend, provisioned } = fixture();
await resources.initialize();
@@ -752,7 +667,7 @@ test("retirement preserves core live-work and owning-scope guards before direct
});
test("retirement waits for background startup to commit its live registry row", async () => {
- const { options, backend, routes, layers } = fixture((sandbox) => {
+ const { options, backend, layers } = fixture((sandbox) => {
sandbox.profile.processSessions = true;
sandbox.startProcess = async () => ({ processId: "job" });
sandbox.readProcess = async () => ({ chunks: "", cursor: 0, status: { state: "running" } });
@@ -768,7 +683,7 @@ test("retirement waits for background startup to commit its live registry row",
throw new Error("live background work");
},
});
- const router = createSandboxRouter({ resources, routes, backends: { local: backend }, defaultBackend: "local" });
+ const router = createSandboxRouter({ resources, backends: { local: backend }, defaultBackend: "local" });
assert.ok(supportsProcessSessions(router));
const record = await resources.create("alice", "personal:alice", "local");
const handle = await router.provision(layers, { sandboxId: record.id });
@@ -822,19 +737,28 @@ test("failed background registration kills its process and releases the resource
});
test("resource activation honors scope defaults and preserves explicit legacy provider routes", async () => {
- const { options, routes, backend } = fixture(undefined, ["personal:alice", "channel:room", "personal:existing"]);
+ const { options, routes, backend, upgrade } = fixture(undefined, [
+ "personal:alice",
+ "channel:room",
+ "personal:existing",
+ ]);
await routes.put("personal:existing", { backend: "aws" });
+ const scopeDefaults = { personal: "modal", channel: "sprites" } as const;
const resources = createSandboxResources({
...options,
+ upgrade: upgrade({
+ availableBackends: ["aws", "modal", "sprites"],
+ legacyBackend: (scope) => legacySandboxBackendForScope(scope, "sprites", scopeDefaults),
+ }),
backends: { modal: backend, sprites: backend, aws: backend },
defaultBackend: "sprites",
- scopeDefaults: { personal: "modal", channel: "sprites" },
});
assert.equal((await resources.resolve("personal:alice"))?.backend, "modal");
assert.equal((await resources.resolve("channel:room"))?.backend, "sprites");
assert.equal((await resources.resolve("personal:existing"))?.backend, "aws");
- assert.equal(resources.defaultBackend("personal:new"), "modal");
- assert.equal(resources.defaultBackend("channel:new"), "sprites");
+ assert.equal(await resources.resolve("personal:new"), null);
+ assert.equal(resources.defaultBackend(), "sprites");
+ assert.equal(legacySandboxBackendForScope("org", "sprites", scopeDefaults), "sprites");
});
for (const [kind, waiting] of [
@@ -844,9 +768,9 @@ for (const [kind, waiting] of [
["sprites", "checkpoint"],
] as const) {
test(`${kind} ${waiting} allows other tools while restart waits`, { timeout: 10000 }, async () => {
- const { options, backend, layers, routes } = fixture();
+ const { options, backend, layers } = fixture();
const resources = createSandboxResources({ ...options, backends: { [kind]: backend }, defaultBackend: kind });
- const router = createSandboxRouter({ routes, backends: { [kind]: backend }, defaultBackend: kind, resources });
+ const router = createSandboxRouter({ backends: { [kind]: backend }, defaultBackend: kind, resources });
const record = await resources.create("alice", "personal:alice", kind);
await resources.setDefault("alice", "personal:alice", record.id);
const handle = await router.provision(layers);
@@ -896,9 +820,9 @@ for (const [kind, waiting] of [
}
test("Modal provisioning and destructive cleanup wait for active operations", { timeout: 10000 }, async () => {
- const { options, backend, layers, routes } = fixture();
+ const { options, backend, layers } = fixture();
const resources = createSandboxResources({ ...options, backends: { modal: backend }, defaultBackend: "modal" });
- const router = createSandboxRouter({ routes, backends: { modal: backend }, defaultBackend: "modal", resources });
+ const router = createSandboxRouter({ backends: { modal: backend }, defaultBackend: "modal", resources });
const record = await resources.create("alice", "personal:alice", "modal");
const handle = await router.provision(layers, { sandboxId: record.id });
const entered = Promise.withResolvers<void>();
@@ -934,9 +858,9 @@ test("Modal provisioning and destructive cleanup wait for active operations", {
});
test("concurrent commands on one Sprites computer run together", { timeout: 10000 }, async () => {
- const { options, backend, layers, routes } = fixture();
+ const { options, backend, layers } = fixture();
const resources = createSandboxResources({ ...options, backends: { sprites: backend }, defaultBackend: "sprites" });
- const router = createSandboxRouter({ routes, backends: { sprites: backend }, defaultBackend: "sprites", resources });
+ const router = createSandboxRouter({ backends: { sprites: backend }, defaultBackend: "sprites", resources });
const record = await resources.create("alice", "personal:alice", "sprites");
const handle = await router.provision(layers, { sandboxId: record.id });
const release = Promise.withResolvers<void>();
@@ -958,10 +882,10 @@ test("concurrent commands on one Sprites computer run together", { timeout: 1000
});
test("parking teardown waits for active commands on the computer", { timeout: 10000 }, async () => {
- const { options, backend, layers, routes } = fixture();
+ const { options, backend, layers } = fixture();
const parking: Sandbox = { ...backend, profile: { ...backend.profile, parksOnTeardown: true } };
const resources = createSandboxResources({ ...options, backends: { e2b: parking }, defaultBackend: "e2b" });
- const router = createSandboxRouter({ routes, backends: { e2b: parking }, defaultBackend: "e2b", resources });
+ const router = createSandboxRouter({ backends: { e2b: parking }, defaultBackend: "e2b", resources });
const record = await resources.create("alice", "personal:alice", "e2b");
const handle = await router.provision(layers, { sandboxId: record.id });
const entered = Promise.withResolvers<void>();
@@ -1008,3 +932,24 @@ test("a verified live turn can create only its own new scope computer without di
await assert.rejects(turn.access("alice", computer.id), /permission/);
await assert.rejects(turn.setDefault("alice", scope, computer.id), /permission/);
});
+
+test("legacy import refuses an unavailable selected provider before writing any adoption state", async () => {
+ const { options, upgrade, records, defaults, marker } = fixture();
+ const resources = createSandboxResources({ ...options, upgrade: upgrade({ availableBackends: [] }) });
+ await assert.rejects(resources.initialize(), /personal:alice: backend local is not configured/);
+ assert.deepEqual(await records.all(), []);
+ assert.deepEqual(await defaults.all(), []);
+ assert.equal(await marker.get("explicit-defaults"), null);
+ await createSandboxResources(options).initialize();
+ assert.ok((await defaults.get("personal:alice"))?.sandboxId);
+});
+
+test("legacy import does not validate obsolete provider choices after explicit selection or clearing", async () => {
+ const { options, upgrade, defaults, marker } = fixture(undefined, ["personal:cleared", "personal:selected"]);
+ await defaults.put("personal:cleared", { sandboxId: null });
+ await defaults.put("personal:selected", { sandboxId: "newer-computer" });
+ await createSandboxResources({ ...options, upgrade: upgrade({ availableBackends: [] }) }).initialize();
+ assert.deepEqual(await defaults.get("personal:cleared"), { sandboxId: null });
+ assert.deepEqual(await defaults.get("personal:selected"), { sandboxId: "newer-computer" });
+ assert.ok(await marker.get("explicit-defaults"));
+});
diff --git a/test/sandbox-routing.test.ts b/test/sandbox-routing.test.ts
index a34be28d1..c8f9be443 100644
--- a/test/sandbox-routing.test.ts
+++ b/test/sandbox-routing.test.ts
@@ -1,20 +1,34 @@
-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";
-import { createMemoryMap } from "../src/persistence/durable-map.ts";
-import { CapabilityUnsupportedError, supportsScopeProfile } from "../src/sandbox/sandbox.ts";
-import type { Sandbox, SandboxHandle, ExecResult, AgentComputerProfile } from "../src/sandbox/sandbox.ts";
-import type { WorkspaceLayer } from "../src/types.ts";
+import { createSandboxRouter, NoDefaultSandboxError, type SandboxBackendName } from "../src/sandbox/sandbox-routing.ts";
+import type { SandboxResource, SandboxResources } from "../src/sandbox/sandbox-resources.ts";
+import {
+ CapabilityUnsupportedError,
+ SandboxProvisionCleanupError,
+ supportsScopeProfile,
+} from "../src/sandbox/sandbox.ts";
+import type {
+ Sandbox,
+ SandboxHandle,
+ ExecResult,
+ AgentComputerProfile,
+ ProvisionOptions,
+} from "../src/sandbox/sandbox.ts";
+import type { ScopeId, WorkspaceLayer } from "../src/types.ts";
-function fakeBackend(name: string): Sandbox & { calls: string[] } {
+type Fake = Sandbox & { calls: string[]; provisioned: Array<{ layers: WorkspaceLayer[]; opts?: ProvisionOptions }> };
+
+function fakeBackend(name: string): Fake {
const calls: string[] = [];
+ const provisioned: Fake["provisioned"] = [];
const profile: AgentComputerProfile = { backend: name, writablePersistence: "resident_disk", processSessions: true };
- const s: Partial<Sandbox> & { calls: string[] } = {
+ const s: Partial<Sandbox> & { calls: string[]; provisioned: Fake["provisioned"] } = {
calls,
+ provisioned,
profile,
- async provision(layers: WorkspaceLayer[]): Promise<SandboxHandle> {
- calls.push(`provision:${(layers[0] as WorkspaceLayer).scopeId}`);
+ async provision(layers: WorkspaceLayer[], opts?: ProvisionOptions): Promise<SandboxHandle> {
+ provisioned.push({ layers, ...(opts ? { opts } : {}) });
+ calls.push(`provision:${layers[0]?.scopeId ?? "-"}`);
return { id: `${name}-box`, rootDir: `/${name}/workspace` };
},
async run(_h, command): Promise<ExecResult> {
@@ -48,206 +62,267 @@ function fakeBackend(name: string): Sandbox & { calls: string[] } {
return [];
},
};
- return s as Sandbox & { calls: string[] };
+ return s as Fake;
+}
+
+const resource = (id: string, backend: SandboxBackendName, ownerScopeId = "personal:a"): SandboxResource => ({
+ id,
+ backend,
+ ownerScopeId: ownerScopeId as ScopeId,
+ backingScopeId: `sandbox:${id}`,
+ name: id,
+ createdBy: "u",
+ createdAt: "2026-10-01T00:00:00Z",
+ legacy: false,
+ state: "ready",
+});
+
+function stubResources(defaults: Record<string, SandboxResource | null>, extra: SandboxResource[] = []) {
+ const byId = new Map<string, SandboxResource>();
+ for (const r of [...Object.values(defaults), ...extra]) if (r) byId.set(r.id, r);
+ const locks: Array<{ id: string; exclusive: boolean }> = [];
+ let held = 0;
+ const stub = {
+ locks,
+ isLocked: () => held > 0,
+ resolve: async (scopeId: string) => defaults[scopeId] ?? null,
+ get: async (id: string) => {
+ const r = byId.get(id);
+ if (!r) throw new Error(`sandbox ${id} not found`);
+ return r;
+ },
+ use: async <T>(id: string, action: () => Promise<T>, exclusive = false) => {
+ locks.push({ id, exclusive });
+ held++;
+ try {
+ return await action();
+ } finally {
+ held--;
+ }
+ },
+ };
+ return stub as typeof stub & SandboxResources;
}
const layersFor = (scopeId: string): WorkspaceLayer[] => [
{ scopeId: scopeId as WorkspaceLayer["scopeId"], mountPath: "/", mode: "rw" },
];
-function build(routeSeed?: Record<string, SandboxRoute>) {
- const routes = createMemoryMap<SandboxRoute>();
+function build(defaults: Record<string, SandboxResource | null>, extra: SandboxResource[] = []) {
const aws = fakeBackend("aws");
const sprites = fakeBackend("sprites");
- const router = createSandboxRouter({ backends: { aws, sprites }, routes, defaultBackend: "aws" });
- const seed = async () => {
- for (const [k, v] of Object.entries(routeSeed ?? {})) await routes.put(k, v);
- };
- return { router, aws, sprites, routes, seed };
+ const resources = stubResources(defaults, extra);
+ const errors: Array<{ code: string; message: string; scopeLabel?: string }> = [];
+ const router = createSandboxRouter({
+ backends: { aws, sprites },
+ defaultBackend: "aws",
+ resources,
+ onError: (e) => errors.push(e),
+ });
+ return { router, aws, sprites, resources, errors };
}
-test("absent route → default backend; a route → the routed backend", async () => {
- const { router, aws, sprites, seed } = build({ "personal:migrated": { backend: "sprites" } });
- await seed();
- const h1 = await router.provision(layersFor("personal:unrouted"));
- assert.equal(h1.backend, "aws");
- assert.ok(aws.calls.includes("provision:personal:unrouted"));
- const h2 = await router.provision(layersFor("personal:migrated"));
- assert.equal(h2.backend, "sprites");
- assert.ok(sprites.calls.includes("provision:personal:migrated"));
+test("provision uses the scope's default resource: backend, backing scope, lock, and handle tags", async () => {
+ const r = resource("r1", "sprites");
+ const { router, aws, sprites, resources } = build({ "personal:a": r });
+ const h = await router.provision(layersFor("personal:a"));
+ assert.equal(h.backend, "sprites");
+ assert.equal(h.resourceId, "r1");
+ assert.equal(h.scopeId, "personal:a");
+ assert.equal(sprites.provisioned[0]!.layers[0]!.scopeId, "sandbox:r1", "rw layer remapped to the backing scope");
+ assert.deepEqual(resources.locks, [{ id: "r1", exclusive: true }]);
+ assert.deepEqual(aws.calls, []);
});
-test("a handle's later calls follow the backend that provisioned it", async () => {
- const { router, aws, sprites, seed } = build({ "personal:m": { backend: "sprites" } });
- await seed();
+test("an explicit sandboxId wins over the scope default", async () => {
+ const def = resource("def", "aws");
+ const pick = resource("pick", "sprites");
+ const { router, aws } = build({ "personal:a": def }, [pick]);
+ const h = await router.provision(layersFor("personal:a"), { sandboxId: "pick" });
+ assert.equal(h.backend, "sprites");
+ assert.equal(h.resourceId, "pick");
+ assert.deepEqual(aws.calls, []);
+});
+
+test("no default resource refuses provision with NoDefaultSandboxError and touches no backend", async () => {
+ const { router, aws, sprites } = build({});
+ await assert.rejects(router.provision(layersFor("personal:none")), NoDefaultSandboxError);
+ assert.deepEqual([...aws.calls, ...sprites.calls], []);
+});
+
+test("an inventory read failure propagates instead of falling back to the default backend", async () => {
+ const { router, aws, resources } = build({});
+ resources.resolve = async () => {
+ throw new Error("db down");
+ };
+ await assert.rejects(router.provision(layersFor("personal:x")), /db down/);
+ assert.deepEqual(aws.calls, []);
+});
+
+test("provision resolves by routeScopeId when the layers don't name the acting scope", async () => {
+ const { router, sprites } = build({ "personal:m": resource("m", "sprites") });
+ const h = await router.provision(layersFor("org:global"), { routeScopeId: "personal:m" });
+ assert.equal(h.backend, "sprites");
+ assert.equal(h.resourceId, "m");
+ assert.equal(sprites.provisioned.length, 1);
+});
+
+test("a resource on an unconstructed backend refuses to substitute", async () => {
+ const { router, aws } = build({ "personal:x": resource("x", "local") });
+ await assert.rejects(router.provision(layersFor("personal:x")), /unavailable: local/);
+ assert.deepEqual(aws.calls, []);
+});
+
+test("scratch picks the default resource's backend but stays isolated from the persistent box", async () => {
+ const { router, sprites, resources } = build({ "personal:a": resource("r1", "sprites") });
+ const layers = layersFor("personal:a");
+ const scratch = { scratch: { key: "turn" }, routeScopeId: "personal:a" } as ProvisionOptions;
+ const h = await router.provision(layers, scratch);
+ assert.equal(h.backend, "sprites");
+ assert.equal(h.scopeId, "personal:a");
+ assert.equal(h.resourceId, undefined, "scratch must not claim the persistent resource");
+ assert.deepEqual(resources.locks, [], "scratch must not take the resource lock");
+ assert.deepEqual(sprites.provisioned[0]!.layers, layers, "scratch keeps its original layers");
+ assert.equal(sprites.provisioned[0]!.opts, scratch);
+});
+
+test("scratch honours an explicit sandboxId for backend choice only", async () => {
+ const { router, aws, sprites, resources } = build({ "personal:a": resource("def", "aws") }, [
+ resource("pick", "sprites"),
+ ]);
+ const h = await router.provision(layersFor("personal:a"), { scratch: { key: "t" }, sandboxId: "pick" });
+ assert.equal(h.backend, "sprites");
+ assert.equal(h.resourceId, undefined);
+ assert.deepEqual(resources.locks, []);
+ assert.equal(sprites.provisioned[0]!.layers[0]!.scopeId, "personal:a");
+ assert.deepEqual(aws.calls, []);
+});
+
+test("scratch with no selected computer uses the installation provider without creating a default", async () => {
+ const { router, aws, sprites, resources } = build({});
+ const handle = await router.provision([], { scratch: { key: "t" }, routeScopeId: "personal:none" });
+ assert.equal(handle.backend, "aws");
+ assert.equal(handle.resourceId, undefined);
+ assert.equal(aws.provisioned.length, 1);
+ assert.deepEqual(sprites.calls, []);
+ assert.deepEqual(resources.locks, []);
+ assert.equal(await resources.resolve("personal:none"), null);
+});
+
+test("failed scratch initialization keeps its selected backend for cleanup", async () => {
+ const { router, sprites } = build({ "personal:p": resource("p", "sprites") });
+ 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:p" }), (e: Error) => {
+ assert.ok(e instanceof SandboxProvisionCleanupError);
+ pending = e.handle;
+ assert.equal(pending.backend, "sprites");
+ return true;
+ });
+ await router.teardown(pending!, { destroy: true });
+ assert.deepEqual(sprites.calls, ["teardown"]);
+});
+
+test("a handle's later calls follow its backend under the resource lock", async () => {
+ const { router, aws, sprites, resources } = build({ "personal:m": resource("m", "sprites") });
const h = await router.provision(layersFor("personal:m"));
- const r = await router.run(h, "whoami");
- assert.equal(r.stdout, "sprites");
+ resources.locks.length = 0;
+ assert.equal((await router.run(h, "whoami")).stdout, "sprites");
await router.teardown(h);
assert.ok(sprites.calls.includes("run:whoami") && sprites.calls.includes("teardown"));
- assert.ok(!aws.calls.some((c) => c.startsWith("run")), "aws must not have seen the routed handle");
+ assert.ok(!aws.calls.some((c) => c.startsWith("run")));
+ assert.deepEqual(
+ resources.locks.map((l) => l.id),
+ ["m", "m"],
+ );
});
-test("profileFor returns the substrate the scope is actually on", async () => {
- const { router, seed } = build({ "personal:m": { backend: "sprites" } });
- await seed();
+test("profileFor reports the resolved resource's provider, explicit id first", async () => {
+ const { router } = build({ "personal:m": resource("m", "sprites") }, [resource("x", "aws")]);
assert.ok(supportsScopeProfile(router));
if (!supportsScopeProfile(router)) return;
- assert.equal((await router.profileFor("personal:unrouted")).backend, "aws");
assert.equal((await router.profileFor("personal:m")).backend, "sprites");
+ assert.equal((await router.profileFor("personal:m", "x")).backend, "aws");
});
-test("a route to an unconstructed backend refuses to substitute the default", async () => {
- const routes = createMemoryMap<SandboxRoute>();
- await routes.put("personal:x", { backend: "local" });
- const aws = fakeBackend("aws");
- const errors: string[] = [];
- const router = createSandboxRouter({
- backends: { aws },
- routes,
- defaultBackend: "aws",
- onError: (e) => errors.push(e.code),
- });
- await assert.rejects(router.provision(layersFor("personal:x")), /refusing to use a substitute/);
- assert.deepEqual(aws.calls, []);
- assert.ok(errors.includes("backend_unavailable"));
+test("profileFor with no default resource advertises the default backend for bootstrap", async () => {
+ const { router } = build({});
+ if (!supportsScopeProfile(router)) return assert.fail("router must expose profileFor");
+ assert.equal((await router.profileFor("personal:none")).backend, "aws");
});
test("fleet sweeps are absent when no backend implements them", async () => {
- const { router } = build();
+ const { router } = build({});
assert.equal(router.reapDeepIdle, undefined);
+ assert.equal(router.computerStatus, undefined);
+ assert.equal(router.restartComputer, undefined);
});
test("reapDeepIdle is exposed when a backend implements it, and sums across backends", async () => {
- const routes = createMemoryMap<SandboxRoute>();
const aws = fakeBackend("aws");
(aws as unknown as { reapDeepIdle: unknown }).reapDeepIdle = async () => ({ reaped: 3 });
- const sprites = fakeBackend("sprites");
- const router = createSandboxRouter({ backends: { aws, sprites }, routes, defaultBackend: "aws" });
- assert.equal(typeof router.reapDeepIdle, "function");
+ const router = createSandboxRouter({
+ backends: { aws, sprites: fakeBackend("sprites") },
+ defaultBackend: "aws",
+ resources: stubResources({}),
+ });
assert.deepEqual(await router.reapDeepIdle!(1000), { reaped: 3 });
});
-test("a capability held by SOME backends stays exposed and dispatches per handle", async () => {
- const routes = createMemoryMap<SandboxRoute>();
+function capabilitySplit(onError?: (e: { code: string; message: string; scopeLabel?: string }) => void) {
const aws = fakeBackend("aws");
(aws as unknown as { exportFiles: unknown }).exportFiles = async () => [];
const sprites = fakeBackend("sprites");
delete (sprites as Partial<Sandbox>).exportFiles;
- await routes.put("personal:s", { backend: "sprites" });
- const router = createSandboxRouter({ backends: { aws, sprites }, routes, defaultBackend: "aws" });
+ const router = createSandboxRouter({
+ backends: { aws, sprites },
+ defaultBackend: "aws",
+ resources: stubResources({
+ "personal:f": resource("f", "aws"),
+ "personal:s": resource("s", "sprites", "personal:s"),
+ }),
+ ...(onError ? { onError } : {}),
+ });
+ return router;
+}
+
+test("a capability held by SOME backends stays exposed and dispatches per handle", async () => {
+ const router = capabilitySplit();
assert.equal(typeof router.exportFiles, "function");
- const onAws = await router.provision(layersFor("personal:f"));
- assert.deepEqual(await router.exportFiles!(onAws), []);
+ assert.deepEqual(await router.exportFiles!(await router.provision(layersFor("personal:f"))), []);
const onSprites = await router.provision(layersFor("personal:s"));
await assert.rejects(
async () => router.exportFiles!(onSprites),
- (e: unknown) => {
- assert.ok(e instanceof CapabilityUnsupportedError);
- assert.match((e as Error).message, /does not support exportFiles/);
- return true;
- },
+ (e: unknown) =>
+ e instanceof CapabilityUnsupportedError && /does not support exportFiles/.test((e as Error).message),
);
});
test("a capability refusal reaches the operator error stream, scope-labelled and de-duped", async () => {
- const routes = createMemoryMap<SandboxRoute>();
- const aws = fakeBackend("aws");
- (aws as unknown as { exportFiles: unknown }).exportFiles = async () => [];
- const sprites = fakeBackend("sprites");
- delete (sprites as Partial<Sandbox>).exportFiles;
- await routes.put("personal:s", { backend: "sprites" });
const errors: Array<{ code: string; message: string; scopeLabel?: string }> = [];
- const router = createSandboxRouter({
- backends: { aws, sprites },
- routes,
- defaultBackend: "aws",
- onError: (e) => errors.push(e),
- });
+ const router = capabilitySplit((e) => errors.push(e));
const handle = await router.provision(layersFor("personal:s"));
- await assert.rejects(async () => router.exportFiles!(handle));
+ for (let i = 0; i < 3; i++) await assert.rejects(async () => router.exportFiles!(handle));
assert.equal(errors.length, 1);
assert.equal(errors[0]!.code, "capability_unsupported");
assert.equal(errors[0]!.scopeLabel, "personal:s");
assert.match(errors[0]!.message, /sprites.*exportFiles/);
- await assert.rejects(async () => router.exportFiles!(handle));
- await assert.rejects(async () => router.exportFiles!(handle));
- assert.equal(errors.length, 1, "a repeated refusal must not re-report");
-});
-
-test("a handle-keyed refusal names the scope its box belongs to", async () => {
- const routes = createMemoryMap<SandboxRoute>();
- const aws = fakeBackend("aws");
- const thin = fakeBackend("sprites");
- delete (thin as Partial<Sandbox>).exportFiles;
- (aws as unknown as { exportFiles: unknown }).exportFiles = async () => [];
- await routes.put("personal:s", { backend: "sprites" });
- const errors: Array<{ scopeLabel?: string; message: string }> = [];
- const router = createSandboxRouter({
- backends: { aws, sprites: thin },
- routes,
- defaultBackend: "aws",
- onError: (e) => errors.push(e),
- });
- const handle = await router.provision(layersFor("personal:s"));
- await assert.rejects(async () => router.exportFiles!(handle));
- assert.equal(errors[0]!.scopeLabel, "personal:s", "publish's silent fallback must still name the scope");
});
test("a throwing error sink cannot replace the typed refusal callers catch", async () => {
- const routes = createMemoryMap<SandboxRoute>();
- const aws = fakeBackend("aws");
- (aws as unknown as { exportFiles: unknown }).exportFiles = async () => [];
- const sprites = fakeBackend("sprites");
- delete (sprites as Partial<Sandbox>).exportFiles;
- await routes.put("personal:s", { backend: "sprites" });
- const router = createSandboxRouter({
- backends: { aws, sprites },
- routes,
- defaultBackend: "aws",
- onError: () => {
- throw new Error("error store is down");
- },
+ const router = capabilitySplit(() => {
+ throw new Error("error store is down");
});
const handle = await router.provision(layersFor("personal:s"));
await assert.rejects(
async () => router.exportFiles!(handle),
- (e: unknown) => {
- assert.ok(e instanceof CapabilityUnsupportedError);
- return true;
- },
+ (e: unknown) => e instanceof CapabilityUnsupportedError,
);
});
-test("a routing-store read failure propagates instead of silently routing to the default", async () => {
- const routes = createMemoryMap<SandboxRoute>();
- const broken = {
- ...routes,
- get: async () => {
- throw new Error("db down");
- },
- };
- const aws = fakeBackend("aws");
- const router = createSandboxRouter({ backends: { aws }, routes: broken, defaultBackend: "aws" });
- await assert.rejects(router.provision(layersFor("personal:x")), /db down/);
-});
-
-test("provision routes by routeScopeId when the layers don't name the acting scope", async () => {
- const { router, sprites, seed } = build({ "personal:m": { backend: "sprites" } });
- await seed();
- const h = await router.provision(layersFor("org:global"), { routeScopeId: "personal:m" });
- assert.equal(h.backend, "sprites");
- assert.ok(sprites.calls.includes("provision:org:global"));
-});
-
-test("computer status/restart are absent when no backend implements them", async () => {
- const { router } = build();
- assert.equal(router.computerStatus, undefined);
- assert.equal(router.restartComputer, undefined);
-});
-
-test("computer status/restart forward to the scope's routed backend", async () => {
- const routes = createMemoryMap<SandboxRoute>();
+function computerBackends() {
const aws = fakeBackend("aws");
const sprites = fakeBackend("sprites");
(sprites as unknown as { computerStatus: unknown }).computerStatus = async (scopeId: string) => {
@@ -257,109 +332,69 @@ test("computer status/restart forward to the scope's routed backend", async () =
(sprites as unknown as { restartComputer: unknown }).restartComputer = async (scopeId: string) => {
sprites.calls.push(`restartComputer:${scopeId}`);
};
- await routes.put("personal:s", { backend: "sprites" });
- const router = createSandboxRouter({ backends: { aws, sprites }, routes, defaultBackend: "aws" });
- assert.equal(typeof router.computerStatus, "function");
+ return { aws, sprites };
+}
+
+test("computer status/restart target the resource's backing scope under its lock", async () => {
+ const { aws, sprites } = computerBackends();
+ const resources = stubResources({ "personal:s": resource("s", "sprites") });
+ const router = createSandboxRouter({ backends: { aws, sprites }, defaultBackend: "aws", resources });
assert.deepEqual(await router.computerStatus!("personal:s"), { machine: "started", guestResponsive: true });
await router.restartComputer!("personal:s");
assert.deepEqual(
- sprites.calls.filter((c) => c.startsWith("computerStatus") || c.startsWith("restartComputer")),
- ["computerStatus:personal:s", "restartComputer:personal:s"],
- );
-});
-
-test("computer status/restart on a scope routed to a backend without them is a typed refusal", async () => {
- const routes = createMemoryMap<SandboxRoute>();
- const aws = fakeBackend("aws");
- (aws as unknown as { computerStatus: unknown }).computerStatus = async () => ({
- machine: "started",
- guestResponsive: true,
- });
- (aws as unknown as { restartComputer: unknown }).restartComputer = async () => {};
- const sprites = fakeBackend("sprites");
- await routes.put("personal:s", { backend: "sprites" });
- const router = createSandboxRouter({ backends: { aws, sprites }, routes, defaultBackend: "aws" });
- await assert.rejects(
- async () => router.computerStatus!("personal:s"),
- (e: unknown) => e instanceof CapabilityUnsupportedError,
- );
- await assert.rejects(
- async () => router.restartComputer!("personal:s"),
- (e: unknown) => e instanceof CapabilityUnsupportedError,
+ sprites.calls.filter((c) => c.startsWith("computer") || c.startsWith("restart")),
+ ["computerStatus:sandbox:s", "restartComputer:sandbox:s"],
);
+ assert.deepEqual(resources.locks, [
+ { id: "s", exclusive: false },
+ { id: "s", exclusive: true },
+ ]);
});
-test("scope defaults select providers while explicit routes and handles retain ownership", async () => {
- const routes = createMemoryMap<SandboxRoute>();
- const modal = fakeBackend("modal");
- const sprites = fakeBackend("sprites");
- const aws = fakeBackend("aws");
+test("computer status/restart with no default resource refuse with NoDefaultSandboxError", async () => {
+ const { aws, sprites } = computerBackends();
const router = createSandboxRouter({
- backends: { modal, sprites, aws },
- routes,
- defaultBackend: "sprites",
- scopeDefaults: { personal: "modal", channel: "sprites" },
+ backends: { aws, sprites },
+ defaultBackend: "aws",
+ resources: stubResources({}),
});
- await routes.put("personal:existing", { backend: "aws" });
- const personal = await router.provision(layersFor("personal:new"));
- const channel = await router.provision(layersFor("channel:shared"));
- const existing = await router.provision(layersFor("personal:existing"));
- assert.equal(personal.backend, "modal");
- assert.equal(channel.backend, "sprites");
- assert.equal(existing.backend, "aws");
- assert.equal((await router.run(personal, "pwd")).stdout, "modal");
- assert.equal((await router.profileFor!("personal:new")).backend, "modal");
- assert.equal((await router.profileFor!("personal:existing")).backend, "aws");
+ await assert.rejects(async () => router.computerStatus!("personal:none"), NoDefaultSandboxError);
+ await assert.rejects(async () => router.restartComputer!("personal:none"), NoDefaultSandboxError);
+ assert.deepEqual(sprites.calls, []);
});
-test("missing scope provider refuses substitution", async () => {
+test("computer status/restart on a backend without them is a typed refusal", async () => {
+ const { aws, sprites } = computerBackends();
const router = createSandboxRouter({
- backends: { sprites: fakeBackend("sprites") },
- routes: createMemoryMap<SandboxRoute>(),
+ backends: { aws, sprites },
defaultBackend: "sprites",
- scopeDefaults: { personal: "modal" },
+ resources: stubResources({ "personal:a": resource("a", "aws") }),
});
- await assert.rejects(router.provision(layersFor("personal:new")), /unavailable: modal/);
+ await assert.rejects(async () => router.computerStatus!("personal:a"), CapabilityUnsupportedError);
+ await assert.rejects(async () => router.restartComputer!("personal:a"), CapabilityUnsupportedError);
});
for (const combined of [true, false]) {
test(`cleanup and listing share one resource lock (provider combined=${combined})`, async () => {
const backend = fakeBackend("sprites");
- let locked = false;
- let acquisitions = 0;
+ const resources = stubResources({});
const calls: string[] = [];
backend.removeDir = async (_h, path) => {
- assert.ok(locked);
+ assert.ok(resources.isLocked());
calls.push(`remove:${path}`);
};
backend.listDir = async (_h, path) => {
- assert.ok(locked);
+ assert.ok(resources.isLocked());
calls.push(`list:${path}`);
return ["keep/file"];
};
if (combined)
backend.removeDirAndList = async (_h, remove, list) => {
- assert.ok(locked);
+ assert.ok(resources.isLocked());
calls.push(`combined:${remove}:${list}`);
return ["keep/file"];
};
- const resources = {
- use: async (_id: string, action: () => Promise<unknown>) => {
- acquisitions++;
- locked = true;
- try {
- return await action();
- } finally {
- locked = false;
- }
- },
- } as unknown as import("../src/sandbox/sandbox-resources.ts").SandboxResources;
- const router = createSandboxRouter({
- backends: { sprites: backend },
- routes: createMemoryMap(),
- defaultBackend: "sprites",
- resources,
- });
+ const router = createSandboxRouter({ backends: { sprites: backend }, defaultBackend: "sprites", resources });
assert.deepEqual(
await router.removeDirAndList!(
{ id: "box", rootDir: "/workspace", backend: "sprites", resourceId: "resource" },
@@ -368,28 +403,7 @@ for (const combined of [true, false]) {
),
["keep/file"],
);
- assert.equal(acquisitions, 1);
+ assert.equal(resources.locks.length, 1);
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/sandbox-upgrade-wiring.test.ts b/test/sandbox-upgrade-wiring.test.ts
new file mode 100644
index 000000000..55bf98eda
--- /dev/null
+++ b/test/sandbox-upgrade-wiring.test.ts
@@ -0,0 +1,22 @@
+import { fakeSprites } from "./support/auto-fake-sprites.ts";
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { buildApp } from "../src/wiring.ts";
+import { testConfig } from "./support/test-config.ts";
+
+test("startup adopts a cold environment target even when it has no session", async () => {
+ const built = buildApp(testConfig());
+ try {
+ const scope = "personal:existing-environment";
+ await built.app.createEnvironment({ scopeId: scope, name: "existing", actorId: "existing-environment" });
+ await built.sandboxResources.initialize();
+ const resource = await built.sandboxResources.resolve(scope);
+ assert.ok(resource?.legacy);
+ assert.equal(resource.backingScopeId, scope);
+ assert.equal(resource.ownerScopeId, scope);
+ assert.equal(resource.state, "unverified");
+ assert.deepEqual(fakeSprites.names(), []);
+ } finally {
+ await built.runtime.stop();
+ }
+});
diff --git a/test/scope-reach.test.ts b/test/scope-reach.test.ts
index 93f4a4c68..8c3d34e9c 100644
--- a/test/scope-reach.test.ts
+++ b/test/scope-reach.test.ts
@@ -334,6 +334,16 @@ function freshApp(extra: Partial<Config> = {}) {
return buildApp(config);
}
+async function roomApp() {
+ const built = freshApp({ reachExecEnabled: true });
+ await built.directory.replaceChannels([{ channelId: "C-ph", name: "project-alpha" }]);
+ const room = scopeId("channel", "C-ph");
+ const resources = built.sandboxResources.forTurn({ actorId: "U1", scopeId: room, isCurrent: async () => true });
+ const record = await resources.create("U1", room, resources.defaultBackend(), "project-alpha", "room-ph");
+ await resources.setDefault("U1", room, record.id);
+ return built;
+}
+
const dm = (text: string): TurnRequest => ({
surface: "test",
actor: { externalId: "U1", displayName: "Alice" },
@@ -355,42 +365,38 @@ const channelTurn = (text: string): TurnRequest => ({
});
test("DM + directory + flag: execute(scope:#room) runs on that channel's own computer", async () => {
- const built = freshApp({ reachExecEnabled: true });
- await built.directory.replaceChannels([{ channelId: "C-ph", name: "project-alpha" }]);
+ const built = await roomApp();
const res = await built.app.turn(
dm("!reach #project-alpha sh -c \"echo 'still here' > smoke.txt && cat smoke.txt\""),
);
assert.equal(res.status, "ok");
assert.equal(res.reply, "still here");
assert.ok(
- fakeSprites.calls.some((c) => c.method === "WS" && /\/sprites\/qm-channel-c-ph-[^/]+\/exec$/.test(c.path)),
+ fakeSprites.calls.some((c) => c.method === "WS" && /\/sprites\/qm-sandbox-room-ph-[^/]+\/exec$/.test(c.path)),
"the command landed on the channel's computer",
);
});
test("reach preserves a durable workspace even without a login-probe cache", async () => {
- const built = freshApp({ reachExecEnabled: true });
- await built.directory.replaceChannels([{ channelId: "C-ph", name: "project-alpha" }]);
+ const built = await roomApp();
await built.app.turn(dm("!reach #project-alpha printf retained > keep.txt"));
- assert.ok(fakeSprites.names().some((n) => n.startsWith("qm-channel-c-ph-")));
+ assert.ok(fakeSprites.names().some((n) => n.startsWith("qm-sandbox-room-ph-")));
const result = await built.app.turn(dm("!reach #project-alpha cat keep.txt"));
assert.equal(result.reply, "retained");
});
test("reach teardown keeps (does not destroy) a room with its own computer", async () => {
- const built = freshApp({ reachExecEnabled: true });
- await built.directory.replaceChannels([{ channelId: "C-ph", name: "project-alpha" }]);
+ const built = await roomApp();
await built.livenessCache.put({ scopeId: scopeId("channel", "C-ph"), checkedAt: 1, connectors: {} });
await built.app.turn(dm("!reach #project-alpha echo hi"));
assert.ok(
- fakeSprites.names().some((n) => n.startsWith("qm-channel-c-ph-")),
+ fakeSprites.names().some((n) => n.startsWith("qm-sandbox-room-ph-")),
"an operated room's computer is kept, not destroyed",
);
});
test("Trap 1 e2e: the reach tool_result is labeled the session scope and survives the audience filter", async () => {
- const built = freshApp({ reachExecEnabled: true });
- await built.directory.replaceChannels([{ channelId: "C-ph", name: "project-alpha" }]);
+ const built = await roomApp();
const res = await built.app.turn(dm("!reach #project-alpha echo hello"));
assert.equal(res.reply, "hello");
const entries = await built.sessions.getEntries(res.sessionId!);
diff --git a/test/secret-schema-conformance.test.ts b/test/secret-schema-conformance.test.ts
index d3ba02bc6..735680320 100644
--- a/test/secret-schema-conformance.test.ts
+++ b/test/secret-schema-conformance.test.ts
@@ -29,7 +29,6 @@ test("runtime schema conditions reference env vars the CLI schema also condition
// so `qm secrets` and core boot validation agree about when a secret becomes required.
const runtimeConditionEnv = [
"SANDBOX_BACKEND",
- "SANDBOX_SCOPE_BACKENDS",
"DEPLOY_PROVIDER",
"AWS_DEPLOY_APPS_DOMAIN",
"DEPLOY_APPS_DOMAIN",
@@ -45,10 +44,7 @@ test("runtime schema conditions reference env vars the CLI schema also condition
conditions?: CliCondition[];
}
const collect = (when: CliCondition): void => {
- if (when.kind === "sandbox-backend") {
- cliConditionEnv.add("SANDBOX_BACKEND");
- cliConditionEnv.add("SANDBOX_SCOPE_BACKENDS");
- }
+ if (when.kind === "sandbox-backend") cliConditionEnv.add("SANDBOX_BACKEND");
if (when.name) cliConditionEnv.add(when.name);
for (const name of when.names ?? []) cliConditionEnv.add(name);
for (const nested of when.conditions ?? []) collect(nested);
diff --git a/test/security-screen-context.test.ts b/test/security-screen-context.test.ts
index e54726f7b..f6eebc5cf 100644
--- a/test/security-screen-context.test.ts
+++ b/test/security-screen-context.test.ts
@@ -5,6 +5,7 @@ import type { AddressInfo } from "node:net";
import { buildApp } from "../src/wiring.ts";
import { createInsecureTestServer } from "../src/api/server.ts";
import { testConfig } from "./support/test-config.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
import type { SecurityScreener } from "../src/security/security-screener.ts";
for (const surface of ["web", "slack", "swarm"]) {
@@ -19,6 +20,7 @@ for (const surface of ["web", "slack", "swarm"]) {
},
},
});
+ await selectDefaultSandbox(built, "U1", "personal:U1");
const server = createInsecureTestServer(built.app);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
diff --git a/test/service-credential-route.test.ts b/test/service-credential-route.test.ts
index ea0f26b6c..333510e74 100644
--- a/test/service-credential-route.test.ts
+++ b/test/service-credential-route.test.ts
@@ -1,4 +1,5 @@
import "./support/auto-fake-sprites.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -1051,6 +1052,7 @@ test("orchestrator vends a capability for only the requested org credential", as
permission: "read",
grantedBy: "admin",
});
+ await selectDefaultSandbox(built, "U1", "personal:U1", "channel:C1");
await built.app.turn(dm("!run echo hi"));
assert.equal(executionEnv()?.AGENT_CREDENTIAL_TOKEN, undefined);
const res = await built.app.turn(
@@ -1101,6 +1103,7 @@ test("orchestrator does NOT stamp a credential granted only to someone else", as
permission: "read",
grantedBy: "admin",
});
+ await selectDefaultSandbox(built, "U1", "personal:U1");
await assert.rejects(
built.app.turn(dm(`!execute ${JSON.stringify({ command: "echo hi", credentials: ["service_x-firehose"] })}`)),
@@ -1140,6 +1143,7 @@ test("a channel grantee stamps the credential in that channel's conversations an
text: "!run echo hi",
});
+ await selectDefaultSandbox(built, "U1", "channel:C1", "channel:C2", "personal:U1");
await built.app.turn(channelTurn("C1"));
assert.equal(executionEnv()?.AGENT_CREDENTIAL_TOKEN, undefined);
let res = await built.app.turn({
@@ -1175,6 +1179,7 @@ test("a channel grantee stamps the credential in that channel's conversations an
test("orchestrator stamps nothing when the org has no service credentials (zero-cost common path)", async () => {
const { built, env } = buildWithCapture();
+ await selectDefaultSandbox(built, "U1", "personal:U1");
const res = await built.app.turn(dm("!run echo hi"));
assert.equal(res.status, "ok", res.reason);
assert.equal(env()?.AGENT_CREDENTIAL_TOKEN, undefined);
diff --git a/test/sessions-background-activity.test.ts b/test/sessions-background-activity.test.ts
index 0c349316f..4972f0c4d 100644
--- a/test/sessions-background-activity.test.ts
+++ b/test/sessions-background-activity.test.ts
@@ -20,7 +20,7 @@ function dm(text: string, thread: string): TurnRequest {
}
test("background output selects the recorded private resource and fails closed when it is unavailable", async () => {
- const built = buildApp(testConfig({ sandboxResourcesEnabled: true }));
+ const built = buildApp(testConfig({}));
try {
const root = await built.app.turn(dm("Start", "resource-output"));
const resource = await built.sandboxResources.create("U1", "personal:U1", "sprites", "Worker");
diff --git a/test/sharing-context-e2e.test.ts b/test/sharing-context-e2e.test.ts
index 0948f4941..0564e8c96 100644
--- a/test/sharing-context-e2e.test.ts
+++ b/test/sharing-context-e2e.test.ts
@@ -29,6 +29,15 @@ async function fixture(t: TestContext, config: Partial<Config> = {}) {
);
};
await roster();
+ for (const [actor, scope] of [
+ ["U1", "personal:U1"],
+ ["U2", "personal:U2"],
+ ["U3", "personal:U3"],
+ ["U1", "channel:C1"],
+ ] as const) {
+ const computer = await built.sandboxResources.create(actor, scope, "sprites", "default");
+ await built.sandboxResources.setDefault(actor, scope, computer.id);
+ }
await built.config.setSharingPosture("org:default-org", "open");
const turn = async (text: string, room = false, actor = "U1", extra: Partial<TurnRequest> = {}) => {
const result = await built.app.turn({
diff --git a/test/skills-callable.test.ts b/test/skills-callable.test.ts
index 7713a2135..4c3eb542d 100644
--- a/test/skills-callable.test.ts
+++ b/test/skills-callable.test.ts
@@ -10,6 +10,12 @@ import type { TurnRequest } from "../src/types.ts";
import { scopeId } from "../src/types.ts";
import { testConfig } from "./support/test-config.ts";
+async function withDefaultComputer(built: ReturnType<typeof buildApp>) {
+ const computer = await built.sandboxResources.create("U1", "personal:U1", "sprites", "default");
+ await built.sandboxResources.setDefault("U1", "personal:U1", computer.id);
+ return built;
+}
+
function freshApp() {
const config = testConfig({
dataDir: mkdtempSync(join(tmpdir(), "ap-skill-")),
@@ -70,7 +76,7 @@ test("a channel session does NOT see a personal skill (scope boundary)", async (
});
test("ordinary sandbox work never touches the skills tree", async () => {
- const { app, skills, sandbox } = freshApp();
+ const { app, skills, sandbox } = await withDefaultComputer(freshApp());
await publishPersonalSkill(skills);
const touched: string[] = [];
const read = sandbox.readFile.bind(sandbox);
@@ -115,7 +121,7 @@ async function publishFileSkill(skills: ReturnType<typeof buildApp>["skills"], n
}
test("skill files live only for the turn that loaded them", async () => {
- const { app, skills } = freshApp();
+ const { app, skills } = await withDefaultComputer(freshApp());
const first = await publishFileSkill(skills, "helper");
const request = {
surface: "test",
diff --git a/test/skills-seed.test.ts b/test/skills-seed.test.ts
index ac9b0f261..917624ba5 100644
--- a/test/skills-seed.test.ts
+++ b/test/skills-seed.test.ts
@@ -14,6 +14,7 @@ import type { Sandbox, SandboxHandle } from "../src/sandbox/sandbox.ts";
import { buildApp } from "../src/wiring.ts";
import { scopeId, type TurnRequest } from "../src/types.ts";
import { testConfig } from "./support/test-config.ts";
+import { selectDefaultSandbox } from "./support/default-sandbox.ts";
test("seed skill parser reads the repo frontmatter subset", () => {
const manifest = parseSeedSkill(`---
@@ -168,6 +169,7 @@ test("a fresh app advertises and materializes only admin-enabled connector skill
dataDir: mkdtempSync(join(tmpdir(), "seeded-skills-")),
});
const built = buildApp(config);
+ await selectDefaultSandbox(built, "U1", scopeId("personal", "U1"));
await built.config.setConnectorClient(scopeId("org", "default-org"), "google", {
clientId: "google-client",
clientSecret: "google-secret",
diff --git a/test/skills-source-read.test.ts b/test/skills-source-read.test.ts
index 0cc48d7ef..81feeb871 100644
--- a/test/skills-source-read.test.ts
+++ b/test/skills-source-read.test.ts
@@ -8,6 +8,10 @@ import type { TurnRequest } from "../src/types.ts";
async function fixture(t: TestContext) {
const built = buildApp(testConfig());
await built.deploymentLayerReady;
+ for (const actor of ["U1", "U2"]) {
+ const computer = await built.sandboxResources.create(actor, `personal:${actor}`, "sprites", "default");
+ await built.sandboxResources.setDefault(actor, `personal:${actor}`, computer.id);
+ }
t.after(async () => {
built.scheduler.stop();
built.deploymentLayerRefresh.stop();
diff --git a/test/support/default-sandbox.ts b/test/support/default-sandbox.ts
new file mode 100644
index 000000000..4805f8033
--- /dev/null
+++ b/test/support/default-sandbox.ts
@@ -0,0 +1,10 @@
+import type { BuiltApp } from "../../src/wiring.ts";
+import type { ScopeId } from "../../src/types.ts";
+
+export async function selectDefaultSandbox(built: BuiltApp, actorId: string, ...scopes: ScopeId[]): Promise<void> {
+ for (const scopeId of scopes) {
+ const resources = built.sandboxResources.forTurn({ actorId, scopeId, isCurrent: async () => true });
+ const record = await resources.create(actorId, scopeId, resources.defaultBackend());
+ await resources.setDefault(actorId, scopeId, record.id);
+ }
+}
diff --git a/test/support/swarm-fixture.ts b/test/support/swarm-fixture.ts
index 519c82fb7..ab893ba50 100644
--- a/test/support/swarm-fixture.ts
+++ b/test/support/swarm-fixture.ts
@@ -62,13 +62,9 @@ export async function swarmFixture(
disks.delete(id);
},
};
- const routes = createMemoryMap<import("../../src/sandbox/sandbox-routing.ts").SandboxRoute>();
const sandboxes = createSandboxResources({
- enabled: true,
- rollout: createMemoryMap(),
records,
defaults: createMemoryMap(),
- routes,
backends: { modal: backend },
defaultBackend: "modal",
lock,
@@ -77,7 +73,6 @@ export async function swarmFixture(
const sandbox = createSandboxRouter({
backends: { modal: backend },
defaultBackend: "modal",
- routes,
resources: sandboxes,
});
const actor = { id: "alice", type: "internal" as const };
diff --git a/test/swarm-orchestrator.test.ts b/test/swarm-orchestrator.test.ts
index 05cdeb3b7..4d310d3e9 100644
--- a/test/swarm-orchestrator.test.ts
+++ b/test/swarm-orchestrator.test.ts
@@ -58,9 +58,7 @@ test.after(() => fake.cleanup());
for (const kind of ["command", "security-screen"] as const) {
test(`workers require their own approval instead of inheriting root-session ${kind} grants`, async () => {
- const built = buildApp(
- testConfig({ sandboxResourcesEnabled: true, modalSandbox: { tokenId: "test", tokenSecret: "test" } }),
- );
+ const built = buildApp(testConfig({ modalSandbox: { tokenId: "test", tokenSecret: "test" } }));
const request: TurnRequest = {
surface: "swarm",
actor: { externalId: "U1" },
@@ -125,7 +123,6 @@ for (const kind of ["command", "security-screen"] as const) {
test("wired swarm outbox drives the real orchestrator, durable runs, and authenticated session viewer", async () => {
const built = buildApp(
testConfig({
- sandboxResourcesEnabled: true,
modalSandbox: { tokenId: "test-id", tokenSecret: "test-secret", nativeSnapshotsEnabled: true },
}),
);
@@ -220,7 +217,7 @@ for (const storage of ["memory", "postgres"] as const) {
databaseUrl,
sessionStore: storage,
runStore: storage,
- sandboxResourcesEnabled: true,
+
modalSandbox: { tokenId: "test", tokenSecret: "test" },
signingSecret: "swarm-http-source-signing-key-distinct",
portalIdentitySecret: "swarm-http-portal-identity-key-distinct",
@@ -474,6 +471,8 @@ test("unbound request fields cannot claim verified swarm provenance", async () =
test("a resolved command approval informs the model without changing its requested command", async () => {
const built = buildApp(testConfig());
+ const sandbox = await built.sandboxResources.create("U1", "personal:U1", "sprites");
+ await built.sandboxResources.setDefault("U1", "personal:U1", sandbox.id);
const request: TurnRequest = {
surface: "web",
actor: { externalId: "U1" },
diff --git a/test/swarm-regressions.test.ts b/test/swarm-regressions.test.ts
index e07243f69..736641d09 100644
--- a/test/swarm-regressions.test.ts
+++ b/test/swarm-regressions.test.ts
@@ -73,11 +73,8 @@ test("provider default is pinned before retries and child provisioning, with no
const { createSwarmService } = await import("../src/swarms/swarm-service.ts");
const f = await swarmFixture();
const options: Parameters<typeof createSandboxResources>[0] = {
- enabled: true,
- rollout: createMemoryMap(),
records: f.records,
defaults: createMemoryMap(),
- routes: createMemoryMap(),
backends: { aws: { ...f.backend, profile: { ...f.backend.profile, backend: "aws" } } },
defaultBackend: "aws",
lock: f.serviceOptions.lock,
@@ -104,11 +101,8 @@ test("selected scope computer determines new worker provider, but its private di
const { createSwarmService } = await import("../src/swarms/swarm-service.ts");
const f = await swarmFixture();
const sandboxes = createSandboxResources({
- enabled: true,
- rollout: createMemoryMap(),
records: f.records,
defaults: createMemoryMap(),
- routes: createMemoryMap(),
backends: { modal: f.backend, aws: { ...f.backend, profile: { ...f.backend.profile, backend: "aws" } } },
defaultBackend: "modal",
lock: f.serviceOptions.lock,
diff --git a/test/turn-stream.test.ts b/test/turn-stream.test.ts
index 7f127d8d4..397952d67 100644
--- a/test/turn-stream.test.ts
+++ b/test/turn-stream.test.ts
@@ -142,6 +142,8 @@ test("a queued tool-using run surfaces its activity + timings via getRun()", asy
reaperIntervalMs: 60_000,
}),
);
+ const computer = await built.sandboxResources.create("U1", "personal:U1", "sprites", "default");
+ await built.sandboxResources.setDefault("U1", "personal:U1", computer.id);
built.runtime.start();
try {
const ack = await built.app.turn({
diff --git a/test/upload-no-default-native.test.ts b/test/upload-no-default-native.test.ts
index fe2b6a125..b10a8cb7b 100644
--- a/test/upload-no-default-native.test.ts
+++ b/test/upload-no-default-native.test.ts
@@ -26,7 +26,7 @@ const PNG = Buffer.from(
);
async function scopeWithoutDefault() {
- const built = buildApp(testConfig({ sandboxResourcesEnabled: true, eagerProvisionEnabled: false }));
+ const built = buildApp(testConfig({ eagerProvisionEnabled: false }));
await built.directory.replace([{ principalId: "U1", displayName: "Synthetic User", type: "internal" }]);
await built.directory.replaceChannels(
[{ channelId: "C1", name: "synthetic-upload", isPrivate: true }],
diff --git a/test/upload-without-default-sandbox.test.ts b/test/upload-without-default-sandbox.test.ts
index be7efe975..127a57dd7 100644
--- a/test/upload-without-default-sandbox.test.ts
+++ b/test/upload-without-default-sandbox.test.ts
@@ -6,7 +6,7 @@ import { testConfig } from "./support/test-config.ts";
import type { TurnRequest } from "../src/types.ts";
test("an upload in a scope without a default sandbox still reaches the agent", async () => {
- const built = buildApp(testConfig({ sandboxResourcesEnabled: true, eagerProvisionEnabled: false }));
+ const built = buildApp(testConfig({ eagerProvisionEnabled: false }));
await built.directory.replace([{ principalId: "U1", displayName: "Synthetic User", type: "internal" }]);
await built.directory.replaceChannels(
[{ channelId: "C1", name: "synthetic-upload", isPrivate: true }],
diff --git a/test/web-ui-sse.test.ts b/test/web-ui-sse.test.ts
index f07a738a7..220bd8401 100644
--- a/test/web-ui-sse.test.ts
+++ b/test/web-ui-sse.test.ts
@@ -94,6 +94,8 @@ test("SSE streams partial frames then a terminal done frame carrying the reply",
});
test("SSE relays tool activity frames and folds them into the done frame", async () => {
+ const computer = await built.sandboxResources.create("alice", "personal:alice", "sprites", "default");
+ await built.sandboxResources.setDefault("alice", "personal:alice", computer.id);
const submit = (await (
await fetch(
`${webBase}/api/turn`,