Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Support sandbox provider defaults by scope kind (#1202)

Regan Bellc673a0aeeb7d
diff --git a/cli/src/config.ts b/cli/src/config.ts
index 25b51b285..2913e8673 100644
--- a/cli/src/config.ts
+++ b/cli/src/config.ts
@@ -1517,11 +1517,6 @@ function validateSandbox(raw: unknown, path: string, target: Target): SandboxCon
if (out.image && !out.app && out.backend !== "local") {
throw new CliError(`${path}: "sandbox.image" requires "sandbox.app" unless "sandbox.backend" is "local"`);
}
- if (out.backend === "sprites" && !out.app) {
- throw new CliError(
- `${path}: "sandbox.backend": ${JSON.stringify(out.backend)} requires "sandbox.app" (the Fly app agents execute in)`,
- );
- }
if (SANDBOX_BACKEND_POLICY[target].requireExplicit && out.backend === undefined) {
throw new CliError(
`${path}: target ${JSON.stringify(target)} requires an explicit "sandbox.backend" — "sprites" runs Fly Sprites; "aws" runs Lambda MicroVM sandboxes (or omit the whole "sandbox" block for the MicroVM default)`,
diff --git a/cli/src/secrets.ts b/cli/src/secrets.ts
index e68a2741b..a158ad5e4 100644
--- a/cli/src/secrets.ts
+++ b/cli/src/secrets.ts
@@ -4,6 +4,7 @@ import { TARGET_ENV_DEFAULTS } from "./target-env-defaults.ts";
import { deploymentSecretValue } from "./util.ts";
type SecretCondition =
+ | { kind: "sandbox-backend"; backend: string }
| { kind: "env-equals"; service: DeclaredServiceName; name: string; value: string }
| { kind: "env-in"; service: DeclaredServiceName; name: string; values: string[] }
| { kind: "env-absent"; service: DeclaredServiceName; name: string }
@@ -125,7 +126,7 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
when: {
kind: "any",
conditions: [
- { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "porter" },
+ { kind: "sandbox-backend", backend: "porter" },
{ kind: "env-equals", service: "core", name: "DEPLOY_PROVIDER", value: "porter" },
],
},
@@ -138,33 +139,33 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
{
name: "SPRITES_TOKEN",
service: "core",
- required: { when: { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "sprites" } },
+ required: { when: { kind: "sandbox-backend", backend: "sprites" } },
description: "Fly Sprites API token for the agent-computer substrate.",
generate: "sprite login # then copy the token from ~/.sprite/credentials",
},
{
name: "E2B_API_KEY",
service: "core",
- required: { when: { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "e2b" } },
+ required: { when: { kind: "sandbox-backend", backend: "e2b" } },
description: "E2B API key used by the e2b sandbox backend (from e2b.dev dashboard).",
},
{
name: "MODAL_TOKEN_ID",
service: "core",
- required: { when: { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "modal" } },
+ required: { when: { kind: "sandbox-backend", backend: "modal" } },
description: "Modal token id used by the modal sandbox backend.",
generate: "modal token new # or create a token in the Modal dashboard",
},
{
name: "MODAL_TOKEN_SECRET",
service: "core",
- required: { when: { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "modal" } },
+ required: { when: { kind: "sandbox-backend", backend: "modal" } },
description: "Modal token secret paired with MODAL_TOKEN_ID.",
},
{
name: "SMOLMACHINES_TOKEN",
service: "core",
- required: { when: { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "smolmachines" } },
+ required: { when: { kind: "sandbox-backend", backend: "smolmachines" } },
description: "smolmachines API key for the agent-computer substrate.",
generate: "create an API key in the smolmachines console (https://smolmachines.com/console)",
},
@@ -175,7 +176,7 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
when: {
kind: "any",
conditions: [
- { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "agent37" },
+ { kind: "sandbox-backend", backend: "agent37" },
{ kind: "env-equals", service: "core", name: "SANDBOX_SECONDARY_BACKEND", value: "agent37" },
],
},
@@ -486,6 +487,17 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
];
function conditionMatches(config: QmConfig, condition: SecretCondition): boolean {
+ if (condition.kind === "sandbox-backend") {
+ const backend =
+ 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);
+ }
if (condition.kind === "service-enabled") return config.services.includes(condition.service);
if (condition.kind === "service-absent") return !config.services.includes(condition.service);
if (condition.kind === "all") return condition.conditions.every((nested) => conditionMatches(config, nested));
@@ -710,6 +722,8 @@ function requiresOtherEmailTransport(config: QmConfig, condition: SecretConditio
}
function conditionClause(condition: SecretCondition): string {
+ if (condition.kind === "sandbox-backend")
+ return `SANDBOX_BACKEND or SANDBOX_SCOPE_BACKENDS 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 4dac1d9f9..5b28596c7 100644
--- a/cli/test/config.test.ts
+++ b/cli/test/config.test.ts
@@ -935,6 +935,11 @@ test("aws target makes the sandbox substrate explicit: backend required with a s
withConfig({ target: "aws", aws, sandbox: { backend: "sprites", app: "acme-sandboxes" } }, ({ path }) => {
assert.equal(loadConfigAt(path).config.sandbox?.backend, "sprites");
});
+ withConfig({ target: "aws", aws, sandbox: { backend: "sprites" } }, ({ path }) => {
+ const { config } = loadConfigAt(path);
+ assert.equal(config.sandbox?.backend, "sprites");
+ assert.equal(config.sandbox?.app, undefined);
+ });
withConfig({ target: "aws", aws, sandbox: { backend: "aws" } }, ({ path }) => {
assert.equal(loadConfigAt(path).config.sandbox?.backend, "aws");
});
diff --git a/cli/test/secrets.test.ts b/cli/test/secrets.test.ts
index c3471f93f..016103c22 100644
--- a/cli/test/secrets.test.ts
+++ b/cli/test/secrets.test.ts
@@ -389,3 +389,14 @@ test("combined auth rejects two source secrets for the same environment name", (
/would receive env RESEND_API_KEY from both/,
);
});
+
+test("scope-selected providers require both Modal and Sprites credentials", () => {
+ const config = makeConfig({
+ env: { core: { SANDBOX_BACKEND: "sprites", SANDBOX_SCOPE_BACKENDS: '{"personal":"modal","channel":"sprites"}' } },
+ });
+ 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);
+});
diff --git a/docs/upgrading-runtime.md b/docs/upgrading-runtime.md
index 00e207464..4b7e18913 100644
--- a/docs/upgrading-runtime.md
+++ b/docs/upgrading-runtime.md
@@ -15,6 +15,16 @@ 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.
- Reach-denied Slack notifications are retired. Consult the audit log for denied
requests.
diff --git a/src/api/routes/admin/sandbox.ts b/src/api/routes/admin/sandbox.ts
index 96839d84b..edafd8ff5 100644
--- a/src/api/routes/admin/sandbox.ts
+++ b/src/api/routes/admin/sandbox.ts
@@ -21,6 +21,7 @@ export async function listSandboxRoutes(ctx: ApiCtx): Promise<void> {
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 })),
});
diff --git a/src/config.ts b/src/config.ts
index df0d4b6a9..2d3dfcd7f 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -1,3 +1,5 @@
+import { parseScopeId } from "./types.ts";
+import type { SandboxScopeDefaults } from "./sandbox/sandbox-routing.ts";
import { existsSync, readdirSync } from "node:fs";
import {
parseProviderBaseUrl,
@@ -54,6 +56,7 @@ export interface Config {
securityPosture: SecurityPosture;
sandboxResourcesEnabled: boolean;
sharingPosture: SharingPosture;
+ sandboxScopeDefaults?: SandboxScopeDefaults;
sandboxBackend: "aws" | "local" | "sprites" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37";
sandboxSecondaryBackend?: "aws" | "local" | "sprites" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37";
deployProvider: "docker" | "aws" | "fly" | "porter";
@@ -1076,6 +1079,19 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
);
}
const sandboxBackend = sandboxBackendEnvStrict(env.SANDBOX_BACKEND);
+ const sandboxScopeDefaults: SandboxScopeDefaults = {};
+ if (env.SANDBOX_SCOPE_BACKENDS) {
+ const values: unknown = JSON.parse(env.SANDBOX_SCOPE_BACKENDS);
+ if (!values || typeof values !== "object" || Array.isArray(values))
+ throw new Error("SANDBOX_SCOPE_BACKENDS must be an object of scope kinds and backend names");
+ for (const [kind, value] of Object.entries(values)) {
+ 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);
+ }
+ }
+
if (env.SANDBOX_SECONDARY_BACKEND?.trim()) {
console.warn(
`[config] SANDBOX_SECONDARY_BACKEND=${JSON.stringify(env.SANDBOX_SECONDARY_BACKEND.trim())} is retired and ignored — every backend whose credential is present is constructed; per-scope routes pick between them. Remove the variable.`,
@@ -1243,6 +1259,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
}
: {}),
sandboxBackend,
+ sandboxScopeDefaults,
sandboxResourcesEnabled: boolEnvStrict("SANDBOX_RESOURCES_ENABLED", env.SANDBOX_RESOURCES_ENABLED) ?? false,
deployProvider,
...(env.EGRESS_SERVICE_HOSTS
diff --git a/src/deployment/secret-schema.ts b/src/deployment/secret-schema.ts
index 8e7d5a724..421b8b746 100644
--- a/src/deployment/secret-schema.ts
+++ b/src/deployment/secret-schema.ts
@@ -51,16 +51,24 @@ export const CORE_SECRET_SPECS: readonly RuntimeSecretSpec[] = [
{ name: "LINEAR_OAUTH_CLIENT_SECRET", requiredWhen: "linear-oauth" },
];
+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);
+}
+
const GATE_PREDICATES: Readonly<Record<SecretGate, (env: NodeJS.ProcessEnv) => boolean>> = {
production: (env) => env.NODE_ENV === "production",
codex: (env) => env.HARNESS?.trim() === "codex" && !env.CODEX_AUTH_FILE?.trim() && !env.CODEX_AUTH_CREDENTIAL?.trim(),
postgres: (env) => env.SESSION_STORE === "postgres" || env.RUN_STORE === "postgres",
- sprites: (env) => env.SANDBOX_BACKEND === "sprites",
- smolmachines: (env) => env.SANDBOX_BACKEND === "smolmachines",
- e2b: (env) => env.SANDBOX_BACKEND === "e2b",
- modal: (env) => env.SANDBOX_BACKEND === "modal",
- porter: (env) => env.SANDBOX_BACKEND === "porter",
- agent37: (env) => env.SANDBOX_BACKEND === "agent37",
+ sprites: (env) => sandboxBackendSelected(env, "sprites"),
+ smolmachines: (env) => sandboxBackendSelected(env, "smolmachines"),
+ e2b: (env) => sandboxBackendSelected(env, "e2b"),
+ modal: (env) => sandboxBackendSelected(env, "modal"),
+ porter: (env) => sandboxBackendSelected(env, "porter"),
+ agent37: (env) => sandboxBackendSelected(env, "agent37"),
"porter-deploy": (env) => env.DEPLOY_PROVIDER === "porter",
"fly-deploy": (env) => env.DEPLOY_PROVIDER === "fly",
"aws-deploy-gate": (env) => Boolean(env.AWS_DEPLOY_APPS_DOMAIN || env.DEPLOY_APPS_DOMAIN),
diff --git a/src/sandbox/sandbox-migration-runner.ts b/src/sandbox/sandbox-migration-runner.ts
index a3f0c30c4..8227758c4 100644
--- a/src/sandbox/sandbox-migration-runner.ts
+++ b/src/sandbox/sandbox-migration-runner.ts
@@ -4,7 +4,12 @@ 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 type { SandboxBackendName, SandboxRoute } from "./sandbox-routing.ts";
+import {
+ sandboxDefaultForScope,
+ type SandboxScopeDefaults,
+ type SandboxBackendName,
+ type SandboxRoute,
+} from "./sandbox-routing.ts";
import {
capabilitiesLostMovingTo,
supportsBlobStaging,
@@ -18,6 +23,7 @@ export interface SandboxMigrationOptions {
backends: Partial<Record<SandboxBackendName, Sandbox>>;
routes: DurableMap<SandboxRoute>;
defaultBackend: SandboxBackendName;
+ scopeDefaults?: SandboxScopeDefaults;
advisoryLock?: AdvisoryLock;
provisionOptions?: (scopeId: string) => Promise<ProvisionOptions>;
settleMs?: number;
@@ -50,6 +56,7 @@ export interface SandboxMigrationRunner {
listRoutes(): Promise<Array<[string, SandboxRoute]>>;
availableBackends(): SandboxBackendName[];
defaultBackend: SandboxBackendName;
+ scopeDefaults?: SandboxScopeDefaults;
}
const scopeLayers = (scopeId: string): WorkspaceLayer[] => [
@@ -68,7 +75,7 @@ export function createSandboxMigrationRunner(opts: SandboxMigrationOptions): San
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 ?? defaultBackend;
+ 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`);
@@ -227,5 +234,6 @@ export function createSandboxMigrationRunner(opts: SandboxMigrationOptions): San
.filter(([, s]) => !!s)
.map(([n]) => n as SandboxBackendName),
defaultBackend,
+ scopeDefaults: opts.scopeDefaults,
};
}
diff --git a/src/sandbox/sandbox-resources.ts b/src/sandbox/sandbox-resources.ts
index 1571d83c3..c5a39e3ee 100644
--- a/src/sandbox/sandbox-resources.ts
+++ b/src/sandbox/sandbox-resources.ts
@@ -2,7 +2,12 @@ import { randomUUID, createHash } from "node:crypto";
import type { DurableMap } from "../persistence/durable-map.ts";
import type { AdvisoryLock } from "../persistence/advisory-lock.ts";
import { parseScopeId, type ScopeId } from "../types.ts";
-import type { SandboxBackendName, SandboxRoute } from "./sandbox-routing.ts";
+import {
+ sandboxDefaultForScope,
+ type SandboxScopeDefaults,
+ type SandboxBackendName,
+ type SandboxRoute,
+} from "./sandbox-routing.ts";
import type { Sandbox, SandboxHandle, AgentComputerSpec, ProvisionOptions, ComputerStatus } from "./sandbox.ts";
export interface SandboxResource {
@@ -62,7 +67,7 @@ export interface SandboxResources {
setDefault(actorId: string, scopeId: ScopeId, id: string | null): Promise<void>;
resolve(scopeId: ScopeId): Promise<SandboxResource | null | undefined>;
get(id: string): Promise<SandboxResource>;
- defaultBackend(): SandboxBackendName;
+ defaultBackend(scopeId?: string): SandboxBackendName;
withLegacyMutation<T>(scopeId: string, action: () => Promise<T>): Promise<T>;
recordLegacy(scopeId: string, backend: SandboxBackendName, handle: SandboxHandle): Promise<string>;
}
@@ -77,6 +82,7 @@ export function createSandboxResources(opts: {
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>;
@@ -117,7 +123,8 @@ export function createSandboxResources(opts: {
if (valid(binding.scopeId)) candidates.set(legacyId(binding.scopeId, binding.backend), binding);
}
for (const scope of scopes) {
- const backend = routeBackends.get(scope) ?? opts.defaultBackend;
+ 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 });
}
@@ -139,7 +146,10 @@ export function createSandboxResources(opts: {
});
}
for (const scope of scopes) {
- const id = legacyId(scope, routeBackends.get(scope) ?? opts.defaultBackend);
+ 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 });
}
@@ -195,7 +205,7 @@ export function createSandboxResources(opts: {
return id;
};
return {
- defaultBackend: () => opts.defaultBackend,
+ defaultBackend: (scopeId) => sandboxDefaultForScope(scopeId, opts.defaultBackend, opts.scopeDefaults),
initialize,
get,
recordLegacy: (scopeId, backend, handle) =>
@@ -220,7 +230,9 @@ 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 ?? opts.defaultBackend;
+ 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))
throw new Error("unset or change this scope's default before retiring its computer");
await opts.beforeRetire?.(current);
diff --git a/src/sandbox/sandbox-routing.ts b/src/sandbox/sandbox-routing.ts
index aa6485ebe..8bff4349b 100644
--- a/src/sandbox/sandbox-routing.ts
+++ b/src/sandbox/sandbox-routing.ts
@@ -1,5 +1,5 @@
import type { SandboxResources } from "./sandbox-resources.ts";
-import type { WorkspaceLayer } from "../types.ts";
+import { parseScopeId, type ScopeKind, type WorkspaceLayer } from "../types.ts";
import type { DurableMap } from "../persistence/durable-map.ts";
import { swallow, swallowAs } from "../util/errors.ts";
import {
@@ -18,6 +18,17 @@ import {
export type SandboxBackendName = "sprites" | "aws" | "local" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37";
+export type SandboxScopeDefaults = Partial<Record<ScopeKind, SandboxBackendName>>;
+
+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;
@@ -31,6 +42,7 @@ export interface RoutingSandboxOptions {
backends: Partial<Record<SandboxBackendName, Sandbox>>;
routes: DurableMap<SandboxRoute>;
defaultBackend: SandboxBackendName;
+ scopeDefaults?: SandboxScopeDefaults;
resources?: SandboxResources;
onError?: (e: { category: string; code: string; message: string; scopeLabel?: string }) => void;
}
@@ -56,7 +68,7 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
async function pick(scopeId: string): Promise<{ name: SandboxBackendName; sandbox: Sandbox }> {
const route = await routeFor(scopeId);
- const name = route?.backend ?? defaultBackend;
+ const name = route?.backend ?? sandboxDefaultForScope(scopeId, defaultBackend, opts.scopeDefaults);
const sandbox = backends[name];
if (sandbox) return { name, sandbox };
opts.onError?.({
@@ -91,7 +103,7 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {
async function pickStrict(scopeId: string): Promise<Sandbox> {
const route = await routeFor(scopeId);
- const name = route?.backend ?? defaultBackend;
+ const name = route?.backend ?? sandboxDefaultForScope(scopeId, defaultBackend, opts.scopeDefaults);
const sandbox = backends[name];
if (!sandbox) {
throw new Error(
diff --git a/src/swarms/swarm-service.ts b/src/swarms/swarm-service.ts
index 3d8e3c5f2..c878ffbd1 100644
--- a/src/swarms/swarm-service.ts
+++ b/src/swarms/swarm-service.ts
@@ -264,7 +264,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();
+ const requested = backend ?? selected?.backend ?? deps.sandboxes.defaultBackend(session.scopeId);
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/wiring.ts b/src/wiring.ts
index 4625d337e..2273a03aa 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -931,6 +931,9 @@ 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 sandboxResources = createSandboxResources({
enabled: config.sandboxResourcesEnabled,
@@ -949,6 +952,7 @@ export function buildApp(
routes: sandboxRoutes,
backends: sandboxBackends,
defaultBackend: config.sandboxBackend,
+ scopeDefaults: config.sandboxScopeDefaults,
lock: advisoryLock,
beforeRetire: async (record) => {
if (
@@ -986,12 +990,14 @@ export function buildApp(
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) => {
diff --git a/test/config.test.ts b/test/config.test.ts
index dddf5110d..8e10f619b 100644
--- a/test/config.test.ts
+++ b/test/config.test.ts
@@ -712,3 +712,25 @@ test("suggestion generation defaults on and can be explicitly disabled", () => {
assert.equal(loadConfig({ SUGGESTED_ACTIVITIES_ENABLED: "false" }).suggestedActivitiesEnabled, false);
assert.throws(() => loadConfig({ SUGGESTED_ACTIVITIES_ENABLED: "maybe" }));
});
+
+test("sandbox scope defaults parse exact scope kinds and reject malformed mappings", () => {
+ const credentials = {
+ SPRITES_TOKEN: "unit-test-sprites",
+ MODAL_TOKEN_ID: "unit-test-modal-id",
+ MODAL_TOKEN_SECRET: "unit-test-modal-secret",
+ };
+ assert.deepEqual(
+ loadConfig({ ...credentials, SANDBOX_SCOPE_BACKENDS: '{"personal":"modal","channel":"sprites"}' })
+ .sandboxScopeDefaults,
+ { personal: "modal", channel: "sprites" },
+ );
+ for (const value of [
+ "[]",
+ "null",
+ '{"personal:someone":"modal"}',
+ '{"personal":"missing"}',
+ '{"unknown":"sprites"}',
+ '{"personal":""}',
+ ])
+ assert.throws(() => loadConfig({ ...credentials, SANDBOX_SCOPE_BACKENDS: value }));
+});
diff --git a/test/sandbox-migration-runner.test.ts b/test/sandbox-migration-runner.test.ts
index f529b2ffe..68c421b68 100644
--- a/test/sandbox-migration-runner.test.ts
+++ b/test/sandbox-migration-runner.test.ts
@@ -409,3 +409,23 @@ test("activation cannot pass a running migration before its final route and tear
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 a98ecc386..62ad8ca6a 100644
--- a/test/sandbox-resources.test.ts
+++ b/test/sandbox-resources.test.ts
@@ -818,3 +818,19 @@ test("failed background registration kills its process and releases the resource
await resources.retire("alice", record.id);
assert.equal((await resources.get(record.id)).cleanupPending, false);
});
+
+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"]);
+ await routes.put("personal:existing", { backend: "aws" });
+ const resources = createSandboxResources({
+ ...options,
+ 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");
+});
diff --git a/test/sandbox-routing.test.ts b/test/sandbox-routing.test.ts
index 03fe4385a..064ca7df6 100644
--- a/test/sandbox-routing.test.ts
+++ b/test/sandbox-routing.test.ts
@@ -287,3 +287,36 @@ test("computer status/restart on a scope routed to a backend without them is a t
(e: unknown) => e instanceof CapabilityUnsupportedError,
);
});
+
+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");
+ const router = createSandboxRouter({
+ backends: { modal, sprites, aws },
+ routes,
+ defaultBackend: "sprites",
+ scopeDefaults: { personal: "modal", channel: "sprites" },
+ });
+ 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");
+});
+
+test("missing scope provider refuses substitution", async () => {
+ const router = createSandboxRouter({
+ backends: { sprites: fakeBackend("sprites") },
+ routes: createMemoryMap<SandboxRoute>(),
+ defaultBackend: "sprites",
+ scopeDefaults: { personal: "modal" },
+ });
+ await assert.rejects(router.provision(layersFor("personal:new")), /unavailable: modal/);
+});
diff --git a/test/secret-schema-conformance.test.ts b/test/secret-schema-conformance.test.ts
index e1a0e361d..d3ba02bc6 100644
--- a/test/secret-schema-conformance.test.ts
+++ b/test/secret-schema-conformance.test.ts
@@ -29,6 +29,7 @@ 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",
@@ -38,11 +39,16 @@ test("runtime schema conditions reference env vars the CLI schema also condition
];
const cliConditionEnv = new Set<string>();
interface CliCondition {
+ kind?: string;
name?: string;
names?: string[];
conditions?: CliCondition[];
}
const collect = (when: CliCondition): void => {
+ if (when.kind === "sandbox-backend") {
+ cliConditionEnv.add("SANDBOX_BACKEND");
+ cliConditionEnv.add("SANDBOX_SCOPE_BACKENDS");
+ }
if (when.name) cliConditionEnv.add(when.name);
for (const name of when.names ?? []) cliConditionEnv.add(name);
for (const nested of when.conditions ?? []) collect(nested);