diff --git a/CHANGELOG.md b/CHANGELOG.md index 81baa08..e1965d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,39 @@ This file records user-visible changes to the BoxCompute CLI. GitHub Releases use the same notes and bind them to the exact source commit. +## [0.12.0] - 2026-10-22 + +Run BoxCompute chats on your own machine with `bxc runner`. + +### CLI users + +- `bxc runner` connects this machine to BoxCompute over an outbound WebSocket + and runs the agent's shell and file commands for chats that use the runner, + in one Docker container per chat (`node:22-bookworm` unless `--image` says + otherwise). Each chat's `/workspace` is a Docker volume that stays until + BoxCompute deletes the chat's sandbox. +- Containers stop after 30 minutes without commands (`--idle-stop`, `0` to + keep them running); the next command starts them again with their files. +- `--dispatch PROGRAM` hands each ensure, exec and delete to your own program + instead of Docker. The README documents the contract and has a complete + Docker example. +- The runner reconnects by itself after network failures and server restarts, + and exits when BoxCompute rejects its token. Ctrl-C stops running commands + but keeps containers and files. +- Requires Node.js 22 or newer, Docker unless `--dispatch` is used, and a + BoxCompute server with self-hosted runners (Settings → Runners). Every other + command still runs on Node.js 20. + +### Security + +- The runner token is read only from `BOXCOMPUTE_RUNNER_TOKEN`, sent in the + first WebSocket message rather than a URL or header, never printed, and + removed from the environment of Docker, containers and dispatch programs. + Plain `ws://` is refused except to loopback. +- The agent's commands run on this machine with its network access, inside + containers; BoxCompute approvals still apply. Delete the runner in Settings → + Runners to revoke its token. + ## [0.11.0] - 2026-10-18 Stop a running VM with `bxc sandbox stop SANDBOX_ID`. diff --git a/README.md b/README.md index 1220c98..1d2c984 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,155 @@ exact `--revoke` command; the server-side lease still expires naturally. Run `bxc` or `bxc --help` for the complete command reference. The previous `bcompute` executable remains available as a compatibility alias. +## Run chats on your own machine (`bxc runner`) + +`bxc runner` lets the BoxCompute agent work on a computer you control. It +opens an outbound WebSocket to BoxCompute, so the machine needs no open ports, +and runs the agent's shell and file commands for chats that use this runner in +one Docker container per chat. Each chat's `/workspace` is a Docker volume on +this machine that stays until BoxCompute deletes the chat's sandbox. + +Requirements: Docker (`docker version` must work for your user) and Node.js 22 +or newer. The other `bxc` commands still run on Node.js 20. + +### Set up a runner + +1. In BoxCompute, open Settings → Runners, create a runner and copy its token. +2. On the machine that should run the commands: + + ```sh + export BOXCOMPUTE_RUNNER_TOKEN=bxr_... + npx -y @boxcompute/cli@latest runner + ``` + + To keep the token out of your shell history, type it at a prompt instead: + `read -rs BOXCOMPUTE_RUNNER_TOKEN && export BOXCOMPUTE_RUNNER_TOKEN`. + + The runner prints `Connected as ""` and then one line per + operation. Leave it running; Ctrl-C disconnects it. +3. In BoxCompute, choose the runner for a chat in the composer. While the + runner is connected, that chat's commands run in a container here. + +The token is read only from `BOXCOMPUTE_RUNNER_TOKEN`, never from a command-line +option, because other users on the machine can read process arguments. + +```sh +# Another image; it needs bash and python3 (default: node:22-bookworm). +bxc runner --image python:3.13 +# Stop a chat's container after 2 hours without commands; 0 never stops it. +bxc runner --idle-stop 2h +# A self-hosted BoxCompute (default: your `bxc login` URL, else app.boxcompute.ai). +bxc runner --url https://boxcompute.example.com +# Also log each command's arguments. +bxc runner --verbose +``` + +Each container is named after the chat's sandbox (`bxs-…`), labelled +`com.boxcompute.runner` and `com.boxcompute.sandbox`, runs with `--init`, and +mounts the volume `bxs-…-workspace` at `/workspace`. List them with +`docker ps -a --filter label=com.boxcompute.runner`. + +**Idle stop.** A container this runner has used stops after 30 minutes without +commands (`--idle-stop`). Its volume and files stay, and the next command +starts it again. + +**Disconnects.** The runner reconnects by itself, backing off up to 30 seconds. +Commands that were running when the connection dropped are stopped; BoxCompute +reports them as failed. Ctrl-C (or SIGTERM) also stops running commands but +keeps every container and its files. The runner exits instead of reconnecting +when BoxCompute rejects the token, runners are not available on the account, or +another `bxc runner` connects with the same token. + +### Custom dispatch + +`--dispatch PROGRAM` hands every operation to your own program instead of the +built-in Docker dispatch, for example to use Podman, a VM or a remote host. The +runner starts `PROGRAM` without a shell for each operation, with the runner's +environment minus `BOXCOMPUTE_RUNNER_TOKEN`, plus: + +| Variable | Value | +| --- | --- | +| `BOXCOMPUTE_OPERATION` | `ensure`, `exec` or `delete` | +| `BOXCOMPUTE_SANDBOX_ID` | The chat's sandbox, `bxs-` and 16 hex digits | +| `BOXCOMPUTE_RUNNER_ID` | This runner's ID | +| `BOXCOMPUTE_IMAGE` | The `--image` value (default `node:22-bookworm`) | + +- **ensure** creates the sandbox if it is missing, with an empty `/workspace`, + or starts it if it is stopped, and exits 0 once commands can run. It must be + safe to repeat. +- **exec** receives the command's argv as its arguments. The runner writes the + command's stdin (often empty) and closes it, streams stdout and stderr, and + reports the program's exit code as the command's. +- **delete** removes the sandbox and its storage. An already missing sandbox is + a success. + +When ensure or delete exits non-zero, the last non-empty line of its stderr is +shown in BoxCompute as the error. A cancelled exec gets SIGKILL for the +program's whole process group; work it started elsewhere, such as through +`docker exec`, can keep running. There is no idle stop in this mode. + +This `dispatch.sh` does what the built-in Docker dispatch does, without idle +stop: + +```sh +#!/bin/sh +# bxc runner --dispatch ./dispatch.sh +set -eu +id="$BOXCOMPUTE_SANDBOX_ID" +fail() { echo "$1" >&2; exit 1; } + +case "$BOXCOMPUTE_OPERATION" in + ensure) + state=$(docker inspect --type container --format '{{.State.Running}}' "$id" 2>/dev/null || true) + case "$state" in + true) ;; + false) docker start "$id" >/dev/null || fail "Could not start $id" ;; + *) + docker run -d --name "$id" --init -w /workspace \ + --label "com.boxcompute.runner=$BOXCOMPUTE_RUNNER_ID" \ + --label "com.boxcompute.sandbox=$id" \ + -v "$id-workspace:/workspace" \ + "$BOXCOMPUTE_IMAGE" sleep infinity >/dev/null \ + || fail "Could not create $id from $BOXCOMPUTE_IMAGE" + docker exec "$id" sh -c 'command -v bash && command -v python3' >/dev/null \ + || fail "The image $BOXCOMPUTE_IMAGE needs bash and python3" + ;; + esac + ;; + exec) + exec docker exec -i "$id" "$@" + ;; + delete) + if docker inspect --type container "$id" >/dev/null 2>&1; then + docker rm -f "$id" >/dev/null || fail "Could not remove $id" + fi + docker volume rm -f "$id-workspace" >/dev/null || fail "Could not remove $id-workspace" + ;; + *) + fail "Unsupported operation: $BOXCOMPUTE_OPERATION" + ;; +esac +``` + +Make it executable with `chmod +x dispatch.sh`. `--idle-stop` cannot be combined +with `--dispatch`. + +### Security + +- The agent's commands run on this machine, inside containers that have this + machine's network access, including your local network. Docker separates + their files from yours, but treat it as running the agent here. BoxCompute + approvals still apply. +- Anyone with the runner token can connect as this runner and receive its + chats' commands and files. Keep it secret. `bxc runner` never prints it, + sends it only in the first WebSocket message (not in a URL or header), and + does not pass it to Docker, containers or a dispatch program. +- The connection uses TLS (`wss://`). Plain `ws://` is refused except to a + loopback development server. +- Delete the runner in Settings → Runners to revoke its token. Stopping + `bxc runner` does not remove containers or volumes; remove them with + `docker rm -f` and `docker volume rm` when you no longer need their files. + ## Upgrade rollout Deploy the server release with both Sandbox API v1 and v2 before publishing CLI diff --git a/package.json b/package.json index cb38370..11a64bd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@boxcompute/cli", - "version": "0.11.0", + "version": "0.12.0", "description": "Connect local AI agents to BoxCompute sandboxes", "keywords": [ "boxcompute", diff --git a/src/cli.ts b/src/cli.ts index 72e02fc..70dd9ff 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -30,6 +30,7 @@ import { clearConnection, loadConnection, loadSavedUrl, + normalizeBaseUrl, saveConnection, type Connection, } from "./config.js"; @@ -49,6 +50,15 @@ import { runSsh } from "./ssh.js"; import { cooperativeConnectionApi } from "./cooperative-connection.js"; import { resumeSandbox } from "./resume.js"; import { stopSandbox } from "./stop.js"; +import { + DEFAULT_IDLE_STOP_MS, + DEFAULT_RUNNER_IMAGE, + RUNNER_IMAGE_PATTERN, + RUNNER_TOKEN_ENV, + RUNNER_TOKEN_PATTERN, + parseDuration, + runRunner, +} from "./runner.js"; const DEFAULT_URL = "https://app.boxcompute.ai"; const CLI_VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version; @@ -89,6 +99,7 @@ Commands: deleted Read deleted sandboxes, their logs, and their costs costs Compute cost per API key and per sandbox audit Page the account's API audit log + runner Run BoxCompute chats in Docker on this machine skill [alias: skills] Manage coding-harness skills detect Detect compatible coding harnesses list [alias: ls] List detected or installed harnesses @@ -125,6 +136,7 @@ Examples: $ bxc costs --from 2026-10-01T00:00:00Z $ bxc audit --outcome error $ BOXCOMPUTE_ENABLE_SSH=1 bxc sandbox ssh SANDBOX_ID + $ BOXCOMPUTE_RUNNER_TOKEN=bxr_... bxc runner Compatibility: @@ -330,6 +342,41 @@ Usage: bxc usage [--days DAYS] Use bxc credits for remaining credit and bxc costs for compute spending. `; +const runnerHelp = `Run BoxCompute chats on this machine + +Usage: bxc runner [options] + + Connects to BoxCompute over an outbound WebSocket and runs the agent's + shell and file commands for chats that use this runner, in one Docker + container per chat. Each chat's files stay in a Docker volume until + BoxCompute deletes its sandbox. + +Options: + + --image IMAGE Container image; needs bash and python3 + (default: ${DEFAULT_RUNNER_IMAGE}) + --idle-stop DURATION Stop a chat's container after this long + without commands, such as 30m or 2h; 0 never + stops (default: 30m). Files stay; the next + command starts it again + --dispatch PROGRAM Hand each operation to PROGRAM instead of + Docker (see the README for the contract) + --url URL BoxCompute web URL (default: the saved login + URL, else https://app.boxcompute.ai) + --verbose Also log each command's arguments + +Environment: + + ${RUNNER_TOKEN_ENV} Required. Create a runner in BoxCompute + (Settings → Runners) and export its token. + It is never accepted on the command line and + never passed to containers or PROGRAM. + + Requires Node.js 22 or newer and, without --dispatch, a running Docker. + Ctrl-C disconnects and stops running commands; containers and files stay. + The agent's commands run here with this machine's network access. +`; + const skillHelp = `Manage coding-harness skills Usage: bxc skill [options] @@ -386,6 +433,9 @@ export type CliDependencies = { openServices?: typeof openServices; proxy?: typeof runProxy; ssh?: typeof runSsh; + runner?: typeof runRunner; + /** null simulates a runtime without a global WebSocket (Node.js 20). */ + webSocket?: typeof WebSocket | null; }; class UsageError extends Error { @@ -1100,6 +1150,63 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr return 0; } + if (command === "runner") { + if (json) throw new UsageError("runner is a foreground stream and does not support --json"); + const image = option(args, "image"); + const dispatch = option(args, "dispatch"); + const idleStop = option(args, "idle-stop"); + const urlOption = option(args, "url"); + const verbose = flag(args, "verbose"); + if (args.length) throw new UsageError(`Unknown runner option: ${args[0]}`); + if (image !== undefined && !RUNNER_IMAGE_PATTERN.test(image)) { + throw new UsageError("--image must be an image reference such as node:22-bookworm"); + } + if (dispatch !== undefined && idleStop !== undefined) { + throw new UsageError("--idle-stop applies only to the built-in Docker dispatch"); + } + let idleStopMs = DEFAULT_IDLE_STOP_MS; + if (idleStop !== undefined) { + try { + idleStopMs = parseDuration(idleStop); + } catch (error) { + throw new UsageError((error as Error).message); + } + } + const WebSocketImpl = supplied.webSocket === undefined ? globalThis.WebSocket : supplied.webSocket; + if (typeof WebSocketImpl !== "function") throw new Error("bxc runner needs Node.js 22 or newer."); + // The token comes only from the environment: argv is visible to every + // local user through ps. + const token = env[RUNNER_TOKEN_ENV]?.trim(); + if (!token) { + throw new Error( + `${RUNNER_TOKEN_ENV} is not set. Create a runner in BoxCompute (Settings → Runners), ` + + `then run \`export ${RUNNER_TOKEN_ENV}=\` and start bxc runner again.`, + ); + } + if (!RUNNER_TOKEN_PATTERN.test(token)) { + throw new Error(`${RUNNER_TOKEN_ENV} is not a runner token (runner tokens start with bxr_). Copy it from Settings → Runners.`); + } + const url = normalizeBaseUrl(urlOption ?? await savedUrl(env) ?? DEFAULT_URL); + const abort = new AbortController(); + const stop = () => abort.abort(); + const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const; + for (const signal of signals) process.on(signal, stop); + try { + return await (supplied.runner ?? runRunner)({ + url, + token, + image: image ?? DEFAULT_RUNNER_IMAGE, + imageChosen: image !== undefined, + dispatch: dispatch ?? null, + idleStopMs, + verbose, + version: CLI_VERSION, + }, { env, stdout: io.stdout, stderr: io.stderr, signal: abort.signal, WebSocket: WebSocketImpl }); + } finally { + for (const signal of signals) process.off(signal, stop); + } + } + if (command === "sandbox" && !args.length) { write(io.stdout, sandboxHelp); return 0; @@ -1400,6 +1507,7 @@ function helpFor(command?: string): string { if (command === "deleted") return deletedHelp; if (command === "costs") return costsHelp; if (command === "audit") return auditHelp; + if (command === "runner") return runnerHelp; return rootHelp; } diff --git a/src/runner-dispatch.ts b/src/runner-dispatch.ts new file mode 100644 index 0000000..9722346 --- /dev/null +++ b/src/runner-dispatch.ts @@ -0,0 +1,550 @@ +import { spawn, type ChildProcess, type StdioOptions } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { accessSync, constants as fsConstants, statSync } from "node:fs"; +import { constants as osConstants } from "node:os"; +import path from "node:path"; + +export const RUNNER_TOKEN_ENV = "BOXCOMPUTE_RUNNER_TOKEN"; + +export type OutputStream = "stdout" | "stderr"; +/** Receives raw output. A returned promise pauses that stream until it settles (socket backpressure). */ +export type OutputSink = (stream: OutputStream, chunk: Buffer) => Promise | undefined; + +export interface Dispatcher { + readonly mode: "docker" | "custom"; + /** Startup check: Docker answers, or the dispatch program exists. */ + check(): Promise; + ensure(sandbox: string, runnerId: string): Promise; + remove(sandbox: string, runnerId: string): Promise; + exec( + sandbox: string, + runnerId: string, + argv: string[], + stdin: Buffer, + output: OutputSink, + signal: AbortSignal, + ): Promise; + /** Stops containers that have been idle longer than --idle-stop. */ + sweep(): Promise; + /** Kills every child process and waits briefly for in-container cleanup. */ + shutdown(): Promise; +} + +export type DispatcherOptions = { + /** Custom dispatch program, or null for the built-in Docker dispatch. */ + program: string | null; + image: string; + idleStopMs: number; + env: NodeJS.ProcessEnv; + log: (line: string) => void; + docker?: string; + now?: () => number; + spawn?: typeof spawn; +}; + +const GROUP_KILL = process.platform !== "win32"; +// A command that exits while a background child still holds its stdout would +// otherwise keep the request open forever. +const EXIT_GRACE_MS = 2_000; +const CLEANUP_WAIT_MS = 5_000; +// Docker may have stopped a container behind our back (daemon restart, Docker +// Desktop update); re-check its state before a command when it is this stale. +const RECHECK_MS = 10_000; + +/** The runner token authenticates this machine to BoxCompute; nothing it starts may read it. */ +export function withoutRunnerToken(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return Object.fromEntries(Object.entries(env).filter(([key]) => key.toUpperCase() !== RUNNER_TOKEN_ENV)); +} + +export function createDispatcher(options: DispatcherOptions): Dispatcher { + const env = withoutRunnerToken(options.env); + const processes = new Processes(options.spawn ?? spawn); + if (options.program !== null) return new CustomDispatcher(options.program, options.image, env, processes); + return new DockerDispatcher({ + command: options.docker ?? "docker", + image: options.image, + idleStopMs: options.idleStopMs, + log: options.log, + now: options.now ?? Date.now, + }, env, processes); +} + +export function dockerWorkspaceVolume(sandbox: string): string { + return `${sandbox}-workspace`; +} + +// Kills every process in the container that inherited this exec's marker. +// Killing the local `docker exec` client alone leaves the command running. +const KILL_EXEC_SCRIPT = [ + "for p in /proc/[0-9]*; do", + " if tr '\\0' '\\n' 2>/dev/null < \"$p/environ\" | grep -qxF \"BOXCOMPUTE_EXEC_ID=$1\"; then kill -9 \"${p#/proc/}\" 2>/dev/null; fi", + "done", + "exit 0", +].join("\n"); + +/** Docker CLI argument vectors. Every value is one argv element; nothing passes through a shell on the host. */ +export const dockerArgs = { + version: (): string[] => ["version", "--format", "{{.Server.Version}}"], + inspect: (sandbox: string): string[] => ["inspect", "--type", "container", "--format", "{{.State.Running}}", sandbox], + run: (sandbox: string, runnerId: string, image: string): string[] => [ + "run", "-d", + "--name", sandbox, + "--label", `com.boxcompute.runner=${runnerId}`, + "--label", `com.boxcompute.sandbox=${sandbox}`, + "--init", + "-w", "/workspace", + "-v", `${dockerWorkspaceVolume(sandbox)}:/workspace`, + image, "sleep", "infinity", + ], + toolCheck: (sandbox: string): string[] => ["exec", sandbox, "sh", "-c", "command -v bash && command -v python3"], + start: (sandbox: string): string[] => ["start", sandbox], + exec: (sandbox: string, argv: string[], execId: string): string[] => [ + "exec", "-i", "--env", `BOXCOMPUTE_EXEC_ID=${execId}`, sandbox, ...argv, + ], + killExec: (sandbox: string, execId: string): string[] => ["exec", sandbox, "sh", "-c", KILL_EXEC_SCRIPT, "sh", execId], + stop: (sandbox: string): string[] => ["stop", "-t", "10", sandbox], + removeContainer: (sandbox: string): string[] => ["rm", "-f", sandbox], + removeVolume: (sandbox: string): string[] => ["volume", "rm", "-f", dockerWorkspaceVolume(sandbox)], +}; + +/** Last non-empty line of a program's stderr, which is where CLIs put the reason they failed. */ +export function lastLine(text: string, skip?: RegExp): string { + const lines = text.split(/\r?\n|\r/).map((line) => line.trim()).filter((line) => line && !skip?.test(line)); + return lines.at(-1) ?? ""; +} + +// Docker ends most errors with "See 'docker run --help'.", which says nothing about the failure. +const dockerError = (stderr: string) => lastLine(stderr, /^(See|Run) '?docker\b.*--help/); + +/** Absolute path of an executable dispatch program, so later spawns do not depend on PATH or cwd. */ +export function resolveProgram(program: string, env: NodeJS.ProcessEnv): string { + const executable = (file: string) => { + try { + if (!statSync(file).isFile()) return false; + accessSync(file, fsConstants.X_OK); + return true; + } catch { + return false; + } + }; + if (program.includes("/") || program.includes(path.sep)) { + const resolved = path.resolve(program); + if (executable(resolved)) return resolved; + throw new Error(`--dispatch ${program} is not an executable file. Make it executable (chmod +x) or choose another program.`); + } + if (process.platform === "win32") return program; + for (const directory of (env.PATH ?? "").split(path.delimiter)) { + if (!directory) continue; + const candidate = path.join(directory, program); + if (executable(candidate)) return candidate; + } + throw new Error(`--dispatch ${program} was not found on PATH.`); +} + +function exitStatus(code: number | null, signal: NodeJS.Signals | null): number { + if (code !== null) return code; + const number = signal ? osConstants.signals[signal] : undefined; + return number ? 128 + number : 1; +} + +function killTree(child: ChildProcess): void { + if (child.exitCode !== null || child.signalCode !== null) return; + if (GROUP_KILL && child.pid) { + try { + process.kill(-child.pid, "SIGKILL"); + return; + } catch { + // The group is already gone; fall back to the direct child. + } + } + child.kill("SIGKILL"); +} + +class Tail { + private chunks: Buffer[] = []; + private size = 0; + constructor(private readonly limit: number) {} + push(chunk: Buffer): void { + this.chunks.push(chunk); + this.size += chunk.length; + while (this.chunks.length > 1 && this.size - this.chunks[0]!.length >= this.limit) { + this.size -= this.chunks.shift()!.length; + } + } + text(): string { + return Buffer.concat(this.chunks).subarray(-this.limit).toString("utf8"); + } +} + +type Collected = { code: number; stdout: string; stderr: string }; + +/** Spawns children in their own process group (no shell) so one SIGKILL reaches everything they started. */ +class Processes { + private readonly live = new Set(); + private readonly cleanups = new Set>(); + constructor(private readonly spawnImpl: typeof spawn) {} + + private start(command: string, args: string[], env: NodeJS.ProcessEnv, stdio: StdioOptions): ChildProcess { + const child = this.spawnImpl(command, args, { env, stdio, detached: GROUP_KILL, windowsHide: true }); + this.live.add(child); + const forget = () => { this.live.delete(child); }; + child.once("exit", forget); + child.once("error", forget); + return child; + } + + collect(command: string, args: string[], env: NodeJS.ProcessEnv): Promise { + return new Promise((resolve, reject) => { + let child: ChildProcess; + try { + child = this.start(command, args, env, ["ignore", "pipe", "pipe"]); + } catch (error) { + reject(error); + return; + } + const stdout = new Tail(65_536); + const stderr = new Tail(16_384); + child.stdout!.on("data", (chunk: Buffer) => stdout.push(chunk)); + child.stderr!.on("data", (chunk: Buffer) => stderr.push(chunk)); + child.once("error", reject); + child.once("close", (code, signal) => resolve({ code: exitStatus(code, signal), stdout: stdout.text(), stderr: stderr.text() })); + }); + } + + stream( + command: string, + args: string[], + env: NodeJS.ProcessEnv, + stdin: Buffer, + output: OutputSink, + signal: AbortSignal, + ): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new Error("cancelled")); + return; + } + let child: ChildProcess; + try { + child = this.start(command, args, env, ["pipe", "pipe", "pipe"]); + } catch (error) { + reject(error); + return; + } + let settled = false; + let grace: NodeJS.Timeout | undefined; + const abort = () => killTree(child); + const finish = (settle: () => void) => { + if (settled) return; + settled = true; + clearTimeout(grace); + signal.removeEventListener("abort", abort); + settle(); + }; + signal.addEventListener("abort", abort, { once: true }); + child.stdin!.on("error", () => undefined); + child.stdin!.end(stdin); + for (const name of ["stdout", "stderr"] as const) { + const source = child[name]!; + source.on("data", (chunk: Buffer) => { + const pending = output(name, chunk); + if (!pending) return; + source.pause(); + void pending.then(() => source.resume()); + }); + } + child.once("error", (error) => finish(() => reject(error))); + child.once("exit", () => { + grace = setTimeout(() => { + child.stdout?.destroy(); + child.stderr?.destroy(); + }, EXIT_GRACE_MS); + }); + child.once("close", (code, signalName) => finish(() => resolve(exitStatus(code, signalName)))); + }); + } + + /** Best-effort follow-up that must outlive a kill-all, such as stopping a cancelled command in its container. */ + detach(command: string, args: string[], env: NodeJS.ProcessEnv): void { + let child: ChildProcess; + try { + child = this.spawnImpl(command, args, { env, stdio: "ignore", detached: GROUP_KILL, windowsHide: true }); + } catch { + return; + } + const done = new Promise((resolve) => { + child.once("error", () => resolve()); + child.once("exit", () => resolve()); + }); + this.cleanups.add(done); + void done.then(() => this.cleanups.delete(done)); + child.unref(); + } + + async stop(): Promise { + for (const child of this.live) killTree(child); + const pending = [...this.cleanups]; + if (!pending.length) return; + await new Promise((resolve) => { + const timer = setTimeout(resolve, CLEANUP_WAIT_MS); + void Promise.allSettled(pending).then(() => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +/** Runs lifecycle work for one sandbox at a time, so ensure, idle stop and delete never interleave. */ +class KeyedLock { + private readonly tails = new Map>(); + async run(key: string, task: () => Promise): Promise { + const previous = this.tails.get(key) ?? Promise.resolve(); + let release!: () => void; + const current = new Promise((resolve) => { release = resolve; }); + const tail = previous.then(() => current); + this.tails.set(key, tail); + await previous; + try { + return await task(); + } finally { + release(); + if (this.tails.get(key) === tail) this.tails.delete(key); + } + } +} + +type Tracked = { lastActive: number; verifiedAt: number; running: number; stopped: boolean }; +type DockerSettings = { + command: string; + image: string; + idleStopMs: number; + log: (line: string) => void; + now: () => number; +}; + +class DockerDispatcher implements Dispatcher { + readonly mode = "docker" as const; + // Sandboxes this process ensured or started; only these are idle-stopped. + private readonly tracked = new Map(); + private readonly lock = new KeyedLock(); + private sweeping = false; + + constructor( + private readonly settings: DockerSettings, + private readonly env: NodeJS.ProcessEnv, + private readonly processes: Processes, + ) {} + + async check(): Promise { + let result: Collected; + try { + result = await this.docker(dockerArgs.version()); + } catch { + throw new Error("Docker is not installed or not on PATH. Install Docker, or use --dispatch with your own program."); + } + if (result.code !== 0) { + const detail = dockerError(result.stderr); + throw new Error( + `Docker is not reachable${detail ? ` (${detail})` : ""}. ` + + "Start Docker and check that `docker version` works for this user, or use --dispatch.", + ); + } + } + + ensure(sandbox: string, runnerId: string): Promise { + return this.lock.run(sandbox, async () => { + const state = await this.state(sandbox); + if (state === "missing") { + await this.must(dockerArgs.run(sandbox, runnerId, this.settings.image)); + const tools = await this.docker(dockerArgs.toolCheck(sandbox)); + if (tools.code !== 0) { + // Leave the volume, but not a container that the next ensure would accept as ready. + await this.docker(dockerArgs.removeContainer(sandbox)).catch(() => undefined); + throw new Error(`The image ${this.settings.image} needs bash and python3. Choose another with --image.`); + } + } else if (state === "stopped") { + await this.must(dockerArgs.start(sandbox)); + } + this.touch(sandbox); + }); + } + + async exec( + sandbox: string, + _runnerId: string, + argv: string[], + stdin: Buffer, + output: OutputSink, + signal: AbortSignal, + ): Promise { + const entry = await this.lock.run(sandbox, async () => { + let current = this.tracked.get(sandbox); + if (!current || current.stopped || this.settings.now() - current.verifiedAt >= RECHECK_MS) { + // Idle stop, a runner restart or a Docker restart may have left the + // container stopped between BoxCompute's ensure and this command. + const state = await this.state(sandbox); + if (state === "missing") throw new Error("This sandbox does not exist on the runner; ensure it first."); + if (state === "stopped") await this.must(dockerArgs.start(sandbox)); + current = this.touch(sandbox); + } + current.running += 1; + return current; + }); + if (signal.aborted) { + entry.running -= 1; + throw new Error("cancelled"); + } + const execId = randomUUID(); + try { + return await this.processes.stream(this.settings.command, dockerArgs.exec(sandbox, argv, execId), this.env, stdin, output, signal); + } finally { + entry.running -= 1; + entry.lastActive = this.settings.now(); + entry.verifiedAt = entry.lastActive; + if (signal.aborted) this.processes.detach(this.settings.command, dockerArgs.killExec(sandbox, execId), this.env); + } + } + + remove(sandbox: string): Promise { + return this.lock.run(sandbox, async () => { + const container = await this.docker(dockerArgs.removeContainer(sandbox)); + if (container.code !== 0 && !/no such container/i.test(container.stderr)) { + throw new Error(dockerError(container.stderr) || `docker rm exited with code ${container.code}`); + } + const volume = await this.docker(dockerArgs.removeVolume(sandbox)); + if (volume.code !== 0 && !/no such volume/i.test(volume.stderr)) { + throw new Error(dockerError(volume.stderr) || `docker volume rm exited with code ${volume.code}`); + } + this.tracked.delete(sandbox); + }); + } + + async sweep(): Promise { + if (!this.settings.idleStopMs || this.sweeping) return; + this.sweeping = true; + try { + for (const [sandbox, entry] of this.tracked) { + if (!this.idle(entry)) continue; + await this.lock.run(sandbox, async () => { + if (this.tracked.get(sandbox) !== entry || !this.idle(entry)) return; + const result = await this.docker(dockerArgs.stop(sandbox)); + if (result.code === 0) { + entry.stopped = true; + this.settings.log(`idle-stop ${sandbox} after ${minutes(this.settings.idleStopMs)} without commands; files kept`); + } else if (/no such container/i.test(result.stderr)) { + this.tracked.delete(sandbox); + } else { + this.settings.log(`idle-stop ${sandbox} failed: ${dockerError(result.stderr) || `exit ${result.code}`}`); + } + }).catch((error: unknown) => { + this.settings.log(`idle-stop ${sandbox} failed: ${(error as Error)?.message ?? String(error)}`); + }); + } + } finally { + this.sweeping = false; + } + } + + shutdown(): Promise { + return this.processes.stop(); + } + + private idle(entry: Tracked): boolean { + return !entry.stopped && entry.running === 0 && this.settings.now() - entry.lastActive >= this.settings.idleStopMs; + } + + private touch(sandbox: string): Tracked { + const entry = this.tracked.get(sandbox) ?? { lastActive: 0, verifiedAt: 0, running: 0, stopped: false }; + entry.lastActive = this.settings.now(); + entry.verifiedAt = entry.lastActive; + entry.stopped = false; + this.tracked.set(sandbox, entry); + return entry; + } + + private docker(args: string[]): Promise { + return this.processes.collect(this.settings.command, args, this.env); + } + + private async must(args: string[]): Promise { + const result = await this.docker(args); + if (result.code !== 0) throw new Error(dockerError(result.stderr) || `docker ${args[0]} exited with code ${result.code}`); + } + + private async state(sandbox: string): Promise<"running" | "stopped" | "missing"> { + const result = await this.docker(dockerArgs.inspect(sandbox)); + if (result.code === 0) return result.stdout.trim() === "true" ? "running" : "stopped"; + if (/no such (container|object)/i.test(result.stderr)) return "missing"; + throw new Error(dockerError(result.stderr) || `docker inspect exited with code ${result.code}`); + } +} + +function minutes(milliseconds: number): string { + const total = Math.round(milliseconds / 60_000); + if (total < 1) return `${Math.round(milliseconds / 1000)}s`; + return total % 60 === 0 ? `${total / 60}h` : `${total}m`; +} + +class CustomDispatcher implements Dispatcher { + readonly mode = "custom" as const; + private program = ""; + private readonly lock = new KeyedLock(); + + constructor( + private readonly requested: string, + private readonly image: string, + private readonly env: NodeJS.ProcessEnv, + private readonly processes: Processes, + ) {} + + async check(): Promise { + this.program = resolveProgram(this.requested, this.env); + } + + ensure(sandbox: string, runnerId: string): Promise { + return this.lifecycle("ensure", sandbox, runnerId); + } + + remove(sandbox: string, runnerId: string): Promise { + return this.lifecycle("delete", sandbox, runnerId); + } + + exec( + sandbox: string, + runnerId: string, + argv: string[], + stdin: Buffer, + output: OutputSink, + signal: AbortSignal, + ): Promise { + return this.processes.stream(this.program, argv, this.environment("exec", sandbox, runnerId), stdin, output, signal); + } + + sweep(): Promise { + return Promise.resolve(); + } + + shutdown(): Promise { + return this.processes.stop(); + } + + private environment(operation: string, sandbox: string, runnerId: string): NodeJS.ProcessEnv { + return { + ...this.env, + BOXCOMPUTE_OPERATION: operation, + BOXCOMPUTE_SANDBOX_ID: sandbox, + BOXCOMPUTE_RUNNER_ID: runnerId, + BOXCOMPUTE_IMAGE: this.image, + }; + } + + private lifecycle(operation: "ensure" | "delete", sandbox: string, runnerId: string): Promise { + return this.lock.run(sandbox, async () => { + const result = await this.processes.collect(this.program, [], this.environment(operation, sandbox, runnerId)); + if (result.code !== 0) { + throw new Error(lastLine(result.stderr) || `${path.basename(this.program)} ${operation} exited with code ${result.code}`); + } + }); + } +} diff --git a/src/runner.ts b/src/runner.ts new file mode 100644 index 0000000..6ba9b84 --- /dev/null +++ b/src/runner.ts @@ -0,0 +1,540 @@ +import path from "node:path"; +import type { Writable } from "node:stream"; +import { createDispatcher, type Dispatcher, type OutputSink } from "./runner-dispatch.js"; + +export { RUNNER_TOKEN_ENV } from "./runner-dispatch.js"; + +export const DEFAULT_RUNNER_IMAGE = "node:22-bookworm"; +export const DEFAULT_IDLE_STOP_MS = 30 * 60_000; +export const RUNNER_IMAGE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._/:@+-]{0,254}$/; +export const RUNNER_TOKEN_PATTERN = /^bxr_[\x21-\x7e]+$/; + +const PROTOCOL = 1; +const SANDBOX_ID = /^bxs-[a-f0-9]{16}$/; +const RUNNER_ID = /^[A-Za-z0-9_-]{1,128}$/; +const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/; +const SOCKET_OPEN = 1; +// Output is queued in memory while the socket is slow; pause the command's +// pipes instead of letting several 64 MiB executions pile up. +const HIGH_WATER = 8 * 1024 * 1024; +const LOW_WATER = 1024 * 1024; + +const FATAL_CLOSES = new Map([ + [4400, "BoxCompute rejected a message from this runner. Update the CLI with `bxc update`."], + [4401, "BoxCompute did not accept BOXCOMPUTE_RUNNER_TOKEN. Create a runner in BoxCompute (Settings → Runners) and export its token."], + [4403, "Self-hosted runners are not available on this BoxCompute account."], + [4409, "Another `bxc runner` connected with the same token, so this one stopped."], +]); + +export type RunnerTiming = { + /** Drop the connection when nothing arrives for this long (the server pings every 25 s). */ + silenceMs: number; + backoffMinMs: number; + backoffMaxMs: number; + /** Reconnect window after close code 1012 (server restarting). */ + restartMinMs: number; + restartMaxMs: number; + sweepMs: number; + closeWaitMs: number; +}; + +export type RunnerLimits = { maxConcurrent: number; outputBudget: number; outputChunk: number }; + +const DEFAULT_TIMING: RunnerTiming = { + silenceMs: 70_000, + backoffMinMs: 1_000, + backoffMaxMs: 30_000, + restartMinMs: 1_000, + restartMaxMs: 3_000, + sweepMs: 60_000, + closeWaitMs: 2_000, +}; + +const DEFAULT_LIMITS: RunnerLimits = { + maxConcurrent: 8, + outputBudget: 64 * 1024 * 1024, + outputChunk: 256 * 1024, +}; + +export type RunnerOptions = { + /** BoxCompute web origin, already normalized. */ + url: string; + token: string; + image: string; + /** Whether --image was given; custom dispatch reports only a chosen image. */ + imageChosen: boolean; + dispatch: string | null; + idleStopMs: number; + verbose: boolean; + version: string; +}; + +export type RunnerDependencies = { + env: NodeJS.ProcessEnv; + stdout: Writable; + stderr: Writable; + signal: AbortSignal; + WebSocket: typeof WebSocket; + random?: () => number; + now?: () => number; + timing?: Partial; + limits?: Partial; +}; + +type Frame = Record; +type Operation = "ensure" | "exec" | "delete"; +type Request = { id: string; op: Operation; sandbox: string; argv: string[]; stdin: Buffer }; +type Welcome = { runnerId: string; name: string; maxConcurrent: number | null }; +type Outcome = + | { type: "stopped" } + | { type: "fatal"; message: string } + | { type: "retry"; code: number; welcomed: boolean; message: string }; + +/** The runner endpoint for a BoxCompute origin. Plain ws:// is only for loopback development servers. */ +export function runnerSocketUrl(origin: string): string { + const url = new URL(origin); + if (url.protocol === "https:") return `wss://${url.host}/api/runners/connect`; + if (url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) { + return `ws://${url.host}/api/runners/connect`; + } + throw new Error("bxc runner needs an https:// BoxCompute URL; plain http is allowed only for localhost."); +} + +/** Parses --idle-stop: 0, or hours/minutes/seconds such as 30m, 2h or 1h30m. */ +export function parseDuration(value: string): number { + if (value === "0") return 0; + const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(value); + if (!value || !match) throw new Error("--idle-stop must be a duration such as 30m, 2h or 90s, or 0 to never stop"); + const [hours, minutes, seconds] = match.slice(1).map((part) => Number(part ?? 0)) as [number, number, number]; + const milliseconds = ((hours * 60 + minutes) * 60 + seconds) * 1000; + if (!Number.isSafeInteger(milliseconds)) throw new Error("--idle-stop is too long"); + return milliseconds; +} + +/** One printable line: no control characters, the token never, at most `limit` characters. */ +export function safeText(value: string, limit: number, secret?: string): string { + const text = (secret ? value.split(secret).join("[redacted]") : value) + .replace(/\p{Cc}+/gu, " ") + .replace(/\s+/g, " ") + .trim(); + return text.length > limit ? `${text.slice(0, limit - 1)}…` : text; +} + +/** Validates a request frame. Returns nothing when there is no usable id to answer. */ +export function parseRequest(frame: Frame): { id: string; request?: Request; error?: string } | undefined { + const { id, op, sandbox, argv, stdin } = frame; + if (typeof id !== "string" || !id || id.length > 200) return undefined; + if (op !== "ensure" && op !== "exec" && op !== "delete") return { id, error: "unsupported operation" }; + if (typeof sandbox !== "string" || !SANDBOX_ID.test(sandbox)) return { id, error: "invalid sandbox id" }; + if (op !== "exec") return { id, request: { id, op, sandbox, argv: [], stdin: Buffer.alloc(0) } }; + if (!Array.isArray(argv) || !argv.length || !argv.every((arg) => typeof arg === "string" && !arg.includes("\0"))) { + return { id, error: "invalid argv" }; + } + if (stdin !== undefined && stdin !== null && (typeof stdin !== "string" || stdin.length % 4 !== 0 || !BASE64.test(stdin))) { + return { id, error: "invalid stdin" }; + } + return { + id, + request: { + id, + op, + sandbox, + argv: argv as string[], + stdin: typeof stdin === "string" ? Buffer.from(stdin, "base64") : Buffer.alloc(0), + }, + }; +} + +function parseFrame(data: unknown): Frame | undefined { + if (typeof data !== "string") return undefined; + try { + const value: unknown = JSON.parse(data); + return value && typeof value === "object" && !Array.isArray(value) ? value as Frame : undefined; + } catch { + return undefined; + } +} + +function parseWelcome(frame: Frame): Welcome | undefined { + const { runnerId, name, maxConcurrent } = frame; + if (typeof runnerId !== "string" || !RUNNER_ID.test(runnerId)) return undefined; + return { + runnerId, + name: typeof name === "string" && name.trim() ? name : runnerId, + maxConcurrent: Number.isSafeInteger(maxConcurrent) && Number(maxConcurrent) > 0 ? Number(maxConcurrent) : null, + }; +} + +function closeQuietly(socket: WebSocket, code: number, reason: string): void { + try { + socket.close(code, reason); + } catch { + // Already closing. + } +} + +const elapsed = (milliseconds: number) => `${(milliseconds / 1000).toFixed(1)}s`; + +type Link = { send(frame: Frame): void; drained(): Promise | undefined }; +type SessionContext = { + link: Link; + dispatcher: Dispatcher; + runnerId: string; + limit: number; + limits: RunnerLimits; + token: string; + verbose: boolean; + now: () => number; + log: (line: string) => void; +}; +type Active = { request: Request; controller: AbortController; replied: boolean; started: number }; + +/** Requests on one welcomed connection. A reconnect starts a new session; the server already failed the old one's requests. */ +class Session { + private readonly queue: Request[] = []; + private readonly active = new Map(); + private closed = false; + + constructor(private readonly context: SessionContext) {} + + handle(frame: Frame): void { + if (frame.type === "request") this.request(frame); + else if (frame.type === "cancel") this.cancel(frame.id); + // Unknown frame types are ignored so the server can add new ones. + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.queue.length = 0; + for (const active of this.active.values()) active.controller.abort(); + } + + private request(frame: Frame): void { + const parsed = parseRequest(frame); + if (!parsed) return; + // A repeated id would make two results ambiguous; the first request answers it. + if (this.active.has(parsed.id) || this.queue.some((request) => request.id === parsed.id)) return; + if (!parsed.request) { + this.reply(parsed.id, { ok: false, error: parsed.error }); + this.context.log(`${safeText(String(frame.op), 20) || "request"} rejected: ${parsed.error}`); + return; + } + this.queue.push(parsed.request); + this.pump(); + } + + private cancel(id: unknown): void { + if (typeof id !== "string") return; + const index = this.queue.findIndex((request) => request.id === id); + if (index >= 0) { + const [request] = this.queue.splice(index, 1); + this.reply(id, { ok: false, error: "cancelled" }); + this.finished(request!, this.context.now(), "cancelled before it started"); + return; + } + const active = this.active.get(id); + if (!active || active.replied) return; + active.controller.abort(); + active.replied = true; + this.reply(id, { ok: false, error: "cancelled" }); + this.finished(active.request, active.started, "cancelled"); + } + + private pump(): void { + while (!this.closed && this.active.size < this.context.limit && this.queue.length) { + void this.run(this.queue.shift()!); + } + } + + private async run(request: Request): Promise { + const { dispatcher, runnerId } = this.context; + const active: Active = { request, controller: new AbortController(), replied: false, started: this.context.now() }; + this.active.set(request.id, active); + let result: Frame; + let status: string; + try { + if (request.op === "exec") { + const exitCode = await dispatcher.exec( + request.sandbox, runnerId, request.argv, request.stdin, this.sink(active), active.controller.signal, + ); + result = { ok: true, exitCode }; + status = `exit ${exitCode}`; + } else { + await (request.op === "ensure" ? dispatcher.ensure(request.sandbox, runnerId) : dispatcher.remove(request.sandbox, runnerId)); + result = { ok: true }; + status = "ok"; + } + } catch (error) { + const message = safeText((error as Error)?.message ?? String(error), 500, this.context.token) || "operation failed"; + result = { ok: false, error: message }; + status = `failed: ${message}`; + } finally { + this.active.delete(request.id); + } + if (!active.replied) { + active.replied = true; + if (this.closed) { + this.finished(request, active.started, "interrupted"); + } else { + this.reply(request.id, result); + this.finished(request, active.started, status); + } + } + this.pump(); + } + + private sink(active: Active): OutputSink { + const { limits, link } = this.context; + let forwarded = 0; + let truncated = false; + return (stream, chunk) => { + if (active.replied || this.closed) return undefined; + const room = limits.outputBudget - forwarded; + if (chunk.length > room && !truncated) { + truncated = true; + this.context.log( + `exec ${active.request.sandbox} output passed ${Math.round(limits.outputBudget / 1024 / 1024)} MiB; discarding the rest`, + ); + } + if (room <= 0) return undefined; + const part = chunk.length > room ? chunk.subarray(0, room) : chunk; + forwarded += part.length; + for (let offset = 0; offset < part.length; offset += limits.outputChunk) { + link.send({ + type: "output", + id: active.request.id, + stream, + data: part.subarray(offset, offset + limits.outputChunk).toString("base64"), + }); + } + return link.drained(); + }; + } + + private reply(id: string, result: Frame): void { + this.context.link.send({ type: "result", id, ...result }); + } + + private finished(request: Request, started: number, status: string): void { + let line = `${request.op} ${request.sandbox} ${status} (${elapsed(this.context.now() - started)})`; + if (this.context.verbose && request.op === "exec") line += ` ${safeText(JSON.stringify(request.argv), 1000, this.context.token)}`; + this.context.log(line); + } +} + +function pause(milliseconds: number, signal: AbortSignal): Promise { + return new Promise((resolve) => { + if (signal.aborted) { + resolve(false); + return; + } + const done = () => { + clearTimeout(timer); + resolve(false); + }; + const timer = setTimeout(() => { + signal.removeEventListener("abort", done); + resolve(true); + }, milliseconds); + signal.addEventListener("abort", done, { once: true }); + }); +} + +/** + * Keeps an outbound WebSocket to BoxCompute open and runs the agent's + * operations through the dispatcher. Resolves 0 after a signal and 1 when + * BoxCompute refuses this runner; transient failures reconnect. + */ +export async function runRunner(options: RunnerOptions, deps: RunnerDependencies): Promise { + const timing = { ...DEFAULT_TIMING, ...deps.timing }; + const limits = { ...DEFAULT_LIMITS, ...deps.limits }; + const random = deps.random ?? Math.random; + const now = deps.now ?? Date.now; + const out = (line: string) => { deps.stdout.write(`${line}\n`); }; + const err = (line: string) => { deps.stderr.write(`${line}\n`); }; + const socketUrl = runnerSocketUrl(options.url); + const host = new URL(socketUrl).host; + const dispatcher = createDispatcher({ + program: options.dispatch, + image: options.image, + idleStopMs: options.idleStopMs, + env: deps.env, + log: out, + }); + await dispatcher.check(); + const purpose = dispatcher.mode === "docker" + ? "Chats that run on this runner will start containers here." + : `Chats that run on this runner will run commands through ${path.basename(options.dispatch ?? "")}.`; + let connectedBefore = false; + const hello = { + type: "hello", + protocol: PROTOCOL, + token: options.token, + client: { + name: "bxc", + version: options.version, + platform: process.platform, + arch: process.arch, + dispatch: dispatcher.mode, + image: dispatcher.mode === "docker" || options.imageChosen ? options.image : null, + }, + }; + + const connectOnce = () => new Promise((resolve) => { + let socket: WebSocket; + try { + socket = new deps.WebSocket(socketUrl); + } catch { + resolve({ type: "retry", code: 0, welcomed: false, message: `Could not connect to ${host}.` }); + return; + } + let opened = false; + let stopping = false; + let settled = false; + let session: Session | undefined; + let watchdog: NodeJS.Timeout | undefined; + let stopTimer: NodeJS.Timeout | undefined; + + const link: Link = { + send(frame) { + if (socket.readyState !== SOCKET_OPEN) return; + try { + socket.send(JSON.stringify(frame)); + } catch { + // The close event reports the failure. + } + }, + drained() { + if (socket.readyState !== SOCKET_OPEN || socket.bufferedAmount <= HIGH_WATER) return undefined; + return new Promise((resolveDrain) => { + const check = () => { + if (settled || socket.readyState !== SOCKET_OPEN || socket.bufferedAmount <= LOW_WATER) resolveDrain(); + else setTimeout(check, 20); + }; + setTimeout(check, 20); + }); + }, + }; + const finish = (outcome: Outcome) => { + if (settled) return; + settled = true; + clearTimeout(watchdog); + clearTimeout(stopTimer); + deps.signal.removeEventListener("abort", stop); + session?.close(); + resolve(outcome); + }; + const silent = () => { + finish(opened + ? { type: "retry", code: 0, welcomed: Boolean(session), message: `No message from BoxCompute for ${Math.round(timing.silenceMs / 1000)}s.` } + : { type: "retry", code: 0, welcomed: false, message: `Could not connect to ${host}.` }); + closeQuietly(socket, 1000, "no ping"); + }; + const arm = () => { + clearTimeout(watchdog); + watchdog = setTimeout(silent, timing.silenceMs); + }; + function stop() { + stopping = true; + session?.close(); + closeQuietly(socket, 1000, "runner stopped"); + stopTimer = setTimeout(() => finish({ type: "stopped" }), timing.closeWaitMs); + } + + socket.addEventListener("open", () => { + opened = true; + arm(); + link.send(hello); + }); + socket.addEventListener("message", (event: MessageEvent) => { + if (settled || stopping) return; + arm(); + const frame = parseFrame(event.data); + if (!frame) return; + if (frame.type === "ping") { + link.send({ type: "pong", t: frame.t }); + return; + } + if (session) { + session.handle(frame); + return; + } + if (frame.type === "welcome") { + const welcome = parseWelcome(frame); + if (!welcome) { + finish({ type: "fatal", message: "BoxCompute sent a welcome this CLI does not understand. Update it with `bxc update`." }); + closeQuietly(socket, 1000, "invalid welcome"); + return; + } + session = new Session({ + link, + dispatcher, + runnerId: welcome.runnerId, + limit: Math.min(limits.maxConcurrent, welcome.maxConcurrent ?? limits.maxConcurrent), + limits, + token: options.token, + verbose: options.verbose, + now, + log: out, + }); + const name = safeText(welcome.name, 100, options.token); + out(connectedBefore ? `Reconnected as "${name}".` : `Connected as "${name}". ${purpose} Press Ctrl-C to stop.`); + connectedBefore = true; + return; + } + if (frame.type === "request" && typeof frame.id === "string") { + link.send({ type: "result", id: frame.id, ok: false, error: "runner is not ready" }); + } + }); + socket.addEventListener("close", (event: CloseEvent) => { + if (stopping) { + finish({ type: "stopped" }); + return; + } + const reason = safeText(String(event.reason ?? ""), 200, options.token); + const detail = `${event.code}${reason ? `: ${reason}` : ""}`; + const fatal = FATAL_CLOSES.get(event.code); + if (fatal) finish({ type: "fatal", message: `${fatal} (${detail})` }); + else if (!opened) finish({ type: "retry", code: event.code, welcomed: false, message: `Could not connect to ${host}.` }); + else if (event.code === 1012) finish({ type: "retry", code: 1012, welcomed: Boolean(session), message: "BoxCompute is restarting." }); + else finish({ type: "retry", code: event.code, welcomed: Boolean(session), message: `Disconnected (${detail}).` }); + }); + socket.addEventListener("error", () => undefined); + arm(); + if (deps.signal.aborted) stop(); + else deps.signal.addEventListener("abort", stop, { once: true }); + }); + + const sweep = dispatcher.mode === "docker" && options.idleStopMs > 0 + ? setInterval(() => { void dispatcher.sweep(); }, timing.sweepMs) + : undefined; + try { + let backoff = timing.backoffMinMs; + for (;;) { + if (deps.signal.aborted) break; + if (options.verbose) err(`Connecting to ${socketUrl}`); + const outcome = await connectOnce(); + if (outcome.type === "stopped") break; + if (outcome.type === "fatal") { + err(outcome.message); + return 1; + } + if (outcome.welcomed) backoff = timing.backoffMinMs; + let wait: number; + if (outcome.code === 1012) { + wait = timing.restartMinMs + random() * (timing.restartMaxMs - timing.restartMinMs); + } else { + wait = Math.min(timing.backoffMaxMs, Math.max(timing.backoffMinMs, backoff * (0.75 + random() * 0.5))); + backoff = Math.min(backoff * 2, timing.backoffMaxMs); + } + err(`${outcome.message} Reconnecting in ${Math.max(1, Math.round(wait / 1000))}s.`); + if (!await pause(wait, deps.signal)) break; + } + out(dispatcher.mode === "docker" ? "Runner stopped. Containers and their files stay on this machine." : "Runner stopped."); + return 0; + } finally { + clearInterval(sweep); + await dispatcher.shutdown(); + } +} diff --git a/test/fixtures/fake-dispatch.sh b/test/fixtures/fake-dispatch.sh new file mode 100755 index 0000000..7f3cfb2 --- /dev/null +++ b/test/fixtures/fake-dispatch.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Test double for `bxc runner --dispatch`: runs exec argv directly on the host +# and records each call so tests can see what the runner asked for. A leaked +# runner token would show up in the log instead of "no-token". +printf '%s %s %s %s %s\n' "$BOXCOMPUTE_OPERATION" "$BOXCOMPUTE_SANDBOX_ID" "$BOXCOMPUTE_RUNNER_ID" \ + "${BOXCOMPUTE_IMAGE:-no-image}" "${BOXCOMPUTE_RUNNER_TOKEN:-no-token}" >> "${FAKE_DISPATCH_LOG:?}" +case "$BOXCOMPUTE_OPERATION" in + ensure|delete) + if [ "$BOXCOMPUTE_SANDBOX_ID" = bxs-ffffffffffffffff ]; then + echo "preparing sandbox" >&2 + echo "disk full on test host" >&2 + echo "" >&2 + exit 1 + fi + ;; + exec) + exec "$@" + ;; + *) + echo "unknown operation" >&2 + exit 2 + ;; +esac diff --git a/test/fixtures/fake-docker.sh b/test/fixtures/fake-docker.sh new file mode 100755 index 0000000..32a35b1 --- /dev/null +++ b/test/fixtures/fake-docker.sh @@ -0,0 +1,55 @@ +#!/bin/sh +# Test double for the docker CLI used by `bxc runner`: records every call and +# keeps one container's state in a file instead of talking to a daemon. +printf '%s%s\n' "${BOXCOMPUTE_RUNNER_TOKEN:+TOKEN-LEAKED }" "$*" >> "${FAKE_DOCKER_LOG:?}" +state_file=${FAKE_DOCKER_STATE:?} +state=$(cat "$state_file" 2>/dev/null || echo missing) +case "$1" in + version) + if [ -n "${FAKE_DOCKER_DOWN:-}" ]; then + echo "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?" >&2 + exit 1 + fi + echo 27.0.0 + ;; + inspect) + case "$state" in + missing) echo "Error: No such container: $6" >&2; exit 1 ;; + running) echo true ;; + *) echo false ;; + esac + ;; + run) + if [ -n "${FAKE_DOCKER_PULL_DENIED:-}" ]; then + echo "docker: Error response from daemon: pull access denied for private/image, repository does not exist or may require 'docker login'." >&2 + echo "See 'docker run --help'." >&2 + exit 125 + fi + echo running > "$state_file" + echo 4f0c0ffee + ;; + start) echo running > "$state_file"; echo "$2" ;; + stop) echo stopped > "$state_file"; echo "$4" ;; + rm) + if [ "$state" = missing ]; then echo "Error response from daemon: No such container: $3" >&2; exit 1; fi + echo missing > "$state_file" + echo "$3" + ;; + volume) echo "$4" ;; + exec) + shift + if [ "$1" = -i ]; then + shift + if [ "$1" = --env ]; then shift 2; fi + shift + exec "$@" + fi + case "$4" in + *python3*) exit "${FAKE_DOCKER_TOOLS_EXIT:-0}" ;; + esac + ;; + *) + echo "unexpected docker call: $*" >&2 + exit 64 + ;; +esac diff --git a/test/runner-dispatch.test.ts b/test/runner-dispatch.test.ts new file mode 100644 index 0000000..66cf2cf --- /dev/null +++ b/test/runner-dispatch.test.ts @@ -0,0 +1,301 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { + createDispatcher, + dockerArgs, + dockerWorkspaceVolume, + lastLine, + resolveProgram, + withoutRunnerToken, + type OutputSink, +} from "../src/runner-dispatch.js"; + +const SANDBOX = "bxs-0123456789abcdef"; +const TOKEN = "bxr_test_0123456789abcdef_SECRET"; +const FAKE_DOCKER = fileURLToPath(new URL("./fixtures/fake-docker.sh", import.meta.url)); + +const directories: string[] = []; +afterEach(async () => { + await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))); +}); + +async function fakeDocker(extraEnv: NodeJS.ProcessEnv = {}, idleStopMs = 60_000) { + const directory = await mkdtemp(path.join(tmpdir(), "bxc-docker-")); + directories.push(directory); + const logFile = path.join(directory, "docker.log"); + const stateFile = path.join(directory, "state"); + let clock = 0; + const lines: string[] = []; + const dispatcher = createDispatcher({ + program: null, + image: "node:22-bookworm", + idleStopMs, + env: { + PATH: process.env.PATH, + BOXCOMPUTE_RUNNER_TOKEN: TOKEN, + FAKE_DOCKER_LOG: logFile, + FAKE_DOCKER_STATE: stateFile, + ...extraEnv, + }, + log: (line) => lines.push(line), + docker: FAKE_DOCKER, + now: () => clock, + }); + return { + dispatcher, + lines, + setClock: (value: number) => { clock = value; }, + calls: async () => (await readFile(logFile, "utf8").catch(() => "")).trim().split("\n").filter(Boolean), + reset: () => writeFile(logFile, ""), + stopBehindTheRunnersBack: () => writeFile(stateFile, "stopped\n"), + }; +} + +function collector() { + const text = { stdout: "", stderr: "" }; + const sink: OutputSink = (stream, chunk) => { + text[stream] += chunk.toString("utf8"); + return undefined; + }; + return { text, sink }; +} + +describe("Docker dispatch argv", () => { + it("builds every Docker call as an argument vector", () => { + expect(dockerWorkspaceVolume(SANDBOX)).toBe("bxs-0123456789abcdef-workspace"); + expect(dockerArgs.version()).toEqual(["version", "--format", "{{.Server.Version}}"]); + expect(dockerArgs.inspect(SANDBOX)).toEqual(["inspect", "--type", "container", "--format", "{{.State.Running}}", SANDBOX]); + expect(dockerArgs.run(SANDBOX, "rnr_abc", "node:22-bookworm")).toEqual([ + "run", "-d", + "--name", SANDBOX, + "--label", "com.boxcompute.runner=rnr_abc", + "--label", `com.boxcompute.sandbox=${SANDBOX}`, + "--init", + "-w", "/workspace", + "-v", "bxs-0123456789abcdef-workspace:/workspace", + "node:22-bookworm", "sleep", "infinity", + ]); + expect(dockerArgs.toolCheck(SANDBOX)).toEqual(["exec", SANDBOX, "sh", "-c", "command -v bash && command -v python3"]); + expect(dockerArgs.start(SANDBOX)).toEqual(["start", SANDBOX]); + // The command's argv follows the container name untouched, even when it looks like an option. + expect(dockerArgs.exec(SANDBOX, ["--help", "a b", "$(id)"], "e1")).toEqual([ + "exec", "-i", "--env", "BOXCOMPUTE_EXEC_ID=e1", SANDBOX, "--help", "a b", "$(id)", + ]); + const kill = dockerArgs.killExec(SANDBOX, "e1"); + expect(kill.slice(0, 4)).toEqual(["exec", SANDBOX, "sh", "-c"]); + expect(kill.slice(-2)).toEqual(["sh", "e1"]); + expect(kill[4]).toContain('grep -qxF "BOXCOMPUTE_EXEC_ID=$1"'); + expect(dockerArgs.stop(SANDBOX)).toEqual(["stop", "-t", "10", SANDBOX]); + expect(dockerArgs.removeContainer(SANDBOX)).toEqual(["rm", "-f", SANDBOX]); + expect(dockerArgs.removeVolume(SANDBOX)).toEqual(["volume", "rm", "-f", "bxs-0123456789abcdef-workspace"]); + }); + + it("removes the runner token from child environments", () => { + expect(withoutRunnerToken({ PATH: "/bin", BOXCOMPUTE_RUNNER_TOKEN: TOKEN, BOXCOMPUTE_URL: "https://x" })) + .toEqual({ PATH: "/bin", BOXCOMPUTE_URL: "https://x" }); + }); + + it("reports the last meaningful stderr line", () => { + expect(lastLine("first\nsecond\n\n \n")).toBe("second"); + expect(lastLine("docker: Error response from daemon: denied.\nSee 'docker run --help'.\n", /^See 'docker/)).toBe( + "docker: Error response from daemon: denied.", + ); + }); +}); + +describe("Docker dispatch", () => { + it("creates, reuses, idle-stops, restarts and deletes a sandbox without leaking the token", async () => { + const docker = await fakeDocker(); + await docker.dispatcher.check(); + await docker.dispatcher.ensure(SANDBOX, "rnr_abc"); + expect(await docker.calls()).toEqual([ + "version --format {{.Server.Version}}", + `inspect --type container --format {{.State.Running}} ${SANDBOX}`, + `run -d --name ${SANDBOX} --label com.boxcompute.runner=rnr_abc --label com.boxcompute.sandbox=${SANDBOX} ` + + `--init -w /workspace -v ${SANDBOX}-workspace:/workspace node:22-bookworm sleep infinity`, + `exec ${SANDBOX} sh -c command -v bash && command -v python3`, + ]); + + await docker.reset(); + await docker.dispatcher.ensure(SANDBOX, "rnr_abc"); + expect(await docker.calls()).toEqual([`inspect --type container --format {{.State.Running}} ${SANDBOX}`]); + + await docker.reset(); + const output = collector(); + const status = await docker.dispatcher.exec( + SANDBOX, "rnr_abc", ["sh", "-c", 'printf "%s" "${BOXCOMPUTE_RUNNER_TOKEN-unset}"; printf err >&2; exit 4'], + Buffer.alloc(0), output.sink, new AbortController().signal, + ); + expect(status).toBe(4); + expect(output.text).toEqual({ stdout: "unset", stderr: "err" }); + const [execCall] = await docker.calls(); + expect(execCall).toMatch(new RegExp(`^exec -i --env BOXCOMPUTE_EXEC_ID=[0-9a-f-]{36} ${SANDBOX} sh -c `)); + + // Not idle yet, then idle: stopped once, and the volume stays. + await docker.reset(); + docker.setClock(59_999); + await docker.dispatcher.sweep(); + expect(await docker.calls()).toEqual([]); + docker.setClock(60_000); + await docker.dispatcher.sweep(); + await docker.dispatcher.sweep(); + expect(await docker.calls()).toEqual([`stop -t 10 ${SANDBOX}`]); + expect(docker.lines).toEqual([`idle-stop ${SANDBOX} after 1m without commands; files kept`]); + + // A command after idle stop starts the container again first. + await docker.reset(); + const again = collector(); + expect(await docker.dispatcher.exec(SANDBOX, "rnr_abc", ["printf", "back"], Buffer.alloc(0), again.sink, new AbortController().signal)).toBe(0); + expect(again.text.stdout).toBe("back"); + const restarted = await docker.calls(); + expect(restarted.slice(0, 2)).toEqual([`inspect --type container --format {{.State.Running}} ${SANDBOX}`, `start ${SANDBOX}`]); + + // A running command is never idle-stopped. + await docker.reset(); + const running = docker.dispatcher.exec(SANDBOX, "rnr_abc", ["sleep", "0.5"], Buffer.alloc(0), collector().sink, new AbortController().signal); + await new Promise((resolve) => setTimeout(resolve, 100)); + docker.setClock(10_000_000); + await docker.dispatcher.sweep(); + expect(await running).toBe(0); + expect((await docker.calls()).filter((call) => call.startsWith("stop"))).toEqual([]); + + // Docker stopped it on its own (daemon restart): a command more than 10 s + // after the last check inspects and starts it before running. + await docker.stopBehindTheRunnersBack(); + docker.setClock(10_000_000 + 9_999); + await docker.reset(); + expect(await docker.dispatcher.exec(SANDBOX, "rnr_abc", ["true"], Buffer.alloc(0), collector().sink, new AbortController().signal)).toBe(0); + expect((await docker.calls())[0]).toMatch(/^exec -i /); + await docker.stopBehindTheRunnersBack(); + docker.setClock(10_000_000 + 9_999 + 10_000); + await docker.reset(); + expect(await docker.dispatcher.exec(SANDBOX, "rnr_abc", ["true"], Buffer.alloc(0), collector().sink, new AbortController().signal)).toBe(0); + expect((await docker.calls()).slice(0, 2)).toEqual([`inspect --type container --format {{.State.Running}} ${SANDBOX}`, `start ${SANDBOX}`]); + + await docker.reset(); + await docker.dispatcher.remove(SANDBOX, "rnr_abc"); + await docker.dispatcher.remove(SANDBOX, "rnr_abc"); + expect(await docker.calls()).toEqual([ + `rm -f ${SANDBOX}`, `volume rm -f ${SANDBOX}-workspace`, + `rm -f ${SANDBOX}`, `volume rm -f ${SANDBOX}-workspace`, + ]); + await expect(docker.dispatcher.exec(SANDBOX, "rnr_abc", ["true"], Buffer.alloc(0), collector().sink, new AbortController().signal)) + .rejects.toThrow("does not exist on the runner"); + + expect((await readFile(path.join(directories[0]!, "docker.log"), "utf8"))).not.toContain("TOKEN-LEAKED"); + await docker.dispatcher.shutdown(); + }, 15_000); + + it("kills a cancelled command inside its container as well as the local client", async () => { + const docker = await fakeDocker(); + await docker.dispatcher.ensure(SANDBOX, "rnr_abc"); + await docker.reset(); + const abort = new AbortController(); + const started = Date.now(); + const running = docker.dispatcher.exec(SANDBOX, "rnr_abc", ["sleep", "30"], Buffer.alloc(0), collector().sink, abort.signal); + await new Promise((resolve) => setTimeout(resolve, 200)); + abort.abort(); + expect(await running).toBe(137); + expect(Date.now() - started).toBeLessThan(5_000); + await docker.dispatcher.shutdown(); + const log = (await docker.calls()).join("\n"); + const execId = /BOXCOMPUTE_EXEC_ID=([0-9a-f-]{36})/.exec(log)?.[1]; + expect(execId).toBeDefined(); + expect(log).toContain(`exec ${SANDBOX} sh -c for p in /proc/[0-9]*; do`); + expect(log).toContain(`exit 0 sh ${execId}`); + }, 10_000); + + it("explains Docker, image and tool failures", async () => { + const down = await fakeDocker({ FAKE_DOCKER_DOWN: "1" }); + await expect(down.dispatcher.check()).rejects.toThrow( + "Docker is not reachable (Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?). Start Docker", + ); + + const missing = createDispatcher({ program: null, image: "node:22-bookworm", idleStopMs: 0, env: {}, log: () => undefined, docker: "/nonexistent/docker" }); + await expect(missing.check()).rejects.toThrow("Docker is not installed or not on PATH"); + + const denied = await fakeDocker({ FAKE_DOCKER_PULL_DENIED: "1" }); + await expect(denied.dispatcher.ensure(SANDBOX, "rnr_abc")).rejects.toThrow( + "docker: Error response from daemon: pull access denied for private/image, repository does not exist or may require 'docker login'.", + ); + + const bare = await fakeDocker({ FAKE_DOCKER_TOOLS_EXIT: "1" }); + await expect(bare.dispatcher.ensure(SANDBOX, "rnr_abc")).rejects.toThrow( + "The image node:22-bookworm needs bash and python3. Choose another with --image.", + ); + expect((await bare.calls()).at(-1)).toBe(`rm -f ${SANDBOX}`); + }, 10_000); +}); + +describe("custom dispatch program", () => { + it("resolves the program to an absolute executable path", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "bxc-dispatch-")); + directories.push(directory); + const program = path.join(directory, "dispatch-test"); + await writeFile(program, "#!/bin/sh\nexit 0\n"); + await expect(Promise.resolve().then(() => resolveProgram(program, {}))).rejects.toThrow("is not an executable file"); + await chmod(program, 0o755); + expect(resolveProgram(program, {})).toBe(program); + expect(resolveProgram("dispatch-test", { PATH: `/nonexistent${path.delimiter}${directory}` })).toBe(program); + expect(() => resolveProgram("dispatch-test", { PATH: "/nonexistent" })).toThrow("was not found on PATH"); + }); + + it("runs the README's example dispatch.sh", async () => { + const readme = await readFile(new URL("../README.md", import.meta.url), "utf8"); + const script = /```sh\n(#!\/bin\/sh\n# bxc runner --dispatch \.\/dispatch\.sh\n[\s\S]*?)```/.exec(readme)?.[1]; + expect(script).toBeDefined(); + const directory = await mkdtemp(path.join(tmpdir(), "bxc-readme-dispatch-")); + directories.push(directory); + const bin = path.join(directory, "bin"); + await mkdir(bin); + await symlink(FAKE_DOCKER, path.join(bin, "docker")); + const program = path.join(directory, "dispatch.sh"); + await writeFile(program, script!, { mode: 0o755 }); + const logFile = path.join(directory, "docker.log"); + const make = (extra: NodeJS.ProcessEnv = {}) => createDispatcher({ + program, + image: "node:22-bookworm", + idleStopMs: 0, + env: { + PATH: `${bin}${path.delimiter}${process.env.PATH ?? ""}`, + BOXCOMPUTE_RUNNER_TOKEN: TOKEN, + FAKE_DOCKER_LOG: logFile, + FAKE_DOCKER_STATE: path.join(directory, "state"), + ...extra, + }, + log: () => undefined, + }); + const dispatcher = make(); + await dispatcher.check(); + await dispatcher.ensure(SANDBOX, "rnr_abc"); + await dispatcher.ensure(SANDBOX, "rnr_abc"); + const output = collector(); + expect(await dispatcher.exec(SANDBOX, "rnr_abc", ["printf", "hi"], Buffer.alloc(0), output.sink, new AbortController().signal)).toBe(0); + expect(output.text.stdout).toBe("hi"); + await dispatcher.remove(SANDBOX, "rnr_abc"); + await dispatcher.remove(SANDBOX, "rnr_abc"); + const inspect = `inspect --type container --format {{.State.Running}} ${SANDBOX}`; + expect((await readFile(logFile, "utf8")).trim().split("\n")).toEqual([ + inspect, + `run -d --name ${SANDBOX} --init -w /workspace --label com.boxcompute.runner=rnr_abc ` + + `--label com.boxcompute.sandbox=${SANDBOX} -v ${SANDBOX}-workspace:/workspace node:22-bookworm sleep infinity`, + `exec ${SANDBOX} sh -c command -v bash && command -v python3`, + inspect, + `exec -i ${SANDBOX} printf hi`, + `inspect --type container ${SANDBOX}`, + `rm -f ${SANDBOX}`, + `volume rm -f ${SANDBOX}-workspace`, + `inspect --type container ${SANDBOX}`, + `volume rm -f ${SANDBOX}-workspace`, + ]); + const bare = make({ FAKE_DOCKER_TOOLS_EXIT: "1", FAKE_DOCKER_STATE: path.join(directory, "bare-state") }); + await bare.check(); + await expect(bare.ensure(SANDBOX, "rnr_abc")).rejects.toThrow( + "The image node:22-bookworm needs bash and python3", + ); + await dispatcher.shutdown(); + }, 10_000); +}); diff --git a/test/runner.test.ts b/test/runner.test.ts new file mode 100644 index 0000000..8ca3729 --- /dev/null +++ b/test/runner.test.ts @@ -0,0 +1,470 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { PassThrough } from "node:stream"; +import { fileURLToPath } from "node:url"; +import type { ServerWebSocket } from "bun"; +import { runCli } from "../src/cli.js"; +import { + parseDuration, + parseRequest, + runRunner, + runnerSocketUrl, + safeText, + type RunnerDependencies, + type RunnerOptions, +} from "../src/runner.js"; + +const TOKEN = "bxr_test_0123456789abcdef_SECRET"; +const SANDBOX = "bxs-0123456789abcdef"; +const DISPATCH = fileURLToPath(new URL("./fixtures/fake-dispatch.sh", import.meta.url)); + +type Frame = Record; +type PeerData = { peer: Peer | null; path: string; authorization: string | null }; + +class Peer { + readonly frames: Frame[] = []; + closed: { code: number; reason: string } | null = null; + constructor(private readonly socket: ServerWebSocket, readonly path: string, readonly authorization: string | null) {} + send(frame: Frame): void { + this.socket.send(JSON.stringify(frame)); + } + close(code: number, reason: string): void { + this.socket.close(code, reason); + } + next(match: (frame: Frame) => boolean): Promise { + return until(() => this.frames.find(match)); + } + result(id: string): Promise { + return this.next((frame) => frame.type === "result" && frame.id === id); + } + results(id: string): Frame[] { + return this.frames.filter((frame) => frame.type === "result" && frame.id === id); + } + output(id: string, stream: "stdout" | "stderr"): string { + return Buffer.concat(this.frames + .filter((frame) => frame.type === "output" && frame.id === id && frame.stream === stream) + .map((frame) => Buffer.from(frame.data as string, "base64"))).toString("utf8"); + } + request(id: string, fields: Frame): void { + this.send({ type: "request", id, ...fields }); + } +} + +class Captured { + readonly stream = new PassThrough(); + text = ""; + constructor() { + this.stream.on("data", (chunk: Buffer) => { this.text += chunk.toString("utf8"); }); + } +} + +const sleep = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)); + +type Probe = () => T | undefined | null | false | Promise; + +async function until(probe: Probe, timeout = 5_000): Promise { + const deadline = Date.now() + timeout; + for (;;) { + const value = await probe(); + if (value) return value; + if (Date.now() > deadline) throw new Error("Timed out waiting for the runner"); + await sleep(10); + } +} + +const cleanups: Array<() => unknown> = []; +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); +}); + +function fakeServer() { + const peers: Peer[] = []; + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request, server) { + const url = new URL(request.url); + const data: PeerData = { peer: null, path: `${url.pathname}${url.search}`, authorization: request.headers.get("authorization") }; + return server.upgrade(request, { data }) ? undefined : new Response("upgrade required", { status: 426 }); + }, + websocket: { + data: {} as PeerData, + open(ws) { + const peer = new Peer(ws, ws.data.path, ws.data.authorization); + ws.data.peer = peer; + peers.push(peer); + }, + message(ws, message) { + ws.data.peer?.frames.push(JSON.parse(String(message)) as Frame); + }, + close(ws, code, reason) { + if (ws.data.peer) ws.data.peer.closed = { code, reason }; + }, + }, + }); + // Not awaited: on Bun 1.3.14 stop(true) never settles after the server + // itself closed a WebSocket (the 4401 and 1012 cases). + cleanups.push(() => { void server.stop(true); }); + return { peers, url: `http://127.0.0.1:${server.port}` }; +} + +async function startRunner(url: string, options: Partial = {}, dependencies: Partial = {}) { + const directory = await mkdtemp(path.join(tmpdir(), "bxc-runner-")); + const log = path.join(directory, "dispatch.log"); + const stdout = new Captured(); + const stderr = new Captured(); + const abort = new AbortController(); + const done = runRunner({ + url, + token: TOKEN, + image: "node:22-bookworm", + imageChosen: false, + dispatch: DISPATCH, + idleStopMs: 0, + verbose: false, + version: "0.12.0-test", + ...options, + }, { + env: { PATH: process.env.PATH, BOXCOMPUTE_RUNNER_TOKEN: TOKEN, FAKE_DISPATCH_LOG: log }, + stdout: stdout.stream, + stderr: stderr.stream, + signal: abort.signal, + WebSocket, + random: () => 0, + ...dependencies, + }); + cleanups.push(async () => { + abort.abort(); + await done.catch(() => undefined); + await rm(directory, { recursive: true, force: true }); + }); + return { + done, + abort, + stdout, + stderr, + dispatchLog: () => readFile(log, "utf8").catch(() => ""), + }; +} + +async function welcomed(url: string, options: Partial = {}, dependencies: Partial = {}, maxConcurrent = 8) { + const { peers } = servers.get(url)!; + const runner = await startRunner(url, options, dependencies); + const peer = await until(() => peers[0]); + await peer.next((frame) => frame.type === "hello"); + peer.send({ type: "welcome", runnerId: "rnr_test", name: "Test runner", maxConcurrent }); + await until(() => runner.stdout.text.includes("Connected as")); + return { runner, peer, peers }; +} + +const servers = new Map>(); +function listen() { + const instance = fakeServer(); + servers.set(instance.url, instance); + cleanups.push(() => servers.delete(instance.url)); + return instance.url; +} + +describe("bxc runner protocol", () => { + it("speaks protocol v1 through a dispatch program and keeps the token out of children and logs", async () => { + const url = listen(); + const { peers } = servers.get(url)!; + const runner = await startRunner(url); + const peer = await until(() => peers[0]); + const hello = await peer.next((frame) => frame.type === "hello"); + expect(peer.path).toBe("/api/runners/connect"); + expect(peer.authorization).toBeNull(); + expect(hello).toEqual({ + type: "hello", + protocol: 1, + token: TOKEN, + client: { name: "bxc", version: "0.12.0-test", platform: process.platform, arch: process.arch, dispatch: "custom", image: null }, + }); + + peer.request("early", { op: "ensure", sandbox: SANDBOX }); + expect(await peer.result("early")).toEqual({ type: "result", id: "early", ok: false, error: "runner is not ready" }); + + peer.send({ type: "welcome", runnerId: "rnr_test", name: "Laptop\u0007 runner", maxConcurrent: 8 }); + await until(() => runner.stdout.text.includes("Connected as")); + expect(runner.stdout.text).toContain( + 'Connected as "Laptop runner". Chats that run on this runner will run commands through fake-dispatch.sh. Press Ctrl-C to stop.\n', + ); + + peer.send({ type: "ping", t: 42 }); + expect(await peer.next((frame) => frame.type === "pong")).toEqual({ type: "pong", t: 42 }); + peer.send({ type: "telemetry", id: "ignored", anything: true }); + + peer.request("e1", { op: "ensure", sandbox: SANDBOX }); + expect(await peer.result("e1")).toEqual({ type: "result", id: "e1", ok: true }); + + peer.request("x1", { op: "exec", sandbox: SANDBOX, argv: ["sh", "-c", "printf hello; printf oops >&2; exit 3"] }); + expect(await peer.result("x1")).toEqual({ type: "result", id: "x1", ok: true, exitCode: 3 }); + expect(peer.output("x1", "stdout")).toBe("hello"); + expect(peer.output("x1", "stderr")).toBe("oops"); + // Every output frame precedes its result. + const positions = (type: string) => peer.frames.flatMap((frame, index) => (frame.type === type && frame.id === "x1" ? [index] : [])); + expect(Math.max(...positions("output"))).toBeLessThan(Math.min(...positions("result"))); + + peer.request("x2", { op: "exec", sandbox: SANDBOX, argv: ["cat"], stdin: Buffer.from("piped input\n").toString("base64") }); + expect(await peer.result("x2")).toEqual({ type: "result", id: "x2", ok: true, exitCode: 0 }); + expect(peer.output("x2", "stdout")).toBe("piped input\n"); + + peer.request("x3", { op: "exec", sandbox: SANDBOX, argv: ["cat"] }); + expect(await peer.result("x3")).toEqual({ type: "result", id: "x3", ok: true, exitCode: 0 }); + expect(peer.output("x3", "stdout")).toBe(""); + + peer.request("x4", { + op: "exec", + sandbox: SANDBOX, + argv: ["sh", "-c", 'printf "%s|%s|%s|%s|%s" "${BOXCOMPUTE_RUNNER_TOKEN-unset}" "$BOXCOMPUTE_OPERATION" "$BOXCOMPUTE_SANDBOX_ID" "$BOXCOMPUTE_RUNNER_ID" "$BOXCOMPUTE_IMAGE"'], + }); + expect(await peer.result("x4")).toMatchObject({ ok: true, exitCode: 0 }); + expect(peer.output("x4", "stdout")).toBe(`unset|exec|${SANDBOX}|rnr_test|node:22-bookworm`); + + peer.request("x5", { op: "exec", sandbox: SANDBOX, argv: ["sh", "-c", "kill -TERM $$"] }); + expect(await peer.result("x5")).toEqual({ type: "result", id: "x5", ok: true, exitCode: 143 }); + + peer.request("e2", { op: "ensure", sandbox: "bxs-ffffffffffffffff" }); + expect(await peer.result("e2")).toEqual({ type: "result", id: "e2", ok: false, error: "disk full on test host" }); + + peer.request("d1", { op: "delete", sandbox: SANDBOX }); + expect(await peer.result("d1")).toEqual({ type: "result", id: "d1", ok: true }); + + const invalid: Array<[string, Frame, string]> = [ + ["v1", { op: "exec", sandbox: "bxs-0123456789ABCDEF", argv: ["true"] }, "invalid sandbox id"], + ["v2", { op: "ensure", sandbox: "../../etc" }, "invalid sandbox id"], + ["v3", { op: "exec", sandbox: SANDBOX, argv: [] }, "invalid argv"], + ["v4", { op: "exec", sandbox: SANDBOX, argv: ["echo", 1] }, "invalid argv"], + ["v5", { op: "exec", sandbox: SANDBOX, argv: "true" }, "invalid argv"], + ["v6", { op: "exec", sandbox: SANDBOX, argv: ["cat"], stdin: "not base64!" }, "invalid stdin"], + ["v7", { op: "snapshot", sandbox: SANDBOX }, "unsupported operation"], + ]; + for (const [id, fields, error] of invalid) { + peer.request(id, fields); + expect(await peer.result(id)).toEqual({ type: "result", id, ok: false, error }); + } + + // Only valid requests reached the dispatch program, and never with the token. + const calls = (await runner.dispatchLog()).trim().split("\n"); + expect(calls).toEqual([ + `ensure ${SANDBOX} rnr_test node:22-bookworm no-token`, + ...["x1", "x2", "x3", "x4", "x5"].map(() => `exec ${SANDBOX} rnr_test node:22-bookworm no-token`), + "ensure bxs-ffffffffffffffff rnr_test node:22-bookworm no-token", + `delete ${SANDBOX} rnr_test node:22-bookworm no-token`, + ]); + + runner.abort.abort(); + expect(await runner.done).toBe(0); + expect((await until(() => peer.closed)).code).toBe(1000); + expect(peers).toHaveLength(1); + expect(runner.stdout.text).toContain(`exec ${SANDBOX} exit 3 (`); + expect(runner.stdout.text).toContain("ensure bxs-ffffffffffffffff failed: disk full on test host ("); + expect(runner.stdout.text).toContain("Runner stopped."); + expect(runner.stdout.text).not.toContain("printf hello"); + expect(`${runner.stdout.text}${runner.stderr.text}`).not.toContain(TOKEN); + }, 20_000); + + it("logs exec arguments only with --verbose and redacts the token from them", async () => { + const url = listen(); + const { runner, peer } = await welcomed(url, { verbose: true }); + peer.request("v", { op: "exec", sandbox: SANDBOX, argv: ["echo", `token=${TOKEN}`] }); + await peer.result("v"); + await until(() => runner.stdout.text.includes("exec bxs-")); + expect(runner.stdout.text).toContain('["echo","token=[redacted]"]'); + expect(runner.stdout.text).not.toContain(TOKEN); + }, 10_000); + + it("runs at most eight requests at once, queues the rest and cancels queued and running work", async () => { + const url = listen(); + const { runner, peer } = await welcomed(url, {}, {}, 50); + const execLines = async () => (await runner.dispatchLog()).split("\n").filter((line) => line.startsWith("exec ")).length; + const ids = Array.from({ length: 9 }, (_, index) => `s${index}`); + for (const id of ids) peer.request(id, { op: "exec", sandbox: SANDBOX, argv: ["sleep", "30"] }); + await until(async () => (await execLines()) === 8); + await sleep(300); + expect(await execLines()).toBe(8); + + peer.send({ type: "cancel", id: "s8" }); + expect(await peer.result("s8")).toEqual({ type: "result", id: "s8", ok: false, error: "cancelled" }); + peer.send({ type: "cancel", id: "s0" }); + expect(await peer.result("s0")).toEqual({ type: "result", id: "s0", ok: false, error: "cancelled" }); + + // s0's slot frees once its process is killed; the next request runs. + peer.request("after", { op: "exec", sandbox: SANDBOX, argv: ["sh", "-c", "printf ran"] }); + expect(await peer.result("after")).toEqual({ type: "result", id: "after", ok: true, exitCode: 0 }); + expect(peer.output("after", "stdout")).toBe("ran"); + + for (const id of ids.slice(1, 8)) peer.send({ type: "cancel", id }); + for (const id of ids.slice(1, 8)) expect(await peer.result(id)).toMatchObject({ ok: false, error: "cancelled" }); + peer.send({ type: "cancel", id: "unknown" }); + await sleep(300); + for (const id of [...ids, "after"]) expect(peer.results(id)).toHaveLength(1); + expect(peer.results("unknown")).toHaveLength(0); + expect(runner.stdout.text).toContain(`exec ${SANDBOX} cancelled before it started (`); + expect(runner.stdout.text).toContain(`exec ${SANDBOX} cancelled (`); + }, 20_000); + + it("honours a lower concurrency limit from the welcome", async () => { + const url = listen(); + const { runner, peer } = await welcomed(url, {}, {}, 2); + for (const id of ["a", "b", "c"]) peer.request(id, { op: "exec", sandbox: SANDBOX, argv: ["sleep", "30"] }); + const execLines = async () => (await runner.dispatchLog()).split("\n").filter((line) => line.startsWith("exec ")).length; + await until(async () => (await execLines()) === 2); + await sleep(300); + expect(await execLines()).toBe(2); + peer.send({ type: "cancel", id: "a" }); + await until(async () => (await execLines()) === 3); + }, 10_000); + + it("splits output into bounded chunks and stops forwarding past the budget but reports the exit code", async () => { + const url = listen(); + const { runner, peer } = await welcomed(url, {}, { limits: { outputChunk: 4_096, outputBudget: 10_000 } }); + peer.request("big", { op: "exec", sandbox: SANDBOX, argv: ["sh", "-c", "head -c 50000 /dev/zero; exit 7"] }); + expect(await peer.result("big")).toEqual({ type: "result", id: "big", ok: true, exitCode: 7 }); + const chunks = peer.frames + .filter((frame) => frame.type === "output" && frame.id === "big") + .map((frame) => Buffer.from(frame.data as string, "base64").length); + expect(Math.max(...chunks)).toBeLessThanOrEqual(4_096); + expect(chunks.reduce((sum, size) => sum + size, 0)).toBe(10_000); + expect(runner.stdout.text).toContain("discarding the rest"); + }, 10_000); + + it("exits on 4401 without reconnecting and says what to do", async () => { + const url = listen(); + const { peers } = servers.get(url)!; + const runner = await startRunner(url); + const peer = await until(() => peers[0]); + await peer.next((frame) => frame.type === "hello"); + peer.close(4401, "invalid token"); + expect(await runner.done).toBe(1); + expect(runner.stderr.text).toContain("BoxCompute did not accept BOXCOMPUTE_RUNNER_TOKEN"); + expect(runner.stderr.text).toContain("(4401: invalid token)"); + await sleep(1_500); + expect(peers).toHaveLength(1); + }, 10_000); + + it("reconnects 1–3 seconds after the server restarts (1012)", async () => { + const url = listen(); + const { runner, peer, peers } = await welcomed(url); + peer.close(1012, "restarting"); + const second = await until(() => peers[1], 5_000); + await second.next((frame) => frame.type === "hello"); + expect(runner.stderr.text).toContain("BoxCompute is restarting. Reconnecting in 1s."); + second.send({ type: "welcome", runnerId: "rnr_test", name: "Test runner", maxConcurrent: 8 }); + await until(() => runner.stdout.text.includes('Reconnected as "Test runner".')); + }, 10_000); + + it("drops a silent connection, kills its commands and reconnects", async () => { + const url = listen(); + const { runner, peer, peers } = await welcomed(url, {}, { timing: { silenceMs: 500, backoffMinMs: 50 } }); + peer.request("long", { op: "exec", sandbox: SANDBOX, argv: ["sleep", "30"] }); + await until(async () => (await runner.dispatchLog()).includes("exec ")); + const second = await until(() => peers[1], 5_000); + await second.next((frame) => frame.type === "hello"); + expect(runner.stderr.text).toContain("No message from BoxCompute for 1s. Reconnecting in 1s."); + await until(() => runner.stdout.text.includes(`exec ${SANDBOX} interrupted (`)); + expect(peer.results("long")).toHaveLength(0); + expect(second.results("long")).toHaveLength(0); + }, 10_000); +}); + +describe("bxc runner helpers", () => { + it("derives the WebSocket URL and refuses plain ws:// beyond loopback", () => { + expect(runnerSocketUrl("https://app.boxcompute.ai")).toBe("wss://app.boxcompute.ai/api/runners/connect"); + expect(runnerSocketUrl("https://box.example.com:8443")).toBe("wss://box.example.com:8443/api/runners/connect"); + expect(runnerSocketUrl("http://localhost:3000")).toBe("ws://localhost:3000/api/runners/connect"); + expect(runnerSocketUrl("http://127.0.0.1:3000")).toBe("ws://127.0.0.1:3000/api/runners/connect"); + expect(runnerSocketUrl("http://[::1]:3000")).toBe("ws://[::1]:3000/api/runners/connect"); + expect(() => runnerSocketUrl("http://box.example.com")).toThrow("needs an https:// BoxCompute URL"); + }); + + it("parses idle-stop durations", () => { + expect(parseDuration("0")).toBe(0); + expect(parseDuration("30m")).toBe(1_800_000); + expect(parseDuration("2h")).toBe(7_200_000); + expect(parseDuration("1h30m")).toBe(5_400_000); + expect(parseDuration("90s")).toBe(90_000); + for (const value of ["", "30", "m", "-5m", "1.5h", "30 m", "5d"]) expect(() => parseDuration(value)).toThrow("--idle-stop"); + }); + + it("validates requests before anything runs", () => { + expect(parseRequest({ op: "ensure", sandbox: SANDBOX })).toBeUndefined(); + expect(parseRequest({ id: 7, op: "ensure", sandbox: SANDBOX })).toBeUndefined(); + expect(parseRequest({ id: "a", op: "exec", sandbox: SANDBOX, argv: ["a\0b"] })).toEqual({ id: "a", error: "invalid argv" }); + expect(parseRequest({ id: "a", op: "exec", sandbox: SANDBOX, argv: ["cat"], stdin: "abc" })).toEqual({ id: "a", error: "invalid stdin" }); + expect(parseRequest({ id: "a", op: "exec", sandbox: SANDBOX, argv: ["cat"], stdin: "a=bc" })).toEqual({ id: "a", error: "invalid stdin" }); + expect(parseRequest({ id: "a", op: "exec", sandbox: "bxs-0123456789abcde", argv: ["cat"] })).toEqual({ id: "a", error: "invalid sandbox id" }); + expect(parseRequest({ id: "a", op: "exec", sandbox: SANDBOX, argv: ["cat"], stdin: "aGk=" })?.request?.stdin.toString()).toBe("hi"); + expect(parseRequest({ id: "a", op: "exec", sandbox: SANDBOX, argv: ["cat"], stdin: null })?.request?.stdin.length).toBe(0); + }); + + it("keeps messages to one printable line without the token", () => { + expect(safeText(`line one\n\u001b[31m${TOKEN}\u0000 tail`, 500, TOKEN)).toBe("line one [31m[redacted] tail"); + expect(safeText("x".repeat(600), 500)).toHaveLength(500); + }); +}); + +describe("bxc runner command", () => { + const io = () => ({ stdout: new PassThrough(), stderr: new PassThrough() }); + const base = { env: { BOXCOMPUTE_RUNNER_TOKEN: TOKEN }, loadSavedUrl: async () => null, syncManagedSkills: async () => [] }; + + it("reads the token only from the environment and passes the parsed options", async () => { + const seen: Array<{ options: RunnerOptions; env: NodeJS.ProcessEnv }> = []; + const runner = (async (options: RunnerOptions, dependencies: RunnerDependencies) => { + seen.push({ options, env: dependencies.env }); + return 0; + }) as typeof runRunner; + expect(await runCli(["runner", "--image", "python:3.13", "--idle-stop", "2h", "--url", "http://localhost:3000", "--verbose"], { + ...base, io: io(), runner, + })).toBe(0); + expect(seen[0]!.options).toMatchObject({ + url: "http://localhost:3000", + token: TOKEN, + image: "python:3.13", + imageChosen: true, + dispatch: null, + idleStopMs: 7_200_000, + verbose: true, + }); + expect(await runCli(["runner"], { ...base, io: io(), runner, loadSavedUrl: async () => "https://box.example.com" })).toBe(0); + expect(seen[1]!.options).toMatchObject({ + url: "https://box.example.com", + image: "node:22-bookworm", + imageChosen: false, + idleStopMs: 1_800_000, + verbose: false, + }); + expect(await runCli(["runner", "--dispatch", "./dispatch.sh"], { ...base, io: io(), runner })).toBe(0); + expect(seen[2]!.options).toMatchObject({ url: "https://app.boxcompute.ai", dispatch: "./dispatch.sh" }); + }); + + it("refuses to start without a runner token, Node.js 22 or valid options", async () => { + const runner = (async () => { throw new Error("must not start"); }) as unknown as typeof runRunner; + await expect(runCli(["runner"], { ...base, env: {}, io: io(), runner })).rejects.toThrow( + "BOXCOMPUTE_RUNNER_TOKEN is not set. Create a runner in BoxCompute (Settings → Runners)", + ); + await expect(runCli(["runner"], { ...base, env: { BOXCOMPUTE_RUNNER_TOKEN: "bc_live_cli_key" }, io: io(), runner })) + .rejects.toThrow("is not a runner token"); + await expect(runCli(["runner"], { ...base, io: io(), runner, webSocket: null })).rejects.toThrow("bxc runner needs Node.js 22 or newer."); + await expect(runCli(["--json", "runner"], { ...base, io: io(), runner })).rejects.toThrow("does not support --json"); + await expect(runCli(["runner", "--token", TOKEN], { ...base, io: io(), runner })).rejects.toThrow("Unknown runner option: --token"); + await expect(runCli(["runner", "--idle-stop", "soon"], { ...base, io: io(), runner })).rejects.toThrow("--idle-stop must be a duration"); + await expect(runCli(["runner", "--dispatch", "./d.sh", "--idle-stop", "5m"], { ...base, io: io(), runner })) + .rejects.toThrow("--idle-stop applies only to the built-in Docker dispatch"); + await expect(runCli(["runner", "--image", "-v/:/host"], { ...base, io: io(), runner })).rejects.toThrow("--image must be"); + }); + + it("documents the command", async () => { + const help = io(); + expect(await runCli(["runner", "--help"], { env: {}, io: help })).toBe(0); + const text = help.stdout.read().toString(); + expect(text).toContain("BOXCOMPUTE_RUNNER_TOKEN"); + expect(text).toContain("--idle-stop DURATION"); + expect(text).toContain("--dispatch PROGRAM"); + const root = io(); + expect(await runCli(["--help"], { env: {}, io: root })).toBe(0); + expect(root.stdout.read().toString()).toContain("runner "); + }); +});