Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

sandbox: smolmachines backend (#478)

Regan Bell4a1065d834d6
diff --git a/cli/src/secrets.ts b/cli/src/secrets.ts
index ed061840b..11fefbb28 100644
--- a/cli/src/secrets.ts
+++ b/cli/src/secrets.ts
@@ -131,6 +131,13 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
description: "Fly Sprites API token for the agent-computer substrate.",
generate: "sprite login # then copy the token from ~/.sprite/credentials",
},
+ {
+ name: "SMOLMACHINES_TOKEN",
+ service: "core",
+ required: { when: { kind: "env-equals", service: "core", name: "SANDBOX_BACKEND", value: "smolmachines" } },
+ description: "smolmachines API key for the agent-computer substrate.",
+ generate: "create an API key in the smolmachines console (https://smolmachines.com/console)",
+ },
{
name: "DATABASE_URL",
service: "core",
diff --git a/scripts/dev/cli.ts b/scripts/dev/cli.ts
index 869da576f..61e051060 100644
--- a/scripts/dev/cli.ts
+++ b/scripts/dev/cli.ts
@@ -245,7 +245,7 @@ async function bootOnSlot(slot: string, worktree: string, branch: string): Promi
branch,
callerEnv,
watch: !opts["no-watch"] && callerEnv.DEV_INSTANCE_WATCH !== "0",
- sandbox: opts.sandbox as "local" | "sprites" | "auto",
+ sandbox: opts.sandbox as "local" | "sprites" | "smolmachines" | "auto",
canaryChannel,
strict: opts.strict,
slack: withSlack,
@@ -644,7 +644,7 @@ async function main(): Promise<number> {
return await runDoctor({ json: opts.json, fix: opts.fix, store, slack: withSlack });
default:
console.error(
- "usage: dev [up|down|status|restart|canary|logs|doctor] [--json] [--force] [--rotate] [--strict] [--sandbox local|sprites|auto] [--no-slack] [--no-watch] [--org id] [--fix]",
+ "usage: dev [up|down|status|restart|canary|logs|doctor] [--json] [--force] [--rotate] [--strict] [--sandbox local|sprites|smolmachines|auto] [--no-slack] [--no-watch] [--org id] [--fix]",
);
return EXIT.usage;
}
diff --git a/scripts/dev/lib/sandbox.ts b/scripts/dev/lib/sandbox.ts
index 23d747783..fc22780b4 100644
--- a/scripts/dev/lib/sandbox.ts
+++ b/scripts/dev/lib/sandbox.ts
@@ -7,7 +7,7 @@ import { ensureDockerDaemon } from "./postgres.ts";
import { bestEffortValue, sleep } from "./util.ts";
export interface SandboxResolution {
- backend: "local" | "sprites";
+ backend: "local" | "sprites" | "smolmachines";
env: Record<string, string>;
detail: string;
publicApiUrl: string | null;
@@ -24,7 +24,7 @@ async function localImagePresent(image: string): Promise<boolean> {
export async function resolveSandbox(opts: {
worktree: string;
- requested: "local" | "sprites" | "auto";
+ requested: "local" | "sprites" | "smolmachines" | "auto";
corePort: number;
lock: string;
baseEnv: Record<string, string>;
@@ -63,6 +63,42 @@ export async function resolveSandbox(opts: {
};
}
+ if (backend === "smolmachines") {
+ const smolToken = opts.baseEnv.SMOLMACHINES_TOKEN;
+ if (!smolToken)
+ throw new Error(
+ "--sandbox smolmachines requires SMOLMACHINES_TOKEN in the environment (create an API key in the smolmachines console)",
+ );
+ let smolApiUrl = opts.baseEnv.PUBLIC_API_URL || null;
+ if (!smolApiUrl) {
+ smolApiUrl = await startQuickTunnel(opts.corePort, opts.lock, opts.log);
+ if (!smolApiUrl)
+ warnings.push(
+ "cloudflared tunnel didn't come up -- agent self-API (crons/sends) won't be reachable from the sandbox",
+ );
+ }
+ const smolEnv: Record<string, string> = {
+ SANDBOX_BACKEND: "smolmachines",
+ SMOLMACHINES_TOKEN: smolToken,
+ SMOLMACHINES_NAME_PREFIX: opts.baseEnv.SMOLMACHINES_NAME_PREFIX || "qmdev",
+ };
+ if (opts.baseEnv.SMOLMACHINES_IMAGE) smolEnv.SMOLMACHINES_IMAGE = opts.baseEnv.SMOLMACHINES_IMAGE;
+ if (opts.baseEnv.SMOLMACHINES_EGRESS_PROXY_URL)
+ smolEnv.SMOLMACHINES_EGRESS_PROXY_URL = opts.baseEnv.SMOLMACHINES_EGRESS_PROXY_URL;
+ else
+ warnings.push(
+ "SMOLMACHINES_EGRESS_PROXY_URL unset -- smolmachines sandbox runs with NO egress enforcement; set it to QA the forced-proxy path",
+ );
+ if (smolApiUrl) smolEnv.PUBLIC_API_URL = smolApiUrl;
+ return {
+ backend: "smolmachines",
+ env: smolEnv,
+ detail: "smolmachines (api.smolmachines.com)",
+ publicApiUrl: smolApiUrl,
+ warnings,
+ };
+ }
+
const token = opts.baseEnv.SPRITES_TOKEN;
if (!token)
throw new Error("--sandbox sprites requires SPRITES_TOKEN in the environment (mint one with `sprite login`)");
diff --git a/scripts/dev/lib/types.ts b/scripts/dev/lib/types.ts
index b424eb2f9..13ee9a549 100644
--- a/scripts/dev/lib/types.ts
+++ b/scripts/dev/lib/types.ts
@@ -108,7 +108,7 @@ export interface BootSpec {
branch: string;
callerEnv: Record<string, string>;
watch: boolean;
- sandbox: "local" | "sprites" | "auto";
+ sandbox: "local" | "sprites" | "smolmachines" | "auto";
canaryChannel?: string;
strict: boolean;
slack?: boolean;
diff --git a/src/api/deps.ts b/src/api/deps.ts
index f283740fa..db0d27142 100644
--- a/src/api/deps.ts
+++ b/src/api/deps.ts
@@ -106,6 +106,7 @@ export interface ServerDeps {
sandboxBackend?: string;
egressDeclaredEnforcement?: EgressEnforcement;
egressEnforcement?: EgressEnforcement;
+ egressControlPlaneConfigured?: boolean;
sandboxMigration?: SandboxMigrationRunner;
sandbox?: Sandbox;
advisoryLock?: AdvisoryLock;
diff --git a/src/api/routes/admin/scope-config.ts b/src/api/routes/admin/scope-config.ts
index 17d206168..31ce5a434 100644
--- a/src/api/routes/admin/scope-config.ts
+++ b/src/api/routes/admin/scope-config.ts
@@ -280,8 +280,11 @@ export async function getScopeConfig(ctx: ApiCtx): Promise<void> {
for (const r of ADMIN_RESOURCES) {
if (r.readKey && r.get) values[r.readKey] = await r.get(deps, targetScope);
}
- const declaredEgress = deps.egressDeclaredEnforcement ?? deps.egressEnforcement ?? "none";
- const effectiveEgressFidelity = deps.egressEnforcement ?? "none";
+ const scopeProfile = (await deps.sandbox?.profileFor?.(targetScope)) ?? deps.sandbox?.profile;
+ const declaredEgress =
+ scopeProfile?.egressEnforcement ?? deps.egressDeclaredEnforcement ?? deps.egressEnforcement ?? "none";
+ const controlPlaneConfigured = deps.egressControlPlaneConfigured ?? deps.egressEnforcement === declaredEgress;
+ const effectiveEgressFidelity = controlPlaneConfigured ? declaredEgress : "none";
let egressReason = "ready";
if (declaredEgress !== "domain") egressReason = "backend_unsupported";
else if (effectiveEgressFidelity !== "domain") egressReason = "control_plane_unconfigured";
@@ -332,7 +335,7 @@ export async function getScopeConfig(ctx: ApiCtx): Promise<void> {
modelServiceable(m.id, providersFor(deps.harnessId ?? "pi")),
),
egressEnforcement: {
- backend: deps.sandboxBackend ?? "unknown",
+ backend: scopeProfile?.backend ?? deps.sandboxBackend ?? "unknown",
declaredFidelity: declaredEgress,
effectiveFidelity: effectiveEgressFidelity,
fidelity: effectiveEgressFidelity,
diff --git a/src/config.ts b/src/config.ts
index 16e85a7b6..9f7de1bde 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -31,8 +31,8 @@ export interface Config {
databaseUrl?: string;
harness: "mock" | "pi" | "opencode" | "codex" | "claude";
securityPosture: SecurityPosture;
- sandboxBackend: "aws" | "local" | "sprites";
- sandboxSecondaryBackend?: "aws" | "local" | "sprites";
+ sandboxBackend: "aws" | "local" | "sprites" | "smolmachines";
+ sandboxSecondaryBackend?: "aws" | "local" | "sprites" | "smolmachines";
deployProvider: "docker" | "aws";
egressServiceHosts?: string[];
brandingDefault?: { accent?: string; mark?: string; selfLabel?: string };
@@ -142,6 +142,7 @@ export interface Config {
awsSandbox: AwsSandboxEnv;
localSandbox: LocalSandboxEnv;
spritesSandbox: SpritesSandboxEnv;
+ smolmachinesSandbox: SmolmachinesSandboxEnv;
awsDeploy: AwsDeployEnv;
}
@@ -283,6 +284,28 @@ function spritesSandboxEnv(env: NodeJS.ProcessEnv): SpritesSandboxEnv {
};
}
+interface SmolmachinesSandboxEnv {
+ token?: string;
+ baseUrl?: string;
+ namePrefix?: string;
+ image?: string;
+ egressProxyUrl?: string;
+ defaultTimeoutSec?: number;
+}
+
+function smolmachinesSandboxEnv(env: NodeJS.ProcessEnv): SmolmachinesSandboxEnv {
+ return {
+ ...(env.SMOLMACHINES_TOKEN ? { token: env.SMOLMACHINES_TOKEN } : {}),
+ ...(env.SMOLMACHINES_BASE_URL ? { baseUrl: env.SMOLMACHINES_BASE_URL } : {}),
+ ...(env.SMOLMACHINES_NAME_PREFIX ? { namePrefix: env.SMOLMACHINES_NAME_PREFIX } : {}),
+ ...(env.SMOLMACHINES_IMAGE ? { image: env.SMOLMACHINES_IMAGE } : {}),
+ ...(env.SMOLMACHINES_EGRESS_PROXY_URL ? { egressProxyUrl: env.SMOLMACHINES_EGRESS_PROXY_URL } : {}),
+ ...(numEnvStrict("SANDBOX_TIMEOUT_SEC", env.SANDBOX_TIMEOUT_SEC) !== undefined
+ ? { defaultTimeoutSec: numEnvStrict("SANDBOX_TIMEOUT_SEC", env.SANDBOX_TIMEOUT_SEC) }
+ : {}),
+ };
+}
+
interface AwsDeployEnv {
region: string;
profile?: string;
@@ -476,8 +499,10 @@ function harnessEnvStrict(value: string | undefined): Config["harness"] {
function sandboxBackendEnvStrict(value: string | undefined, name = "SANDBOX_BACKEND"): Config["sandboxBackend"] {
if (value === undefined || value.trim() === "") return "local";
const backend = value.trim();
- if (backend === "aws" || backend === "local" || backend === "sprites") return backend;
- throw new Error(`${name}=${JSON.stringify(value)} is not recognized — use aws, local, or sprites, or unset it.`);
+ if (backend === "aws" || backend === "local" || backend === "sprites" || backend === "smolmachines") return backend;
+ throw new Error(
+ `${name}=${JSON.stringify(value)} is not recognized — use aws, local, sprites, or smolmachines, or unset it.`,
+ );
}
function secretsBackendEnvStrict(value: string | undefined, prefix: string): Config["secretsBackend"] {
@@ -579,7 +604,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
}
const dataDir = resolve(env.DATA_DIR ?? "./data");
if (env.NODE_ENV === "production" && !env.SANDBOX_BACKEND?.trim()) {
- throw new Error("SANDBOX_BACKEND must be set explicitly in production — use sprites, aws, or local.");
+ throw new Error("SANDBOX_BACKEND must be set explicitly in production — use sprites, smolmachines, aws, or local.");
}
const sandboxBackend = sandboxBackendEnvStrict(env.SANDBOX_BACKEND);
const secondaryRaw = env.SANDBOX_SECONDARY_BACKEND?.trim();
@@ -854,6 +879,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
awsSandbox: awsSandboxEnv(env),
localSandbox: localSandboxEnv(env),
spritesSandbox: spritesSandboxEnv(env),
+ smolmachinesSandbox: smolmachinesSandboxEnv(env),
awsDeploy: awsDeployEnv(env),
};
}
diff --git a/src/deployment/secret-schema.ts b/src/deployment/secret-schema.ts
index 47e2e86fa..265cc4258 100644
--- a/src/deployment/secret-schema.ts
+++ b/src/deployment/secret-schema.ts
@@ -5,6 +5,7 @@ type SecretGate =
| "codex"
| "postgres"
| "sprites"
+ | "smolmachines"
| "fly-sandbox"
| "fly-deploy"
| "aws-deploy-gate"
@@ -31,6 +32,7 @@ export const CORE_SECRET_SPECS: readonly RuntimeSecretSpec[] = [
{ name: "OPENROUTER_API_KEY", requiredWhen: "model-openrouter" },
{ name: "DATABASE_URL", requiredWhen: "postgres" },
{ name: "SPRITES_TOKEN", requiredWhen: "sprites" },
+ { name: "SMOLMACHINES_TOKEN", requiredWhen: "smolmachines" },
{ name: "FLY_API_TOKEN", requiredWhen: "fly-sandbox" },
{ name: "FLY_DEPLOY_API_TOKEN", requiredWhen: "fly-deploy" },
{ name: "AWS_DEPLOY_GATE_SECRET", requiredWhen: "aws-deploy-gate" },
@@ -44,6 +46,7 @@ const GATE_PREDICATES: Readonly<Record<SecretGate, (env: NodeJS.ProcessEnv) => b
codex: (env) => env.HARNESS?.trim() === "codex",
postgres: (env) => env.SESSION_STORE === "postgres" || env.RUN_STORE === "postgres",
sprites: (env) => env.SANDBOX_BACKEND === "sprites" || env.SANDBOX_SECONDARY_BACKEND === "sprites",
+ smolmachines: (env) => env.SANDBOX_BACKEND === "smolmachines" || env.SANDBOX_SECONDARY_BACKEND === "smolmachines",
"fly-sandbox": (env) => env.SANDBOX_BACKEND === "fly",
"fly-deploy": (env) => env.DEPLOY_PROVIDER === "fly",
"aws-deploy-gate": (env) => Boolean(env.AWS_DEPLOY_APPS_DOMAIN),
diff --git a/src/index.ts b/src/index.ts
index 5472f3368..f7146d3cf 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -82,6 +82,7 @@ const server = createServer(built.app, {
signingSecret: config.signingSecret,
apiBaseUrl: config.apiBaseUrl,
}),
+ egressControlPlaneConfigured: Boolean(config.signingSecret && config.apiBaseUrl),
sandbox: built.sandbox,
advisoryLock: built.advisoryLock,
...(built.processes ? { processes: built.processes } : {}),
diff --git a/src/sandbox/sandbox-env.ts b/src/sandbox/sandbox-env.ts
index de5e291c6..9980cf05a 100644
--- a/src/sandbox/sandbox-env.ts
+++ b/src/sandbox/sandbox-env.ts
@@ -27,6 +27,20 @@ export const DROPPED_PROXY_ENV = new Set([
"NO_PROXY",
]);
+export function forceThroughProxyEnv(egressProxyUrl: string, token: string): Record<string, string> {
+ const u = new URL(egressProxyUrl);
+ const url = `${u.protocol}//x:${token}@${u.host}`;
+ const noProxy = "localhost,127.0.0.1,::1";
+ return {
+ HTTPS_PROXY: url,
+ HTTP_PROXY: url,
+ NO_PROXY: noProxy,
+ https_proxy: url,
+ http_proxy: url,
+ no_proxy: noProxy,
+ };
+}
+
export function proxyExportPrefix(handle: SandboxHandle): string {
const picked = Object.entries(handle.env ?? {}).filter(([key]) => DROPPED_PROXY_ENV.has(key));
if (!picked.length) return "";
diff --git a/src/sandbox/sandbox-routing.ts b/src/sandbox/sandbox-routing.ts
index 3f90fc073..ccfb75e74 100644
--- a/src/sandbox/sandbox-routing.ts
+++ b/src/sandbox/sandbox-routing.ts
@@ -14,7 +14,7 @@ import {
type TeardownOptions,
} from "./sandbox.ts";
-export type SandboxBackendName = "sprites" | "aws" | "local";
+export type SandboxBackendName = "sprites" | "aws" | "local" | "smolmachines";
export interface SandboxRoute {
backend: SandboxBackendName;
diff --git a/src/sandbox/smolmachines-sandbox.ts b/src/sandbox/smolmachines-sandbox.ts
new file mode 100644
index 000000000..cf3809441
--- /dev/null
+++ b/src/sandbox/smolmachines-sandbox.ts
@@ -0,0 +1,572 @@
+import { randomUUID } from "node:crypto";
+import type { WorkspaceLayer } from "../types.ts";
+import type { WorkspaceStore } from "../workspace/workspace-store.ts";
+import { createKeyedQueue, sleep } from "../util/async.ts";
+import { swallowAs, errMessage } from "../util/errors.ts";
+import { shq } from "../util/shell.ts";
+import { nonInteractiveShellPrefix } from "./sandbox-env.ts";
+import { createExecProcessSessions, type ExecProcessIo } from "./exec-process-session.ts";
+import { materializeRoLayers } from "./ro-layers.ts";
+import {
+ BLOB_TRANSFER_TTL_MS,
+ createExecBackup,
+ createExecBlobStaging,
+ createExecFileOps,
+ posixJoin,
+} from "./exec-file-ops.ts";
+import {
+ ephemeralCredLinkScript,
+ ephemeralCredLinkPaths,
+ type CredentialPathSpec,
+} from "../credentials/resident-paths.ts";
+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 { CAPABILITY_HEADER } from "../api/contract.ts";
+import { killableScript, killScript } from "./exec-kill.ts";
+import { visibleNotInstalled, visibleTools } from "./sandbox.ts";
+import { spriteScopeName } from "./sprites-sandbox.ts";
+import type {
+ AgentComputerProfile,
+ ExecOptions,
+ ExecResult,
+ ProvisionOptions,
+ Sandbox,
+ SandboxHandle,
+ TeardownOptions,
+} from "./sandbox.ts";
+
+const HOME_DIR = "/root";
+const WORKSPACE_BASENAME = "workspace";
+const RO_LAYERS_TAR = ".ro-layers.tar";
+const RO_LAYERS_MANIFEST = ".ro-layers.manifest";
+const INLINE_LIMIT = 256 * 1024;
+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 DEFAULT_SMOLMACHINES_BASE_URL = "https://api.smolmachines.com";
+const DEFAULT_IMAGE = "codex";
+const RUNNING_STATES = new Set(["running", "started", "ready"]);
+
+interface MachineInfo {
+ id: string;
+ name?: string | null;
+ state: string;
+}
+
+interface MachineExecResponse {
+ stdout: string;
+ stderr: string;
+ exitCode: number;
+ stdoutTruncated?: boolean;
+ stderrTruncated?: boolean;
+}
+
+export interface SmolmachinesSandboxOptions {
+ token?: string;
+ baseUrl?: string;
+ namePrefix?: string;
+ image?: string;
+ defaultTimeoutSec?: number;
+ egressProxyUrl?: string;
+ blobTransfer?: BlobTransferStore;
+ signingSecret?: string;
+ capabilitySecret?: string;
+ apiBaseUrl?: string;
+ extraTools?: string[];
+ credentialPaths?: CredentialPathSpec[];
+ fetchImpl?: typeof fetch;
+ onError?: (e: { category: string; code: string; message: string; scopeLabel?: string }) => void;
+}
+
+export function createSmolmachinesSandbox(workspace: WorkspaceStore, opts: SmolmachinesSandboxOptions = {}): Sandbox {
+ if (!opts.token && !opts.fetchImpl) throw new Error("SANDBOX_BACKEND=smolmachines requires SMOLMACHINES_TOKEN");
+ const fetchImpl = opts.fetchImpl ?? fetch;
+ const baseUrl = (opts.baseUrl ?? DEFAULT_SMOLMACHINES_BASE_URL).replace(/\/+$/, "");
+ const prefix = opts.namePrefix ?? "qm";
+ const image = opts.image ?? DEFAULT_IMAGE;
+ const defaultTimeoutSec = opts.defaultTimeoutSec ?? 600;
+ const workspaceDir = `${HOME_DIR}/${WORKSPACE_BASENAME}`;
+ const provisionQueue = createKeyedQueue<string>();
+
+ const idByName = new Map<string, string>();
+ const scopeByName = new Map<string, string>();
+ const scratchKeyByName = new Map<string, string>();
+ const activeScratch = new Map<string, number>();
+
+ async function api(method: string, path: string, body?: unknown, timeoutMs = 60_000): Promise<Response> {
+ const res = await fetchImpl(`${baseUrl}${path}`, {
+ method,
+ headers: {
+ authorization: `Bearer ${opts.token ?? ""}`,
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
+ },
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ return res;
+ }
+
+ async function apiJson<T>(method: string, path: string, body?: unknown, timeoutMs = 60_000): Promise<T> {
+ const res = await api(method, path, body, timeoutMs);
+ if (!res.ok) {
+ throw new Error(`smolmachines ${method} ${path}: http ${res.status} ${(await res.text()).slice(0, 200)}`);
+ }
+ return (await res.json()) as T;
+ }
+
+ async function findMachine(name: string): Promise<MachineInfo | null> {
+ const machines = await apiJson<MachineInfo[]>("GET", "/v1/machines");
+ return machines.find((m) => m.name === name) ?? null;
+ }
+
+ async function awaitRunning(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})`);
+ await sleep(READY_POLL_MS);
+ }
+ }
+
+ async function createMachine(name: string, ephemeral: boolean): Promise<{ info: MachineInfo; created: boolean }> {
+ const res = await api("POST", "/v1/machines", {
+ name,
+ source: { type: "image", reference: image },
+ network: { mode: "open" },
+ workdir: HOME_DIR,
+ ephemeral,
+ });
+ if (res.status === 409) {
+ const existing = await findMachine(name);
+ if (!existing) throw new Error(`smolmachines create ${name}: http 409 but the machine is not listed`);
+ await startMachine(existing.id);
+ return { info: existing, created: false };
+ }
+ if (!res.ok) {
+ throw new Error(`smolmachines create ${name}: http ${res.status} ${(await res.text()).slice(0, 200)}`);
+ }
+ const info = (await res.json()) as MachineInfo;
+ await startMachine(info.id);
+ return { info, created: true };
+ }
+
+ async function startMachine(id: string): Promise<void> {
+ const res = await api("POST", `/v1/machines/${encodeURIComponent(id)}/start`);
+ if (!res.ok && res.status !== 409) {
+ throw new Error(`smolmachines start ${id}: http ${res.status} ${(await res.text()).slice(0, 200)}`);
+ }
+ await awaitRunning(id);
+ }
+
+ async function machineIdFor(name: string): Promise<string> {
+ const cached = idByName.get(name);
+ if (cached) return cached;
+ const found = await findMachine(name);
+ if (!found) throw new Error(`smolmachines machine ${name}: not found`);
+ idByName.set(name, found.id);
+ return found.id;
+ }
+
+ async function deleteMachine(name: string): Promise<void> {
+ const found = idByName.get(name) ?? (await findMachine(name))?.id;
+ idByName.delete(name);
+ if (!found) return;
+ const res = await api("DELETE", `/v1/machines/${encodeURIComponent(found)}`);
+ if (!res.ok && res.status !== 404) {
+ throw new Error(`smolmachines delete ${name}: http ${res.status} ${(await res.text()).slice(0, 200)}`);
+ }
+ }
+
+ async function postExec(
+ name: string,
+ script: string,
+ timeoutSec: number,
+ stdinB64?: string,
+ ): Promise<MachineExecResponse> {
+ 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 api("POST", `/v1/machines/${encodeURIComponent(id)}/exec`, body, timeoutMs);
+ let res = first;
+ if (!first.ok) {
+ const detail = (await first.text()).slice(0, 200);
+ if (first.status === 404) idByName.delete(name);
+ if (first.status !== 409 && first.status !== 404 && !/stopped|suspended/i.test(detail)) {
+ throw new Error(`smolmachines exec ${name}: http ${first.status} ${detail}`);
+ }
+ const retryId = await machineIdFor(name);
+ await startMachine(retryId);
+ res = await api("POST", `/v1/machines/${encodeURIComponent(retryId)}/exec`, body, timeoutMs);
+ if (!res.ok) {
+ throw new Error(`smolmachines exec ${name}: http ${res.status} ${(await res.text()).slice(0, 200)}`);
+ }
+ }
+ 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 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);
+ }
+
+ async function execRaw(name: string, script: string, timeoutSec: number): Promise<ExecResult> {
+ 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 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)`,
+ );
+ }
+ } 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),
+ );
+ }
+ return { stdout: outBuf.toString("utf8"), stderr: errBuf.toString("utf8"), code, timedOut: code === 124 };
+ }
+
+ async function writeAbsBytes(name: string, absPath: string, data: Uint8Array): Promise<void> {
+ const id = await machineIdFor(name);
+ const res = await fetchImpl(`${baseUrl}${filesUrl(id, absPath)}`, {
+ method: "PUT",
+ headers: { authorization: `Bearer ${opts.token ?? ""}`, "content-type": "application/octet-stream" },
+ body: Buffer.from(data),
+ signal: AbortSignal.timeout(FILE_TRANSFER_TIMEOUT_MS),
+ });
+ if (!res.ok) {
+ throw new Error(`smolmachines write ${absPath}: http ${res.status} ${(await res.text()).slice(0, 200)}`);
+ }
+ }
+
+ async function readAbsBytes(name: string, absPath: string): Promise<Uint8Array | null> {
+ const id = await machineIdFor(name);
+ const res = await fetchImpl(`${baseUrl}${filesUrl(id, absPath)}`, {
+ headers: { authorization: `Bearer ${opts.token ?? ""}` },
+ signal: AbortSignal.timeout(FILE_TRANSFER_TIMEOUT_MS),
+ });
+ if (res.status === 404) return null;
+ if (!res.ok) {
+ throw new Error(`smolmachines read ${absPath}: http ${res.status} ${(await res.text()).slice(0, 200)}`);
+ }
+ return new Uint8Array(await res.arrayBuffer());
+ }
+
+ async function ensureMachine(
+ key: string,
+ name: string,
+ onStatus?: (text: string) => void,
+ ): Promise<{ coldStart: boolean }> {
+ return provisionQueue(key, async () => {
+ 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)) 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 };
+ });
+ }
+
+ async function ensureScratch(key: string): Promise<{ name: string; coldStart: boolean }> {
+ const name = spriteScopeName(`${prefix}-scratch`, key);
+ return provisionQueue(`scratch:${key}`, async () => {
+ scratchKeyByName.set(name, key);
+ const active = activeScratch.get(name) ?? 0;
+ if (active === 0 && !idByName.has(name)) {
+ await deleteMachine(name).catch(swallowAs("smolmachines-sandbox: stale scratch delete", undefined));
+ const { info } = await createMachine(name, true);
+ idByName.set(name, info.id);
+ }
+ activeScratch.set(name, active + 1);
+ return { name, coldStart: active === 0 };
+ });
+ }
+
+ const profile: AgentComputerProfile = {
+ backend: "smolmachines",
+ writablePersistence: "resident_disk",
+ processSessions: true,
+ egressEnforcement: "none",
+ spec: {
+ os: "Debian 12 — smolmachines microVM (auto-stops when idle; the whole disk persists)",
+ runtimes: ["Node", "Python 3"],
+ get tools() {
+ return visibleTools(["git", "curl", "jq", "tar", "python3", ...(opts.extraTools ?? [])]);
+ },
+ get notInstalled() {
+ return visibleNotInstalled(["gh", "aws", "gcloud", "kubectl", "flyctl", "glab"], opts.extraTools ?? []);
+ },
+ homeDir: HOME_DIR,
+ workdir: workspaceDir,
+ },
+ };
+
+ const procIo: ExecProcessIo = {
+ async run(handle, command, execOpts): Promise<ExecResult> {
+ const timeoutSec = execOpts?.timeoutMs ? Math.ceil(execOpts.timeoutMs / 1000) : defaultTimeoutSec;
+ return execRaw(handle.id, command, timeoutSec);
+ },
+ };
+ const procSessions = createExecProcessSessions(procIo);
+
+ const execFileOps = createExecFileOps({
+ label: "smolmachines",
+ exec: (id, script, t) => execRaw(id, script, t),
+ writeInline: (id, abs, data) => writeAbsBytes(id, abs, data),
+ });
+
+ const blobSigningSecret = opts.capabilitySecret ?? opts.signingSecret;
+ const blobStaging =
+ opts.blobTransfer && blobSigningSecret && opts.apiBaseUrl
+ ? createExecBlobStaging({
+ label: "smolmachines",
+ exec: (id, script, t) => execRaw(id, script, t),
+ proxyPrefix: proxyExportPrefix,
+ apiBaseUrl: opts.apiBaseUrl,
+ capabilityHeader: CAPABILITY_HEADER,
+ mintToken: (grant) =>
+ mintCapabilityToken(
+ {
+ actorId: "smolmachines-sandbox",
+ aud: BLOB_TRANSFER_AUD,
+ scopeId: "personal:smolmachines-sandbox",
+ blob: grant,
+ exp: Date.now() + BLOB_TRANSFER_TTL_MS,
+ },
+ blobSigningSecret,
+ ),
+ })
+ : null;
+
+ const execBackup = createExecBackup({
+ label: "smolmachines",
+ exec: (id, script, t) => execRaw(id, script, t),
+ readAbsBytes,
+ defaultHomeDir: HOME_DIR,
+ ephemeralCredentialPrefixes: ephemeralCredLinkPaths(opts.credentialPaths ?? []).map(({ rel }) => rel),
+ });
+
+ const sandbox: Sandbox = {
+ profile,
+ startProcess: procSessions.startProcess,
+ readProcess: procSessions.readProcess,
+ writeStdin: procSessions.writeStdin,
+ signalProcess: procSessions.signalProcess,
+ listProcesses: procSessions.listProcesses,
+ ...execFileOps,
+ ...(blobStaging
+ ? {
+ async stageIn(handle: SandboxHandle, destRelPath: string, blobId: string): Promise<void> {
+ await blobStaging.stageInAbs(handle, posixJoin(handle.rootDir, destRelPath), blobId);
+ },
+ async stageOut(handle: SandboxHandle, srcRelPath: string): Promise<string> {
+ return blobStaging.stageOutAbs(handle, posixJoin(handle.rootDir, srcRelPath));
+ },
+ }
+ : {}),
+
+ async provision(layers: WorkspaceLayer[], provOpts?: ProvisionOptions): Promise<SandboxHandle> {
+ const scratch = provOpts?.scratch;
+ const writable = layers.find((l) => l.mode === "rw") ?? layers[0];
+ const scope = writable?.scopeId ?? "default";
+ let name: string;
+ let coldStart: boolean;
+ if (scratch) {
+ ({ name, coldStart } = await ensureScratch(scratch.key));
+ } else {
+ name = spriteScopeName(prefix, scope);
+ scopeByName.set(name, scope);
+ ({ coldStart } = await ensureMachine(scope, name, provOpts?.onStatus));
+ }
+
+ const forceEgress = !!opts.egressProxyUrl && !!provOpts?.egressToken;
+ const turnEnv = Object.fromEntries(
+ Object.entries(provOpts?.env ?? {}).filter(([k]) => !DROPPED_PROXY_ENV.has(k)),
+ );
+ const env = {
+ ...turnEnv,
+ ...(forceEgress ? forceThroughProxyEnv(opts.egressProxyUrl!, provOpts!.egressToken!) : {}),
+ };
+ const handle: SandboxHandle = {
+ id: name,
+ rootDir: workspaceDir,
+ homeDir: HOME_DIR,
+ coldStart,
+ ...(scratch ? { scratch: true } : {}),
+ ...(Object.keys(env).length ? { env } : {}),
+ };
+
+ try {
+ const credLinks = scratch ? "" : ` && ${ephemeralCredLinkScript(HOME_DIR, opts.credentialPaths ?? [])}`;
+ const prep = await execRaw(name, `mkdir -p ${shq(workspaceDir)}${credLinks}`, 60);
+ if (prep.code !== 0)
+ throw new Error(`smolmachines provision prep failed: ${(prep.stderr || prep.stdout).slice(0, 200)}`);
+
+ await materializeRoLayers(
+ workspace,
+ layers,
+ handle,
+ {
+ readFile: (h, rel) => sandbox.readFile(h, rel),
+ writeFileBytes: (h, rel, data) => sandbox.writeFileBytes(h, rel, data),
+ exec: (script, t) => execRaw(name, script, t),
+ },
+ { manifest: RO_LAYERS_MANIFEST, tar: RO_LAYERS_TAR, label: "smolmachines" },
+ );
+
+ return handle;
+ } catch (err) {
+ await sandbox
+ .teardown(handle)
+ .catch(swallowAs("smolmachines-sandbox: teardown after failed provision", undefined));
+ throw err;
+ }
+ },
+
+ async run(handle, command, execOpts?: ExecOptions): Promise<ExecResult> {
+ const timeoutSec = execOpts?.timeoutMs ? Math.ceil(execOpts.timeoutMs / 1000) : defaultTimeoutSec;
+ const exports = Object.entries(handle.env ?? {})
+ .map(([k, v]) => `export ${k}=${shq(v)}`)
+ .join("; ");
+ const script = `${nonInteractiveShellPrefix()}${exports ? exports + "; " : ""}cd ${handle.rootDir} 2>/dev/null; ${command}`;
+ const signal = execOpts?.signal;
+ if (!signal) return execRaw(handle.id, script, timeoutSec);
+ const killUid = randomUUID();
+ const fireKill = () => {
+ execRaw(handle.id, killScript(killUid), 15).catch(
+ swallowAs("smolmachines-sandbox: kill in-flight exec", undefined),
+ );
+ };
+ if (signal.aborted) fireKill();
+ const onAbort = () => fireKill();
+ signal.addEventListener("abort", onAbort, { once: true });
+ try {
+ return await execRaw(handle.id, killableScript(script, killUid), timeoutSec);
+ } finally {
+ signal.removeEventListener("abort", onAbort);
+ }
+ },
+
+ async writeFileBytes(handle, relPath, data): Promise<void> {
+ await writeAbsBytes(handle.id, posixJoin(handle.rootDir, relPath), data);
+ },
+ async writeFile(handle, relPath, data): Promise<void> {
+ await sandbox.writeFileBytes(handle, relPath, Buffer.from(data, "utf8"));
+ },
+ async readFileBytes(handle, relPath): Promise<Uint8Array | null> {
+ return readAbsBytes(handle.id, posixJoin(handle.rootDir, relPath));
+ },
+ async readFile(handle, relPath): Promise<string | null> {
+ const bytes = await sandbox.readFileBytes(handle, relPath);
+ return bytes === null ? null : Buffer.from(bytes).toString("utf8");
+ },
+
+ backupComputer: execBackup.backupComputer,
+
+ async teardown(handle, tdOpts?: TeardownOptions): Promise<void> {
+ if (handle.scratch) {
+ const key = scratchKeyByName.get(handle.id);
+ return provisionQueue(key ? `scratch:${key}` : handle.id, async () => {
+ const remaining = (activeScratch.get(handle.id) ?? 1) - 1;
+ if (remaining > 0) {
+ activeScratch.set(handle.id, remaining);
+ return;
+ }
+ activeScratch.delete(handle.id);
+ if (tdOpts?.destroy) await deleteMachine(handle.id);
+ else await deleteMachine(handle.id).catch(swallowAs("smolmachines-sandbox: scratch delete", undefined));
+ });
+ }
+ if (!tdOpts?.destroy) return;
+ await deleteMachine(handle.id).catch((e) => {
+ const scope = scopeByName.get(handle.id);
+ opts.onError?.({
+ category: "sandbox_teardown",
+ code: "machine_delete_failed",
+ message: errMessage(e),
+ ...(scope ? { scopeLabel: scope } : {}),
+ });
+ });
+ },
+ };
+
+ return sandbox;
+}
diff --git a/src/sandbox/sprites-sandbox.ts b/src/sandbox/sprites-sandbox.ts
index 9908b0399..c9fd517be 100644
--- a/src/sandbox/sprites-sandbox.ts
+++ b/src/sandbox/sprites-sandbox.ts
@@ -16,7 +16,7 @@ import {
posixJoin,
} from "./exec-file-ops.ts";
import { ephemeralCredLinkScript, type CredentialPathSpec } from "../credentials/resident-paths.ts";
-import { DROPPED_PROXY_ENV, proxyExportPrefix } from "./sandbox-env.ts";
+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 { CAPABILITY_HEADER } from "../api/contract.ts";
@@ -206,20 +206,6 @@ export function createSpritesSandbox(workspace: WorkspaceStore, opts: SpritesSan
egressPolicyByName.set(name, want);
}
- function spritesProxyEnv(token: string): Record<string, string> {
- const u = new URL(opts.egressProxyUrl!);
- const url = `${u.protocol}//x:${token}@${u.host}`;
- const noProxy = "localhost,127.0.0.1,::1";
- return {
- HTTPS_PROXY: url,
- HTTP_PROXY: url,
- NO_PROXY: noProxy,
- https_proxy: url,
- http_proxy: url,
- no_proxy: noProxy,
- };
- }
-
async function readAbsBytes(name: string, absPath: string): Promise<Uint8Array | null> {
const script =
`[ -e ${shq(absPath)} ] || exit ${MISSING_RC}; s=$(wc -c < ${shq(absPath)}); echo "$s"; ` +
@@ -410,7 +396,10 @@ export function createSpritesSandbox(workspace: WorkspaceStore, opts: SpritesSan
const turnEnv = Object.fromEntries(
Object.entries(provOpts?.env ?? {}).filter(([k]) => !DROPPED_PROXY_ENV.has(k)),
);
- const env = { ...turnEnv, ...(forceEgress ? spritesProxyEnv(provOpts!.egressToken!) : {}) };
+ const env = {
+ ...turnEnv,
+ ...(forceEgress ? forceThroughProxyEnv(opts.egressProxyUrl!, provOpts!.egressToken!) : {}),
+ };
const handle: SandboxHandle = {
id: name,
rootDir: workspaceDir,
diff --git a/src/wiring.ts b/src/wiring.ts
index c665b6573..a92c23a41 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -104,6 +104,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 {
createSandboxRouter,
ROUTE_CACHE_TTL_MS,
@@ -592,6 +593,17 @@ export function buildApp(
...(config.apiBaseUrl ? { apiBaseUrl: config.apiBaseUrl } : {}),
onError: sandboxOnError,
});
+ const buildSmolmachines = (): Sandbox =>
+ createSmolmachinesSandbox(workspace, {
+ ...config.smolmachinesSandbox,
+ blobTransfer,
+ extraTools: deploymentLayer.advertisedTools,
+ credentialPaths: deploymentLayer.credentialPaths,
+ ...(config.signingSecret ? { signingSecret: config.signingSecret } : {}),
+ ...(config.capabilitySecret ? { capabilitySecret: config.capabilitySecret } : {}),
+ ...(config.apiBaseUrl ? { apiBaseUrl: config.apiBaseUrl } : {}),
+ onError: sandboxOnError,
+ });
const buildAws = (): Sandbox => {
if (!config.awsSandbox.s3Bucket) throw new Error("SANDBOX_BACKEND=aws requires AWS_SANDBOX_S3_BUCKET");
return createAwsSandbox(workspace, {
@@ -607,6 +619,7 @@ export function buildApp(
const buildBackend: Record<Config["sandboxBackend"], () => Sandbox> = {
local: buildLocal,
sprites: buildSprites,
+ smolmachines: buildSmolmachines,
aws: buildAws,
};
const sandboxBackends: Partial<Record<SandboxBackendName, Sandbox>> = {
diff --git a/test/smolmachines-sandbox.test.ts b/test/smolmachines-sandbox.test.ts
new file mode 100644
index 000000000..1b332d222
--- /dev/null
+++ b/test/smolmachines-sandbox.test.ts
@@ -0,0 +1,182 @@
+import { test, after, beforeEach } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createSmolmachinesSandbox } from "../src/sandbox/smolmachines-sandbox.ts";
+import { spriteScopeName } from "../src/sandbox/sprites-sandbox.ts";
+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 {
+ installFakeSmolmachines,
+ FAKE_SMOLMACHINES_TOKEN,
+ type FakeSmolmachines,
+} from "./support/fake-smolmachines.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 }];
+
+function make(extra: Record<string, unknown> = {}): Sandbox {
+ return createSmolmachinesSandbox(createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "smol-ws-"))), {
+ token: FAKE_SMOLMACHINES_TOKEN,
+ namePrefix: "qmt",
+ fetchImpl: fake.fetchImpl,
+ ...extra,
+ });
+}
+
+beforeEach(() => {
+ fake = installFakeSmolmachines();
+ sandbox = make();
+});
+after(() => fake?.cleanup());
+
+test("provision runs commands with env and cwd", async () => {
+ const h = await sandbox.provision(layers, { env: { MY_VAR: "v1" } });
+ assert.equal(h.coldStart, true);
+ const r = await sandbox.run(h, "pwd; echo VAR=$MY_VAR");
+ assert.equal(r.code, 0);
+ assert.match(r.stdout, /workspace/);
+ assert.match(r.stdout, /VAR=v1/);
+});
+
+test("streams and exit codes are exact", async () => {
+ const h = await sandbox.provision(layers);
+ const r = await sandbox.run(h, "echo out; echo err >&2; exit 3");
+ assert.equal(r.code, 3);
+ assert.equal(r.stdout.trim(), "out");
+ assert.equal(r.stderr.trim(), "err");
+});
+
+test("file roundtrip incl. large binary and missing file", async () => {
+ const h = await sandbox.provision(layers);
+ await sandbox.writeFile(h, "a/b.txt", "hello\n");
+ assert.equal(await sandbox.readFile(h, "a/b.txt"), "hello\n");
+ assert.equal(await sandbox.readFile(h, "nope.txt"), null);
+ const big = Buffer.alloc(200 * 1024);
+ for (let i = 0; i < big.length; i++) big[i] = (i * 7) % 256;
+ await sandbox.writeFileBytes(h, "big.bin", big);
+ const back = await sandbox.readFileBytes(h, "big.bin");
+ assert.ok(back && Buffer.from(back).equals(big));
+ const huge = Buffer.alloc(1300 * 1024);
+ for (let i = 0; i < huge.length; i++) huge[i] = (i * 13) % 256;
+ await sandbox.writeFileBytes(h, "huge.bin", huge);
+ const hugeBack = await sandbox.readFileBytes(h, "huge.bin");
+ assert.ok(hugeBack && Buffer.from(hugeBack).equals(huge));
+});
+
+test("empty file roundtrip", async () => {
+ const h = await sandbox.provision(layers);
+ await sandbox.writeFileBytes(h, "empty.bin", Buffer.alloc(0));
+ const back = await sandbox.readFileBytes(h, "empty.bin");
+ assert.ok(back);
+ assert.equal(back.length, 0);
+});
+
+test("process sessions capability works end to end", async () => {
+ assert.ok(supportsProcessSessions(sandbox));
+ if (!supportsProcessSessions(sandbox)) return;
+ const h = await sandbox.provision(layers);
+ const { processId } = await sandbox.startProcess(h, "echo one; echo two");
+ let cursor = 0,
+ chunks = "",
+ state = "running";
+ for (let i = 0; i < 10 && state === "running"; i++) {
+ const r = await sandbox.readProcess(h, processId, { sinceCursor: cursor });
+ chunks += r.chunks;
+ cursor = r.cursor;
+ state = r.status.state;
+ }
+ assert.match(chunks, /one/);
+ assert.match(chunks, /two/);
+});
+
+test("force-through proxy env is set when a proxy url and token are present", 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 });
+ 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 () => {
+ const h = await sandbox.provision(layers, { egressToken: "ignored" });
+ assert.equal(h.env?.HTTPS_PROXY, undefined);
+});
+
+test("machine is reused across provisions and warm start is reported", async () => {
+ const a = await sandbox.provision(layers);
+ const b = await sandbox.provision(layers);
+ assert.equal(a.id, b.id);
+ assert.equal(b.coldStart, false);
+ assert.equal(fake.names().filter((n) => n === a.id).length, 1);
+});
+
+test("exec on a stopped machine restarts it and retries", 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.machine(h.id)?.state.toLowerCase(), "running");
+});
+
+test("scratch machines are ephemeral and deleted at release", async () => {
+ const h = await sandbox.provision(layers, { scratch: { key: "job-1" } });
+ assert.equal(h.scratch, true);
+ assert.equal(fake.machine(h.id)?.ephemeral, true);
+ await sandbox.teardown(h);
+ assert.equal(fake.machine(h.id), null);
+});
+
+test("teardown without destroy keeps the machine; destroy deletes it", async () => {
+ const h = await sandbox.provision(layers);
+ await sandbox.teardown(h);
+ assert.ok(fake.machine(h.id));
+ await sandbox.teardown(h, { destroy: true });
+ assert.equal(fake.machine(h.id), null);
+});
+
+test("large command output survives the API's truncation cap exactly", async () => {
+ const h = await sandbox.provision(layers);
+ const r = await sandbox.run(h, "python3 -c \"print('x' * (900 * 1024), end='')\"");
+ assert.equal(r.code, 0);
+ assert.equal(r.stdout.length, 900 * 1024);
+ assert.equal(r.stdout, "x".repeat(900 * 1024));
+});
+
+test("a name conflict on create adopts the existing machine instead of failing", async () => {
+ await fake.fetchImpl("https://api.smolmachines.com/v1/machines", {
+ method: "POST",
+ body: JSON.stringify({ name: spriteScopeName("qmt", scope), ephemeral: false }),
+ });
+ const h = await sandbox.provision(layers);
+ assert.equal(h.coldStart, false);
+ const r = await sandbox.run(h, "echo alive");
+ assert.equal(r.stdout.trim(), "alive");
+});
+
+test("timeouts beyond the API's sync exec ceiling run detached and poll to completion", async () => {
+ const h = await sandbox.provision(layers);
+ const r = await sandbox.run(h, "echo long-path-ok; echo warn >&2; exit 9", { timeoutMs: 400_000 });
+ assert.equal(r.code, 9);
+ assert.equal(r.stdout.trim(), "long-path-ok");
+ assert.equal(r.stderr.trim(), "warn");
+ const leftovers = await sandbox.run(h, "ls /root/.qm-exec-*.rc 2>/dev/null | wc -l");
+ assert.equal(leftovers.stdout.trim(), "0");
+});
+
+test("profile advertises resident disk and process sessions", () => {
+ assert.equal(sandbox.profile.backend, "smolmachines");
+ assert.equal(sandbox.profile.writablePersistence, "resident_disk");
+ assert.equal(sandbox.profile.processSessions, true);
+});
diff --git a/test/support/fake-smolmachines.ts b/test/support/fake-smolmachines.ts
new file mode 100644
index 000000000..301eb1927
--- /dev/null
+++ b/test/support/fake-smolmachines.ts
@@ -0,0 +1,194 @@
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+export interface SmolCall {
+ method: string;
+ path: string;
+ script?: string;
+}
+
+interface FakeMachine {
+ id: string;
+ name: string | null;
+ state: string;
+ ephemeral: boolean;
+ home: string;
+}
+
+export interface FakeSmolmachines {
+ fetchImpl: typeof fetch;
+ calls: SmolCall[];
+ homeDir(name: string): string;
+ names(): string[];
+ machine(name: string): { state: string; ephemeral: boolean } | null;
+ stop(name: string): void;
+ execScripts(): string[];
+ reset(): void;
+ cleanup(): void;
+}
+
+export const FAKE_SMOLMACHINES_TOKEN = "test-token";
+
+export function installFakeSmolmachines(): FakeSmolmachines {
+ const root = mkdtempSync(join(tmpdir(), "fake-smol-"));
+ const machines = new Map<string, FakeMachine>();
+ const execScripts: string[] = [];
+ const calls: SmolCall[] = [];
+ let nextId = 1;
+
+ const byName = (name: string): FakeMachine | undefined => [...machines.values()].find((m) => m.name === name);
+
+ const create = (name: string | null, ephemeral: boolean): FakeMachine => {
+ const id = `m-${nextId++}`;
+ const m: FakeMachine = { id, name, state: "stopped", ephemeral, home: join(root, id) };
+ mkdirSync(m.home, { recursive: true });
+ machines.set(id, m);
+ return m;
+ };
+
+ const remap = (m: FakeMachine, script: string): string => {
+ const homeRe = m.home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const remapPath = new RegExp(`${homeRe}/tmp/|${homeRe}(?![A-Za-z0-9._-])|/tmp/`, "g");
+ return (
+ `export HOME=${JSON.stringify(m.home)}; ` +
+ script
+ .replace(/\btimeout \d+ /g, "")
+ .replace(/\/root/g, m.home)
+ .replace(remapPath, (mm) => (mm.startsWith(m.home) ? mm : `${m.home}/tmp/`))
+ );
+ };
+
+ const runExec = (m: FakeMachine, script: string, stdinB64?: string): 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");
+ return Response.json({
+ stdout: stdout.slice(0, cap),
+ stderr: stderr.slice(0, cap),
+ exitCode: code,
+ durationMs: 1,
+ machineId: m.id,
+ stdoutTruncated: stdout.length > cap,
+ stderrTruncated: stderr.length > cap,
+ });
+ };
+
+ const info = (m: FakeMachine) => ({
+ id: m.id,
+ name: m.name,
+ state: m.state,
+ ephemeral: m.ephemeral,
+ source: { type: "image", reference: "ubuntu:24.04" },
+ resources: {},
+ network: { mode: "open" },
+ env: {},
+ createdAt: "2026-01-01T00:00:00Z",
+ updatedAt: "2026-01-01T00:00:00Z",
+ });
+
+ const toBuf = (body: unknown): Buffer => {
+ if (Buffer.isBuffer(body)) return body;
+ if (typeof body === "string") return Buffer.from(body);
+ return Buffer.alloc(0);
+ };
+
+ 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 });
+ if (url.pathname === "/v1/machines" && method === "GET") {
+ 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;
+ };
+ 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)), { status: 201 });
+ }
+ const files = /^\/v1\/machines\/([^/]+)\/files(\/.+)$/.exec(url.pathname);
+ if (files) {
+ const m = machines.get(decodeURIComponent(files[1]!));
+ if (!m) return new Response("machine not found", { status: 404 });
+ const abs = files[2]!.split("/").map(decodeURIComponent).join("/");
+ if (abs.startsWith("/tmp/")) return new Response("file not found", { status: 404 });
+ const hostPath = abs.replace(/^\/root/, m.home);
+ if (method === "PUT") {
+ m.state = "Running";
+ mkdirSync(dirname(hostPath), { recursive: true });
+ writeFileSync(hostPath, toBuf(init?.body));
+ return Response.json({ path: abs, size: toBuf(init?.body).length });
+ }
+ if (method === "GET") {
+ if (!existsSync(hostPath)) return new Response("file not found", { status: 404 });
+ return new Response(new Uint8Array(readFileSync(hostPath)), { status: 200 });
+ }
+ }
+ const sub = /^\/v1\/machines\/([^/]+)(?:\/(exec|start|stop))?$/.exec(url.pathname);
+ if (sub) {
+ const m = machines.get(decodeURIComponent(sub[1]!));
+ 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 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);
+ }
+ if (sub[2] === "start") {
+ m.state = "Running";
+ return Response.json(info(m));
+ }
+ if (sub[2] === "stop") {
+ m.state = "stopped";
+ return Response.json(info(m));
+ }
+ if (method === "GET") return Response.json(info(m));
+ if (method === "DELETE") {
+ rmSync(m.home, { recursive: true, force: true });
+ machines.delete(m.id);
+ return new Response(null, { status: 204 });
+ }
+ }
+ return new Response("not found", { status: 404 });
+ };
+
+ return {
+ fetchImpl,
+ calls,
+ homeDir: (name) => (byName(name) ?? create(name, false)).home,
+ names: () => [...machines.values()].map((m) => m.name ?? m.id),
+ machine: (name) => {
+ const m = byName(name);
+ return m ? { state: m.state, ephemeral: m.ephemeral } : null;
+ },
+ stop: (name) => {
+ const m = byName(name);
+ if (m) m.state = "stopped";
+ },
+ execScripts: () => [...execScripts],
+ reset: () => {
+ for (const m of machines.values()) rmSync(m.home, { recursive: true, force: true });
+ machines.clear();
+ execScripts.length = 0;
+ calls.length = 0;
+ },
+ cleanup: () => rmSync(root, { recursive: true, force: true }),
+ };
+}