Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix: harden agent37 sandbox integration

Josh Francec56a736b4897
diff --git a/adrs/agent37-sandbox-backend.md b/adrs/agent37-sandbox-backend.md
index 131d35f21..94bb9f4ca 100644
--- a/adrs/agent37-sandbox-backend.md
+++ b/adrs/agent37-sandbox-backend.md
@@ -15,7 +15,7 @@ What the PR adds
What it does not do
- No idle reaping and no snapshot to the workspace. The instance stays running until destroy; the disk is the machine's own and survives stop and start.
-- No image plumbing. The default template, `agent37-qm-computer`, is built from your `sandbox-base` image and will be published on our side before this merges, so the tools qm expects are the tools it gets. Any other Agent37 template can be named with `AGENT37_TEMPLATE`.
+- No image plumbing. The default uses Agent37's `agent37-codex` system template. Any other Agent37 template can be named with `AGENT37_TEMPLATE`.
- No new CLI target. `qm init` still deploys the core to Docker, Fly or AWS; this only changes where the computers live.
Tests run against an in-process fake of our API, so CI needs no Agent37 account. We would rather this live upstream than in a fork, and we will keep it green as the sandbox contract moves.
diff --git a/cli/src/backends/aws.ts b/cli/src/backends/aws.ts
index 89bc69e60..82bb73596 100644
--- a/cli/src/backends/aws.ts
+++ b/cli/src/backends/aws.ts
@@ -252,6 +252,7 @@ export function serviceEnvironment(config: QmConfig, service: ServiceName): Reco
...(service === "core" ? securityScreenEnv(config) : {}),
};
if (service === "core") {
+ const sandboxBackend = config.env.core?.SANDBOX_BACKEND?.trim() || config.sandbox?.backend;
const stores = {
DEPLOY_PROVIDER: "aws",
AWS_DEPLOY_REGION: aws.region,
@@ -262,9 +263,9 @@ export function serviceEnvironment(config: QmConfig, service: ServiceName): Reco
S3_BUCKET: config.env.core?.S3_BUCKET?.trim() || awsObjectStoreBucket(config),
S3_REGION: aws.region,
};
- if (usesFlySandboxes(config)) {
+ if (sandboxBackend && sandboxBackend !== "aws") {
Object.assign(env, sandboxCoreEnv(config).env, {
- SANDBOX_BACKEND: config.env.core?.SANDBOX_BACKEND?.trim() || config.sandbox?.backend || "sprites",
+ SANDBOX_BACKEND: sandboxBackend,
...stores,
});
} else {
diff --git a/cli/src/config.ts b/cli/src/config.ts
index 769d6a506..9c5d930d1 100644
--- a/cli/src/config.ts
+++ b/cli/src/config.ts
@@ -45,7 +45,7 @@ export interface PluginEntry {
}
export interface SandboxConfig {
- backend?: "local" | "sprites" | "aws";
+ backend?: "local" | "sprites" | "aws" | "agent37";
app?: string;
image?: string;
baseImage?: string;
@@ -236,6 +236,10 @@ export function sandboxCoreEnv(
if (sb.image) env.LOCAL_SANDBOX_IMAGE = sb.image;
return { env, missingSecrets };
}
+ if (sb.backend === "agent37") {
+ env.SANDBOX_BACKEND = "agent37";
+ return { env, missingSecrets };
+ }
if (sb.app) {
if (!sb.image) throw new CliError(SANDBOX_PIN_PENDING, { clause: "config.v1" });
const violation = sandboxImagePinErrors(config)[0];
@@ -1335,9 +1339,14 @@ function validateSandbox(raw: unknown, path: string, target: Target): SandboxCon
};
const out: SandboxConfig = {};
if (o["backend"] !== undefined) {
- if (o["backend"] !== "local" && o["backend"] !== "sprites" && o["backend"] !== "aws") {
+ if (
+ o["backend"] !== "local" &&
+ o["backend"] !== "sprites" &&
+ o["backend"] !== "aws" &&
+ o["backend"] !== "agent37"
+ ) {
throw new CliError(
- `${path}: "sandbox.backend" must be "local" (Docker containers on the deployment host), "sprites" (Fly Sprites), or "aws" (Lambda MicroVM sandboxes)`,
+ `${path}: "sandbox.backend" must be "local" (Docker containers on the deployment host), "sprites" (Fly Sprites), "aws" (Lambda MicroVM sandboxes), or "agent37"`,
);
}
out.backend = o["backend"];
@@ -1395,6 +1404,14 @@ function validateSandbox(raw: unknown, path: string, target: Target): SandboxCon
);
}
}
+ if (out.backend === "agent37") {
+ const stray = (["app", "image", "baseImage", "env", "secretEnv"] as const).filter((key) => out[key] !== undefined);
+ if (stray.length) {
+ throw new CliError(
+ `${path}: "sandbox.backend": "agent37" ignores ${stray.map((key) => `"sandbox.${key}"`).join(", ")} — remove them`,
+ );
+ }
+ }
if (out.image && !out.app && out.backend !== "local") {
throw new CliError(`${path}: "sandbox.image" requires "sandbox.app" unless "sandbox.backend" is "local"`);
}
diff --git a/cli/src/providers.ts b/cli/src/providers.ts
index dc478dfc7..af7cd671f 100644
--- a/cli/src/providers.ts
+++ b/cli/src/providers.ts
@@ -5,7 +5,7 @@ export type Target = (typeof HOSTING_PROVIDER_IDS)[number];
export const isTarget = (value: unknown): value is Target =>
typeof value === "string" && (HOSTING_PROVIDER_IDS as readonly string[]).includes(value);
-export type SandboxBackendId = "local" | "sprites" | "aws";
+export type SandboxBackendId = "local" | "sprites" | "aws" | "agent37";
export interface SandboxBackendPolicy {
/** Sandbox backends this hosting target can run. */
@@ -16,9 +16,9 @@ export interface SandboxBackendPolicy {
/** Keyed by hosting target so adding a target forces a sandbox-backend decision. */
export const SANDBOX_BACKEND_POLICY: Record<Target, SandboxBackendPolicy> = {
- docker: { allowed: ["local", "sprites"], requireExplicit: false },
- fly: { allowed: ["sprites"], requireExplicit: false },
- aws: { allowed: ["sprites", "aws"], requireExplicit: true },
+ docker: { allowed: ["local", "sprites", "agent37"], requireExplicit: false },
+ fly: { allowed: ["sprites", "agent37"], requireExplicit: false },
+ aws: { allowed: ["sprites", "aws", "agent37"], requireExplicit: true },
};
export const targetsAllowingSandboxBackend = (backend: SandboxBackendId): Target[] =>
diff --git a/cli/src/secrets.ts b/cli/src/secrets.ts
index 0e019dce1..11ce00b56 100644
--- a/cli/src/secrets.ts
+++ b/cli/src/secrets.ts
@@ -159,7 +159,15 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
{
name: "AGENT37_API_KEY",
service: "core",
- required: { when: { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "agent37" } },
+ required: {
+ when: {
+ kind: "any",
+ conditions: [
+ { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "agent37" },
+ { kind: "env-equals", service: "core", name: "SANDBOX_SECONDARY_BACKEND", value: "agent37" },
+ ],
+ },
+ },
description: "Agent37 API key for the agent-computer substrate.",
generate: "mint a key in the Agent37 dashboard (https://agent37.com/dashboard/cloud/api-keys)",
},
@@ -451,8 +459,12 @@ function conditionMatches(config: QmConfig, condition: SecretCondition): boolean
if (condition.kind === "env-all-absent") {
return condition.names.every((name) => !config.env[condition.service]?.[name]?.trim());
}
+ const configuredSandboxBackend =
+ condition.service === "core" && condition.name === "SANDBOX_BACKEND" ? config.sandbox?.backend : undefined;
const value = (
- config.env[condition.service]?.[condition.name] ?? targetEnvDefault(config, condition.service, condition.name)
+ config.env[condition.service]?.[condition.name] ??
+ configuredSandboxBackend ??
+ targetEnvDefault(config, condition.service, condition.name)
)?.trim();
if (condition.kind === "env-absent") return !value;
if (condition.kind === "env-present") return Boolean(value);
diff --git a/cli/test/aws.test.ts b/cli/test/aws.test.ts
index 8fb0dde59..cdab4e818 100644
--- a/cli/test/aws.test.ts
+++ b/cli/test/aws.test.ts
@@ -4227,6 +4227,14 @@ test("env.core.SANDBOX_BACKEND adopts the deployment's substrate; the default is
env: { ...config.env, core: { ...config.env.core, SANDBOX_BACKEND: "sprites" } },
};
assert.equal(serviceEnvironment(adopted, "core").SANDBOX_BACKEND, "sprites");
+ const agent37: QmConfig = {
+ ...config,
+ sandbox: undefined,
+ env: { ...config.env, core: { ...config.env.core, SANDBOX_BACKEND: "agent37" } },
+ };
+ const agent37Env = serviceEnvironment(agent37, "core");
+ assert.equal(agent37Env.SANDBOX_BACKEND, "agent37");
+ assert.equal(agent37Env.AWS_SANDBOX_IMAGE, undefined);
});
test("env.core.S3_BUCKET adopts a pre-existing snapshot bucket; the derived object store remains the default", () => {
diff --git a/cli/test/config.test.ts b/cli/test/config.test.ts
index a670aec44..c5b00a621 100644
--- a/cli/test/config.test.ts
+++ b/cli/test/config.test.ts
@@ -860,11 +860,11 @@ test("sandbox shape errors: object, app non-empty string, env string-map, secret
{ sandbox: { secretEnv: ["1BAD"] }, rx: /not a valid env var name/ },
{
sandbox: { backend: "k8s", app: "acme-sandboxes" },
- rx: /"sandbox.backend" must be "local".*"sprites".*or "aws"/,
+ rx: /"sandbox.backend" must be "local".*"sprites".*"aws".*or "agent37"/,
},
{
sandbox: { backend: "fly", app: "acme-sandboxes" },
- rx: /"sandbox.backend" must be "local".*"sprites".*or "aws"/,
+ rx: /"sandbox.backend" must be "local".*"sprites".*"aws".*or "agent37"/,
},
{ sandbox: { backend: "sprites" }, rx: /"sandbox.backend": "sprites" requires "sandbox.app"/ },
{
@@ -900,6 +900,21 @@ test("local sandbox config is docker-only and rejects unused Fly settings", () =
});
});
+test("agent37 is a deployment backend on every target and rejects unused Fly settings", () => {
+ for (const target of ["docker", "fly"] as const) {
+ withConfig({ target, sandbox: { backend: "agent37" } }, ({ path }) => {
+ const { config } = loadConfigAt(path);
+ assert.deepEqual(sandboxCoreEnv(config), {
+ env: { SANDBOX_BACKEND: "agent37" },
+ missingSecrets: [],
+ });
+ });
+ }
+ withConfig({ sandbox: { backend: "agent37", app: "unused" } }, ({ path }) => {
+ assert.throws(() => loadConfigAt(path), /"sandbox.backend": "agent37" ignores "sandbox.app"/);
+ });
+});
+
test("aws target makes the sandbox substrate explicit: backend required with a sandbox block, sprites needs app, aws forbids fly-image settings", () => {
const aws = {
accountId: "123456789012",
@@ -920,6 +935,11 @@ test("aws target makes the sandbox substrate explicit: backend required with a s
withConfig({ target: "aws", aws, sandbox: { backend: "aws" } }, ({ path }) => {
assert.equal(loadConfigAt(path).config.sandbox?.backend, "aws");
});
+ withConfig({ target: "aws", aws, sandbox: { backend: "agent37" } }, ({ path }) => {
+ const { config } = loadConfigAt(path);
+ assert.equal(config.sandbox?.backend, "agent37");
+ assert.equal(sandboxCoreEnv(config).env.SANDBOX_BACKEND, "agent37");
+ });
withConfig({ target: "aws", aws, sandbox: { backend: "sprites", app: "acme-sandboxes" } }, ({ path }) => {
assert.equal(loadConfigAt(path).config.sandbox?.backend, "sprites");
});
diff --git a/cli/test/secrets.test.ts b/cli/test/secrets.test.ts
index 25db02b84..44a1c373a 100644
--- a/cli/test/secrets.test.ts
+++ b/cli/test/secrets.test.ts
@@ -192,6 +192,16 @@ test("the sprites token is a catalog secret when the sandbox backend is sprites"
);
});
+test("the Agent37 key is required for either sandbox route", () => {
+ for (const config of [
+ makeConfig({ env: { core: { SANDBOX_BACKEND: "agent37" } } }),
+ makeConfig({ env: { core: { SANDBOX_SECONDARY_BACKEND: "agent37" } } }),
+ makeConfig({ sandbox: { backend: "agent37" } }),
+ ]) {
+ assert.equal(secretByName(config, "AGENT37_API_KEY").required, true);
+ }
+});
+
test("naming a base model provider makes that provider's key a required deployment secret", () => {
for (const [provider, key] of [
["anthropic", "ANTHROPIC_API_KEY"],
diff --git a/src/sandbox/agent37-sandbox.ts b/src/sandbox/agent37-sandbox.ts
index 979cc7e8f..05f67829d 100644
--- a/src/sandbox/agent37-sandbox.ts
+++ b/src/sandbox/agent37-sandbox.ts
@@ -22,6 +22,7 @@ import {
import { DROPPED_PROXY_ENV, forceThroughProxyEnv, proxyExportPrefix } from "./sandbox-env.ts";
import { BLOB_TRANSFER_AUD, mintCapabilityToken } from "../auth/capability-token.ts";
import type { BlobTransferStore } from "../persistence/blob-transfer.ts";
+import { createNoopAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";
import { CAPABILITY_HEADER } from "../api/contract.ts";
import { killableScript, killScript } from "./exec-kill.ts";
import { visibleNotInstalled, visibleTools } from "./sandbox.ts";
@@ -41,6 +42,7 @@ const WORKSPACE_BASENAME = "workspace";
const RO_LAYERS_TAR = ".ro-layers.tar";
const RO_LAYERS_MANIFEST = ".ro-layers.manifest";
const INLINE_LIMIT = 128 * 1024;
+const MAX_EXEC_OUTPUT_BYTES = 16 * 1024 * 1024;
const READ_CHUNK = 256 * 1024;
const WRITE_CHUNK_B64 = 64 * 1024;
const MISSING_RC = 44;
@@ -52,7 +54,7 @@ const START_TIMEOUT_MS = 830_000;
const READY_TIMEOUT_MS = 300_000;
const READY_POLL_MS = 2_000;
const DEFAULT_AGENT37_BASE_URL = "https://api.agent37.com";
-const DEFAULT_TEMPLATE = "agent37-qm-computer";
+const DEFAULT_TEMPLATE = "agent37-codex";
const DEFAULT_CPUS = 2;
const DEFAULT_MEMORY_GB = 4;
const DEFAULT_DISK_GB = 8;
@@ -90,6 +92,7 @@ export interface Agent37SandboxOptions {
extraTools?: string[];
credentialPaths?: CredentialPathSpec[];
fetchImpl?: typeof fetch;
+ advisoryLock?: AdvisoryLock;
onError?: (e: { category: string; code: string; message: string; scopeLabel?: string }) => void;
}
@@ -105,6 +108,7 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37San
disk: opts.diskGb ?? DEFAULT_DISK_GB,
};
const defaultTimeoutSec = opts.defaultTimeoutSec ?? 600;
+ const advisoryLock = opts.advisoryLock ?? createNoopAdvisoryLock();
const workspaceDir = `${HOME_DIR}/${WORKSPACE_BASENAME}`;
const provisionQueue = createKeyedQueue<string>();
@@ -266,6 +270,9 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37San
const code = Number.parseInt(header[0]!, 10);
const outLen = Number.parseInt(header[1]!, 10);
const errLen = Number.parseInt(header[2]!, 10);
+ if (![code, outLen, errLen].every(Number.isSafeInteger) || outLen < 0 || errLen < 0) {
+ throw new Error(`agent37 exec ${name}: bad envelope sizes: ${header.join(" ")}`);
+ }
let outBuf: Buffer;
let errBuf: Buffer;
if (outLen <= INLINE_LIMIT && errLen <= INLINE_LIMIT) {
@@ -279,11 +286,17 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37San
);
}
} else {
- outBuf = await readSpooled(name, out, outLen);
- errBuf = await readSpooled(name, err, errLen);
- await postExec(name, `rm -f ${shq(out)} ${shq(err)} ${shq(rcf)}`, 60).catch(
- swallowAs("agent37-sandbox: spool cleanup", undefined),
- );
+ try {
+ if (outLen > MAX_EXEC_OUTPUT_BYTES - errLen) {
+ throw new Error(`agent37 exec ${name}: output exceeds ${MAX_EXEC_OUTPUT_BYTES} bytes`);
+ }
+ outBuf = await readSpooled(name, out, outLen);
+ errBuf = await readSpooled(name, err, errLen);
+ } finally {
+ await postExec(name, `rm -f ${shq(out)} ${shq(err)} ${shq(rcf)}`, 60).catch(
+ swallowAs("agent37-sandbox: spool cleanup", undefined),
+ );
+ }
}
return { stdout: outBuf.toString("utf8"), stderr: errBuf.toString("utf8"), code, timedOut: code === 124 };
}
@@ -352,23 +365,25 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37San
name: string,
onStatus?: (text: string) => void,
): Promise<{ coldStart: boolean }> {
- return provisionQueue(key, async () => {
- if (idByName.has(name)) return { coldStart: false };
- const existing = await findInstance(name);
- if (existing) {
- idByName.set(name, existing.id);
- if (existing.status !== "running") await ensureRunning(existing.id);
- return { coldStart: false };
- }
- try {
- onStatus?.("Creating the sandbox…");
- } catch (error) {
- void error;
- }
- const info = await createInstance(name);
- idByName.set(name, info.id);
- return { coldStart: true };
- });
+ return provisionQueue(key, () =>
+ advisoryLock.withLock(`agent37-provision:${key}`, async () => {
+ if (idByName.has(name)) return { coldStart: false };
+ const existing = await findInstance(name);
+ if (existing) {
+ idByName.set(name, existing.id);
+ if (existing.status !== "running") await ensureRunning(existing.id);
+ return { coldStart: false };
+ }
+ try {
+ onStatus?.("Creating the sandbox…");
+ } catch (error) {
+ void error;
+ }
+ const info = await createInstance(name);
+ idByName.set(name, info.id);
+ return { coldStart: true };
+ }),
+ );
}
async function ensureScratch(key: string): Promise<{ name: string; coldStart: boolean }> {
@@ -540,10 +555,10 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37San
const fireKill = () => {
execRaw(handle.id, killScript(killUid), 15).catch(swallowAs("agent37-sandbox: kill in-flight exec", undefined));
};
- if (signal.aborted) fireKill();
const onAbort = () => fireKill();
signal.addEventListener("abort", onAbort, { once: true });
try {
+ signal.throwIfAborted();
return await execRaw(handle.id, killableScript(script, killUid), timeoutSec);
} finally {
signal.removeEventListener("abort", onAbort);
diff --git a/src/sandbox/aws-sandbox.ts b/src/sandbox/aws-sandbox.ts
index 55a1270a1..be84a809a 100644
--- a/src/sandbox/aws-sandbox.ts
+++ b/src/sandbox/aws-sandbox.ts
@@ -410,6 +410,7 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOpti
async run(handle, command, execOpts?: ExecOptions): Promise<ExecResult> {
const timeoutSec = execOpts?.timeoutMs ? Math.ceil(execOpts.timeoutMs / 1000) : defaultTimeoutSec;
+ execOpts?.signal?.throwIfAborted();
await ensureRunning(handle.id);
const exports = Object.entries(handle.env ?? {})
.map(([k, v]) => `export ${k}=${shq(v)}`)
diff --git a/src/sandbox/local-sandbox.ts b/src/sandbox/local-sandbox.ts
index 988e25e36..a4896116a 100644
--- a/src/sandbox/local-sandbox.ts
+++ b/src/sandbox/local-sandbox.ts
@@ -440,10 +440,10 @@ export function createLocalSandbox(workspace: WorkspaceStore, opts: LocalSandbox
const fireKill = () => {
execRaw(handle.id, killScript(killUid), 15).catch(swallowAs("local-sandbox: kill in-flight exec", undefined));
};
- if (signal.aborted) fireKill();
const onAbort = () => fireKill();
signal.addEventListener("abort", onAbort, { once: true });
try {
+ signal.throwIfAborted();
return await execRaw(handle.id, killableScript(script, killUid), timeoutSec, signal);
} finally {
signal.removeEventListener("abort", onAbort);
diff --git a/src/sandbox/porter-sandbox.ts b/src/sandbox/porter-sandbox.ts
index b8a3dc3f3..d0bc2d97a 100644
--- a/src/sandbox/porter-sandbox.ts
+++ b/src/sandbox/porter-sandbox.ts
@@ -393,10 +393,10 @@ export function createPorterSandbox(workspace: WorkspaceStore, opts: PorterSandb
const fireKill = () => {
execRaw(handle.id, killScript(killUid), 15).catch(swallowAs("porter-sandbox: kill in-flight exec", undefined));
};
- if (signal.aborted) fireKill();
const onAbort = () => fireKill();
signal.addEventListener("abort", onAbort, { once: true });
try {
+ signal.throwIfAborted();
return await execRaw(handle.id, killableScript(script, killUid), timeoutSec);
} finally {
signal.removeEventListener("abort", onAbort);
diff --git a/src/sandbox/smolmachines-sandbox.ts b/src/sandbox/smolmachines-sandbox.ts
index 78f426cd2..3bde1abfe 100644
--- a/src/sandbox/smolmachines-sandbox.ts
+++ b/src/sandbox/smolmachines-sandbox.ts
@@ -527,10 +527,10 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
swallowAs("smolmachines-sandbox: kill in-flight exec", undefined),
);
};
- if (signal.aborted) fireKill();
const onAbort = () => fireKill();
signal.addEventListener("abort", onAbort, { once: true });
try {
+ signal.throwIfAborted();
return await execRaw(handle.id, killableScript(script, killUid), timeoutSec);
} finally {
signal.removeEventListener("abort", onAbort);
diff --git a/src/sandbox/sprites-sandbox.ts b/src/sandbox/sprites-sandbox.ts
index c9fd517be..1d778eb44 100644
--- a/src/sandbox/sprites-sandbox.ts
+++ b/src/sandbox/sprites-sandbox.ts
@@ -447,10 +447,10 @@ export function createSpritesSandbox(workspace: WorkspaceStore, opts: SpritesSan
const fireKill = () => {
execRaw(handle.id, killScript(killUid), 15).catch(swallowAs("sprites-sandbox: kill in-flight exec", undefined));
};
- if (signal.aborted) fireKill();
const onAbort = () => fireKill();
signal.addEventListener("abort", onAbort, { once: true });
try {
+ signal.throwIfAborted();
return await execRaw(handle.id, killableScript(script, killUid), timeoutSec);
} finally {
signal.removeEventListener("abort", onAbort);
diff --git a/src/wiring.ts b/src/wiring.ts
index 06d25343d..128ccf8db 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -662,6 +662,7 @@ export function buildApp(
const buildAgent37 = (): Sandbox =>
createAgent37Sandbox(workspace, {
...config.agent37Sandbox,
+ advisoryLock,
blobTransfer,
extraTools: deploymentLayer.advertisedTools,
credentialPaths: deploymentLayer.credentialPaths,
diff --git a/test/agent37-sandbox.test.ts b/test/agent37-sandbox.test.ts
index 0366cd85f..b6a9afe4f 100644
--- a/test/agent37-sandbox.test.ts
+++ b/test/agent37-sandbox.test.ts
@@ -9,6 +9,7 @@ import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";
import { supportsProcessSessions } from "../src/sandbox/sandbox.ts";
import { scopeId } from "../src/types.ts";
import { mintCapabilityToken, EGRESS_PROXY_AUD } from "../src/auth/capability-token.ts";
+import { createMemoryAdvisoryLock } from "../src/persistence/advisory-lock.ts";
import { installFakeAgent37, FAKE_AGENT37_API_KEY, type FakeAgent37 } from "./support/fake-agent37.ts";
import type { Sandbox } from "../src/sandbox/sandbox.ts";
@@ -123,6 +124,16 @@ test("instance is reused across provisions and warm start is reported", async ()
assert.equal(fake.names().filter((n) => n === a.id).length, 1);
});
+test("a shared advisory lock prevents duplicate instances across core replicas", async () => {
+ const advisoryLock = createMemoryAdvisoryLock();
+ const [a, b] = await Promise.all([
+ make({ advisoryLock }).provision(layers),
+ make({ advisoryLock }).provision(layers),
+ ]);
+ assert.equal(a.id, b.id);
+ assert.equal(fake.names().filter((name) => name === a.id).length, 1);
+});
+
test("exec on a sleeping instance wakes it and retries", async () => {
const h = await sandbox.provision(layers);
await sandbox.writeFile(h, "keep.txt", "still here\n");
@@ -195,6 +206,25 @@ test("large command output survives the API's output cap exactly", async () => {
assert.equal(r.stdout, "x".repeat(900 * 1024));
});
+test("command output is bounded and spool files are removed on rejection", async () => {
+ const h = await sandbox.provision(layers);
+ await assert.rejects(
+ sandbox.run(h, `python3 -c "print('x' * (${17 * 1024 * 1024}), end='')"`),
+ /output exceeds 16777216 bytes/,
+ );
+ const leftovers = await sandbox.run(h, "ls /home/node/.qm-exec-* 2>/dev/null | wc -l");
+ assert.equal(leftovers.stdout.trim(), "2", "only the inspection command's stdout/stderr spools exist");
+});
+
+test("an already-aborted command is never executed", async () => {
+ const h = await sandbox.provision(layers);
+ const before = fake.execScripts().length;
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(sandbox.run(h, "touch should-not-exist", { signal: controller.signal }), /aborted/i);
+ assert.equal(fake.execScripts().length, before);
+});
+
test("an instance already named after the scope is adopted instead of duplicated", async () => {
await fake.fetchImpl("https://api.agent37.com/v1/instances", {
method: "POST",
@@ -220,7 +250,7 @@ test("timeouts beyond the API's sync exec ceiling run detached and poll to compl
test("create requests the template, the default shape and no auto sleep", async () => {
const h = await sandbox.provision(layers);
const created = fake.instance(h.id);
- assert.equal(created?.template, "agent37-qm-computer");
+ assert.equal(created?.template, "agent37-codex");
assert.equal(created?.autoSleep, false);
assert.deepEqual(created?.resources, { cpu: 2, memory: 4, disk: 8 });
});
diff --git a/test/aws-sandbox.test.ts b/test/aws-sandbox.test.ts
index f3646cd6e..fe2908cf3 100644
--- a/test/aws-sandbox.test.ts
+++ b/test/aws-sandbox.test.ts
@@ -45,6 +45,19 @@ test("first provision launches a body (cold) and run() execs over the daemon", a
assert.equal(r.stdout.trim(), "hello");
});
+test("an already-aborted command neither resumes the body nor executes", async () => {
+ const fake = installFakeMicrovm();
+ const sb = makeSandbox(fake);
+ const h = await sb.provision(rw(scopeId("personal", "U-aborted")));
+ await sb.teardown(h);
+ const commandCount = fake.commands.length;
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(sb.run(h, "echo should-not-run", { signal: controller.signal }), /aborted/i);
+ assert.equal(fake.bodies.get(h.id)!.state, "SUSPENDED");
+ assert.equal(fake.commands.length, commandCount);
+});
+
test("declared credential paths are symlinked outside the snapshotted home", async () => {
const fake = installFakeMicrovm();
const sb = makeSandbox(fake, {
diff --git a/test/exec-kill.test.ts b/test/exec-kill.test.ts
index 7f9b4fbe5..e2f866c05 100644
--- a/test/exec-kill.test.ts
+++ b/test/exec-kill.test.ts
@@ -56,14 +56,13 @@ test("run() with a signal wraps the command in the killable process group; witho
assert.ok(ff.execScripts()[mark]!.includes("exec setsid sh -c"), "a signal ⇒ the command runs killable");
});
-test("run(): an already-aborted signal fires a separate SIGKILL exec at the recorded group", async () => {
+test("run(): an already-aborted signal never starts the command", async () => {
const sb = sprites();
const h = await sb.provision(rw);
+ const before = ff.execScripts().length;
const ctrl = new AbortController();
ctrl.abort();
- await sb.run(h, "true", { signal: ctrl.signal });
- await new Promise((r) => setTimeout(r, 50));
- const killCalls = ff.execScripts().filter((script) => script.includes("kill -KILL"));
- assert.ok(killCalls.length >= 1, "an aborted signal fires a separate kill-the-group exec");
+ await assert.rejects(sb.run(h, "true", { signal: ctrl.signal }), /aborted/i);
+ assert.equal(ff.execScripts().length, before);
});
diff --git a/test/support/fake-agent37.ts b/test/support/fake-agent37.ts
index 9acdafccb..df4e47ebb 100644
--- a/test/support/fake-agent37.ts
+++ b/test/support/fake-agent37.ts
@@ -112,7 +112,7 @@ export function installFakeAgent37(): FakeAgent37 {
const info = (m: FakeInstance) => ({
id: m.id,
status: m.status,
- template: m.template ?? "agent37-qm-computer",
+ template: m.template ?? "agent37-codex",
resources: m.resources ?? {},
name: m.name,
auto_sleep: m.autoSleep === true,