Multiplayer agent harness for work.
fix: keep agent37 computers awake and harden start against transient states
Vishnu6f8dd2a3e6f3
diff --git a/adrs/agent37-sandbox-backend.md b/adrs/agent37-sandbox-backend.mdindex c46b84720..131d35f21 100644--- a/adrs/agent37-sandbox-backend.md+++ b/adrs/agent37-sandbox-backend.md@@ -2,20 +2,20 @@Vishnu from Agent37 here. You asked whether we could host qm. The honest answer is that the part of qm that wants hosting is the agent computer, so this is a fifth sandbox backend, next to Sprites, smolmachines, Porter and AWS.-Agent37 rents isolated Linux machines over a small REST API: create, exec, start, stop, delete. Each one keeps its disk, goes to sleep when idle, and comes back when the next command arrives. That is the lifecycle your Sprites and smolmachines backends already assume, so the mapping is direct: one Agent37 instance per qm scope, created on first use, named after the scope so an operator can recognise it in their Agent37 dashboard, deleted when qm tears the scope down.+Agent37 rents isolated Linux machines over a small REST API: create, exec, start, stop, delete. Each one keeps its disk across stop and start, which is the lifecycle your Sprites and smolmachines backends already assume, so the mapping is direct: one Agent37 instance per qm scope, created on first use, named after the scope so an operator can recognise it in their Agent37 dashboard, deleted when qm tears the scope down.What the PR adds- `SANDBOX_BACKEND=agent37` with `AGENT37_API_KEY`. Optional knobs: `AGENT37_API_BASE_URL`, `AGENT37_NAME_PREFIX`, `AGENT37_TEMPLATE`, `AGENT37_CPUS`, `AGENT37_MEMORY_GB`, `AGENT37_DISK_GB`, `AGENT37_EGRESS_PROXY_URL`, and the shared `SANDBOX_TIMEOUT_SEC`.- `src/sandbox/agent37-sandbox.ts`, modeled on the smolmachines backend. Provision creates the instance and waits for it to run. Run is our exec endpoint. Teardown with destroy deletes the instance. Files move over the same exec endpoint in base64 chunks, the way the Porter backend does it, because our API has no separate file transfer. Process sessions, home backup, ro layers and blob staging come from the shared exec helpers unchanged.- Exec on our side returns within 280 seconds and caps each stream at 512 KiB. Longer commands run detached and are polled; larger output is spooled to disk and read back in chunks, so the agent never sees a truncated result.-- A command sent to a sleeping instance starts it first, then runs. That is a retry inside the backend, not a heartbeat; the provider decides when a machine sleeps.+- Auto sleep is off. Agent37 counts only traffic through the instance's routed port as activity, and qm drives the machine through exec alone, so an idle timer would freeze it mid-command. A command sent to a stopped or sleeping instance (an operator stop, a past-due park) starts it first, then runs, and retries while a checkpoint is still in flight. We are making exec count as activity on our side; once that ships, sleeping when idle is a one-line change here.- Profile: `writablePersistence: "resident_disk"`, `processSessions: true`, `egressEnforcement: "none"`. Our sandboxes reach the public internet and nothing private, but there is no per-domain allowlist, so the backend declares none rather than pretend.What it does not do-- No idle reaping and no snapshot to the workspace. The disk is the machine's own and survives sleep, stop and start.-- No image plumbing. The default template, `agent37-qm-computer`, is built from your `sandbox-base` image and published on our side, so the tools qm expects are the tools it gets. A different Agent37 template can be named with `AGENT37_TEMPLATE`.-- No new CLI target. `qm init` still deploys the core to Fly, AWS or Porter; this only changes where the computers live.+- 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 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/src/sandbox/agent37-sandbox.ts b/src/sandbox/agent37-sandbox.tsindex 7673b2d2e..979cc7e8f 100644--- a/src/sandbox/agent37-sandbox.ts+++ b/src/sandbox/agent37-sandbox.ts@@ -48,7 +48,8 @@ const EXEC_SYNC_MAX_SEC = 240;const EXEC_POLL_MS = 2_000;const EXIT_GRACE_MS = 60_000;const CREATE_TIMEOUT_MS = 330_000;-const READY_TIMEOUT_MS = 180_000;+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";@@ -56,7 +57,8 @@ const DEFAULT_CPUS = 2;const DEFAULT_MEMORY_GB = 4;const DEFAULT_DISK_GB = 8;const STARTABLE_STATES = new Set(["stopped", "sleeping"]);-const DEAD_STATES = new Set(["failed", "deleting", "deleted"]);+const GONE_STATES = new Set(["deleting", "deleted"]);+const DEAD_STATES = new Set(["failed", ...GONE_STATES]);interface InstanceInfo {id: string;@@ -133,10 +135,10 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37Sanasync function findInstance(name: string): Promise<InstanceInfo | null> {const { data } = await apiJson<{ data: InstanceInfo[] }>("GET", "/v1/instances");- return data.find((i) => i.name === name && !DEAD_STATES.has(i.status)) ?? null;+ return data.find((i) => i.name === name && !GONE_STATES.has(i.status)) ?? null;}- async function awaitRunning(id: string): Promise<void> {+ async function ensureRunning(id: string): Promise<void> {const deadline = Date.now() + READY_TIMEOUT_MS;for (;;) {const info = await apiJson<InstanceInfo>("GET", `/v1/instances/${encodeURIComponent(id)}`);@@ -144,30 +146,25 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37Sanif (DEAD_STATES.has(info.status)) throw new Error(`agent37 instance ${id}: ${info.status}`);if (Date.now() > deadline)throw new Error(`agent37 instance ${id}: not running after ${READY_TIMEOUT_MS}ms (status=${info.status})`);- await sleep(READY_POLL_MS);- }- }-- async function ensureRunning(id: string): Promise<void> {- const info = await apiJson<InstanceInfo>("GET", `/v1/instances/${encodeURIComponent(id)}`);- if (info.status === "running") return;- if (STARTABLE_STATES.has(info.status)) {- const res = await api("POST", `/v1/instances/${encodeURIComponent(id)}/start`, undefined, 120_000);- if (!res.ok && res.status !== 400) {- throw new Error(`agent37 start ${id}: http ${res.status} ${(await res.text()).slice(0, 200)}`);+ if (STARTABLE_STATES.has(info.status)) {+ const res = await api("POST", `/v1/instances/${encodeURIComponent(id)}/start`, undefined, START_TIMEOUT_MS);+ if (res.ok) continue;+ if (res.status !== 400 && res.status !== 409) {+ throw new Error(`agent37 start ${id}: http ${res.status} ${(await res.text()).slice(0, 200)}`);+ }}+ await sleep(READY_POLL_MS);}- await awaitRunning(id);}async function createInstance(name: string): Promise<InstanceInfo> {const info = await apiJson<InstanceInfo>("POST","/v1/instances",- { template, name, resources, auto_sleep: true },+ { template, name, resources, auto_sleep: false },CREATE_TIMEOUT_MS,);- await awaitRunning(info.id);+ await ensureRunning(info.id);return info;}@@ -237,11 +234,11 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37Sanif (timeoutSec <= EXEC_SYNC_MAX_SEC) {r = await postExec(name,- `timeout ${timeoutSec} sh -c ${shq(script)} > ${out} 2> ${err}; __rc=$?; ${envelope}`,+ `timeout -k 5 ${timeoutSec} sh -c ${shq(script)} > ${out} 2> ${err}; __rc=$?; ${envelope}`,timeoutSec,);} else {- const body = `timeout ${timeoutSec} sh -c ${shq(script)} > ${out} 2> ${err}; echo $? > ${rcf}`;+ const body = `timeout -k 5 ${timeoutSec} sh -c ${shq(script)} > ${out} 2> ${err}; echo $? > ${rcf}`;const start = await postExec(name, `nohup sh -c ${shq(body)} >/dev/null 2>&1 & echo launched`, 30);if (start.exit_code !== 0 || !/launched/.test(start.stdout)) {throw new Error(`agent37 exec ${name}: background launch failed (rc=${start.exit_code})`);@@ -395,7 +392,7 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37SanprocessSessions: true,egressEnforcement: "none",spec: {- os: "Debian 12, Agent37 sandbox (sleeps when idle; the whole disk persists)",+ os: "Debian 12, Agent37 sandbox (the whole disk persists)",runtimes: ["Node 24", "Python 3"],get tools() {return visibleTools(["git", "curl", "jq", "tar", "python3", ...(opts.extraTools ?? [])]);diff --git a/test/agent37-sandbox.test.ts b/test/agent37-sandbox.test.tsindex 549901ee9..0366cd85f 100644--- a/test/agent37-sandbox.test.ts+++ b/test/agent37-sandbox.test.ts@@ -131,7 +131,44 @@ test("exec on a sleeping instance wakes it and retries", async () => {assert.equal(r.code, 0);assert.equal(r.stdout, "still here\n");assert.equal(fake.instance(h.id)?.status, "running");- assert.ok(fake.calls.some((c) => c.method === "POST" && /\/start$/.test(c.path)));+ assert.ok(fake.calls.some((c) => c.method === "POST" && c.path.endsWith("/start")));+});++test("exec during the sleep checkpoint retries start until the freeze clears", async () => {+ const h = await sandbox.provision(layers);+ fake.sleep(h.id, { freezing: 2 });+ const r = await sandbox.run(h, "echo woke");+ assert.equal(r.stdout.trim(), "woke");+ assert.equal(fake.calls.filter((c) => c.method === "POST" && c.path.endsWith("/start")).length, 3);+});++test("exec on a stopping instance waits for it to stop, then starts it", async () => {+ const h = await sandbox.provision(layers);+ await sandbox.writeFile(h, "keep.txt", "still here\n");+ fake.stop(h.id);+ const r = await sandbox.run(h, "cat keep.txt");+ assert.equal(r.code, 0);+ assert.equal(r.stdout, "still here\n");+ assert.equal(fake.instance(h.id)?.status, "running");+});++test("a failed instance is surfaced, not replaced, and destroy deletes it", async () => {+ const h = await sandbox.provision(layers);+ fake.fail(h.id);+ const fresh = make();+ await assert.rejects(fresh.provision(layers), /failed/);+ assert.equal(fake.names().filter((n) => n === h.id).length, 1);+ await fresh.teardown(h, { destroy: true });+ assert.equal(fake.instance(h.id), null);+});++test("every timed exec carries a kill-after so a TERM-ignoring command cannot outlive the API's ceiling", async () => {+ const h = await sandbox.provision(layers);+ await sandbox.run(h, "true", { timeoutMs: 60_000 });+ await sandbox.run(h, "true", { timeoutMs: 400_000 });+ const timed = fake.execScripts().filter((s) => /\btimeout /.test(s));+ assert.ok(timed.length >= 2);+ assert.ok(timed.every((s) => /\btimeout -k 5 \d+ /.test(s)));});test("scratch instances are created on demand and deleted at release", async () => {@@ -180,11 +217,11 @@ test("timeouts beyond the API's sync exec ceiling run detached and poll to complassert.equal(leftovers.stdout.trim(), "0");});-test("create requests the template, the default shape and auto sleep", async () => {+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?.autoSleep, true);+ assert.equal(created?.autoSleep, false);assert.deepEqual(created?.resources, { cpu: 2, memory: 4, disk: 8 });});diff --git a/test/support/fake-agent37.ts b/test/support/fake-agent37.tsindex 5f977598e..9acdafccb 100644--- a/test/support/fake-agent37.ts+++ b/test/support/fake-agent37.ts@@ -16,6 +16,7 @@ interface FakeInstance {template?: string;autoSleep?: boolean;resources?: Record<string, number>;+ freezing?: number;home: string;}@@ -31,7 +32,9 @@ export interface FakeAgent37 {calls: Agent37Call[];names(): string[];instance(name: string): FakeInstanceView | null;- sleep(name: string): void;+ sleep(name: string, opts?: { freezing?: number }): void;+ stop(name: string): void;+ fail(name: string): void;execScripts(): string[];cleanup(): void;}@@ -81,7 +84,7 @@ export function installFakeAgent37(): FakeAgent37 {return (`export HOME=${JSON.stringify(m.home)}; ` +script- .replace(/\btimeout \d+ /g, "")+ .replace(/\btimeout (?:-k \d+ )?\d+ /g, "").replace(/\/home\/node/g, m.home).replace(remapPath, (mm) => (mm.startsWith(m.home) ? mm : `${m.home}/tmp/`)));@@ -150,6 +153,10 @@ export function installFakeAgent37(): FakeAgent37 {}if (sub[2] === "start") {if (m.status === "running") return Response.json({ id: m.id, status: "running" });+ if (m.freezing) {+ m.freezing--;+ return error(409, "try_again", "A sleep checkpoint is in flight. Retry in a few seconds.");+ }if (m.status !== "stopped" && m.status !== "sleeping") {return error(400, "invalid_request", "Only stopped or sleeping instances can be started.");}@@ -157,10 +164,14 @@ export function installFakeAgent37(): FakeAgent37 {return Response.json({ id: m.id, status: m.status });}if (sub[2] === "stop") {- m.status = "stopped";- return Response.json({ id: m.id, status: "stopped" });+ m.status = "stopping";+ return Response.json({ id: m.id, status: "stopping" });+ }+ if (method === "GET") {+ const body = info(settle(m));+ if (m.status === "stopping") m.status = "stopped";+ return Response.json(body);}- if (method === "GET") return Response.json(info(settle(m)));if (method === "DELETE") {rmSync(m.home, { recursive: true, force: true });m.status = "deleted";@@ -185,9 +196,20 @@ export function installFakeAgent37(): FakeAgent37 {}: null;},- sleep: (name) => {+ sleep: (name, opts) => {+ const m = byName(name);+ if (m) {+ m.status = "sleeping";+ m.freezing = opts?.freezing ?? 0;+ }+ },+ stop: (name) => {+ const m = byName(name);+ if (m) m.status = "stopping";+ },+ fail: (name) => {const m = byName(name);- if (m) m.status = "sleeping";+ if (m) m.status = "failed";},execScripts: () => [...execScripts],cleanup: () => rmSync(root, { recursive: true, force: true }),