AGENT.RUN() / GET STARTED

Set up AgentRun
with your agent.

Follow the AgentRun quickstart with your coding agent. Open the prompt in an app, or copy it into your terminal agent.

Download Markdown

DOCUMENTATION / HARNESSES & COMPUTERS / COMPUTERS AND PROVIDERS

Based on AgentRun release · Synced .

Docker

import { DockerProvider } from "@parcha/agentrun-computer/docker";

const docker = new DockerProvider({ daemonPath: "dist/computerd-linux-amd64" });
const made = await docker.create({ image: "debian:bookworm-slim", lifetimeMs: 600_000, network: "none" }, { requestId: "r1#3" });
if (!made.ok) throw new Error(made.error.message);
const connected = await docker.connect(made.value);
if (connected.ok) {
	const ran = await connected.value.client.call("exec.run", { argv: ["uname", "-m"], timeoutMs: 5000 });
	await connected.value.close();
}
await docker.release(made.value, "delete");

Every create takes a request id (CreateContext.requestId, required): the request, not the computer, so a retry of the same request passes the same id. The contract makes one computer per id, named computer-<12 hex of sha256(id)> (computerNameFor), answers it again while it starts or runs, and refuses exists once it has ended (spec/computer/provider.md). Docker names the container for the request: a retry finds the name taken and answers that container, or exists when it is stopped, of another spec, or was deleted.

  • capabilities() declares kind linux, daemon pid1, groups exec, files and processes, maxLifetimeMs of 30 days, and mount: ["bind"] (below); there is no extend() or stream(), and init gets no --max-deadline.
  • new DockerProvider({ daemonPath, desktop: {} }) makes desktops: kind desktop, with screen, input.pointer, input.keys and apps too, on an image with an X server (test/fixtures/desktop/Dockerfile is Alpine, Xvfb and xterm, the stock app apps.launch-terminate opens, about 50 MB). create gives the daemon DISPLAY (display, default :0), then starts the X server through it with process.start (server, default Xvfb :0 -screen 0 1280x800x24 -nolisten tcp), as the computer's user and as any program: computerd stays PID 1 and starts nothing itself, and the server is one process in its table that ends with the computer. It runs no window manager. create waits (timeoutMs, default 30 s) until hello declares the display, then runs the drift check; a server that ends first, with its last words on stderr, or a display that is not up in time deletes the computer in words.
  • check(spec) refuses in words, with no Docker call: no image, no or a bad lifetimeMs (checkLifetime: at most 30 days), a network that is not none, open or an allowlist the egress proxy takes (below), a NUL byte in any string, and any field Docker does not support. Once the host has been read (below), it also refuses with field: "host" for each enforcement the host lacks. create never throws on a spec check passes.
  • Before docker run, create reads the host's enforcement once per provider (host(), from docker info; see below), and refuses a host that lacks any of it in words, having made nothing.
  • create runs docker run as a non-root user (--user, below), with every capability dropped (--cap-drop ALL), --security-opt no-new-privileges, --ipc private --cgroupns private (never the daemon's defaults, which a host can set to shareable or, on cgroup v1, the host's cgroup namespace), --network none for every network (open and an allowlist go through the computer's egress proxy, below), serve's sizes unless the spec gives its own (2 CPUs as a quota, --cpu-period 100000 --cpu-quota 200000, so a host with fewer CPUs still runs one; 4 GiB with swap the same; 1024 pids), and the daemon (its copy, next) bind-mounted read-only at /opt/agentrun/computerd as the entrypoint, computerd init --deadline <time>, which is PID 1, holds every process and reaps orphans. The label agentrun.computer.deadline holds the time lifetimeMs ends, and init gets the same time: then it ends every process as on SIGTERM (below) and exits 0, which stops the container. Init refuses to start with no deadline. Deleting a stopped computer is the janitor's (lifetime: "janitor"). A container that is not running after its start is removed. The lifetime counts from just before the proxy (for open or an allowlist) and docker run, so a Docker host that holds the start eats into it: a computer whose init exited 0 because its deadline passed before docker run finished fails create as timeout, with the lifetime and how long the start took ("its lifetime of 45 s ended before docker run finished (it took 101.2 s)").
  • A computer binds the provider's own copy of the daemon, never daemonPath. daemonPath may have any mode this process can read (npm installs it 0700 under umask 077). create copies it to computerd-<sha256 of its bytes>, mode 0755, in daemonCache (default ~/.cache/agentrun-computer; XDG_CACHE_HOME is not read), so every computer user may run it, and binds that copy. The copy is written to a temporary file and renamed into place, then hashed again before each bind. The directory is made 0700 if missing and is never changed: a link, another user's directory, a mode other than 0700, or a directory above it another user may write is refused in words. The drift check and attach compare the copy's path, which the same daemon bytes give in every process.
  • A computer runs as a non-root user by default; root must be asked for in the spec. user is a uid or uid:gid in numbers (a name is refused: the image may not have it; a uid alone is its own gid). The spec's user wins, then the provider's user option, then this process's uid:gid, or 1000:1000 when this process's uid or gid is 0. The provider option refuses root and root's group ("1000:0" throws); only a spec's user: "0" runs a computer as root, and only a spec's gid 0 (such as "1000:0") puts it in root's group. That root has no capability either.
  • /run/agentrun, init's socket directory, is a tmpfs owned by the computer's user, mode 700, with noexec, nosuid and nodev, and size=1m: it holds only the socket.
  • /work is the computer's home (HOME=/work) and its workdir unless the spec names one: a tmpfs owned by the computer's user, mode 700, the one place a non-root user can surely write. It is memory: what it holds counts against the memory limit, and it does not survive a stop. So it holds at most half of memoryMb (size=2048m by default): a full /work fails a write with "No space left on device" instead of letting the memory limit OOM-kill a process, PID 1 included. What lasts is the run's folder, bound at /workspace when the spec asks (below).
  • create ends with the drift check (below): a computer that is not what was declared is deleted, and create refuses with every mismatch in words.
  • create(spec, { requestId, signal }) passes the signal to every step: docker info before docker run (an abort there makes nothing), docker run, and after it inspect and hello (hello also has its own 30 s limit). An abort at any step after docker run deletes the computer and returns aborted; create never returns ok once its signal has aborted.
  • connect runs docker exec -i <name> /opt/agentrun/computerd stdio, the bridge to init's socket, and says hello. Each connect is a connection of its own; processes are shared by all of them. A daemon whose version is not the provider's, or that lacks a capability the provider declares, is refused (refused) and the stream closed.
  • attach({ id }) finds a computer by its name (computer-<12 hex digits>) or its container id (12 to 64 hex digits); attach({ labels }) by labels, which must match exactly one computer: none is not_found, more is invalid ("2 computers match ..."). Then attach runs the drift check on what it found: the spec is read back from the computer's own report (image, network, sizes, user, workdir, deadline) and held to what check allows (and the deadline to the ISO time create writes, at most 30 days away), then the whole inspect is checked as at create, and, when the computer runs, its daemon's hello. A computer that drifts is refused (refused) with every mismatch, and left as it is: attach did not make it, so it does not delete it. A stopped computer is checked by inspect alone. A computer that passes is returned as its ref with spec, the spec read back ({ image, user, network, cpus, memoryMb, pids, workdir, deadline, mount? }), so a caller sees what it attached to: user is uid:gid ("0:0" for a computer whose spec asked for root), network the policy read back, and mount the run's folder bound at /workspace, when one is. list keeps its own shape (ComputerInfo).
  • list(labels) runs docker ps -a --filter label=agentrun.computer=1 --filter label=k=v ..., then inspects the matches 50 at a time, reading only the fields it reports, so any number of computers is listed (a computer gone between the two is left out). It returns each computer's ref, labels, deadline (a Date, or undefined when the label is missing or is not the ISO time the provider writes), state (running or stopped), network as read back, and mount when something is mounted at /workspace.
  • network(ref) reads the network back: none (network mode none, on no network but Docker's own none), open (network mode none, and an egress proxy serving --open public, below), { allow: [...] } (below), or { other: "<words>" } for anything else, Docker's bridge included, which is never reported as a policy. network(ref, policy) returns the policy when it is the computer's (an allowlist with the same entries, normalized, in any order); any change is refused: a Docker computer's network is fixed at create, since Docker cannot move a container with no network onto one, and an allowlist needs its volume mounted at create.
  • release(ref, "stop" | "delete") runs docker stop, or docker rm --force --volumes, then stops or removes the computer's egress proxy and, on delete, its volume, each found by its label (below); capabilities().release declares both, and stopDeletes is false: a stopped container is kept until it is deleted. A computer already gone is ok.
  • Only containers with the label agentrun.computer=1 and a computer's name count for attach, list and network; any other container is not_found.

Expected failures are results ({ ok: false, error: { code, message } }), not throws.

What a Docker computer cannot do: run as root or in root's group unless its spec asks, switch users, gain a capability, reach any network when asked for none, reach anything but its list, through its own proxy, when asked for an allowlist, reach a private, loopback, link-local or metadata address when asked for open, write the daemon, or run past its deadline.

Open and an allowlist: the egress proxy

const made = await docker.create({ image: "debian:bookworm-slim", lifetimeMs: 600_000, network: { allow: ["pypi.org", "*.pythonhosted.org", "93.184.215.0/24"] } }, { requestId: "r1#3" });
// In the computer, HTTP_PROXY and HTTPS_PROXY name port 3128 on its own loopback for every program computerd starts.

A computer whose network is open or an allowlist stays --network none: its own loopback, no route, no resolver. Its one way out is its own egress proxy, in a second container the provider makes, reads back and removes with it. Under open the proxy runs with --open public and no list: every public host, and the same refusals of private, loopback, link-local, metadata and this host's own addresses as under a list. A Docker computer is never on Docker's bridge itself. The proxy is serve's (src/docker/egress-proxy.ts, with its address table in src/docker/egress-table.ts), moved here; it holds no key.

  • The volume computer-<hex>-egress: a tmpfs of 1 MiB, mode 0700, owned by the computer's uid:gid. The proxy makes its Unix socket there (0600); the computer mounts it read-only at /opt/agentrun/egress (EGRESS_MOUNT).
  • The proxy container computer-<hex>-egress: node in EGRESS_IMAGE (node:22.23.5-trixie-slim, pinned by digest; new DockerProvider({ daemonPath, egress: { image } }) replaces it) runs dist/docker/egress-main.js, this package's own build, bound read-only with its package.json. It is on Docker's default bridge alone, publishes no port, and runs as the computer's uid:gid with a read-only root, --cap-drop ALL, no-new-privileges, 256 MiB, 64 pids, half a CPU (a fixed quota, not the computer's own cpus), 1024 open files and a bounded log. Its argv holds the list (or --open public), the computer's deadline (it ends itself then), this machine's own public addresses (refused as this-host), and egress.hint, the words a refusal adds (printable ASCII). EGRESS_IMAGE is the one place its digest is written. create pulls it at the first allow computer when the host lacks it (see Lifetime), so a host with no registry access pulls it ahead, reading the name from this package: docker pull "$(node --input-type=module -e 'import { EGRESS_IMAGE } from "@parcha/agentrun-computer"; console.log(EGRESS_IMAGE)')" (in this repository, from packages/computer after a build: node -e 'import("./dist/index.js").then((m) => console.log(m.EGRESS_IMAGE))').
  • The computer: init gets --egress /opt/agentrun/egress/egress.sock, listens on port 3128 of its own loopback, carries each connection to the socket, and gives every program it starts HTTP_PROXY and HTTPS_PROXY (and their lowercase forms) naming that port, with NO_PROXY naming the loopback itself. A program that ignores them reaches nothing; one that dials the socket itself meets the same proxy. Init refuses to start when it cannot listen.
  • What a list holds (capabilities().allow): names, exact or *.suffix (two labels or more), and CIDRs, IPv4 or IPv6, with host bits zero and over no range the address rule refuses; both in one list, at most 256 of each, each on ports 80 and 443. check refuses anything else in words: an empty list (ask for none), an address with no prefix, a port, a URL, a private range. On a Docker host that remaps user ids (userns-remap or rootless Docker), open and an allowlist are refused before anything is made, as a bind is: the volume's owner and the proxy's code are host ids the computer's user does not map to, and the provider does not guess the mapping.
  • The Docker host's own addresses. The proxy refuses them as this-host, so it must know them. Docker does not report them; the provider passes this machine's public interface addresses, which are the Docker host's only when the provider runs on it. When it runs in a container (/.dockerenv, /run/.containerenv, or a container's cgroup in /proc/self/cgroup), or its docker CLI talks to a daemon that is not a local unix socket (docker context inspect, which resolves the context and DOCKER_HOST as the CLI does), open and an allowlist are refused in words before anything is made, and check says so once it knows, unless egress.hostAddresses names the host's addresses (IP addresses), which then go to the proxy beside this machine's own. A plain local host is as before. egress.hostRoot (default /) is the root those container signs are read under, for tests and embedders. An address that is not on any interface is never seen: a cloud machine's NAT'd or elastic public IP. Put those in egress.hostAddresses too. The read-back holds every proxy to the addresses as they are now, so a host that gains an address after create reads its older proxies back as other (fail closed).
  • What the proxy refuses, each before any socket opens: a name off the list, before any lookup, so it never leaves the host; an IP literal outside a listed CIDR of its own family; any port but 80 and 443; a listed name or address that is private, loopback, link-local, metadata, multicast or reserved, in any form it is written (decimal, octal, hex, IPv4-mapped, NAT64, 6to4), or one of this machine's own; a Host header that names another host than the URI; SOCKS5 BIND and UDP ASSOCIATE; an HTTP upgrade; past 64 connections open at once or 20,000 in all. A name is resolved once, every answer is checked, and the checked address is the one dialled, so rebinding a name between the check and the dial reaches nothing new; a redirect reaches the client as sent and is never followed. A log line holds the host, port, address and class, never a path, query or header. A refusal reads 403 <host> is not on this box's network list: <hint>, the words serve's model sees today. The proxy does not open TLS, so a CONNECT to a listed CDN name can carry an SNI for any other tenant of that CDN (domain fronting); listing a CDN's shared name lists every site behind it. That is inherent to a CONNECT proxy, and the same as serve.
  • Lifetime. create first makes sure the computer's image and the proxy's are on the host (docker image inspect, then docker pull for one that is not; a failed pull fails create in words, with nothing made). It then makes the volume, starts the proxy and waits for its ready line (egress.readyMs, 10 s), then runs the computer; both runs take --pull never, so no pull happens between the volume and the computer. A proxy that ends first, or is not ready in time, fails create in its own words; the proxy and the volume are removed, and the computer is never run. release removes the proxy and the volume after the computer, each found by the label agentrun.computer.egress=<computer>, never by name alone, so the janitor's sweep and releaseOlder remove them too. Parts left with no computer (one removed by hand, or a provider that died between its proxy and its computer) the sweep removes too (sweepLeftovers): a proxy or volume with the egress label, and the sweep's labels, whose deadline label has passed, or whose computer is gone and that is older than a create could take (its ready wait and two minutes), removed by what the label found. The volume carries the computer's deadline and the spec's labels for this. Until then the proxy stops forwarding at its deadline.
  • Read-back. network, list and attach read open or the allowlist from Docker: network mode none, the egress volume read-only at its path, init's relay in its command, and a proxy container that carries the computer's label and deadline, runs while the computer runs, is hardened and bounded as above (its memory and swap, pids limit, private IPC and cgroup namespaces, and json-file log of 1m and 2 files included) with exactly its volume and code, and whose argv holds the list (or --open public) and refuses every one of the Docker host's own addresses the provider requires now (more is fine). Anything less is { other: "network allow, but its egress proxy ... <why>" } (or network open, ...). A crashed proxy is not restarted: the computer then reaches nothing, its network reads back other ("is not running"), and attach refuses it, so a caller makes a new computer. list reads every listed computer's proxy in one more inspect.

Mounting the run's folder

A computer mounts the run's folder; tools then run inside it. The spec has one field for it, mount, and every computer has the folder at one path, /workspace (WORKSPACE). HOME stays where the provider puts it (/work on Docker): /workspace is only the mount.

import { WORKSPACE } from "@parcha/agentrun-computer";
import { DockerProvider } from "@parcha/agentrun-computer/docker";

const docker = new DockerProvider({ daemonPath: "dist/computerd-linux-amd64" });
// The run folder must exist, by its canonical path, and be writable by docker.user (below).
const made = await docker.create({ image: "debian:bookworm-slim", lifetimeMs: 600_000, network: "none", mount: { kind: "bind", path: "/data/runs/r1/work" } }, { requestId: "r1#3" });
// In the computer: files.read({ path: `${WORKSPACE}/notes.md` }), exec.run({ argv: ["make"], cwd: WORKSPACE, ... })
  • ComputerSpec.mount is { kind: "bind", path }, a folder on the provider's host bound in (the local Docker computer), or { kind: "archil", disk, region, folder, token }, the run's folder (such as agents/<a>/runs/<r>/work) inside an Archil disk in its region, mounted in a remote computer. capabilities().mount lists the kinds a provider takes; absent, it takes none. Each provider's descriptor declares the same kinds as mounts (Docker ["bind"]; Modal and E2B ["archil"]; Daytona [] for now), so a caller tells which provider binds a local folder from its descriptor (descriptorOf(id)) without building one.
  • checkMount(mount, declared) (src/mount.ts) is the one rule every provider's check runs, with no vendor call: a kind the provider does not declare is refused in words (this provider does not take a mount of kind archil; it takes bind); a bind's path is absolute, canonical (its own realpath, so what is read back is what is bound: Docker reports a bind's source as given, a symlink included), an existing directory on the host, with no NUL; an Archil mount's disk, region, folder and token are non-empty strings with no NUL, the folder relative to the disk's root and with no .. part. A field the kind does not have is refused.
  • The token is a secret. No refusal names an Archil field's value (a token put in the wrong field is not echoed), and what a provider reads back of a mount, MountReadBack (readBackOf(mount, epoch)), is its kind and source alone: { kind: "bind", path } or { kind: "archil", disk, region, folder, exclusive, epoch }, or { other: "<words>" } for a mount at /workspace the provider never makes. An Archil mount's epoch is the computer's agentrun.epoch label (Archil's hold on a folder carries none); an Archil mount with no epoch reads back as { other }, in words. The token is never in a label, a read-back or an error.
  • An Archil egress gateway (HostedOptions.archilEgress; Daytona's DAYTONA_ARCHIL_EGRESS). For a target whose runners reach Archil only through a gateway, <IPv4 gateway>:<mount lane>:<data lane> (such as 192.0.2.40:18100:42050), an Archil egress relay the operator runs. The helper's mount then starts computerd archil-relay on the computer's loopback (127.0.0.1:3129) and an nftables table of its own (inet agentrun_archil) that redirects root's TCP to 8100 (the mount endpoint) and 32050 (the file servers, at the raw addresses the mount endpoint returns) to the relay and resets every other TCP to those ports. The relay sends each connection to the gateway's lane for its port with a PROXY v2 header naming the original destination; the gateway admits only a destination that proves, by certificate, the Archil name the client asked for. A relay that cannot reach the gateway closes the connection, so the client reaches nothing. Unset, nothing changes.
  • Docker takes a bind. create adds --mount type=bind,src=<path>,dst=/workspace after the daemon's mount: read-write, propagation rprivate. A path Docker's --mount cannot hold (a comma, a double quote, a line break) is refused by check.
  • The run folder must be writable by the computer's user. The provider binds the folder as it is and never chowns or chmods it: whoever makes the run folder gives it that user, the spec's user or the provider's (docker.user, this process's uid:gid by default). create checks it after reading the host (docker info) and before docker run, as the kernel will: the owner's, the group's or others' bits of the folder's mode, by the user's uid and gid, must allow write and search; else it refuses in words (the run folder /data/runs/r1/work is not writable by the computer's user 1000:1000: it is owned by 0:0 with mode 0755; ...). A computer's user has no capabilities, root included, so no other way in. On an SELinux host the folder needs a label containers may use; the provider does not relabel it.
  • No bind on a host that remaps user ids. Under userns-remap or rootless Docker (docker info's SecurityOptions holds name=userns or name=rootless; host().remap), a computer's uid is another uid on the host, so the folder's owner says nothing about whether the computer can write it. The provider does not guess the mapping from /etc/subuid: create with a bind on such a host is refused in words before any docker run (this Docker host remaps user ids (rootless Docker), so the run folder's owner on the host is not the computer's user, ...), and check refuses it too once the host is read. A computer with no mount is made there as before. The conformance case mount.run-folder-bind fails on such a host, in those words: the provider declares a bind this host cannot give.
  • attach and list read the mount back from docker inspect (mountOf(inspected)): a read-write bind at /workspace is { kind: "bind", path }; a read-only one, a volume or two mounts there is { other }, and attach refuses such a computer. The drift check (below) holds a computer to the mount it was asked for: the bind there, from that path, read-write, rprivate, and no other mount.

A provider in a container: the volume option

A provider that runs in a container of the Docker it drives, given that Docker's socket (the server under docker compose), has paths the Docker daemon does not: its files are on a named volume the daemon mounted into its container. A bind of its daemon copy or of a run folder names a path that exists only inside that container, so every docker run would fail. The volume option says where its files are:

// The server's container has the named volume agentrun_agentrun-data mounted at /data.
const docker = new DockerProvider({
	daemonPath: "dist/computerd-linux-amd64",
	daemonCache: "/data/computer-cache", // at or below volume.root
	volume: { name: "agentrun_agentrun-data", root: "/data" },
});
await docker.create({ image: "debian:bookworm-slim", lifetimeMs: 600_000, network: "none", mount: { kind: "bind", path: "/data/disk/agents/a1/runs/r1/work" } }, { requestId: "r1#3" });
  • volume: { name, root }: name is the named volume, as docker volume ls names it; root is where this process has it mounted, an absolute path. Without the option, nothing changes: every path is bound as it is.
  • With it, the daemon and the run's folder are mounted as the volume's subpaths, never binds of this process's paths and never the volume's root, and every subpath is a directory (Docker mounts a directory subpath on every engine that has volume-subpath; nothing leans on a file). The daemon is staged in daemonCache as daemon-<sha256>/, holding computerd (0755) and an empty egress/, written in a temporary directory and renamed into place, reused when the same; that directory is mounted read-only at /opt/agentrun, so the daemon is /opt/agentrun/computerd as on every computer and an allowlist's egress volume has its mount point. --mount type=volume,src=<name>,dst=/opt/agentrun, volume-subpath=<daemon dir below root>,volume-nocopy,readonly, and --mount type=volume,src=<name>,dst=/workspace, volume-subpath=<folder below root>,volume-nocopy. volume-nocopy: Docker never copies the image's files at the destination into the volume.
  • daemonCache must be at or below root; the provider throws in words when it is made with one that is not. A run folder must be below root; check and create refuse one that is not, or the root itself, in words, before any docker run.
  • volume-subpath takes Docker Engine 26 or later (API 1.45). The provider reads the engine with docker info (host().engine); create refuses an older one, or one that reports no version, in words before anything is made, and check does too once the host is read.
  • attach and list read the run's folder back from the volume's subpath (HostConfig.Mounts) as the path below root that create was given, { kind: "bind", path }. The drift check holds the daemon's and the folder's mounts to the volume, its subpaths, read-only and read-write, and no bind.
  • The run folder is still checked for the computer's user as above: the provider reads it at its own path.
  • An allowlist's proxy too. The egress proxy's code (dist/docker/egress-main.js, egress-proxy.js, egress-table.js and the package's package.json) is bound from this package's build, a path the Docker daemon does not have either. With the option, create stages those four files below the volume's root first, as it stages the daemon: in daemonCache, in egress-<sha256 of the files>/ (docker/ holding the three modules, package.json beside it; 0755 directories, 0644 files), written in a temporary directory and renamed into place, and reused when one with the same bytes and modes is there. A published tree, the daemon's or the proxy's, is never removed or written over, since a running computer may have it mounted: providers sharing daemonCache that stage at once use the tree the first one renamed into place, and a tree at that name that no longer holds the same (a hand edit) is left as it is, the new one published beside it as <name>-<random>. The read-back (attach, list, network, the drift check) takes a computer mounted on <name> or any <name>-<anything> in that directory whose contents verify, byte for byte and mode for mode: two providers that repaired the same tree at once each mounted their own copy, and both are as create makes one. A source that is not a regular file (a named pipe) is refused in words, never waited on. The proxy then mounts that one directory, the layout it runs from, whole at /code as the volume's subpath, read-only, and the read-back holds it to it. The egress volume is a named volume of its own, as before. In a container the provider still needs egress.hostAddresses for an allowlist (see the egress proxy).

The image: ensureImage

The provider owns the image its computers start from and makes it ready in its own process. There is no state file and no other process to wait on: Docker's own tag is the shared state.

import { DockerProvider } from "@parcha/agentrun-computer/docker";

const docker = new DockerProvider({ daemonPath: "dist/computerd-linux-amd64" }); // image: the default recipe
const image = await docker.image({ signal });   // built once; one inspect when Docker has it
if (!image.ok) throw new Error(image.error.message);
const made = await docker.create({ image: image.value, lifetimeMs: 600_000, network: "none" }, { requestId: "r1#3" });
  • ensureImage(source, { docker?, signal?, timeoutMs?, onWait? }) (src/docker/image.ts) gives the tag. source is { recipe }, a Dockerfile with no build context, or { image }, an image by name.
    • A recipe is built with docker build --quiet --label agentrun.computer.recipe=<sha256> --tag agentrun-computer:<first 12 hex digits> -, the recipe on stdin (recipeTag(recipe), recipeHash(recipe), RECIPE_LABEL). It is built only when docker image inspect finds no image under the tag, or one whose label is not this recipe's whole sha256: a changed recipe is a new tag, and the same recipe is never built twice.
    • An image by name is ready when Docker has it, and pulled once (docker pull --quiet) when it has none. It is never built.
  • DockerProvider's image option is that source; the default is { recipe: DOCKER_RECIPE }, the provider's own image (DEFAULT_DOCKER_IMAGE): python:3.12-slim pinned by its index digest (DOCKER_BASE), with git, curl, nodejs, npm, ripgrep and socat from apt. docker.image({ signal?, timeoutMs?, onWait? }) is ensureImage of it with the provider's docker CLI. A source that is neither throws at construction, in words.
  • The image is an option only; there is no env name for it. Another image is named with the image option, to new DockerProvider(...) or to create({ image: { image: "..." } }). The library reads no environment (see Settings), and Docker's conformance module reads no image name either: a COMPUTER_DOCKER_IMAGE in its environment is ignored. serve keeps its own setting, AGENTRUN_DOCKER_IMAGE, and at the cutover passes it in as the image option, so there is one name and the owner's setting keeps working.
  • One build per process. Concurrent callers share one flight per docker CLI and recipe (or image): the first starts it, the rest wait on it and ask Docker nothing. A flight is forgotten once it settles, so the next call inspects again, and a failure is never kept: the next call tries again.
  • Two processes need no state file. Same recipe, same tag, same label, so a build is idempotent. Two processes that both miss the tag both build, BuildKit sharing its cache. With Docker 29's containerd image store the first to tag wins and the others fail with already exists; with the classic store the last one wins. Either way a build or pull that fails asks Docker once more, and the tag on an image of this recipe is the answer, so every process ends with the tag. A computer made from an image that lost its tag keeps it, as Docker holds an image by its id.
  • onWait(making, tag) is told once, before a caller waits on a build or pull ("build" or "pull"), its own or one it joined, and never when Docker has the image: a caller shows its own "preparing" row with it (DOCKER_RECIPE_HAS is the default image's contents in words). docker.image() takes it too.
  • One bound, the caller's signal. timeoutMs (default IMAGE_TIMEOUT_MS, 10 minutes) covers a flight's inspect and its build or pull, and the first caller's bound is the flight's; past it the docker CLI is killed (timeout). A caller's signal ends its own wait (aborted); when the last caller waiting aborts, the build or pull is killed.
  • The words hold none of Docker's output, only what happened and the next step: Docker not answering ("is it running, and may this user reach it?"); a build that could not reach the network, could not pull its base, ran out of disk space, or could not install a package; a recipe Docker could not parse (at line 2) or whose step failed (failed at the step `RUN make` with exit code 2), the recipe's own words; a registry that refused a pull, has no such image, or could not be reached. A source that is neither a recipe with a FROM line nor an image name, or a bound that is not one, is invalid before Docker is called.

The drift check

After docker run, create reads the computer's own report and compares it with the spec, in drift(spec, inspected, hello, expected), a pure function that returns one sentence per mismatch (inspectDrift is its inspect half). The check is closed: every field of HostConfig and Config is either one create asks for, one with a stated default, or one that widens nothing the box bounds; any other field, one a later Docker adds included, must be empty (absent, null, "", 0, false, [] or {}), or it is drift naming it. The table below was made from docker inspect of a computer this provider made on Docker 29.

From docker inspect, what create asks for:

Field Must be
network (HostConfig.NetworkMode, NetworkSettings.Networks, and for open or an allowlist the egress volume, init's relay and the proxy container) none, open or the allowlist as declared, read back as network(ref) does
HostConfig.CapDrop, CapAdd, Privileged ["ALL"], nothing added, false
HostConfig.SecurityOpt exactly ["no-new-privileges"]: seccomp=unconfined, apparmor=unconfined, label=disable, systempaths=unconfined or any other option is drift
HostConfig.IpcMode, CgroupnsMode private, private
HostConfig.Runtime runc
HostConfig.MaskedPaths, ReadonlyPaths hold Docker's own since 20.10 (/proc/acpi, /proc/asound, /proc/kcore, /proc/keys, /proc/latency_stats, /proc/sched_debug, /proc/scsi, /proc/timer_list, /proc/timer_stats, /sys/firmware; /proc/bus, /proc/fs, /proc/irq, /proc/sys, /proc/sysrq-trigger); a newer Docker's extra masked paths are fine
HostConfig.PidsLimit pids, or 1024
HostConfig.Memory, MemorySwap both memoryMb MiB, or 4096 MiB
HostConfig.CpuPeriod, CpuQuota 100000, and cpus (or 2) times 100000
HostConfig.Tmpfs exactly /work and /run/agentrun, each with that uid and gid, mode=0700, nosuid and nodev (/work exec and size= half of memoryMb in MiB, /run/agentrun noexec and size=1m); options in any order; a missing or other size, or another tmpfs, is drift
HostConfig.Mounts, Mounts the provider's daemon binary bound read-only at /opt/agentrun/computerd (propagation rprivate); when the spec has a mount, then the run's folder bound read-write at /workspace from exactly that path (propagation rprivate); for an allowlist, then the computer's own egress volume read-only at /opt/agentrun/egress; and no other mount of any type: an image's VOLUME is drift too, so an image that declares one is refused
Config.User the uid:gid asked for: the spec's, the provider's, or the default
Config.Image, WorkingDir the spec's image; its workdir, or /work
Config.Env one HOME, HOME=/work; the image's other variables are its own
Config.Entrypoint, Cmd ["/opt/agentrun/computerd"], ["init", "--deadline", <the deadline label's value>], and for open or an allowlist "--egress", "/opt/agentrun/egress/egress.sock" after it
Config.Labels agentrun.computer=1, the deadline as written, and every label the spec asked for; others are the image's
AppArmorProfile docker-default when the host has AppArmor, else empty
ProcessLabel of type container_t when the host has SELinux, else empty

Defaults other than empty: HostConfig.RestartPolicy no restart ({"Name": "no"}; a restart policy would bring a computer back after its deadline), Isolation empty or default, MemorySwappiness null or -1.

Must be empty, each a mismatch by name: Binds, VolumeDriver, VolumesFrom, PortBindings, PublishAllPorts, Links, ExtraHosts, Dns, DnsOptions, DnsSearch, PidMode, UTSMode, UsernsMode, Cgroup, CgroupParent, GroupAdd, Devices, DeviceCgroupRules, DeviceRequests, Sysctls, OomKillDisable, OomScoreAdj, CpuShares, NanoCpus, CpuRealtimePeriod, CpuRealtimeRuntime, CpusetCpus, CpusetMems, CpuCount, CpuPercent, MemoryReservation, KernelMemory, KernelMemoryTCP, BlkioWeight, BlkioWeightDevice, BlkioDeviceReadBps, BlkioDeviceWriteBps, BlkioDeviceReadIOps, BlkioDeviceWriteIOps, IOMaximumIOps, IOMaximumBandwidth, StorageOpt, Init, Annotations, AutoRemove, ReadonlyRootfs; Config.Volumes; and every field not named in this section.

Irrelevant, not checked: HostConfig.LogConfig (the host's log driver), ConsoleSize, ContainerIDFile (a client-side file), ShmSize (/dev/shm is charged to the computer's memory), Ulimits (an rlimit cannot raise a cgroup limit); Config.Hostname, Domainname, AttachStdin, AttachStdout, AttachStderr, Tty, OpenStdin, StdinOnce, ExposedPorts (nothing is published), Healthcheck, ArgsEscaped, OnBuild, StopSignal, StopTimeout, Shell, MacAddress, NetworkDisabled: the image's settings, which act only inside the computer. The rest of the report (State, NetworkSettings past its networks, paths, Driver) is Docker's own bookkeeping.

From the daemon's hello, over one short connection: the provider's version, os linux, kind linux, exactly the groups in capabilities().groups (in any order; one more or one fewer is drift), and arch the Docker host's architecture (docker info, x86_64 as amd64, aarch64 as arm64). attach also reports the hello's kind in the spec it reads back, when the computer is running.

Any mismatch, or a computer that cannot be inspected or whose daemon does not answer, and the computer is deleted before create returns refused with every mismatch. A computer is never left running wider than it was declared. attach runs the same check and refuses, but never deletes.

The host's enforcement

A computer's sizes are cgroup limits, which only a host that enforces them makes real. host() reads docker info once per provider (a failed read is not kept, so the next call reads again), and hostOf(info) turns it into the host's architecture, its security modules, and each enforcement it lacks:

docker info Required Refusal
MemoryLimit true this Docker host does not enforce memory limits, so a computer's memory size is only configuration
SwapLimit true ... swap limits, so a computer could swap past its memory size
PidsLimit true ... pids limits, so a computer's pids limit is only configuration
CPUCfsQuota, CPUCfsPeriod true ... CPU quotas (periods), so a computer's cpus are only configuration
SecurityOptions seccomp present, its profile not unconfined this Docker host has no seccomp (its default seccomp profile is unconfined), so a computer could make any system call
SecurityOptions apparmor, selinux reported none: the drift check expects the profile or label Docker then gives every container

Seccomp is required: it is a computer's only system call filter, and every Linux Docker has it. AppArmor and SELinux are reported, not required: a host has the one its distribution ships, or neither, and a computer's confinement does not rest on them (no capabilities, no-new-privileges, seccomp, its own namespaces); where the host has one, a computer without its profile or label is drift. create and attach refuse on a host that lacks any requirement, before any other Docker call; check refuses too once the host has been read.

The janitor

A Docker computer stops itself at its deadline (init exits), but Docker deletes nothing, so the provider declares lifetime: "janitor" and sweep(provider, { labels?, now?, signal? }) (in src/janitor.ts) deletes computers instead. It works for any provider that declares lifetime: "janitor" and refuses one that declares "vendor". It lists the provider's computers with labels (all of them by default) and deletes each whose deadline is at or before now, or whose deadline is missing or unreadable, stopped or running (a computer past its deadline has usually stopped itself already). A deadline more than the provider's maxLifetimeMs past now (and a minute of clock skew) counts as unreadable: no computer the provider made carries one. It keeps the rest and returns { deleted, kept }. It never touches a container the provider does not list: on Docker, one without agentrun.computer=1 and a computer's name. A computer it cannot delete does not stop it; the result is then an error naming it and what was deleted.

This package does not schedule the janitor. Whoever runs computers runs sweep on a schedule (a cron job, or a timer in a long-lived service), with Docker's CLI on its PATH. A computer stops at its deadline whether the janitor runs or not; its stopped container may stay up to one interval longer.

import { sweep } from "@parcha/agentrun-computer";
import { DockerProvider } from "@parcha/agentrun-computer/docker";

const swept = await sweep(new DockerProvider({ daemonPath: "dist/computerd-linux-amd64" }));
if (swept.ok) console.log(`deleted ${swept.value.deleted.join(", ") || "none"}; kept ${swept.value.kept}`);

Run and epoch labels: releaseOlder

The claim epoch is the one fence for runs and computers. Every computer of a run carries two labels, set in one place (src/labels.ts): agentrun.run (RUN_LABEL), the run's id, and agentrun.epoch (EPOCH_LABEL), the claim epoch of the runner that made it, in decimal. A new claim is epoch + 1, and its first step is to release the run's computers of a lower epoch. The labels sit outside each provider's own agentrun.computer namespace, so every provider takes them as a caller's labels, with no code of its own: Docker writes them with --label and lists them with --filter.

  • runLabels(run, epoch) gives the two labels for ComputerSpec.labels. A run id is a non-empty string with no NUL byte, the strictest rule the providers share for a label's value (runProblem); an epoch is a whole number from 0 to 2^53 - 1 (epochProblem). Anything else throws, in words.
  • epochOf(labels) reads a computer's epoch: decimal digits with no sign, leading zero or space, up to 2^53 - 1. A missing label is not_found; anything else is invalid, in words naming what the label reads.
  • releaseOlder(provider, run, epoch, { signal? }) (in src/janitor.ts) lists the run's computers by agentrun.run and deletes each with a lower epoch, and each whose epoch label is missing or unreadable, since it cannot prove it is current (named in unproven, with why). It keeps the run's computers of this epoch. It holds each listed computer to the run's label again, so a computer of another run is never touched, whatever list gives. It returns { released, kept, unproven }.
  • Fenced. A computer of the run with a higher epoch means a later claim holds the run: releaseOlder is refused (refused, fenced: run "r1" has computer-… at epoch 4, above this claim's epoch 3; …) before it releases anything.
  • A partial cleanup is a failure. Every release is attempted; when any fails, the result is an error naming each computer left and why, and what was released. A takeover goes on (revoke, then mount) only on ok. An aborted call starts no further release and says which ran.
  • It revokes no mount: there is no unmount on the provider. Revoking an Archil mount is the root helper's, run inside the computer through the provider's own exec, and a deleted computer holds no mount.
import { releaseOlder, runLabels } from "@parcha/agentrun-computer";
import { DockerProvider } from "@parcha/agentrun-computer/docker";

const docker = new DockerProvider({ daemonPath: "dist/computerd-linux-amd64" });
// A claim at epoch 3 takes the run over: the computers of epochs 1 and 2 go first.
const older = await releaseOlder(docker, "r1", 3);
if (!older.ok) throw new Error(older.error.message); // fenced, or a computer that could not be released
await docker.create({ image: "debian:bookworm-slim", lifetimeMs: 600_000, network: "none", labels: runLabels("r1", 3) }, { requestId: "r1#3" });

Waiting for a vendor: waitUntil

waitUntil(read, done, { boundMs, signal?, minMs?, maxMs?, what?, describe? }) (in src/wait.ts) is the one bounded wait a provider uses when the vendor reads a state back later than it acted, such as a computer ended by a release. It reads at once, then after pauses that double from minMs (250 ms) to maxMs (5 s), never past boundMs, and returns the first state done accepts. Each read gets a signal that aborts at the bound or on the caller's abort; a read still pending then is not waited for, and one that throws is not done. Past the bound it returns a timeout, on the caller's abort an aborted, each naming what was waited for and the last state read (describe). It has no vendor's types: the shared adapter's release, a create that deletes its machine, and the one live sweep wait through it (settle, until get answers none for a machine twice running; one read gone is still going), for every hosted vendor.