Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Align the Smolmachines backend with its lifecycle and exec docs (#1422)

Regan Bell5eaaf8ab3a09
diff --git a/docs/sandbox-preservation.md b/docs/sandbox-preservation.md
index f018ad2ab..167667bc8 100644
--- a/docs/sandbox-preservation.md
+++ b/docs/sandbox-preservation.md
@@ -15,4 +15,6 @@ When enabled, Modal uses native directory checkpoints of `/root`, mounted into a
E2B creates persistent machines with an explicit pause-on-timeout lifecycle and pauses them at teardown unless `keepWarm` retains running background work. The provider timeout still applies; `keepWarm` does not extend that timeout. Routine native pause does not create a second tar backup. Provider pause retains disk and normally memory; provider fallback may retain disk only, so reconnectable processes must not depend on RAM surviving. Status can inspect a paused machine without waking it. Pause failures are recorded and returned, with the running machine retained for retry. A lost native machine requires explicit recovery rather than an automatic blank replacement. Existing E2B machines whose lifecycle does not confirm pause-on-timeout retain legacy portable checkpointing.
-Explicit home export/import and `persistHomeSnapshot` continue to use the portable tar format for cross-provider moves and chosen recovery. Configure `MODAL_SNAPSHOT_S3_BUCKET` or `E2B_SNAPSHOT_S3_BUCKET` to retain those portable copies durably. They are not silently selected instead of a failed newer provider checkpoint.
+Smolmachines machines keep their disk across stop and start, and an idle machine stops after `SMOLMACHINES_AUTOSTOP_SEC` seconds without activity when that knob is set (the provider sweeps every 15 seconds; an in-flight exec keeps the machine alive). The provider documents that stopping is not a backup and that the cloud API has no machine snapshot; export to a `.smolmachine` artifact is the only native capture and it is a whole-disk registry artifact, so core keeps portable home tars instead. Every non-scratch teardown snapshots the home to `SMOLMACHINES_SNAPSHOT_S3_BUCKET` when the home changed, throttled by `SMOLMACHINES_SNAPSHOT_INTERVAL_SEC`; a replacement machine for a scope hydrates from that tar and a failed hydration deletes the incomplete replacement instead of adopting it. Initialization is marked pending in the durable sandbox record before create, so a lost create response or core restart cannot make the next core skip restoration. Provisioning, capture, and destruction share a lifecycle lock across cores; initialization is only marked complete after hydration succeeds. Status reports `recovery.strategy: "workspace_snapshot"` with the last capture time and error. Without the bucket the backend offers no `persistHomeSnapshot` and reports no recovery. Scratch machines are created ephemeral with a 24-hour `ttlSeconds` so a core crash cannot leave them running.
+
+Explicit home export/import and `persistHomeSnapshot` continue to use the portable tar format for cross-provider moves and chosen recovery. Configure `MODAL_SNAPSHOT_S3_BUCKET`, `E2B_SNAPSHOT_S3_BUCKET` or `SMOLMACHINES_SNAPSHOT_S3_BUCKET` to retain those portable copies durably. They are not silently selected instead of a failed newer provider checkpoint.
diff --git a/src/config.ts b/src/config.ts
index 35778a914..cd864abfb 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -465,7 +465,10 @@ interface SmolmachinesSandboxEnv {
cpus?: number;
memoryMb?: number;
diskGb?: number;
+ autoStopSec?: number;
egressProxyUrl?: string;
+ snapshotS3Bucket?: string;
+ snapshotIntervalSec?: number;
defaultTimeoutSec?: number;
}
@@ -484,7 +487,19 @@ function smolmachinesSandboxEnv(env: NodeJS.ProcessEnv): SmolmachinesSandboxEnv
...(numEnvStrict("SMOLMACHINES_DISK_GB", env.SMOLMACHINES_DISK_GB) !== undefined
? { diskGb: numEnvStrict("SMOLMACHINES_DISK_GB", env.SMOLMACHINES_DISK_GB) }
: {}),
+ ...(numEnvStrict("SMOLMACHINES_AUTOSTOP_SEC", env.SMOLMACHINES_AUTOSTOP_SEC) !== undefined
+ ? { autoStopSec: numEnvStrict("SMOLMACHINES_AUTOSTOP_SEC", env.SMOLMACHINES_AUTOSTOP_SEC) }
+ : {}),
...(env.SMOLMACHINES_EGRESS_PROXY_URL ? { egressProxyUrl: env.SMOLMACHINES_EGRESS_PROXY_URL } : {}),
+ ...(env.SMOLMACHINES_SNAPSHOT_S3_BUCKET ? { snapshotS3Bucket: env.SMOLMACHINES_SNAPSHOT_S3_BUCKET } : {}),
+ ...(numEnvStrict("SMOLMACHINES_SNAPSHOT_INTERVAL_SEC", env.SMOLMACHINES_SNAPSHOT_INTERVAL_SEC) !== undefined
+ ? {
+ snapshotIntervalSec: numEnvStrict(
+ "SMOLMACHINES_SNAPSHOT_INTERVAL_SEC",
+ env.SMOLMACHINES_SNAPSHOT_INTERVAL_SEC,
+ ),
+ }
+ : {}),
...(numEnvStrict("SANDBOX_TIMEOUT_SEC", env.SANDBOX_TIMEOUT_SEC) !== undefined
? { defaultTimeoutSec: numEnvStrict("SANDBOX_TIMEOUT_SEC", env.SANDBOX_TIMEOUT_SEC) }
: {}),
@@ -1145,6 +1160,11 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
"[config] modal sandbox backend enabled without MODAL_SNAPSHOT_S3_BUCKET — native home checkpoints have limited retention; portable recovery snapshots are memory-only. Set MODAL_SNAPSHOT_S3_BUCKET for durable portable recovery and configure DATABASE_URL for durable checkpoint references.",
);
}
+ if (env.SMOLMACHINES_TOKEN && !env.SMOLMACHINES_SNAPSHOT_S3_BUCKET) {
+ console.warn(
+ "[config] smolmachines sandbox backend enabled without SMOLMACHINES_SNAPSHOT_S3_BUCKET — stopping a machine is not a backup; set SMOLMACHINES_SNAPSHOT_S3_BUCKET for durable home recovery snapshots.",
+ );
+ }
if (env.NODE_ENV === "production" && harnessEnvStrict(env.HARNESS) === "mock") {
console.warn(
`[config] HARNESS is ${env.HARNESS?.trim() ? '"mock"' : "unset, which means mock"} in production — this deployment answers every message with canned text and calls no model provider. Set HARNESS=pi to run real agent turns.`,
@@ -1155,6 +1175,11 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
"[config] SANDBOX_BACKEND=sprites without SPRITES_EGRESS_PROXY_URL — sandboxes run with NO egress enforcement (fail-open); set SPRITES_EGRESS_PROXY_URL to the public egress proxy to force sandbox traffic through it.",
);
}
+ if (env.SANDBOX_BACKEND === "smolmachines" && !env.SMOLMACHINES_EGRESS_PROXY_URL) {
+ console.warn(
+ "[config] SANDBOX_BACKEND=smolmachines without SMOLMACHINES_EGRESS_PROXY_URL — machines are created with open outbound networking and NO egress enforcement (fail-open); set SMOLMACHINES_EGRESS_PROXY_URL to allow-list only the egress proxy.",
+ );
+ }
const dataDir = resolve(env.DATA_DIR ?? "./data");
const porterSandboxSelected = env.SANDBOX_BACKEND === "porter";
if (porterSandboxSelected && !env.PORTER_SANDBOX_EGRESS_PROXY_URL) {
diff --git a/src/sandbox/smolmachines-sandbox.ts b/src/sandbox/smolmachines-sandbox.ts
index 0b095b98e..c95af4ef6 100644
--- a/src/sandbox/smolmachines-sandbox.ts
+++ b/src/sandbox/smolmachines-sandbox.ts
@@ -1,7 +1,10 @@
import { randomUUID } from "node:crypto";
import type { WorkspaceStore } from "../workspace/workspace-store.ts";
+import { createMemoryAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";
+import type { DurableMap } from "../persistence/durable-map.ts";
+import { createMemoryMap } from "../persistence/durable-map.ts";
import { fetchWithRetry, sleep } from "../util/async.ts";
-import { httpFailure, swallowAs } from "../util/errors.ts";
+import { httpFailure, errMessage, swallowAs } from "../util/errors.ts";
import { shq } from "../util/shell.ts";
import { createExecProcessSessions, type ExecProcessIo } from "./exec-process-session.ts";
import {
@@ -14,35 +17,55 @@ import { ephemeralCredLinkPaths, type CredentialPathSpec } from "../credentials/
import { visibleNotInstalled, visibleTools } from "./sandbox.ts";
import { createExecSandboxBase, sandboxScopeName } from "./exec-sandbox-base.ts";
import { createLayerToolInstaller } from "./layer-tool-install.ts";
+import { createHomeSnapshotOps, HOME_SNAPSHOT_PRUNE, snapshotDue, type HomeSnapshotStore } from "./home-snapshot.ts";
import type { LayerInstallFile } from "../deployment/load-layer.ts";
-import type { AgentComputerProfile, ExecResult, Sandbox } from "./sandbox.ts";
+import type { AgentComputerProfile, ComputerStatus, ExecResult, Sandbox, TeardownOptions } from "./sandbox.ts";
const HOME_DIR = "/root";
-const INLINE_LIMIT = 256 * 1024;
+const HOME_TAR = `${HOME_DIR}/.qm-home.tar`;
const FILE_TRANSFER_TIMEOUT_MS = 300_000;
const EXEC_SYNC_MAX_SEC = 240;
const EXEC_POLL_MS = 2_000;
const EXIT_GRACE_MS = 60_000;
const READY_TIMEOUT_MS = 180_000;
const READY_POLL_MS = 1_000;
+const GUEST_PROBE_TIMEOUT_SEC = 15;
+const SCRATCH_TTL_SEC = 24 * 3600;
const DEFAULT_SMOLMACHINES_BASE_URL = "https://api.smolmachines.com";
const DEFAULT_IMAGE = "codex";
+const DEFAULT_CPUS = 4;
+const DEFAULT_MEMORY_MB = 8192;
const RUNNING_STATES = new Set(["running", "started", "ready"]);
+type MachineNetwork =
+ { mode: "open" } | { mode: "blocked" } | { mode: "allowCidrs"; cidrs?: string[]; hosts?: string[] };
+
interface MachineInfo {
id: string;
name?: string | null;
state: string;
+ ready?: boolean;
+ error?: string | null;
+ network?: MachineNetwork;
}
interface MachineExecResponse {
stdout: string;
stderr: string;
exitCode: number;
+ stdoutB64?: string;
+ stderrB64?: string;
stdoutTruncated?: boolean;
stderrTruncated?: boolean;
}
+export interface StoredSmolmachinesSandbox {
+ initializationPending?: boolean;
+ lastSnapshotMs?: number;
+ homeDirty?: boolean;
+ snapshotError?: string;
+}
+
export interface SmolmachinesSandboxOptions extends BlobStagingOptions {
token?: string;
baseUrl?: string;
@@ -51,8 +74,13 @@ export interface SmolmachinesSandboxOptions extends BlobStagingOptions {
cpus?: number;
memoryMb?: number;
diskGb?: number;
+ autoStopSec?: number;
defaultTimeoutSec?: number;
egressProxyUrl?: string;
+ snapshotIntervalMs?: number;
+ store?: DurableMap<StoredSmolmachinesSandbox>;
+ advisoryLock?: AdvisoryLock;
+ snapshots?: HomeSnapshotStore;
extraTools?: string[];
credentialPaths?: CredentialPathSpec[];
layerToolFiles?: () => readonly LayerInstallFile[];
@@ -72,8 +100,18 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
...(opts.diskGb ? { diskGb: opts.diskGb } : {}),
};
const defaultTimeoutSec = opts.defaultTimeoutSec ?? 600;
+ const snapshotIntervalMs = opts.snapshotIntervalMs ?? 0;
+ const store = opts.store ?? createMemoryMap<StoredSmolmachinesSandbox>();
+ const advisoryLock = opts.advisoryLock ?? createMemoryAdvisoryLock();
+ const lifecycleKey = (scope: string): string => `smolmachines-provision:${prefix}:${scope}`;
+ const egressProxyHost = opts.egressProxyUrl ? new URL(opts.egressProxyUrl).hostname : undefined;
+ const network: MachineNetwork = egressProxyHost ? { mode: "allowCidrs", hosts: [egressProxyHost] } : { mode: "open" };
const idByName = new Map<string, string>();
+ const egressVerified = new Set<string>();
+
+ const isRunning = (info: MachineInfo): boolean => RUNNING_STATES.has(info.state.toLowerCase());
+ const machinePath = (id: string): string => `/v1/machines/${encodeURIComponent(id)}`;
function send(
method: string,
@@ -113,13 +151,17 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
return machines.find((m) => m.name === name) ?? null;
}
- async function awaitRunning(id: string): Promise<void> {
+ async function awaitReady(id: string): Promise<void> {
const deadline = Date.now() + READY_TIMEOUT_MS;
for (;;) {
- const info = await apiJson<MachineInfo>("GET", `/v1/machines/${encodeURIComponent(id)}`);
- if (RUNNING_STATES.has(info.state.toLowerCase())) return;
- if (Date.now() > deadline)
- throw new Error(`smolmachines machine ${id}: not running after ${READY_TIMEOUT_MS}ms (state=${info.state})`);
+ const info = await apiJson<MachineInfo>("GET", machinePath(id));
+ if (info.state.toLowerCase() === "error") {
+ throw new Error(`smolmachines machine ${id}: entered error state${info.error ? `: ${info.error}` : ""}`);
+ }
+ if (info.ready === true || (info.ready === undefined && isRunning(info))) return;
+ if (Date.now() > deadline) {
+ throw new Error(`smolmachines machine ${id}: not ready after ${READY_TIMEOUT_MS}ms (state=${info.state})`);
+ }
await sleep(READY_POLL_MS);
}
}
@@ -129,9 +171,11 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
name,
source: { type: "image", reference: image },
...(Object.keys(resources).length ? { resources } : {}),
- network: { mode: "open" },
+ network,
workdir: HOME_DIR,
ephemeral,
+ ...(ephemeral ? { ttlSeconds: SCRATCH_TTL_SEC } : {}),
+ ...(opts.autoStopSec ? { autoStopSeconds: opts.autoStopSec } : {}),
});
if (res.status === 409) {
const existing = await findMachine(name);
@@ -148,11 +192,11 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
}
async function startMachine(id: string): Promise<void> {
- const res = await api("POST", `/v1/machines/${encodeURIComponent(id)}/start`);
+ const res = await api("POST", `${machinePath(id)}/start`);
if (!res.ok && res.status !== 409) {
throw new Error(`smolmachines start ${id}: ${await httpFailure(res)}`);
}
- await awaitRunning(id);
+ await awaitReady(id);
}
async function machineIdFor(name: string): Promise<string> {
@@ -170,27 +214,34 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
idByName.delete(name);
return;
}
- const res = await api("DELETE", `/v1/machines/${encodeURIComponent(found)}`);
+ const res = await api("DELETE", machinePath(found));
if (!res.ok && res.status !== 404) {
throw new Error(`smolmachines delete ${name}: ${await httpFailure(res)}`);
}
idByName.delete(name);
}
- async function postExec(
+ function decodeStream(
name: string,
- script: string,
- timeoutSec: number,
- stdinB64?: string,
- ): Promise<MachineExecResponse> {
+ label: string,
+ b64: string | undefined,
+ text: string,
+ truncated?: boolean,
+ ): string {
+ if (b64 !== undefined) return Buffer.from(b64, "base64").toString("utf8");
+ if (truncated) throw new Error(`smolmachines exec ${name}: ${label} truncated and no byte-exact stream returned`);
+ return text;
+ }
+
+ async function postExec(name: string, script: string, timeoutSec: number): Promise<ExecResult> {
const id = await machineIdFor(name);
const body = {
command: ["sh", "-c", script],
timeoutSeconds: timeoutSec + Math.ceil(EXIT_GRACE_MS / 1000),
- ...(stdinB64 !== undefined ? { stdin: stdinB64 } : {}),
};
const timeoutMs = timeoutSec * 1000 + 2 * EXIT_GRACE_MS;
- const first = await send("POST", `/v1/machines/${encodeURIComponent(id)}/exec`, body, timeoutMs);
+ const execPath = (machineId: string): string => `${machinePath(machineId)}/exec?output=b64`;
+ const first = await send("POST", execPath(id), body, timeoutMs);
let res = first;
if (!first.ok) {
const detail = await httpFailure(first);
@@ -200,93 +251,45 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
}
const retryId = await machineIdFor(name);
await startMachine(retryId);
- res = await send("POST", `/v1/machines/${encodeURIComponent(retryId)}/exec`, body, timeoutMs);
+ res = await send("POST", execPath(retryId), body, timeoutMs);
if (!res.ok) {
throw new Error(`smolmachines exec ${name}: ${await httpFailure(res)}`);
}
}
- const parsed = (await res.json()) as MachineExecResponse;
- if (parsed.stdoutTruncated || parsed.stderrTruncated) {
- throw new Error(`smolmachines exec ${name}: output truncated by the API — chunk the read instead`);
- }
- return parsed;
+ const r = (await res.json()) as MachineExecResponse;
+ return {
+ stdout: decodeStream(name, "stdout", r.stdoutB64, r.stdout, r.stdoutTruncated),
+ stderr: decodeStream(name, "stderr", r.stderrB64, r.stderr, r.stderrTruncated),
+ code: r.exitCode,
+ timedOut: r.exitCode === 124,
+ };
}
const filesUrl = (id: string, absPath: string): string =>
- `/v1/machines/${encodeURIComponent(id)}/files${absPath.split("/").map(encodeURIComponent).join("/")}`;
-
- async function readSpooled(name: string, absPath: string, declared: number): Promise<Buffer> {
- const data = await readAbsBytes(name, absPath);
- if (!data || data.length !== declared) {
- throw new Error(`smolmachines read ${absPath}: truncated (${data?.length ?? 0}/${declared})`);
- }
- return Buffer.from(data);
- }
+ `${machinePath(id)}/files${absPath.split("/").map(encodeURIComponent).join("/")}`;
async function execRaw(name: string, script: string, timeoutSec: number): Promise<ExecResult> {
+ const guarded = `timeout ${timeoutSec} sh -c ${shq(script)}`;
+ if (timeoutSec <= EXEC_SYNC_MAX_SEC) return postExec(name, guarded, timeoutSec);
const uid = randomUUID();
const out = `${HOME_DIR}/.qm-exec-${uid}.out`;
const err = `${HOME_DIR}/.qm-exec-${uid}.err`;
const rcf = `${HOME_DIR}/.qm-exec-${uid}.rc`;
- const envelope =
- `__o=$(wc -c < ${out}); __e=$(wc -c < ${err}); printf '%s %s %s\\n' "$__rc" "$__o" "$__e"; ` +
- `if [ "$__o" -le ${INLINE_LIMIT} ] && [ "$__e" -le ${INLINE_LIMIT} ]; then base64 < ${out}; base64 < ${err}; rm -f ${out} ${err} ${rcf}; fi`;
- let r: MachineExecResponse;
- if (timeoutSec <= EXEC_SYNC_MAX_SEC) {
- r = await postExec(
- name,
- `timeout ${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 start = await postExec(name, `nohup sh -c ${shq(body)} >/dev/null 2>&1 & echo launched`, 30);
- if (start.exitCode !== 0 || !/launched/.test(start.stdout)) {
- throw new Error(`smolmachines exec ${name}: background launch failed (rc=${start.exitCode})`);
- }
- const deadline = Date.now() + timeoutSec * 1000 + EXIT_GRACE_MS;
- for (;;) {
- const p = await postExec(name, `[ -f ${rcf} ] && echo settled || echo running`, 30);
- if (/settled/.test(p.stdout)) break;
- if (Date.now() > deadline) {
- throw new Error(`smolmachines exec ${name}: no exit after ${timeoutSec}s (+grace); leaving ${rcf}`);
- }
- await sleep(EXEC_POLL_MS);
- }
- r = await postExec(name, `__rc=$(cat ${rcf}); ${envelope}`, 60);
- }
- const text = r.stdout;
- const nl = text.indexOf("\n");
- const header = text
- .slice(0, nl < 0 ? undefined : nl)
- .trim()
- .split(/\s+/);
- if (r.exitCode !== 0 || nl < 0 || header.length !== 3) {
- throw new Error(`smolmachines exec ${name}: bad envelope (rc=${r.exitCode}): ${text.slice(0, 120)}`);
+ const body = `${guarded} > ${out} 2> ${err}; echo $? > ${rcf}`;
+ const start = await postExec(name, `nohup sh -c ${shq(body)} >/dev/null 2>&1 & echo launched`, 30);
+ if (start.code !== 0 || !/launched/.test(start.stdout)) {
+ throw new Error(`smolmachines exec ${name}: background launch failed (rc=${start.code})`);
}
- const code = Number.parseInt(header[0]!, 10);
- const outLen = Number.parseInt(header[1]!, 10);
- const errLen = Number.parseInt(header[2]!, 10);
- let outBuf: Buffer;
- let errBuf: Buffer;
- if (outLen <= INLINE_LIMIT && errLen <= INLINE_LIMIT) {
- const b64 = text.slice(nl + 1).replace(/\s+/g, "");
- const outB64 = Math.ceil(outLen / 3) * 4;
- outBuf = Buffer.from(b64.slice(0, outB64), "base64");
- errBuf = Buffer.from(b64.slice(outB64), "base64");
- if (outBuf.length !== outLen || errBuf.length !== errLen) {
- throw new Error(
- `smolmachines exec ${name}: truncated stream (${outBuf.length}/${outLen} out, ${errBuf.length}/${errLen} err)`,
- );
+ const deadline = Date.now() + timeoutSec * 1000 + EXIT_GRACE_MS;
+ for (;;) {
+ const p = await postExec(name, `[ -f ${rcf} ] && echo settled || echo running`, 30);
+ if (/settled/.test(p.stdout)) break;
+ if (Date.now() > deadline) {
+ throw new Error(`smolmachines exec ${name}: no exit after ${timeoutSec}s (+grace); leaving ${rcf}`);
}
- } 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("smolmachines-sandbox: spool cleanup", undefined),
- );
+ await sleep(EXEC_POLL_MS);
}
- return { stdout: outBuf.toString("utf8"), stderr: errBuf.toString("utf8"), code, timedOut: code === 124 };
+ return postExec(name, `__rc=$(cat ${rcf}); cat ${out}; cat ${err} >&2; rm -f ${out} ${err} ${rcf}; exit $__rc`, 60);
}
async function writeAbsBytes(name: string, absPath: string, data: Uint8Array): Promise<void> {
@@ -325,6 +328,111 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
return new Uint8Array(await res.arrayBuffer());
}
+ async function ensureEgress(name: string): Promise<void> {
+ const id = await machineIdFor(name);
+ if (egressVerified.has(id)) return;
+ const info = await apiJson<MachineInfo>("GET", machinePath(id));
+ const got = info.network;
+ const hosts = got?.mode === "allowCidrs" ? (got.hosts ?? []).map((h) => h.toLowerCase()) : [];
+ const cidrs = got?.mode === "allowCidrs" ? (got.cidrs ?? []) : [];
+ const bound = hosts.length === 1 && hosts[0] === egressProxyHost!.toLowerCase() && cidrs.length === 0;
+ if (!bound) {
+ throw new Error(
+ `smolmachines egress ${name}: machine network is ${JSON.stringify(got)}, expected ${JSON.stringify(network)}; destroy the sandbox so it is recreated with the allow list`,
+ );
+ }
+ egressVerified.add(id);
+ }
+
+ const homeSnapshots = opts.snapshots
+ ? createHomeSnapshotOps<string>({
+ label: "smolmachines",
+ homeDir: HOME_DIR,
+ homeTarPath: HOME_TAR,
+ prunePaths: [
+ ...HOME_SNAPSHOT_PRUNE,
+ ...ephemeralCredLinkPaths(opts.credentialPaths ?? []).map(({ rel }) => `./${rel}`),
+ ],
+ store: opts.snapshots,
+ io: {
+ runCommand: async (name, script, timeoutMs) => {
+ const r = await execRaw(name, script, Math.ceil(timeoutMs / 1000));
+ return { exitCode: r.code, stdout: r.stdout, stderr: r.stderr };
+ },
+ readFileBytes: readAbsBytes,
+ writeFileBytes: writeAbsBytes,
+ },
+ })
+ : undefined;
+
+ async function mergeStored(scope: string, patch: Partial<StoredSmolmachinesSandbox>): Promise<void> {
+ await store.putIfAbsent(scope, {});
+ await store.merge(scope, patch);
+ }
+
+ async function snapshotHome(scope: string, name: string): Promise<void> {
+ try {
+ await homeSnapshots!.snapshotHome(scope, name);
+ await mergeStored(scope, { lastSnapshotMs: Date.now(), homeDirty: false, snapshotError: undefined });
+ } catch (e) {
+ await mergeStored(scope, { snapshotError: errMessage(e) });
+ throw e;
+ }
+ }
+
+ function ensureMachine(
+ name: string,
+ scope: string,
+ onStatus?: (text: string) => void,
+ ): Promise<{ coldStart: boolean }> {
+ return advisoryLock.withLock(lifecycleKey(scope), () => initializeMachine(name, scope, onStatus));
+ }
+
+ async function initializeMachine(
+ name: string,
+ scope: string,
+ onStatus?: (text: string) => void,
+ ): Promise<{ coldStart: boolean }> {
+ const stored = await store.get(scope);
+ if (idByName.has(name) && !stored?.initializationPending) return { coldStart: false };
+ const existing = await findMachine(name);
+ if (existing && !stored?.initializationPending) {
+ idByName.set(name, existing.id);
+ if (!isRunning(existing)) await startMachine(existing.id);
+ return { coldStart: false };
+ }
+ await mergeStored(scope, { initializationPending: true });
+ try {
+ onStatus?.("Preparing the sandbox…");
+ } catch (error) {
+ void error;
+ }
+ try {
+ const info = existing ?? (await createMachine(name, false)).info;
+ idByName.set(name, info.id);
+ if (existing && !isRunning(existing)) await startMachine(existing.id);
+ const hydrated = homeSnapshots ? await homeSnapshots.hydrateHome(scope, name) : false;
+ await mergeStored(scope, { initializationPending: undefined, ...(hydrated ? { homeDirty: false } : {}) });
+ return { coldStart: !hydrated };
+ } catch (e) {
+ if (idByName.has(name))
+ await deleteMachine(name).catch(swallowAs("smolmachines-sandbox: delete after failed hydration", undefined));
+ idByName.delete(name);
+ opts.onError?.({
+ category: "sandbox_hydrate",
+ code: "hydrate_failed",
+ message: errMessage(e),
+ scopeLabel: scope,
+ });
+ throw new Error(
+ `smolmachines provision: home hydration failed (${errMessage(e)}); not risking the stored snapshot`,
+ {
+ cause: e,
+ },
+ );
+ }
+ }
+
const base = createExecSandboxBase({
workspace,
label: "smolmachines",
@@ -339,39 +447,26 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
exec: execRaw,
writeAbsBytes,
readAbsBytes,
- async ensureResident(name, onStatus) {
- if (idByName.has(name)) return { coldStart: false };
- const existing = await findMachine(name);
- if (existing) {
- idByName.set(name, existing.id);
- if (!RUNNING_STATES.has(existing.state.toLowerCase())) await startMachine(existing.id);
- return { coldStart: false };
- }
- try {
- onStatus?.("Creating the sandbox…");
- } catch (error) {
- void error;
- }
- const { info, created } = await createMachine(name, false);
- idByName.set(name, info.id);
- return { coldStart: created };
- },
+ ensureResident: (name, onStatus) => ensureMachine(name, base.scopeFor(name) ?? "default", onStatus),
isProvisioned: (name) => idByName.has(name),
async recreateScratch(name) {
await deleteMachine(name).catch(swallowAs("smolmachines-sandbox: stale scratch delete", undefined));
const { info } = await createMachine(name, true);
idByName.set(name, info.id);
},
- deleteInstance: deleteMachine,
+ deleteInstance: (name) =>
+ advisoryLock.withLock(lifecycleKey(base.scopeFor(name) ?? name), () => deleteMachine(name)),
+ ...(egressProxyHost ? { ensureEgress } : {}),
});
+ const idleNote = opts.autoStopSec ? `; stops after ${opts.autoStopSec}s idle and restarts on the next command` : "";
const profile: AgentComputerProfile = {
backend: "smolmachines",
writablePersistence: "resident_disk",
processSessions: true,
- egressEnforcement: "none",
+ egressEnforcement: egressProxyHost ? "domain" : "none",
spec: {
- os: "Debian 12 — smolmachines microVM (auto-stops when idle; the whole disk persists)",
+ os: `smolmachines microVM booted from the ${image} image (the whole disk persists across stops${idleNote})`,
runtimes: ["Node", "Python 3"],
get tools() {
return visibleTools(["git", "curl", "jq", "tar", "python3", ...(opts.extraTools ?? [])]);
@@ -379,8 +474,8 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
get notInstalled() {
return visibleNotInstalled(["gh", "aws", "gcloud", "kubectl", "flyctl", "glab"], opts.extraTools ?? []);
},
- ...(opts.cpus ? { cpus: opts.cpus } : {}),
- ...(opts.memoryMb ? { memoryMb: opts.memoryMb } : {}),
+ cpus: opts.cpus ?? DEFAULT_CPUS,
+ memoryMb: opts.memoryMb ?? DEFAULT_MEMORY_MB,
...(opts.diskGb ? { diskGb: opts.diskGb } : {}),
homeDir: HOME_DIR,
workdir: base.workspaceDir,
@@ -411,6 +506,18 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
ephemeralCredentialPrefixes: ephemeralCredLinkPaths(opts.credentialPaths ?? []).map(({ rel }) => rel),
});
+ async function recoveryFor(scopeId: string): Promise<Pick<ComputerStatus, "recovery">> {
+ if (!homeSnapshots) return {};
+ const stored = await store.get(scopeId);
+ return {
+ recovery: {
+ strategy: "workspace_snapshot",
+ ...(stored?.lastSnapshotMs ? { checkpointAtMs: stored.lastSnapshotMs } : {}),
+ ...(stored?.snapshotError ? { error: stored.snapshotError } : {}),
+ },
+ };
+ }
+
return {
profile,
startProcess: procSessions.startProcess,
@@ -428,11 +535,93 @@ export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: Smolm
readFile: base.readFile,
exportFiles: execExport.exportFiles,
+ ...(homeSnapshots
+ ? {
+ async persistHomeSnapshot(scopeId: string): Promise<void> {
+ const name = sandboxScopeName(prefix, scopeId);
+ await base.provisionQueue(scopeId, () =>
+ advisoryLock.withLock(lifecycleKey(scopeId), async () => {
+ await initializeMachine(name, scopeId);
+ await snapshotHome(scopeId, name);
+ }),
+ );
+ },
+ }
+ : {}),
+
+ async computerStatus(scopeId: string): Promise<ComputerStatus> {
+ const name = sandboxScopeName(prefix, scopeId);
+ const recovery = await recoveryFor(scopeId);
+ let info: MachineInfo | null;
+ try {
+ info = await findMachine(name);
+ } catch (e) {
+ return { ...recovery, machine: `lookup failed: ${errMessage(e)}`, guestResponsive: false };
+ }
+ if (!info)
+ return { ...recovery, machine: "no machine provisioned yet", provisioned: false, guestResponsive: false };
+ idByName.set(name, info.id);
+ const machine = `machine ${info.id} ${info.state}${info.error ? `: ${info.error}` : ""}`;
+ if (!isRunning(info)) {
+ return {
+ ...recovery,
+ machine,
+ listed: info.state,
+ lifecycleState: "paused",
+ provisioned: true,
+ guestResponsive: false,
+ };
+ }
+ let guestResponsive = false;
+ let probeError: string | undefined;
+ try {
+ guestResponsive = (await execRaw(name, "true", GUEST_PROBE_TIMEOUT_SEC)).code === 0;
+ } catch (e) {
+ probeError = errMessage(e);
+ }
+ return {
+ ...recovery,
+ machine,
+ listed: info.state,
+ lifecycleState: "running",
+ provisioned: true,
+ guestResponsive,
+ ...(probeError ? { probeError } : {}),
+ };
+ },
+
async destroyScope(scopeId: string): Promise<void> {
- return base.provisionQueue(scopeId, async () => {
- await deleteMachine(sandboxScopeName(prefix, scopeId));
- });
+ return base.provisionQueue(scopeId, () =>
+ advisoryLock.withLock(lifecycleKey(scopeId), async () => {
+ await deleteMachine(sandboxScopeName(prefix, scopeId));
+ await store.delete(scopeId);
+ }),
+ );
+ },
+
+ async teardown(handle, tdOpts?: TeardownOptions): Promise<void> {
+ if (homeSnapshots && !handle.scratch && !tdOpts?.destroy) {
+ const scope = base.scopeFor(handle.id) ?? "default";
+ await base.provisionQueue(scope, () =>
+ advisoryLock.withLock(lifecycleKey(scope), async () => {
+ const stored = await store.get(scope);
+ if (stored?.initializationPending) return;
+ if (!tdOpts?.homeUnchanged) await mergeStored(scope, { homeDirty: true });
+ if (!snapshotDue(stored, tdOpts, snapshotIntervalMs)) return;
+ try {
+ await snapshotHome(scope, handle.id);
+ } catch (e) {
+ opts.onError?.({
+ category: "sandbox_snapshot",
+ code: "teardown_snapshot_failed",
+ message: errMessage(e),
+ scopeLabel: scope,
+ });
+ }
+ }),
+ );
+ }
+ return base.teardown(handle, tdOpts);
},
- teardown: base.teardown,
};
}
diff --git a/src/wiring.ts b/src/wiring.ts
index e5723a329..87adc7cb8 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -211,7 +211,7 @@ import { createPostgresFileArtifactStore } from "./files/postgres-file-artifact-
import { createAwsSandbox, type StoredMicrovm } from "./sandbox/aws-sandbox.ts";
import { createLocalSandbox } from "./sandbox/local-sandbox.ts";
import { createSpritesSandbox } from "./sandbox/sprites-sandbox.ts";
-import { createSmolmachinesSandbox } from "./sandbox/smolmachines-sandbox.ts";
+import { createSmolmachinesSandbox, type StoredSmolmachinesSandbox } from "./sandbox/smolmachines-sandbox.ts";
import { createAgent37Sandbox } from "./sandbox/agent37-sandbox.ts";
import {
createConfigEpochResolver,
@@ -852,9 +852,12 @@ export function buildApp(
...(config.apiBaseUrl ? { apiBaseUrl: config.apiBaseUrl } : {}),
onError: sandboxOnError,
});
- const buildSmolmachines = (): Sandbox =>
- createSmolmachinesSandbox(workspace, {
- ...config.smolmachinesSandbox,
+ const smolmachinesBodies = artifactMap<StoredSmolmachinesSandbox>("smolmachines_sandbox_bodies");
+ const buildSmolmachines = (): Sandbox => {
+ const { snapshotS3Bucket, snapshotIntervalSec, ...smol } = config.smolmachinesSandbox;
+ return createSmolmachinesSandbox(workspace, {
+ ...smol,
+ ...(snapshotIntervalSec !== undefined ? { snapshotIntervalMs: snapshotIntervalSec * 1000 } : {}),
blobTransfer,
extraTools: deploymentLayer.advertisedTools,
credentialPaths: deploymentLayer.credentialPaths,
@@ -862,8 +865,14 @@ export function buildApp(
...(config.signingSecret ? { signingSecret: config.signingSecret } : {}),
...(config.capabilitySecret ? { capabilitySecret: config.capabilitySecret } : {}),
...(config.apiBaseUrl ? { apiBaseUrl: config.apiBaseUrl } : {}),
+ store: smolmachinesBodies,
+ advisoryLock,
+ ...(snapshotS3Bucket
+ ? { snapshots: createS3SnapshotStore({ bucket: snapshotS3Bucket, prefix: "smolmachines-home" }) }
+ : {}),
onError: sandboxOnError,
});
+ };
const e2bBodies = artifactMap<StoredE2bSandbox>("e2b_sandbox_bodies");
const modalBodies = artifactMap<StoredModalSandbox>("modal_sandbox_bodies");
const awsBodies = artifactMap<StoredMicrovm>("aws_sandbox_bodies");
diff --git a/test/config.test.ts b/test/config.test.ts
index d1ce62239..b403c8a94 100644
--- a/test/config.test.ts
+++ b/test/config.test.ts
@@ -824,6 +824,24 @@ test("Modal native retention and interval configuration are independent of legac
assert.equal(config.modalSandbox.snapshotIntervalSec, 315360000);
});
+test("Smolmachines lifecycle, egress, and snapshot knobs are parsed into Config", () => {
+ const config = loadConfig({
+ SMOLMACHINES_TOKEN: "smk_test",
+ SMOLMACHINES_AUTOSTOP_SEC: "900",
+ SMOLMACHINES_EGRESS_PROXY_URL: "https://proxy.example.com",
+ SMOLMACHINES_SNAPSHOT_S3_BUCKET: "qm-home-snapshots",
+ SMOLMACHINES_SNAPSHOT_INTERVAL_SEC: "300",
+ });
+ assert.equal(config.smolmachinesSandbox.autoStopSec, 900);
+ assert.equal(config.smolmachinesSandbox.egressProxyUrl, "https://proxy.example.com");
+ assert.equal(config.smolmachinesSandbox.snapshotS3Bucket, "qm-home-snapshots");
+ assert.equal(config.smolmachinesSandbox.snapshotIntervalSec, 300);
+ const bare = loadConfig({ SMOLMACHINES_TOKEN: "smk_test" });
+ assert.equal(bare.smolmachinesSandbox.autoStopSec, undefined);
+ assert.equal(bare.smolmachinesSandbox.snapshotS3Bucket, undefined);
+ assert.throws(() => loadConfig({ SMOLMACHINES_AUTOSTOP_SEC: "soon" }), /SMOLMACHINES_AUTOSTOP_SEC/);
+});
+
test("Modal native activation is default-off and uses strict boolean configuration", () => {
assert.equal(loadConfig({}).modalSandbox.nativeSnapshotsEnabled, false);
for (const value of ["true", "on", "1"])
diff --git a/test/smolmachines-sandbox.test.ts b/test/smolmachines-sandbox.test.ts
index 799067656..04a537c89 100644
--- a/test/smolmachines-sandbox.test.ts
+++ b/test/smolmachines-sandbox.test.ts
@@ -15,12 +15,28 @@ import {
FAKE_SMOLMACHINES_TOKEN,
type FakeSmolmachines,
} from "./support/fake-smolmachines.ts";
+import { instrumentedSnapshotStore } from "./support/snapshot-stores.ts";
+import { createMemorySnapshotStore } from "../src/sandbox/home-snapshot.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { createMemoryAdvisoryLock } from "../src/persistence/advisory-lock.ts";
+import type { StoredSmolmachinesSandbox } from "../src/sandbox/smolmachines-sandbox.ts";
import type { Sandbox } from "../src/sandbox/sandbox.ts";
let fake: FakeSmolmachines;
let sandbox: Sandbox;
const scope = scopeId("personal", "tester");
const layers = [{ scopeId: scope, mountPath: "/", mode: "rw" as const }];
+const scopeName = (): string => sandboxScopeName("qmt", scope);
+const proxyToken = (): Promise<string> =>
+ mintCapabilityToken(
+ { actorId: "tester", scopeId: scope, aud: EGRESS_PROXY_AUD, exp: Date.now() + 600_000 },
+ "secret",
+ );
+const preCreate = (name: string): Promise<Response> =>
+ fake.fetchImpl("https://api.smolmachines.com/v1/machines", {
+ method: "POST",
+ body: JSON.stringify({ name, ephemeral: false }),
+ });
function make(extra: Record<string, unknown> = {}): Sandbox {
return createSmolmachinesSandbox(createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "smol-ws-"))), {
@@ -90,20 +106,31 @@ test("process sessions capability works end to end", async () => {
assert.match(output, /two/);
});
-test("force-through proxy env is set when a proxy url and token are present", async () => {
+test("a configured egress proxy allow-lists only the proxy host at create and injects the proxy env", async () => {
const s = make({ egressProxyUrl: "https://proxy.example.com" });
- const token = await mintCapabilityToken(
- { actorId: "tester", scopeId: scope, aud: EGRESS_PROXY_AUD, exp: Date.now() + 600_000 },
- "secret",
- );
- const h = await s.provision(layers, { egressToken: token });
+ assert.equal(s.profile.egressEnforcement, "domain");
+ const h = await s.provision(layers, { egressToken: await proxyToken() });
+ assert.deepEqual(fake.machine(h.id)?.network, { mode: "allowCidrs", hosts: ["proxy.example.com"] });
const r = await s.run(h, "echo PROXY=$HTTPS_PROXY");
assert.match(r.stdout, /PROXY=https?:\/\/[^ ]*proxy\.example\.com/);
});
-test("no proxy env without a proxy url", async () => {
+test("without a proxy url machines are created open, with no proxy env and no enforcement claim", async () => {
+ assert.equal(sandbox.profile.egressEnforcement, "none");
const h = await sandbox.provision(layers, { egressToken: "ignored" });
assert.equal(h.env?.HTTPS_PROXY, undefined);
+ assert.deepEqual(fake.machine(h.id)?.network, { mode: "open" });
+});
+
+test("force-through fails closed on a machine that was created with open networking", async () => {
+ const open = await sandbox.provision(layers);
+ assert.deepEqual(fake.machine(open.id)?.network, { mode: "open" });
+ const s = make({ egressProxyUrl: "https://proxy.example.com" });
+ await assert.rejects(
+ s.provision(layers, { egressToken: await proxyToken() }),
+ /machine network is .*"open".*allowCidrs/,
+ );
+ assert.ok(fake.machine(open.id), "the open machine is left for the operator to destroy, never silently replaced");
});
test("machine is reused across provisions and warm start is reported", async () => {
@@ -169,12 +196,40 @@ test("teardown without destroy keeps the machine; destroy deletes it", async ()
assert.equal(fake.machine(h.id), null);
});
-test("large command output survives the API's truncation cap exactly", async () => {
+test("command output is read byte-exact from the base64 stream past the 1 MiB text cap", async () => {
const h = await sandbox.provision(layers);
- const r = await sandbox.run(h, "python3 -c \"print('x' * (900 * 1024), end='')\"");
+ const size = 1500 * 1024;
+ const r = await sandbox.run(
+ h,
+ `python3 -c "import sys; sys.stdout.write('x' * ${size}); sys.stderr.write('e' * ${size})"`,
+ );
assert.equal(r.code, 0);
- assert.equal(r.stdout.length, 900 * 1024);
- assert.equal(r.stdout, "x".repeat(900 * 1024));
+ assert.equal(r.stdout, "x".repeat(size));
+ assert.equal(r.stderr, "e".repeat(size));
+ const execs = fake.calls.filter((c) => c.path.endsWith("/exec"));
+ assert.ok(execs.length > 0);
+ assert.ok(
+ execs.every((c) => c.query === "output=b64"),
+ "every exec asks for the byte-exact family only",
+ );
+});
+
+test("a control plane without base64 output still fails closed on truncated text", async () => {
+ const textOnly: typeof fetch = async (input, init) => {
+ const url = new URL(String(input));
+ if (!url.pathname.endsWith("/exec")) return fake.fetchImpl(input, init);
+ url.search = "";
+ const res = await fake.fetchImpl(url, init);
+ const body = (await res.json()) as Record<string, unknown>;
+ delete body.stdoutB64;
+ delete body.stderrB64;
+ return Response.json(body);
+ };
+ const s = make({ fetchImpl: textOnly });
+ const h = await s.provision(layers);
+ const small = await s.run(h, "echo legacy");
+ assert.equal(small.stdout, "legacy\n");
+ await assert.rejects(s.run(h, "python3 -c \"print('x' * (1100 * 1024), end='')\""), /stdout truncated/);
});
test("a name conflict on create adopts the existing machine instead of failing", async () => {
@@ -207,10 +262,150 @@ test("configured resources are requested at create and advertised in the profile
assert.equal(s.profile.spec?.cpus, 4);
});
-test("profile advertises resident disk and process sessions", () => {
+test("profile advertises resident disk, process sessions, and the documented default shape", () => {
assert.equal(sandbox.profile.backend, "smolmachines");
assert.equal(sandbox.profile.writablePersistence, "resident_disk");
assert.equal(sandbox.profile.processSessions, true);
+ assert.equal(sandbox.profile.spec?.cpus, 4);
+ assert.equal(sandbox.profile.spec?.memoryMb, 8192);
+ assert.equal(sandbox.profile.spec?.diskGb, undefined);
+ assert.match(sandbox.profile.spec?.os ?? "", /codex image/);
+ assert.doesNotMatch(sandbox.profile.spec?.os ?? "", /Debian|idle/);
+ const idle = make({ image: "ubuntu:24.04", autoStopSec: 900 });
+ assert.match(idle.profile.spec?.os ?? "", /ubuntu:24\.04 image/);
+ assert.match(idle.profile.spec?.os ?? "", /900s idle/);
+});
+
+test("a machine the provider reports in error state fails fast with the provider's reason", async () => {
+ await preCreate(scopeName());
+ fake.fail(scopeName(), "start failed: no capacity in region");
+ await assert.rejects(sandbox.provision(layers), /error state: start failed: no capacity in region/);
+});
+
+test("started is not ready: provisioning polls until the machine reports ready", async () => {
+ await preCreate(scopeName());
+ fake.notReadyFor(scopeName(), 2);
+ const h = await sandbox.provision(layers);
+ const isMachineGet = (c: { method: string; path: string }): boolean =>
+ c.method === "GET" && /\/v1\/machines\/[^/]+$/.test(c.path);
+ const machineGets = fake.calls.filter(isMachineGet);
+ assert.ok(machineGets.length >= 3, `polled the machine ${machineGets.length} times before acting`);
+ const readyGet = fake.calls.indexOf(machineGets[2]!);
+ const firstExec = fake.calls.findIndex((c) => c.path.endsWith("/exec"));
+ assert.ok(firstExec > readyGet, "no work is dispatched before the ready poll succeeds");
+ assert.equal((await sandbox.run(h, "echo up")).stdout.trim(), "up");
+});
+
+test("scratch machines carry a hard TTL and configured idle stop is sent on every create", async () => {
+ const s = make({ autoStopSec: 900 });
+ const scratch = await s.provision(layers, { scratch: { key: "job-ttl" } });
+ assert.equal(fake.machine(scratch.id)?.ttlSeconds, 24 * 3600);
+ assert.equal(fake.machine(scratch.id)?.autoStopSeconds, 900);
+ const resident = await s.provision(layers);
+ assert.equal(fake.machine(resident.id)?.ttlSeconds, undefined);
+ assert.equal(fake.machine(resident.id)?.autoStopSeconds, 900);
+ const plain = await sandbox.provision([
+ { scopeId: scopeId("personal", "other"), mountPath: "/", mode: "rw" as const },
+ ]);
+ assert.equal(fake.machine(plain.id)?.autoStopSeconds, undefined);
+});
+
+test("exec requests carry no stdin field", async () => {
+ const h = await sandbox.provision(layers);
+ await sandbox.run(h, "echo x");
+ const execCall = fake.calls.filter((c) => c.path.endsWith("/exec")).at(-1)!;
+ assert.ok(execCall.body && typeof execCall.body === "object");
+ assert.equal(Object.hasOwn(execCall.body, "stdin"), false);
+ assert.ok(fake.execScripts().every((script) => !/stdin/.test(script)));
+});
+
+test("teardown snapshots the home to the configured store and a lost machine is rehydrated from it", async () => {
+ const snapshots = createMemorySnapshotStore();
+ const s = make({ snapshots });
+ const a = await s.provision(layers);
+ await s.writeFile(a, "notes.txt", "keep me\n");
+ await s.teardown(a);
+ assert.ok(await snapshots.open(scope), "teardown stored a home snapshot");
+ const status = await s.computerStatus!(scope);
+ assert.equal(status.recovery?.strategy, "workspace_snapshot");
+ assert.ok(status.recovery?.checkpointAtMs);
+ fake.deleteBehindCore(a.id);
+ const s2 = make({ snapshots });
+ const b = await s2.provision(layers);
+ assert.equal(b.coldStart, false, "a hydrated replacement is not a cold start");
+ assert.equal(await s2.readFile(b, "notes.txt"), "keep me\n");
+});
+
+test("teardown snapshots are throttled by snapshotIntervalMs and skipped for scratch machines", async () => {
+ const counting = instrumentedSnapshotStore();
+ const s = make({ snapshots: counting.store, snapshotIntervalMs: 60 * 60_000 });
+ const a = await s.provision(layers);
+ await s.teardown(a);
+ const b = await s.provision(layers);
+ await s.teardown(b);
+ assert.equal(counting.puts(), 1, "second teardown inside the interval skips the snapshot");
+ const scratch = await s.provision(layers, { scratch: { key: "job-snap" } });
+ await s.teardown(scratch);
+ assert.equal(counting.puts(), 1, "scratch machines are never snapshotted");
+});
+
+test("a failing snapshot store is recorded in status and a failed hydration never cold-starts empty", async () => {
+ const flaky = instrumentedSnapshotStore();
+ const errors: string[] = [];
+ const s = make({
+ snapshots: flaky.store,
+ onError: (e: { code: string }) => {
+ errors.push(e.code);
+ },
+ });
+ const a = await s.provision(layers);
+ await s.writeFile(a, "precious.txt", "irreplaceable\n");
+ await s.teardown(a);
+ flaky.failWrites(true);
+ await s.teardown(await s.provision(layers));
+ assert.ok(errors.includes("teardown_snapshot_failed"));
+ assert.match((await s.computerStatus!(scope)).recovery?.error ?? "", /simulated S3 outage/);
+ flaky.failWrites(false);
+ fake.deleteBehindCore(a.id);
+ const restarted = make({ snapshots: flaky.store });
+ flaky.failReads(true);
+ await assert.rejects(restarted.provision(layers), /hydration failed/);
+ assert.equal(fake.machine(a.id), null, "the empty replacement is deleted rather than adopted");
+ flaky.failReads(false);
+ const b = await restarted.provision(layers);
+ assert.equal(await restarted.readFile(b, "precious.txt"), "irreplaceable\n");
+});
+
+test("persistHomeSnapshot exists only with a snapshot store and stores the home on demand", async () => {
+ assert.equal(sandbox.persistHomeSnapshot, undefined);
+ assert.equal((await sandbox.computerStatus!(scope)).recovery, undefined);
+ const snapshots = createMemorySnapshotStore();
+ const s = make({ snapshots });
+ const h = await s.provision(layers);
+ await s.writeFile(h, "explicit.txt", "saved\n");
+ await s.persistHomeSnapshot!(scope);
+ assert.ok(await snapshots.open(scope));
+});
+
+test("computerStatus reports a stopped machine as paused without waking it", async () => {
+ assert.deepEqual(await sandbox.computerStatus!(scope), {
+ machine: "no machine provisioned yet",
+ provisioned: false,
+ guestResponsive: false,
+ });
+ const h = await sandbox.provision(layers);
+ const running = await sandbox.computerStatus!(scope);
+ assert.equal(running.lifecycleState, "running");
+ assert.equal(running.guestResponsive, true);
+ fake.stop(h.id);
+ const execsBefore = fake.calls.filter((c) => c.path.endsWith("/exec")).length;
+ const stopped = await sandbox.computerStatus!(scope);
+ assert.equal(stopped.lifecycleState, "paused");
+ assert.equal(stopped.guestResponsive, false);
+ assert.equal(fake.calls.filter((c) => c.path.endsWith("/exec")).length, execsBefore);
+ assert.equal(fake.machine(h.id)?.state, "stopped");
+ fake.fail(h.id, "auto-start failed: node lost");
+ assert.match((await sandbox.computerStatus!(scope)).machine, /error: auto-start failed: node lost/);
});
test("read and write refuse parent path segments before any provider request", async () => {
@@ -246,3 +441,69 @@ test("exec is never retried and its failure names the request id", async () => {
await assert.rejects(sandbox.run(h, "echo hi"), /smolmachines exec .*: http 502 .*\[request id req-exec\]/);
assert.equal(fake.calls.filter((c) => c.path.endsWith("/exec")).length, before + 1);
});
+
+for (const lostResponse of ["disconnect", "503"] as const) {
+ test(`accepted replacement create with ${lostResponse} restores the home on the next core`, async () => {
+ const snapshots = createMemorySnapshotStore();
+ const store = createMemoryMap<StoredSmolmachinesSandbox>();
+ const advisoryLock = createMemoryAdvisoryLock();
+ const first = make({ snapshots, store, advisoryLock });
+ const original = await first.provision(layers);
+ await first.writeFile(original, "notes.txt", "preserve me");
+ await first.teardown(original);
+ fake.deleteBehindCore(original.id);
+ let inject = true;
+ const fetchImpl: typeof fetch = async (input, init) => {
+ const response = await fake.fetchImpl(input, init);
+ if (inject && init?.method === "POST" && new URL(String(input)).pathname === "/v1/machines") {
+ inject = false;
+ if (lostResponse === "disconnect") throw new TypeError("response lost after create");
+ return new Response("response lost after create", { status: 503 });
+ }
+ return response;
+ };
+ const replacing = make({ snapshots, store, advisoryLock, fetchImpl });
+ await assert.rejects(replacing.provision(layers), /response lost after create/);
+ assert.equal((await store.get(scope))?.initializationPending, true);
+ const next = make({ snapshots, store, advisoryLock });
+ const restored = await next.provision(layers);
+ assert.equal(await next.readFile(restored, "notes.txt"), "preserve me");
+ assert.equal((await store.get(scope))?.initializationPending, undefined);
+ assert.equal(fake.names().length, 1);
+ });
+}
+
+test("destructive teardown waits for another core's lifecycle lock", async () => {
+ const shared = createMemoryAdvisoryLock();
+ const requested = Promise.withResolvers<void>();
+ let destroying = false;
+ const adapter = make({
+ advisoryLock: {
+ withLock: <T>(key: string, run: () => Promise<T>) => {
+ if (destroying) {
+ assert.equal(key, `smolmachines-provision:qmt:${scope}`);
+ requested.resolve();
+ }
+ return shared.withLock(key, run);
+ },
+ },
+ });
+ const handle = await adapter.provision(layers);
+ const held = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const holding = shared.withLock(`smolmachines-provision:qmt:${scope}`, async () => {
+ held.resolve();
+ await release.promise;
+ });
+ await held.promise;
+ destroying = true;
+ const teardown = adapter.teardown(handle, { destroy: true });
+ try {
+ await requested.promise;
+ assert.ok(fake.machine(handle.id));
+ } finally {
+ release.resolve();
+ }
+ await Promise.all([holding, teardown]);
+ assert.equal(fake.machine(handle.id), null);
+});
diff --git a/test/support/fake-smolmachines.ts b/test/support/fake-smolmachines.ts
index 8b7b88776..2abf25bb0 100644
--- a/test/support/fake-smolmachines.ts
+++ b/test/support/fake-smolmachines.ts
@@ -6,15 +6,33 @@ import { dirname, join } from "node:path";
export interface SmolCall {
method: string;
path: string;
+ query?: string;
+ body?: unknown;
script?: string;
}
+export interface FakeMachineView {
+ state: string;
+ ready: boolean;
+ error?: string;
+ ephemeral: boolean;
+ resources?: Record<string, number>;
+ network: unknown;
+ ttlSeconds?: number;
+ autoStopSeconds?: number;
+}
+
interface FakeMachine {
id: string;
name: string | null;
state: string;
+ error?: string;
+ notReadyGets: number;
ephemeral: boolean;
resources?: Record<string, number>;
+ network: unknown;
+ ttlSeconds?: number;
+ autoStopSeconds?: number;
home: string;
}
@@ -23,14 +41,26 @@ export interface InjectedFailure {
match?: (call: { method: string; path: string }) => boolean;
}
+interface CreateBody {
+ name?: string | null;
+ ephemeral?: boolean;
+ resources?: Record<string, number>;
+ network?: unknown;
+ ttlSeconds?: number;
+ autoStopSeconds?: number;
+}
+
export interface FakeSmolmachines {
fetchImpl: typeof fetch;
calls: SmolCall[];
homeDir(name: string): string;
names(): string[];
- machine(name: string): { state: string; ephemeral: boolean; resources?: Record<string, number> } | null;
+ machine(name: string): FakeMachineView | null;
stop(name: string): void;
failNext(status: number, opts?: InjectedFailure): void;
+ fail(name: string, reason: string): void;
+ notReadyFor(name: string, gets: number): void;
+ deleteBehindCore(name: string): void;
execScripts(): string[];
reset(): void;
cleanup(): void;
@@ -48,14 +78,18 @@ export function installFakeSmolmachines(): FakeSmolmachines {
const byName = (name: string): FakeMachine | undefined => [...machines.values()].find((m) => m.name === name);
- const create = (name: string | null, ephemeral: boolean, resources?: Record<string, number>): FakeMachine => {
+ const create = (body: CreateBody): FakeMachine => {
const id = `m-${nextId++}`;
const m: FakeMachine = {
id,
- name,
+ name: body.name ?? null,
state: "stopped",
- ephemeral,
- ...(resources ? { resources } : {}),
+ notReadyGets: 0,
+ ephemeral: body.ephemeral ?? false,
+ ...(body.resources ? { resources: body.resources } : {}),
+ network: body.network ?? { mode: "open" },
+ ...(body.ttlSeconds !== undefined ? { ttlSeconds: body.ttlSeconds } : {}),
+ ...(body.autoStopSeconds !== undefined ? { autoStopSeconds: body.autoStopSeconds } : {}),
home: join(root, id),
};
mkdirSync(m.home, { recursive: true });
@@ -75,38 +109,46 @@ export function installFakeSmolmachines(): FakeSmolmachines {
);
};
- const runExec = (m: FakeMachine, script: string, stdinB64?: string): Response => {
+ const runExec = (m: FakeMachine, script: string, output: string | null): Response => {
execScripts.push(script);
mkdirSync(join(m.home, "tmp"), { recursive: true });
const r = spawnSync("sh", ["-c", remap(m, script)], {
encoding: "buffer",
maxBuffer: 128 * 1024 * 1024,
env: { ...process.env, COPYFILE_DISABLE: "1" },
- ...(stdinB64 !== undefined ? { input: Buffer.from(stdinB64, "utf8") } : {}),
});
const code = r.status ?? (r.signal ? 137 : -1);
const cap = 1024 * 1024;
- const stdout = (r.stdout ?? Buffer.alloc(0)).toString("utf8");
- const stderr = (r.stderr ?? Buffer.alloc(0)).toString("utf8");
+ const stdout = r.stdout ?? Buffer.alloc(0);
+ const stderr = r.stderr ?? Buffer.alloc(0);
+ const text = output !== "b64";
+ const bytes = output !== "text";
return Response.json({
- stdout: stdout.slice(0, cap),
- stderr: stderr.slice(0, cap),
+ stdout: text ? stdout.toString("utf8").slice(0, cap) : "",
+ stderr: text ? stderr.toString("utf8").slice(0, cap) : "",
exitCode: code,
durationMs: 1,
machineId: m.id,
- stdoutTruncated: stdout.length > cap,
- stderrTruncated: stderr.length > cap,
+ stdoutTruncated: text && stdout.length > cap,
+ stderrTruncated: text && stderr.length > cap,
+ ...(bytes ? { stdoutB64: stdout.toString("base64"), stderrB64: stderr.toString("base64") } : {}),
});
};
+ const ready = (m: FakeMachine): boolean => m.state.toLowerCase() === "running" && m.notReadyGets <= 0;
+
const info = (m: FakeMachine) => ({
id: m.id,
name: m.name,
state: m.state,
+ ready: ready(m),
+ error: m.error ?? null,
ephemeral: m.ephemeral,
source: { type: "image", reference: "ubuntu:24.04" },
resources: m.resources ?? {},
- network: { mode: "open" },
+ network: m.network,
+ ttlSeconds: m.ttlSeconds ?? null,
+ autoStopSeconds: m.autoStopSeconds ?? null,
env: {},
createdAt: "2026-01-01T00:00:00Z",
updatedAt: "2026-01-01T00:00:00Z",
@@ -121,7 +163,8 @@ export function installFakeSmolmachines(): FakeSmolmachines {
const fetchImpl: typeof fetch = async (input, init) => {
const url = new URL(typeof input === "string" ? input : input.toString());
const method = init?.method ?? "GET";
- calls.push({ method, path: url.pathname });
+ const call: SmolCall = { method, path: url.pathname, ...(url.search ? { query: url.search.slice(1) } : {}) };
+ calls.push(call);
const at = injected.findIndex((f) => !f.match || f.match({ method, path: url.pathname }));
if (at >= 0) {
const [next] = injected.splice(at, 1);
@@ -131,13 +174,10 @@ export function installFakeSmolmachines(): FakeSmolmachines {
return Response.json([...machines.values()].map(info));
}
if (url.pathname === "/v1/machines" && method === "POST") {
- const body = JSON.parse(toBuf(init?.body).toString() || "{}") as {
- name?: string | null;
- ephemeral?: boolean;
- resources?: Record<string, number>;
- };
+ const body = JSON.parse(toBuf(init?.body).toString() || "{}") as CreateBody;
+ call.body = body;
if (body.name && byName(body.name)) return new Response("machine name conflict", { status: 409 });
- return Response.json(info(create(body.name ?? null, body.ephemeral ?? false, body.resources)), { status: 201 });
+ return Response.json(info(create(body)), { status: 201 });
}
const files = /^\/v1\/machines\/([^/]+)\/files(\/.+)$/.exec(url.pathname);
if (files) {
@@ -163,16 +203,15 @@ export function installFakeSmolmachines(): FakeSmolmachines {
if (!m) return new Response("machine not found", { status: 404 });
if (sub[2] === "exec") {
if (m.state.toLowerCase() !== "running") return new Response("machine is stopped", { status: 409 });
- const body = JSON.parse(toBuf(init?.body).toString() || "{}") as {
- command?: string[] | string;
- stdin?: string;
- };
+ const body = JSON.parse(toBuf(init?.body).toString() || "{}") as { command?: string[] | string };
+ call.body = body;
const argv = Array.isArray(body.command) ? body.command : ["sh", "-c", body.command ?? ""];
const script = argv[argv.length - 1] ?? "";
- calls[calls.length - 1]!.script = script;
- return runExec(m, script, body.stdin);
+ call.script = script;
+ return runExec(m, script, url.searchParams.get("output"));
}
if (sub[2] === "start") {
+ if (m.error) return new Response(`machine failed: ${m.error}`, { status: 409 });
m.state = "Running";
return Response.json(info(m));
}
@@ -180,7 +219,11 @@ export function installFakeSmolmachines(): FakeSmolmachines {
m.state = "stopped";
return Response.json(info(m));
}
- if (method === "GET") return Response.json(info(m));
+ if (method === "GET") {
+ const body = info(m);
+ m.notReadyGets--;
+ return Response.json(body);
+ }
if (method === "DELETE") {
rmSync(m.home, { recursive: true, force: true });
machines.delete(m.id);
@@ -193,11 +236,21 @@ export function installFakeSmolmachines(): FakeSmolmachines {
return {
fetchImpl,
calls,
- homeDir: (name) => (byName(name) ?? create(name, false)).home,
+ homeDir: (name) => (byName(name) ?? create({ name })).home,
names: () => [...machines.values()].map((m) => m.name ?? m.id),
machine: (name) => {
const m = byName(name);
- return m ? { state: m.state, ephemeral: m.ephemeral, ...(m.resources ? { resources: m.resources } : {}) } : null;
+ if (!m) return null;
+ return {
+ state: m.state,
+ ready: ready(m),
+ ...(m.error ? { error: m.error } : {}),
+ ephemeral: m.ephemeral,
+ ...(m.resources ? { resources: m.resources } : {}),
+ network: m.network,
+ ...(m.ttlSeconds !== undefined ? { ttlSeconds: m.ttlSeconds } : {}),
+ ...(m.autoStopSeconds !== undefined ? { autoStopSeconds: m.autoStopSeconds } : {}),
+ };
},
stop: (name) => {
const m = byName(name);
@@ -206,6 +259,22 @@ export function installFakeSmolmachines(): FakeSmolmachines {
failNext: (status, opts = {}) => {
injected.push({ status, ...opts });
},
+ fail: (name, reason) => {
+ const m = byName(name);
+ if (!m) return;
+ m.state = "error";
+ m.error = reason;
+ },
+ notReadyFor: (name, gets) => {
+ const m = byName(name);
+ if (m) m.notReadyGets = gets;
+ },
+ deleteBehindCore: (name) => {
+ const m = byName(name);
+ if (!m) return;
+ rmSync(m.home, { recursive: true, force: true });
+ machines.delete(m.id);
+ },
execScripts: () => [...execScripts],
reset: () => {
for (const m of machines.values()) rmSync(m.home, { recursive: true, force: true });