An open-source, faster Devin alternative
TypeScript
computer: a thread's runner in its own container, steps 6-10 (work 103) (#1069)
opencomputer-app[bot]75aeb6158199
diff --git a/computer/README.md b/computer/README.mdindex de49ff8b..33ae3b9b 100644--- a/computer/README.md+++ b/computer/README.md@@ -494,13 +494,16 @@ environment, which any session can change.| `SP_FORK_FETCH_FRESH` | `60s` | a fork skips its fetch of a clone fetched this recently and not pushed to since (push webhook); `0` always fetches || `SP_FORK_RETENTION_DAYS` | `14` | idle forks with nothing unpushed are removed after this || `SP_ARTIFACTS_IDLE_HOURS` | `24` | forks idle this long (no live runner) lose their git-ignored build and dependency directories (`node_modules`, Rust `target`, `.venv`, `.next`, caches; `src/workspaces/idle.ts`); an install or build restores them |-| `SP_POOL_SIZE` | `2` | spare runners a host keeps with Claude Code parked, so a new session's first message skips the runner's launch and Claude Code's start (`host/pool.ts`, work 069). A spare is claimed into the session's fork; resumed sessions, and hosts without a prepared workspace for the owner, start cold. `0` turns the pool off |+| `SP_SWEEP_AGE_MS` | `600000` | with `SP_LAUNCH=podman`: how old a container, home volume or run directory that belongs to no thread must be before the host's sweep removes it (`src/host/sandbox/sweep.ts`); the sweep runs every half of it, at most every 5 minutes |+| `SP_POOL_SIZE` | `2` | spare runners a host keeps with Claude Code parked, so a new session's first message skips the runner's launch and Claude Code's start (`host/pool.ts`, work 069). A spare is claimed into the session's fork; resumed sessions, and hosts without a prepared workspace for the owner, start cold. On a `podman` host a spare is a container with no thread: no record, no mount of anyone's files, no journal, a token socket that answers nobody; a new thread's record takes the spare's id and its mounts and worktrees go into the running container before the claim (`host/sandbox/spares.ts`). A spare that could not be claimed is removed and the message starts cold; spares do not outlive their host (it tells them to go when it stops, and the next host removes every container of its run root that has no record). `0` turns the pool off || `SP_MODEL_PROXY` | unset (the model proxy is down: no session starts, logged as an error) | oc-modelproxy's control socket (`/run/oc-modelproxy/control.sock`); the host binds every runner there to its session's model profile (work 097, `host/model-access.ts`). Required || `SP_RUNNER_USER` | unset (runners run as the host's user) | start runners as this user through `sudo -n -u` (work 077, `host/runner-user.ts`), for a host running as `sp-host` |-| `SP_MODEL_SOCKET` | `/run/oc-modelproxy/api.sock` | the proxy's API socket, which runners' model clients connect to; sent to runners in their credentials' `model.endpoint` |+| `SP_MODEL_SOCKET` | `/run/oc-modelproxy/api.sock` | the proxy's API socket, which runners' model clients connect to; sent to runners in their credentials' `model.endpoint`. With `SP_LAUNCH=podman` a session's container mounts this one socket, at the same path, and nothing else of the proxy's || `SP_CODEX_BIN` | `/usr/local/lib/codex/bin/codex` | the pinned Codex CLI a `harness: 'codex'` session runs as `codex app-server` (work 082); passed to runners || `SP_CODEX_PEER_CHECK` | on | `off` lets any local process use a Codex session's model loopback; only where runners are not systemd units (a laptop). On, a connection is forwarded only when a process in the runner's own cgroup holds it, and refused if the cgroup cannot be read. Read from the host's own environment only: runners always get `on` unless the host runs with `off` |-| `SP_IMAGE` / `SP_IMAGE_ABI` | unset | the session image of this release and the integer in `deploy/image/ABI` (work 103). The image is `ghcr.io/diggerhq/computer-session@sha256:<digest>`, the line in the release's `deploy/image.pin`: the release pipeline writes it with `deploy/image-pin.sh`, which names only the image main's CI built from the release's `deploy/image`. A release without the file is refused, except on a test computer provisioned with `SP_IMAGE_BRANCH=1`, which runs `:branch-<git tree of deploy/image>`, the tag CI pushes for a branch. Never set by hand: `deploy/vm/provision.sh` writes both to the release's `.sp-version.env`, which the host unit loads, and pulls and warms the image before it switches to the release (`deploy/vm/sandbox.sh`). Nothing reads them yet |+| `SP_IMAGE` / `SP_IMAGE_ABI` | unset | the session image of this release and the integer in `deploy/image/ABI` (work 103). The image is `ghcr.io/diggerhq/computer-session@sha256:<digest>`, the line in the release's `deploy/image.pin`: the release pipeline writes it with `deploy/image-pin.sh`, which names only the image main's CI built from the release's `deploy/image`. A release without the file is refused, except on a test computer provisioned with `SP_IMAGE_BRANCH=1`, which runs `:branch-<git tree of deploy/image>`, the tag CI pushes for a branch. Never set by hand: `deploy/vm/provision.sh` writes both to the release's `.sp-version.env`, which the host unit loads, and pulls and warms the image before it switches to the release (`deploy/vm/sandbox.sh`). A host with `SP_LAUNCH=podman` refuses to start without both |+| `SP_LAUNCH` | `systemd` on a hosted computer, `detached` elsewhere | how a runner is started (`host/launch.ts`): `systemd` (a user unit of the runner user), `detached` (a child process, on a laptop), or `podman` (work 103: each session in its own container `sp-runner-<id>` of `SP_IMAGE`, started by `podman start --attach` in a unit of the runner user; `host/sandbox/`). `podman` needs `SP_RUNNER_USER`, `SP_IMAGE` and `SP_IMAGE_ABI`, and a computer prepared by `deploy/vm/sandbox.sh`; a session's workspace, the person's clones and the thread's own worktree registries are mounted into it by `bin/sandbox-mount.py`, and its worktrees are added inside it by `bin/ws-add.sh`; clones, fetches and the question which build directories git ignores run in helper containers, so the host runs no git on what a session wrote. A session's previews go through a socket of its runner (`SP_PREVIEW_SOCKET`), and its terminal and `/files` run inside its container, or for `/files` of a stopped session in a helper container. Until the work is finished it is for trying out only: a restarted host does not take its containers back |+| `SP_PREVIEW_SOCKET` | unset | set by the host for a runner in a container only (`host/sandbox/podman-args.ts`, work 103): the socket in the session's run directory (`runners/<id>.preview.sock`) where the runner pipes the host's preview proxy to the ports this session previewed (`runner/preview-socket.ts`). Without it nothing listens and the proxy dials `127.0.0.1` |**Telemetry** (work 054; runners always hand telemetry to their host, which sends it only if `SP_TELEMETRY_URL` is set)@@ -539,6 +542,7 @@ of them need a real Slack workspace.| `npx tsx src/dev/fake-run.ts "<prompt>" ["<steer sent 8s later>"]` | A real agent session against a fake Slack client. Prints every Slack API call with a timestamp and approves prompts automatically. The fast loop for event mapping, batching and steering. || `npx tsx src/dev/e2e-check.ts [--keep]` | The whole split deployment on one machine, with fake Slack and GitHub APIs served by the check itself: `/setup`, mention → fork → runner → turn, thread replies, mid-turn messages, a permission button, host and gateway restarts under a live runner, GitHub tokens through the credential helper and `gh` shim, a push webhook. Prints the latency rows it can measure. Scratch space is `/tmp/spe2e`. || `npx tsx src/dev/host-check.ts [--claude]` | The host agent against an in-process fake gateway, with oc-modelproxy built from `modelproxy/` (needs Go and openssl; Linux) and run with `-identity=single`: spawn, forwarding, token relay, restart with rediscovery, idle exit. `--claude` makes the first turn real, on `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` as the gateway routes them. With a fake telemetry collector (work 054): host events per trace, the `new`/`warm`/`resume` path, spooling through a collector outage and a host restart, gap-free batch numbers, and `turn.abandoned` for a runner killed mid-turn (its request held by a profile whose upstream never answers), before and after a host restart. |+| `sudo -u sp-host env SP_RUNNER_USER=agent SP_IMAGE=… SP_IMAGE_ABI=… node --import tsx src/dev/sandbox-check.ts` (on a computer, from its release directory, with no host agent running) | The host with `SP_LAUNCH=podman` against an in-process fake gateway and a fake Slack (work 103): a session's runner is a container in a unit of the runners' slice, its record is written, its cwd is `/workspace`, its report names the host's path, its token socket is linked into its run directory, it exits when idle leaving its container, and the next message resumes the same container with its home intact. With a definition of two public repositories: helper containers clone them, a thread has its workspace, its worktree and its own registry mounted, a sibling thread and another person's thread see none of it, `git worktree prune` in one leaves the other, the mount helper refuses what is not the person's, a session of the API has its journal directory, `checkout` adds a repository, and housekeeping removes a stopped thread's ignored `node_modules`. Step 9: two threads, each with a server on the same port and the check's own on the host's; the real `preview` tool, called by a scripted stand-in for the model inside the container (`src/dev/fake-model.mjs`, no credential), reaches the gateway as a virtual port, and the proxy answers from inside the right container and never from the host's port; the probe; a terminal and `/files` over the wire socket (`src/dev/wire-client.ts`), running and stopped, each inside its own thread only (`src/dev/sandbox-check-reach.ts`). Both together: an upload to a running thread is in its workspace directory on the host and reads back while it is stopped, one to a stopped thread (a helper container) is in `/workspace` once it runs again; a terminal commits in the worktree; links to a sibling thread's workspace and to another person's lead nowhere, running or stopped; and a session of the API has `terminal.opened`, `terminal.closed` and `files.pushed` in its journal, written by its runner. With `SP_RUN` / `SP_DATA` it runs on roots of its own, laid out as `deploy/vm/provision.sh` lays out the computer's. With `--spares` it runs step 10 instead (`src/dev/sandbox-check-spares.ts`), on four hosts it starts one after the other: what an unclaimed spare container holds (its mounts, environment, `boot.env`, token socket: nothing of anyone) and costs (its unit's cgroup), a new thread's claim of one (the record under the spare's id, the mounts and worktrees made in the running container, the timings of each part), the pool's size and refill, a delivery beside a refill, new threads back to back, a claim that fails (the spares are paused) answered by a cold start under the same id, the spares of a killed host removed by the next one, which runs another `SP_VERSION` and image name, a spare that outlives the idle time, a spare told to go when its host stops, and the image lock when its file is there; it prints the first reply of new threads with a spare and without, with a repository and with none (`SP_CHECK_N` threads each, 6 unless set). Model access is the release's oc-modelproxy (`modelproxy/oc-modelproxy`), run by the check with a profile whose upstream is `src/dev/fake-model.mjs`. Needs podman, openssl and the network (github.com), so it does not run in CI. || `npx tsx src/dev/workspaces-check.ts [--real]` | Clones, forks, housekeeping and git auth against local bare repositories. || `npx tsx src/dev/gateway-check.ts`, `setup-check.ts` | Gateway routing and `/setup`. || `npx tsx src/dev/links-check.ts` | Linked threads against a fake workspace: public, private, DM, guest and Slack Connect cases, other workspaces, caps, and injected instructions in linked text. |@@ -572,7 +576,8 @@ src/variables-ui.ts: !var; threads.ts: read_thread and post_thread;access-store.ts, access-flow.ts, access-ui.ts: who can drive a sessionhost/ host agent: forks, runner lifecycle, token relay;- previews.ts: preview URLs (cloudflared, preview-proxy.ts, preview-probe.ts)+ previews.ts: preview URLs (cloudflared, preview-proxy.ts, preview-probe.ts,+ preview-dial.ts and sandbox/preview-ports.ts for sessions in containers)runner/ one session per process:main.ts the process: socket to the host, credentials, deliveriessession.ts one conversation: a long-lived Agent SDK query() mapped to Slack;@@ -586,6 +591,7 @@ src/spawn.ts the spawn_thread toolthreads.ts the read_thread and post_thread toolspreview.ts the preview and unpreview tools: public URLs for a session's servers+ preview-socket.ts the socket that lets the host's preview proxy into a container's previewed portssend-file.ts the send_file tool: workspace files → the threadpost-card.ts the post_card tool: json-render specs → Block Kit cardssession-secrets.ts a session's secrets: env file, redaction, the request_secret tooldiff --git a/computer/bin/ws-add.sh b/computer/bin/ws-add.shindex 65c408b8..2f6c167e 100755--- a/computer/bin/ws-add.sh+++ b/computer/bin/ws-add.sh@@ -1,27 +1,38 @@#!/bin/sh-# ws-add.sh <clones> <workspace> <branch> <fetch 0/1> <repo[=base]>…+# ws-add.sh <clones> <workspace> <branch> <fetch 0/1> [<repo[=base]>…]## Give the workspace a git worktree of each repository, <workspace>/<repo>, on-# <branch> (forkRepo in src/workspaces/fork.ts): the branch if the clone has-# it, else a new one from origin/<base>, not tracking it (the session pushes-# its own branch). <base> is the branch forks start from; not given, origin/HEAD-# (ws-lib.sh). With <fetch> 1, origin/<base> is fetched first; a fetch that-# fails is reported and the worktree is made from what the clone has.+# <branch> (forkRepo in src/workspaces/fork.ts; a thread's container, work 103):+# the branch if the clone has it, else a new one from origin/<base>, not+# tracking it (the session pushes its own branch). <base> is the branch forks+# start from; not given, origin/HEAD (ws-lib.sh). With <fetch> 1, origin/<base>+# is fetched first, for at most 5 s; a fetch that fails or runs out of time is+# reported and the worktree is made from what the clone has.+#+# The repositories are worked on at the same time, each on its own clone; the+# lines come out in the order of the arguments.## A destination that is already this clone's worktree is left as it is; one# that is anything else is an error and is not touched. A worktree that could# not be made completely is removed.#+# Stdin, when it is not empty, is a tar stream of files for the workspace's+# root (.fork.json, AGENTS.md): unpacked last, over what is there. With no+# repository that is all the script does.+## Prints `<repo> ok <branch> <base> <HEAD> <fetch error>` (the last field empty# unless a fetch failed), or `<repo> failed <message>`.set -eu. "$(dirname "$0")/ws-lib.sh"-[ $# -ge 4 ] || { echo "usage: ws-add.sh <clones> <workspace> <branch> <fetch 0/1> <repo[=base]>…" >&2; exit 2; }+[ $# -ge 4 ] || { echo "usage: ws-add.sh <clones> <workspace> <branch> <fetch 0/1> [<repo[=base]>…]" >&2; exit 2; }clones=$1 workspace=$2 branch=$3 fetch=$4shift 4+FETCH_SECONDS=5+# Before anything else could read it.+cat >"$ws_tmp/root.tar"adding=-ws_cleanup() {+add_cleanup() {[ -n "$adding" ] || return 0rm -rf -- "$adding"(cd "$clone" && git worktree prune) >/dev/null 2>&1 || :@@ -48,8 +59,10 @@ add() {fifetch_error=if [ "$fetch" = 1 ]; then- ws_in "$clone" git fetch --quiet --no-tags origin "$base" >/dev/null ||- fetch_error=$(ws_why "Command failed: git fetch --quiet --no-tags origin $base")+ rc=0+ ws_in "$clone" timeout "$FETCH_SECONDS" git fetch --quiet --no-tags origin "$base" >/dev/null || rc=$?+ if [ "$rc" = 124 ]; then fetch_error='timed out'+ elif [ "$rc" != 0 ]; then fetch_error=$(ws_why "Command failed: git fetch --quiet --no-tags origin $base"); fifiif [ ! -e "$dest" ]; then# A worktree whose directory the session deleted is still registered; forget it so it can be added again.@@ -63,7 +76,7 @@ add() {fiif [ "$added" = 0 ]; thenwhy=$(ws_why "Command failed: git worktree add --quiet $dest")- ws_cleanup+ add_cleanupadding=ws_failed "$repo" "$why"return 0@@ -77,4 +90,35 @@ add() {ws_ok "$repo" "$branch" "$base" "$head" "$fetch_error"}-for r in "$@"; do add "$r"; done+# Each repository in its own subshell, with its own stderr file and its own+# half-made worktree to remove when stopped; a stopped script stops them all.+jobs=+ws_cleanup() {+ [ -n "$jobs" ] || return 0+ # shellcheck disable=SC2086+ kill $jobs 2>/dev/null || :+ wait+}+n=0+for r in "$@"; do+ n=$((n + 1))+ (+ ws_tmp=$ws_tmp/$n+ mkdir "$ws_tmp"+ ws_cleanup() { add_cleanup; }+ trap ws_stop TERM INT HUP+ add "$r"+ ) >"$ws_tmp/out.$n" &+ jobs="$jobs $!"+done+i=0+for j in $jobs; do+ i=$((i + 1))+ wait "$j" || :+ cat "$ws_tmp/out.$i"+done+jobs=++if [ -s "$ws_tmp/root.tar" ]; then+ tar -x -f "$ws_tmp/root.tar" -C "$workspace" --no-same-owner --no-same-permissions || exit 1+fidiff --git a/computer/bin/ws-clone.sh b/computer/bin/ws-clone.shindex 35922798..7a6f0626 100755--- a/computer/bin/ws-clone.sh+++ b/computer/bin/ws-clone.sh@@ -3,7 +3,8 @@## Clone <url> as <clones>/<repo> (cloneRepo in src/workspaces/clones.ts): into# <repo>.cloning, renamed when complete, so a clone that exists is whole. Then-# each <setup> command through `sh -c` in the clone, stopping at the first+# its garbage collection is told never to prune (ws_keep in ws-lib.sh), and+# each <setup> command runs through `sh -c` in the clone, stopping at the first# that fails. <filter> (`blob:none` for a partial clone) and <branch> may be# empty. A clone already there is left as it is and its setup is not run again.#@@ -35,6 +36,7 @@ if ! mv -T -- "$tmp" "$clone" 2>"$ws_tmp/err"; thenws_failed "$repo" "$(ws_why "Command failed: mv -T $tmp $clone")"exit 0fi+ws_keep "$clone"# Setup commands are the repository's own: they run without the script's GIT_TERMINAL_PROMPT.unset GIT_TERMINAL_PROMPTfor cmd in "$@"; dodiff --git a/computer/bin/ws-inspect.sh b/computer/bin/ws-inspect.shindex df9092f3..4121f132 100755--- a/computer/bin/ws-inspect.sh+++ b/computer/bin/ws-inspect.sh@@ -6,6 +6,8 @@# <worktree> is a path below <workspace>: a repository's name, or `.wt/<name>`# for one an agent added. Read-only: nothing here writes to a worktree, not# even its index (--no-optional-locks: a refreshed index would look like use).+# Nothing the worktree's configuration names is run either: no file system+# monitor and no hook (a session writes that configuration; work 103).## state: whether it has uncommitted changes (`dirty`, also when git cannot# say), the number of commits on no remote (-1: cannot count; not@@ -29,6 +31,7 @@ case ${1:-} in --only=*) only=${1#--only=}; shift ;; esac[ $# -ge 2 ] || { echo "usage: ws-inspect.sh [--only=state|ignored] <clones> <workspace> <worktree>…" >&2; exit 2; }workspace=$2shift 2+git='git -c core.fsmonitor=false -c core.hooksPath=/dev/null'if [ "$only" = state ]; then : >"$ws_tmp/dirs"; else cat >"$ws_tmp/dirs"; fin=0@@ -38,12 +41,12 @@ for repo in "$@"; dostate=- unpushed=- branch=- common=-if [ "$only" != ignored ]; thenstate=dirty- if changes=$(ws_q "$wt" git --no-optional-locks status --porcelain) && [ -z "$changes" ]; then+ if changes=$(ws_q "$wt" $git --no-optional-locks status --porcelain) && [ -z "$changes" ]; thenstate=clean- unpushed=$(ws_q "$wt" git rev-list --count HEAD --not --remotes) || unpushed=-1+ unpushed=$(ws_q "$wt" $git rev-list --count HEAD --not --remotes) || unpushed=-1fi- branch=$(ws_q "$wt" git symbolic-ref --quiet --short HEAD) || branch=- common=$(ws_q "$wt" git rev-parse --git-common-dir) || common=+ branch=$(ws_q "$wt" $git symbolic-ref --quiet --short HEAD) || branch=+ common=$(ws_q "$wt" $git rev-parse --git-common-dir) || common=fiset -- "$state" "$unpushed" "$branch" "$common"line=0@@ -51,7 +54,7 @@ for repo in "$@"; doline=$((line + 1))[ "$of" = "$n" ] && [ -n "$rel" ] || continue# check-ignore exits 0 only for an ignored path.- if ws_q "$wt" git check-ignore -q "$rel"; then set -- "$@" "$line"; fi+ if ws_q "$wt" $git check-ignore -q "$rel"; then set -- "$@" "$line"; fidone <"$ws_tmp/dirs"ws_ok "$n" "$@"donediff --git a/computer/bin/ws-lib.sh b/computer/bin/ws-lib.shindex f1c5658f..68ef1913 100644--- a/computer/bin/ws-lib.sh+++ b/computer/bin/ws-lib.sh@@ -82,6 +82,18 @@ ws_failed() {printf '%s\tfailed\t%s\n' "$1" "$(printf '%s' "$2" | tr '\t\r\n' ' ')"}+# ws_keep <clone>: a clone whose worktrees are registered elsewhere (a thread's+# container sees its own registry over .git/worktrees; work 103) must never+# drop what only they reach, and has the directory the registries mount over.+# Written only when it differs: a session's git may hold the configuration's lock.+ws_keep() {+ for ws_k in gc.pruneExpire gc.worktreePruneExpire; do+ [ "$(cd "$1" && git config --local --get "$ws_k" 2>/dev/null)" = never ] ||+ (cd "$1" && git config --local "$ws_k" never) 2>/dev/null || :+ done+ mkdir -p -- "$1/.git/worktrees" 2>/dev/null || :+}+# ws_base <clone>: sets ws_b to the branch the clone's forks start from:# origin/HEAD, asked of the remote once when the clone does not know it.ws_base() {diff --git a/computer/bin/ws-sync.sh b/computer/bin/ws-sync.shindex eeb40888..97bb6a5c 100755--- a/computer/bin/ws-sync.sh+++ b/computer/bin/ws-sync.sh@@ -3,9 +3,10 @@## Keep the clone <clones>/<repo> current (syncRepo and fastForward in# src/workspaces/housekeep.ts, defaultBranch in clones.ts): fetch origin with-# --prune, then fast-forward the clone's own checkout of <base>. <base> is the-# branch forks start from; empty or absent, origin/HEAD (asked of the remote-# when the clone does not know it).+# --prune (after ws_keep in ws-lib.sh, so that no garbage collection prunes),+# then fast-forward the clone's own checkout of <base>. <base> is the branch+# forks start from; empty or absent, origin/HEAD (asked of the remote when the+# clone does not know it).## The checkout is only ever fast-forwarded: never when it is on another# branch, has local changes or has diverged. A fetch that fails does not stop@@ -34,6 +35,7 @@ fiproblem=if [ "$only" != forward ]; then+ ws_keep "$clone"if ! ws_in "$clone" git fetch --quiet --prune origin >/dev/null; thenwhy=$(ws_why 'Command failed: git fetch --quiet --prune origin')[ "$only" != fetch ] || { ws_failed "$repo" "$why"; exit 0; }diff --git a/computer/deploy/vm/modelproxy.sh b/computer/deploy/vm/modelproxy.shindex f14c6b0e..c60656b7 100755--- a/computer/deploy/vm/modelproxy.sh+++ b/computer/deploy/vm/modelproxy.sh@@ -10,7 +10,8 @@# /etc/oc-modelproxy/profiles.d/, then writes the socket and service units.# Nothing is compiled on a computer.#-# /run/oc-modelproxy/api.sock group agent: the sessions' model clients (SP_MODEL_SOCKET)+# /run/oc-modelproxy/api.sock group agent: the sessions' model clients (SP_MODEL_SOCKET);+# a session's container mounts this file alone (work 103)# /run/oc-modelproxy/control.sock group sp-host: the host agent only (SP_MODEL_PROXY, sp-host.sh)## Invariants:@@ -25,6 +26,9 @@# - Files in profiles.d that the release does not ship (an operator's own)# are left as they are, and checked with the rest.# - Profiles are 0640 root:modelproxy: the proxy reads them, sessions do not.+# - `-caller-uid` (only a process of the sessions' uid is a session: in a+# container every other uid is one of its subordinate ids, work 103) is+# passed only when this release's binary knows the option.# - The proxy runs as its own system user with no home and no write access# outside its runtime directory, so a runner (uid agent) can read neither its# memory nor its credentials.@@ -57,6 +61,10 @@ cp "${shipped[@]}" "$tmp/profiles.d/""$src" -check -profiles "$tmp/profiles.d" \|| die "this release's oc-modelproxy does not load the profiles it would serve; nothing installed"+caller_uid=""+help="$("$src" -help 2>&1 || true)" # not a pipe: under pipefail, grep -q closing early would fail it+if grep -q -- '-caller-uid' <<<"$help"; then caller_uid=" -caller-uid=$(id -u "$AGENT_USER")"; fi+getent group sp-host >/dev/null || groupadd --system sp-hostid "$USER_" >/dev/null 2>&1 || useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin "$USER_"@@ -139,7 +147,7 @@ NotifyAccess=allUser=$USER_Group=$USER_ExecStartPre=$BIN -check -profiles $PROFILES-ExecStart=$BIN -profiles $PROFILES+ExecStart=$BIN -profiles $PROFILES$caller_uid# The handoff: a replacement with the binary and profiles now on disk.ExecReload=/bin/kill -USR2 \$MAINPIDRestart=alwaysdiff --git a/computer/deploy/vm/sandbox-gates.sh b/computer/deploy/vm/sandbox-gates.shindex 52cf9568..e35c8e3c 100755--- a/computer/deploy/vm/sandbox-gates.sh+++ b/computer/deploy/vm/sandbox-gates.sh@@ -45,6 +45,7 @@ AGENT_UID=1500SLICE=slack-presence-runners.sliceSP_RUN=${SP_GATES_RUN:-/run/sp-gates}SP_DATA=${SP_GATES_DATA:-/data/sp-gates}+MODEL_SOCKET=/run/oc-modelproxy/api.sockGATES=$SP_RUN/gates # this script's own files, readable by agentPEOPLE=$SP_DATA/peopleQUICK_IMAGE=localhost/sp-gates-session:3@@ -113,9 +114,11 @@ run_dir() { echo "$SP_RUN/sandbox/$1"; }# network of `docker compose` inside cannot be made (G9). $NETWORK and# $CREATE_MORE are for the gates that compare (G2) or watch (G4).create() {- local id=$1 run+ local id=$1 run model=()run=$(run_dir "$id")IDS+=("$id")+ # The model proxy's API socket, the file alone; a computer without the proxy has none to mount.+ [[ ! -S $MODEL_SOCKET ]] || model=(-v "$MODEL_SOCKET:$MODEL_SOCKET")install -d -m 2750 -o root -g "$AGENT" "$run" # a -v source must existq pm create --name "sp-runner-$id" --hostname session \--label "sp.runner=$id" --label sp.abi=1 \@@ -134,7 +137,7 @@ create() {--env "SP_PREVIEW_SOCKET=$run/runners/$id.preview.sock" \-v "sp-home-$id:/home/agent" \-v "$run:$run" \- -v /run/oc-modelproxy/api:/run/oc-modelproxy/api \+ "${model[@]}" \-v /opt/slack-presence:/opt/slack-presence:ro \"${CREATE_MORE[@]}" \"$IMAGE"@@ -381,9 +384,8 @@ EOFinstall -d -m 0700 "$SP_DATA/state" "$SP_DATA/state/sandboxes"install -d -o "$AGENT" -g "$AGENT" "$PEOPLE"install -m 0644 "$HERE/../../bin/sandbox-mount.py" "$GATES/sandbox-mount.py" || die "bin/sandbox-mount.py is not beside this script's repository"- # Create's fixed -v sources: there on a provisioned computer, made here when not.+ # Create's fixed -v source: there on a provisioned computer, made here when not.[[ -d /opt/slack-presence ]] || install -d /opt/slack-presence- [[ -d /run/oc-modelproxy/api ]] || install -d -m 0750 -g "$AGENT" /run/oc-modelproxy/apilocal had=1 tif [[ -z $IMAGE ]]; thendiff --git a/computer/deploy/vm/sandbox.sh b/computer/deploy/vm/sandbox.shindex 6dd69e25..470e020e 100755--- a/computer/deploy/vm/sandbox.sh+++ b/computer/deploy/vm/sandbox.sh@@ -38,6 +38,11 @@# - `image` succeeds only with the image present and warm. provision.sh switches# `current` after it, so a computer never runs a release whose image it lacks.# It pulls only with room for the image and its warm copy, and says so otherwise.+# - `image` holds an exclusive flock on $IMAGE_LOCK while it pulls and warms:+# both hold Podman's storage lock, and with it every Podman call of the+# agent, for minutes. The host waits for this lock before each of its own+# calls (src/host/sandbox/image-lock.ts) instead of timing out in them. The+# file is root's and only the host's group reads it: a session cannot hold it.# - `prune-images` never forces: an image a container still uses is refused by# Podman and stays.set -euo pipefail@@ -64,6 +69,9 @@ SUBID_COUNT=65536STORE_GB=10BLOBS=/var/tmpBLOBS_GB=2+# The same path in src/host/sandbox/image-lock.ts.+IMAGE_LOCK=/run/slack-presence-image.lock+HOST_USER="${HOST_USER:-sp-host}"log() { printf '\n== sandbox: %s\n' "$*"; }die() { echo "sandbox: $*" >&2; exit 1; }@@ -236,10 +244,26 @@ room() {# image (113 s for 3.77 GB on a 2 vCPU computer, against 0.2 s afterwards), and# the storage lock holds every other Podman call meanwhile. Paying that here,# before the release runs, keeps it out of a person's first message.+#+# Measured with sessions alive (2 vCPU, 3.78 GB): exec, stop, start, create,+# rm, ps and inspect of other containers each waited the 124 s of a warm-up,+# and up to 13 s while one 300 MB layer was applied. Hence the lock.image() {- local ref="${1:?usage: sandbox.sh image <ref>}" try t0=$SECONDS+ local ref="${1:?usage: sandbox.sh image <ref>}" try t0=$SECONDS group=root# Whichever the release's .sp-version.env names: a digest, or a tag (a test computer's, or a release from before the pin).[[ $ref == "$REPOSITORY":* || $ref == "$REPOSITORY"@sha256:* ]] || die "$ref is not an image of $REPOSITORY"+ # The lock ends with this process, whatever ends it, and sudo closes it for what+ # `pm` starts, so nothing of Podman's can keep it. The file is there only while+ # a run works (the host's check is then one stat, 7 ms of flock(1) otherwise),+ # so a run that waited for another finds its file gone and takes the next one.+ getent group "$HOST_USER" >/dev/null && group="$HOST_USER"+ while :; do+ [[ -e $IMAGE_LOCK ]] || install -m 0640 -o root -g "$group" /dev/null "$IMAGE_LOCK"+ exec 9<"$IMAGE_LOCK" || continue+ flock 9+ [[ /dev/fd/9 -ef $IMAGE_LOCK ]] && break+ exec 9<&-+ doneif ! pm image exists "$ref"; thenroom "$ref"log "pulling $ref"@@ -253,6 +277,8 @@ image() {pm rm --ignore sp-warm >/dev/nullpm create --name sp-warm "--userns=keep-id:uid=$AGENT_UID,gid=$AGENT_UID" "$ref" >/dev/nullpm rm sp-warm >/dev/null+ rm -f "$IMAGE_LOCK"+ exec 9<&-echo "image $ref present and warm ($(( SECONDS - t0 )) s)"}diff --git a/computer/src/api/socket.ts b/computer/src/api/socket.tsindex a6ef61b7..c6d9351a 100644--- a/computer/src/api/socket.ts+++ b/computer/src/api/socket.ts@@ -196,10 +196,10 @@ export interface ApiClient {const gone = (): CallOutcome => ({ error: apiError('unavailable', 'the session writer went away', 503, { retryable: true, retryAfterMs: 250 }) });-/** Connect to a writer's socket and say hello. */-export function dialApi(path: string, token: string): Promise<ApiClient> {+/** Connect to a writer's socket and say hello. `connect`: how, when the socket is where its path cannot be trusted (it may throw). */+export function dialApi(path: string, token: string, connect: (path: string) => net.Socket = net.connect): Promise<ApiClient> {return new Promise((resolve, reject) => {- const sock = net.connect(path);+ const sock = connect(path);const pending = new Map<string, (o: CallOutcome) => void>();let next = 0;let handlers: SubscribeOptions | undefined;diff --git a/computer/src/dev/fake-model.mjs b/computer/src/dev/fake-model.mjsnew file mode 100644index 00000000..098f9c11--- /dev/null+++ b/computer/src/dev/fake-model.mjs@@ -0,0 +1,85 @@+// A stand-in for the Anthropic API that calls a tool when the person's+// message asks for one, so a dev check can drive the real runner and the real+// Agent SDK through a tool call with no model and no credential+// (sandbox-check.ts runs it inside a session's container, whose loopback is+// the only address the session's harness and this can share; or, with a key+// and a certificate, over https on a host, as the upstream of a profile of+// oc-modelproxy: sandbox-check-model.ts):+// node src/dev/fake-model.mjs <port> [<key.pem> <cert.pem>]+//+// A message whose text has `call <tool> <json>` is answered with a `tool_use`+// of the offered tool whose name is `<tool>` or ends in `__<tool>`; the+// request that carries its result is answered `done`, and the result's text+// is kept. `GET /calls` returns what was kept: `[{ tool, input, result }]`.+//+// Invariants: plain Node, no dependency, no file written: it runs from a+// release mounted read-only. It listens on 127.0.0.1 only.++import { readFileSync } from 'node:fs';+import http from 'node:http';+import https from 'node:https';++const port = Number(process.argv[2]);+const [key, cert] = process.argv.slice(3);+if (!port || (key && !cert)) {+ console.error('usage: fake-model.mjs <port> [<key.pem> <cert.pem>]');+ process.exit(2);+}++/** @type {{ tool: string, input: unknown, result?: string }[]} */+const calls = [];+const ASK = /call ([a-z_]+) (\{[^\n]*\})/;++const textOf = (content) =>+ typeof content === 'string' ? content : Array.isArray(content) ? content.map((b) => (b.type === 'text' ? b.text : b.type === 'tool_result' ? textOf(b.content) : '')).join('\n') : '';++/** What the model "says" to a request body: a tool call, or a word. */+function answer(j) {+ const last = [...(j.messages ?? [])].reverse().find((m) => m.role === 'user');+ const blocks = Array.isArray(last?.content) ? last.content : [];+ const result = blocks.find((b) => b.type === 'tool_result');+ if (result) {+ const call = calls.find((c) => c.id === result.tool_use_id);+ if (call) call.result = textOf(result.content);+ return { text: 'done' };+ }+ const m = ASK.exec(textOf(last?.content));+ const tool = m && (j.tools ?? []).find((t) => t.name === m[1] || t.name.endsWith(`__${m[1]}`));+ if (!m || !tool) return { text: 'ok' };+ const call = { id: `toolu_${calls.length + 1}`, tool: tool.name, input: JSON.parse(m[2]) };+ calls.push(call);+ return { call };+}++const handle = (req, res) => {+ let body = '';+ req.on('data', (c) => (body += c));+ req.on('end', () => {+ const json = (code, v) => (res.writeHead(code, { 'content-type': 'application/json' }), res.end(JSON.stringify(v)));+ if (req.method === 'GET' && req.url === '/calls') return json(200, calls.map(({ tool, input, result }) => ({ tool, input, result })));+ if (!req.url?.startsWith('/v1/messages')) return json(404, { type: 'error', error: { type: 'not_found_error', message: 'not found' } });+ if (req.url.startsWith('/v1/messages/count_tokens')) return json(200, { input_tokens: 10 });+ const j = body ? JSON.parse(body) : {};+ const a = j.stream ? answer(j) : { text: 'ok' }; // only a turn streams; the side requests (a title) get a word+ const content = a.call ? [{ type: 'tool_use', id: a.call.id, name: a.call.tool, input: a.call.input }] : [{ type: 'text', text: a.text }];+ const stop_reason = a.call ? 'tool_use' : 'end_turn';+ const msg = { id: `msg_${Date.now()}`, type: 'message', role: 'assistant', model: j.model, content, stop_reason, stop_sequence: null, usage: { input_tokens: 5, output_tokens: 1 } };+ if (!j.stream) return json(200, msg);+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ const ev = (type, d) => res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...d })}\n\n`);+ ev('message_start', { message: { ...msg, content: [], stop_reason: null, usage: { input_tokens: 5, output_tokens: 0 } } });+ if (a.call) {+ ev('content_block_start', { index: 0, content_block: { type: 'tool_use', id: a.call.id, name: a.call.tool, input: {} } });+ ev('content_block_delta', { index: 0, delta: { type: 'input_json_delta', partial_json: JSON.stringify(a.call.input) } });+ } else {+ ev('content_block_start', { index: 0, content_block: { type: 'text', text: '' } });+ ev('content_block_delta', { index: 0, delta: { type: 'text_delta', text: a.text } });+ }+ ev('content_block_stop', { index: 0 });+ ev('message_delta', { delta: { stop_reason, stop_sequence: null }, usage: { output_tokens: 1 } });+ ev('message_stop', {});+ res.end();+ });+};+const server = key ? https.createServer({ key: readFileSync(key), cert: readFileSync(cert) }, handle) : http.createServer(handle);+server.listen(port, '127.0.0.1');diff --git a/computer/src/dev/host-check.ts b/computer/src/dev/host-check.tsindex 0f6f3c60..a952973f 100644--- a/computer/src/dev/host-check.ts+++ b/computer/src/dev/host-check.ts@@ -48,8 +48,10 @@ if (DEFINITION) {}const RUN = path.join(dir, 'run');const KEY = `C_CHECK:${Date.now() / 1000}`;+// Runners are named by an id the host mints (work 069), a new one per start: the check finds them by what they left in RUN.const RUNNERS = path.join(RUN, 'runners');const LOGS = path.join(RUN, 'logs');+const ls = (d: string) => (existsSync(d) ? readdirSync(d) : []);const t0 = Date.now();const say = (...a: unknown[]) => console.log(`+${((Date.now() - t0) / 1000).toFixed(1)}s`, ...a);let failed = 0;@@ -187,11 +189,15 @@ function startHost(idleMs: number): ChildProcess {for (const s of [h.stdout!, h.stderr!]) s.on('data', (d) => process.stdout.write(String(d).replace(/^(?=.)/gm,' host| ')));return h;}-// Runners are named by id, not session. The session's runner is the only one: with -identity=single the host keeps no spares.-const runnerId = () => (existsSync(RUNNERS) ? readdirSync(RUNNERS).find((f) => f.endsWith('.sock') && !f.endsWith('.api.sock'))?.slice(0, -'.sock'.length) : undefined);-const runnerPid = () => {- const f = path.join(RUNNERS, `${runnerId()}.pid`);- return existsSync(f) ? Number(readFileSync(f, 'utf8')) : 0;+/** The pid files in RUN/runners: runner id → pid. A runner removes its own when it exits by itself. */+const pids = () => new Map(ls(RUNNERS).filter((f) => f.endsWith('.pid')).map((f) => [f.replace(/\.pid$/, ''), Number(readFileSync(path.join(RUNNERS, f), 'utf8'))]));+/** The session's runner: the living one started last (0: none). */+const runnerPid = () => [...pids()].filter(([, p]) => alive(p)).map(([id, p]) => ({ p, at: statSync(path.join(RUNNERS, `${id}.pid`)).mtimeMs })).sort((a, b) => b.at - a.at)[0]?.p ?? 0;+const socketOf = (pid: number) => [...pids()].flatMap(([id, p]) => (p === pid ? [path.join(RUNNERS, `${id}.sock`)] : []))[0];+/** Never 0 or 1: `kill(0)` is this check's own process group. */+const kill = (pid: number, signal: NodeJS.Signals) => {+ if (pid > 1) process.kill(pid, signal);+ else say(`not signalling pid ${pid}: no runner found`);};const alive = (pid: number) => {try {@@ -200,9 +206,8 @@ const alive = (pid: number) => {return false;}};-/** Every runner's log, oldest first. */-const runnerLog = () => (existsSync(LOGS) ? readdirSync(LOGS).map((f) => path.join(LOGS, f)).sort((a, b) => statSync(a).mtimeMs - statSync(b).mtimeMs)- .map((f) => readFileSync(f, 'utf8')).join('') : '');+/** What every runner of this run wrote, oldest first. */+const runnerLog = () => ls(LOGS).map((f) => ({ f: path.join(LOGS, f), at: statSync(path.join(LOGS, f)).mtimeMs })).sort((a, b) => a.at - b.at).map((x) => readFileSync(x.f, 'utf8')).join('');function askToken(sessionKey: string, socket = path.join(RUN, 'token.sock')) {return new Promise<any>((resolve, reject) => {const s = net.createConnection(socket, () => s.write(JSON.stringify({ sessionKey }) + '\n'));@@ -223,7 +228,7 @@ try {const r1 = await request({ t: 'deliver', id: randomUUID(), session: spec, msg: { userId: 'U_OWNER', text, ts: '2.1' }, credentials: scopedCredentials, trace: tr1 });check(!!r1?.ok, `deliver "${text}" → reply ok (${r1?.error ?? ''})`);pid = runnerPid();- check(alive(pid) && !!runnerId(), `runner process ${pid} spawned, listening on its socket`);+ check(alive(pid) && existsSync(socketOf(pid) ?? ''), `runner process ${pid} spawned, listening on its socket`);if (CLAUDE) {await until(() => reports().some((r) => r.status === 'busy') && reports().at(-1)?.status === 'idle' ? true : undefined, 120_000);check(/chat\.(startStream|postMessage)/.test(runnerLog()) && !!reports().at(-1)?.sdkSessionId, 'Claude turn rendered to fake Slack, sdkSessionId reported');@@ -285,7 +290,7 @@ try {check(batches.every((b) => b.auth === 'Bearer check-credential'), 'batches carry the credential');check(!!(await until(() => (!alive(pid) ? true : undefined), 20_000)), 'runner exited after the idle timeout');- check(reports().at(-1)?.status === 'stopped' && !runnerId(), 'runner reported stopped and removed its socket');+ check(reports().at(-1)?.status === 'stopped' && !ls(RUNNERS).some((f) => f.endsWith('.sock')), 'runner reported stopped and removed its socket');check(!!(await until(() => tel().find((e) => e.event_name === 'runner.exited' && e.data.exit_reason === 'idle' && e.data.busy === false))),'runner.exited: idle, not busy');@@ -310,7 +315,7 @@ try {const tr6 = mkTrace();check(!!(await request({ t: 'deliver', id: randomUUID(), session: spec, msg: { userId: 'U_OWNER', text: 'hello', ts: '2.6' }, credentials: scopedCredentials, model: HANG, trace: tr6 }))?.ok&& !!(await until(busy)) && !!(await until(() => hangs.length || undefined)), 'a turn is running: its request reached the model, which never answers');- if (alive(pid)) process.kill(pid, 'SIGKILL'); // never 0: that is this process's group+ kill(pid, 'SIGKILL');const ab6 = await until(() => telOf(tr6, 'turn.abandoned')[0]);check(ab6?.outcome === 'abandoned' && ab6.data.exit_reason === 'unknown' && typeof ab6.duration_ms === 'number','runner killed mid-turn → turn.abandoned with its trace');@@ -324,7 +329,7 @@ try {await sleep(500);host = startHost(600_000);check(!!(await until(() => hellos()[2]))?.sessions.some((s) => s.key === KEY && s.status === 'busy'), 'restarted host found the busy runner');- if (alive(pid)) process.kill(pid, 'SIGKILL');+ kill(pid, 'SIGKILL');check(!!(await until(() => telOf(tr7, 'turn.abandoned')[0])), 'host restarted mid-turn, then the runner killed → turn.abandoned still names the trace');if (WORKSPACE) {@@ -355,7 +360,7 @@ try {} finally {host.kill('SIGTERM');proxy.kill('SIGTERM');- if (alive(pid)) process.kill(pid, 'SIGTERM');+ for (const p of pids().values()) if (alive(p)) kill(p, 'SIGTERM');await sleep(500);say('runner log (last lines):\n' + runnerLog().split('\n').slice(-12).map((l) => ' runner| ' + l).join('\n'));rmSync(dir, { recursive: true, force: true });diff --git a/computer/src/dev/sandbox-check-model.ts b/computer/src/dev/sandbox-check-model.tsnew file mode 100644index 00000000..7d0911a5--- /dev/null+++ b/computer/src/dev/sandbox-check-model.ts@@ -0,0 +1,93 @@+// The model access of sandbox-check.ts (work 097 and 103): the release's+// oc-modelproxy, run by the check beside its host, with the shipped profiles+// and one more, `stand-in`, whose upstream is src/dev/fake-model.mjs on this+// host. A session's harness in its container connects to the proxy's API+// socket (the one file of the proxy its container mounts), is named by its+// unit's cgroup like any runner of a computer, and its turn is answered by+// the stand-in. No model and no credential is involved.+//+// Invariants:+// - The computer's own proxy (/run/oc-modelproxy) is neither used nor changed.+// - The sockets are in a directory of the run root, which the runners' user+// can enter. The API socket is opened to every user (0666): this proxy runs+// as the check's user, not as `modelproxy` with the runners' group.+// - stop() ends both processes and removes the directory.++import { type ChildProcess, execFileSync, spawn } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import https from 'node:https';+import path from 'node:path';+import { modelKey } from '../model-key.js';+import type { ModelRoute } from '../protocol.js';++/** Where the stand-in listens, on the host's loopback. */+const MODEL_PORT = 18443;+const PROFILE = 'stand-in';++export interface ModelCall { tool: string; input: unknown; result?: string }++export interface CheckModel {+ /** The proxy's sockets: the host's SP_MODEL_PROXY and SP_MODEL_SOCKET. */+ control: string;+ api: string;+ /** The route every session of the check runs on. */+ route: ModelRoute;+ /** The tool calls the stand-in made, with the results it was given. */+ calls(): Promise<ModelCall[]>;+ stop(): void;+}++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++/** Start the stand-in and the proxy; throws when the release has no proxy, or it does not come up. */+export async function checkModel(o: { root: string; run: string }): Promise<CheckModel> {+ const bin = path.join(o.root, 'modelproxy', 'oc-modelproxy');+ if (!existsSync(bin)) throw new Error(`${bin} is absent: deploy/bundle.sh builds it into a release (or: cd modelproxy && go build -o oc-modelproxy .)`);+ const dir = path.join(o.run, 'check-model');+ rmSync(dir, { recursive: true, force: true });+ mkdirSync(dir);+ chmodSync(dir, 0o755);+ const key = path.join(dir, 'model.key');+ const cert = path.join(dir, 'model.crt');+ // A profile's upstream is https: the stand-in gets a certificate of its own, which only this proxy trusts.+ execFileSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-days', '1', '-subj', '/CN=127.0.0.1',+ '-addext', 'subjectAltName=IP:127.0.0.1', '-keyout', key, '-out', cert], { stdio: 'ignore' });+ const shipped = JSON.parse(readFileSync(path.join(o.root, 'modelproxy', 'profiles', 'default.json'), 'utf8'));+ const profiles = path.join(dir, 'profiles.d');+ mkdirSync(profiles);+ writeFileSync(path.join(profiles, 'default.json'), JSON.stringify(shipped));+ writeFileSync(path.join(profiles, `${PROFILE}.json`), JSON.stringify({ [PROFILE]: {+ upstream: `https://127.0.0.1:${MODEL_PORT}`,+ routes: { 'POST /v1/messages': {}, 'POST /v1/messages/count_tokens': {} },+ set: { 'X-Api-Key': '{token}' },+ harness: { claude: shipped['anthropic-key'].harness.claude },+ } }));+ const control = path.join(dir, 'control.sock');+ const api = path.join(dir, 'api.sock');+ const out = (name: string, p: ChildProcess) => {+ for (const s of [p.stdout!, p.stderr!]) s.on('data', (d) => process.stdout.write(String(d).replace(/^(?=.)/gm, ` ${name}| `)));+ return p;+ };+ const model = out('model', spawn(process.execPath, [path.join(o.root, 'src/dev/fake-model.mjs'), String(MODEL_PORT), key, cert], { stdio: ['ignore', 'pipe', 'pipe'] }));+ const proxy = out('proxy', spawn(bin, ['-profiles', profiles, '-api-socket', api, '-control-socket', control, '-bindings-file', ''], {+ env: { PATH: process.env.PATH, SSL_CERT_FILE: cert }, stdio: ['ignore', 'pipe', 'pipe'],+ }));+ const stop = () => {+ for (const p of [proxy, model]) p.kill('SIGKILL'); // no stream of the check is worth its drain+ rmSync(dir, { recursive: true, force: true });+ };+ for (const end = Date.now() + 10_000; !(existsSync(api) && existsSync(control)); await sleep(100))+ if (Date.now() > end || proxy.exitCode !== null) {+ stop();+ throw new Error(`${bin} did not open its sockets in ${dir}`);+ }+ chmodSync(api, 0o666);+ const token = 'check-not-a-credential';+ const calls = () => new Promise<ModelCall[]>((resolve) => {+ https.get({ host: '127.0.0.1', port: MODEL_PORT, path: '/calls', ca: readFileSync(cert), timeout: 5000 }, (res) => {+ let body = '';+ res.setEncoding('utf8').on('data', (d) => (body += d)).on('end', () => resolve(JSON.parse(body || '[]')));+ }).on('timeout', function (this: { destroy(): void }) { this.destroy(); }).on('error', () => resolve([]));+ });+ return { control, api, route: { mode: 'profile', profile: PROFILE, vars: { token }, key: modelKey(PROFILE, { token }) }, calls, stop };+}diff --git a/computer/src/dev/sandbox-check-reach.ts b/computer/src/dev/sandbox-check-reach.tsnew file mode 100644index 00000000..0fa1952c--- /dev/null+++ b/computer/src/dev/sandbox-check-reach.ts@@ -0,0 +1,392 @@+// The part of sandbox-check.ts about reaching into a session's container+// (work 103, step 9; C9 and C13): its previews through the runner's preview+// socket, the virtual ports and the host's proxy; its terminal; and its files,+// while it runs, while it is stopped and once it runs again. sandbox-check.ts+// owns the host, the fake gateway and the threads; this file only asks and+// compares.+//+// The `preview` and `unpreview` tools are called by the real runner and the+// real Agent SDK: the turn's model is src/dev/fake-model.mjs behind the+// check's model proxy (sandbox-check-model.ts), which answers `call <tool>+// <json>` with that tool call. No model and no credential is involved.+//+// Invariants:+// - Two threads of one person, each serving a different answer on the same+// port number inside its container, and the check itself listening on that+// number on the host: whose answer comes back says who was reached.+// - `/files` has one place per thread, the workspace directory on the host+// that is mounted at `/workspace`: what is uploaded while the thread runs is+// read back while it is stopped, and the other way round.+// - A third thread, another person's and with a session id of the API, is+// what a link out of a workspace points at, and whose journal is read.+// - What it makes inside a container goes with the container; what it uploads+// to a stopped thread is in the thread's workspace, which sandbox-check.ts+// removes with the person's directory.++import { type ChildProcess, execFileSync } from 'node:child_process';+import { lstatSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import http from 'node:http';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { sandboxDialer } from '../host/preview-dial.js';+import { PREVIEW_PROXY_PORT } from '../host/preview-proxy.js';+import type { Place } from '../host/workspace-files.js';+import { VIRTUAL_PORTS } from '../host/sandbox/preview-ports.js';+import { type RunRoot, previewSocketFor } from '../ipc.js';+import type { PreviewRequest, SessionSpec } from '../protocol.js';+import { signPreview } from '../signed-header.js';+import type { ModelCall } from './sandbox-check-model.js';+import type { WireClient } from './wire-client.js';++/** The port every server of the check listens on: inside each container, and on the host. */+export const APP_PORT = 5173;+/** A second port a server listens on inside a container, which no preview names. */+const OTHER_PORT = 18080;++export interface Thread {+ name: string;+ spec: SessionSpec;+ /** The `cs_…` id the wire knows it by. */+ sessionId: string;+ /** Its sandbox id and run directory. */+ id: string;+ run: RunRoot;+ /** Its workspace on the host. */+ workspace: string;+ /** Its owner, as the wire names a member. */+ member: string;+}++export interface Kit {+ root: string;+ dataDir: string;+ /** The preview config's signing key. */+ key: string;+ member: string;+ say(...a: unknown[]): void;+ check(ok: boolean, what: string): void;+ until<T>(f: () => T | undefined | Promise<T | undefined>, ms?: number): Promise<T | undefined>;+ /** `sh -c` inside a thread's container, as the session's user. */+ inside(id: string, script: string): Promise<string>;+ /** The tool calls the model stand-in made, with their results (sandbox-check-model.ts); one list for every thread, and turns are told one at a time. */+ calls(): Promise<ModelCall[]>;+ /** A detached process inside a thread's container. */+ detached(id: string, argv: string[]): Promise<unknown>;+ /** A command as the runners' user on the host. */+ asRunner(argv: string[]): Promise<string>;+ status(id: string): Promise<string>;+ /** A message delivered to a thread. */+ tell(t: Thread, text: string): Promise<unknown>;+ /** The `preview` requests the gateway got, with who asked. */+ asked: { from: string; req: PreviewRequest }[];+ wire: WireClient;+ /** Where a `/files` script of a thread runs (sandbox/scripts.ts), as the host would be given it: `running` or stopped. */+ filesPlace(t: Thread, running: boolean): Place;+}++type Got = { status: number; body: string; headers: http.IncomingHttpHeaders } | { refused: string };+export const show = (g: Got) => ('refused' in g ? `refused (${g.refused})` : `${g.status} ${JSON.stringify(g.body.slice(0, 60))}`);+export const said = (g: Got, body: string) => !('refused' in g) && g.status === 200 && g.body === body;++function get(o: http.RequestOptions): Promise<Got> {+ return new Promise((resolve) => {+ const req = http.get({ ...o, timeout: 10_000 }, (res) => {+ let body = '';+ res.setEncoding('utf8').on('data', (d) => (body += d)).on('end', () => resolve({ status: res.statusCode ?? 0, body, headers: res.headers }));+ });+ req.on('timeout', () => req.destroy(new Error('timeout'))).on('error', (e) => resolve({ refused: e.message }));+ });+}+/** A request through the host's preview proxy, signed as the previews Worker signs it. */+export const viaProxy = (k: Kit, port: number) =>+ get({ host: '127.0.0.1', port: PREVIEW_PROXY_PORT, path: '/', headers: { 'x-preview-port': String(port), 'x-preview-auth': signPreview(k.key, port), 'x-preview-host': 'check.opencomputer.app' } });+/** A request to a port of a thread through its runner's preview socket, as the proxy dials it. */+const viaSocket = (t: Thread, port: number) => get({ host: '127.0.0.1', port, path: '/', createConnection: () => sandboxDialer(t.run, t.id)(port) as never });++export const serve = (k: Kit, t: Thread, port: number) =>+ k.detached(t.id, ['node', '-e', `require("http").createServer((q,s)=>s.end("inside ${t.name}")).listen(${port},"127.0.0.1")`]);++/** One turn in which the (fake) model calls `tool` with `input`: the tool's result as the model got it, parsed when it is JSON. */+export async function toolCall(k: Kit, t: Thread, tool: string, input: object): Promise<{ text: string; json?: Record<string, unknown>; ms: number }> {+ const before = (await k.calls()).length;+ const at = Date.now();+ await k.tell(t, `sandbox-check: call ${tool} ${JSON.stringify(input)}`);+ const c = await k.until(async () => (await k.calls()).slice(before).find((x) => x.result !== undefined), 60_000);+ const text = c?.result ?? '(the tool was never called, or its result never reached the model)';+ let json: Record<string, unknown> | undefined;+ try {+ json = JSON.parse(text);+ } catch {+ // an error sentence+ }+ return { text, json, ms: Date.now() - at };+}++function tarOf(files: Record<string, string>): Buffer {+ const dir = mkdtempSync(path.join(tmpdir(), 'sandbox-check-'));+ try {+ for (const [name, text] of Object.entries(files)) writeFileSync(path.join(dir, name), text);+ return execFileSync('/usr/bin/tar', ['-cf', '-', '-C', dir, ...Object.keys(files)], { maxBuffer: 64 << 20 });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}+type Listing = { entries: { path: string; type: string; pushedBy: { id: string } | null }[] };+const list = async (k: Kit, t: Thread) =>+ (await k.wire.call<Listing>({ t: 'files.list', sessionId: t.sessionId, member: t.member, path: '', depth: 3, limit: 200 })).result?.entries.map((e) => e.path) ?? [];+const code = (r: object) => ('error' in r ? (r.error as { code?: string; reason?: string }) : undefined);+/** A path that was not followed out of a workspace: refused, or not there where the script ran. */+const kept = (r: object) => ['invalid_path', 'path_not_found'].includes(code(r)?.code ?? '');+/** What `/files` answers for each of these names of `t`, as an archive and as a file. */+const reads = async (k: Kit, t: Thread, names: string[]) => (await Promise.all(names.flatMap((n) => [k.wire.get(t.sessionId, t.member, n, false), k.wire.get(t.sessionId, t.member, `${n}/marker-q`, true)])));+const codes = (rs: object[]) => rs.map((r) => code(r)?.code ?? 'READ').join(' ');++const exit = (p: ChildProcess) => new Promise<number | null>((resolve) => p.once('close', (c) => resolve(c)).once('error', () => resolve(null)));+/** Nothing of a `/files` script is left where `t`'s scripts run, and no upload's directory in its workspace. Waits: the host ends what is left after its own command ended. */+async function nothingLeft(k: Kit, t: Thread, running: boolean): Promise<string> {+ let left = '';+ await k.until(async () => {+ const procs = running+ ? await k.inside(t.id, 'pgrep -af "[O]PC_FILES=|[s]leep 30[0-9]|[s]9-big" || true')+ : (await k.asRunner(['/usr/bin/podman', 'ps', '--all', '--filter', 'name=sp-files-', '--format', '{{.Names}} {{.Status}}'])).trim();+ const dirs = (await k.asRunner(['/bin/sh', '-c', 'ls -A "$1" | grep "^\\.opc-" || true', 'sh', t.workspace])).trim();+ left = [procs, dirs].filter(Boolean).join('; ');+ return left ? undefined : true;+ }, 20_000);+ return left || 'nothing';+}+/**+ * `/files` scripts of `t` that do not run to their end (the spec's "Timeouts and failures"): one that reaches its+ * limit, one whose command the host ends, an upload whose body stops, a download nobody reads on.+ */+async function filesEnded(k: Kit, t: Thread, running: boolean) {+ const { check } = k;+ const where = running ? "running A's container" : 'a helper of stopped A';+ const place = k.filesPlace(t, running);+ const t0 = Date.now();+ const limit = await exit(await place.spawn(['/bin/sh', '-c', 'sleep 300 & sleep 301', 'sh'], { seconds: 2 }));+ const ms = Date.now() - t0;+ // In the container timeout(1) ends it (124); a helper is ended by Podman, which says 255.+ const l1 = await nothingLeft(k, t, running);+ check(limit === (running ? 124 : 255) && l1 === 'nothing', `a /files script in ${where} that reaches its limit of 2 s exits ${limit} after ${ms} ms and leaves ${l1}`);+ const p = await place.spawn(['/bin/sh', '-c', 'sleep 302', 'sh'], { seconds: 120 });+ const closed = exit(p);+ await new Promise((r) => setTimeout(r, 3000));+ p.kill('SIGTERM');+ const ended = await closed;+ const l2 = await nothingLeft(k, t, running);+ check(l2 === 'nothing', `one that writes nothing and whose command the host ends (exit ${ended}) leaves ${l2}`);+ const big = tarOf({ 'big.bin': 'x'.repeat(24 << 20) });+ const cut = await k.wire.putCut(t.sessionId, t.member, 's9-cut', big, big.length >> 1);+ const l3 = await nothingLeft(k, t, running);+ check(!!cut.error && l3 === 'nothing' && !(await list(k, t)).some((x) => x.startsWith('s9-cut')), `an upload whose body stops halfway is ${cut.error?.code}, and leaves ${l3} and no s9-cut`);+ const part = await k.wire.getCut(t.sessionId, t.member, 's9-big', true);+ const l4 = await nothingLeft(k, t, running);+ check('got' in part && part.got > 0 && l4 === 'nothing', `a download of 90 MB whose reader hangs up after ${'got' in part ? part.got : JSON.stringify(part.error)} bytes leaves ${l4}`);+}++/**+ * All three threads run: `a` and `b` of one person, `q` of another, with a journal. Leaves `a`'s preview of APP_PORT taken down, `b`'s up.+ */+export async function reachRunning(k: Kit, a: Thread, b: Thread, q: Thread) {+ const { check } = k;+ const host = http.createServer((_, res) => res.end('the host')).listen(APP_PORT, '127.0.0.1');+ try {+ await new Promise((r, j) => host.once('listening', r).once('error', j));+ for (const t of [a, b]) {+ await serve(k, t, OTHER_PORT);+ await serve(k, t, APP_PORT);+ }+ check((await k.until(async () => ((await k.inside(a.id, `curl -s -m 2 127.0.0.1:${APP_PORT}`).catch(() => '')) === 'inside A' ? true : undefined), 15_000)) === true+ && said(await get({ host: '127.0.0.1', port: APP_PORT, path: '/' }), 'the host'),+ `a server listens on ${APP_PORT} inside each container, and the check on the host's ${APP_PORT}`);++ // ---- the preview socket, before any preview+ const st = lstatSync(previewSocketFor(a.run, a.id));+ check(st.isSocket() && (st.mode & 0o777) === 0o660, `the runner listens on ${previewSocketFor(a.run, a.id)} (mode ${(st.mode & 0o777).toString(8)})`);+ const early = await viaSocket(a, APP_PORT);+ check('refused' in early, `before a preview its socket gives no way to port ${APP_PORT}: ${show(early)}`);+ const early2 = await viaProxy(k, APP_PORT);+ check(!('refused' in early2) && early2.status === 403 && /port not previewed/.test(early2.body), `and the proxy refuses port ${APP_PORT}, which the gateway's list allows: ${show(early2)}`);++ // ---- preview, in thread A+ const pa = await toolCall(k, a, 'preview', { port: APP_PORT, name: 's9-a' });+ const va = k.asked.find((x) => x.req.name === 's9-a');+ check(!!va && va.from === a.spec.key && va.req.port >= VIRTUAL_PORTS.first && va.req.port <= VIRTUAL_PORTS.last,+ `the runner's preview tool reached the gateway as port ${va?.req.port} (a virtual port) from ${va?.from}`);+ check(pa.json?.url === 'https://s9-a.opencomputer.app' && pa.json.listening === true && !/3\d{4}/.test(pa.text),+ `the model was answered in ${pa.ms} ms: ${pa.text}`);+ if (!va) throw new Error('no preview reached the gateway: nothing more of previews can be checked');+ const ga = await viaProxy(k, va.req.port);+ check(said(ga, 'inside A') && !('refused' in ga) && ga.headers['x-preview-origin'] === 'computer', `the proxy, asked for ${va.req.port}, answers from inside A's container: ${show(ga)}`);+ const raw = await viaProxy(k, APP_PORT);+ check(!('refused' in raw) && raw.status === 403, `asked for ${APP_PORT} itself it still refuses, so the host's own ${APP_PORT} never answers: ${show(raw)}`);+ check(said(await viaSocket(a, APP_PORT), 'inside A'), `the runner's socket now carries port ${APP_PORT}`);+ const other = await viaSocket(a, OTHER_PORT);+ check('refused' in other, `and no other port of the session (${OTHER_PORT}, where another server of it listens): ${show(other)}`);++ // ---- the probe, on a port nothing listens on+ const pn = await toolCall(k, a, 'preview', { port: APP_PORT + 1, name: 's9-none' });+ const vn = k.asked.find((x) => x.req.name === 's9-none');+ check(pn.json?.listening === false, `a port nothing listens on is reported so, after ${pn.ms} ms: ${pn.text}`);+ const gn = vn && (await viaProxy(k, vn.req.port));+ check(!!gn && !('refused' in gn) && gn.status === 503 && gn.headers['x-preview-state'] === 'closed', `and the proxy says closed for ${vn?.req.port}: ${gn && show(gn)}`);++ // ---- thread B: the same port number, another container+ const earlyB = await viaSocket(b, APP_PORT);+ check('refused' in earlyB, `B's socket gives no way to ${APP_PORT} because A previewed it: ${show(earlyB)}`);+ const pb = await toolCall(k, b, 'preview', { port: APP_PORT, name: 's9-b' });+ const vb = k.asked.find((x) => x.req.name === 's9-b');+ check(!!vb && vb.from === b.spec.key && vb.req.port !== va.req.port && pb.json?.listening === true, `B previews its own ${APP_PORT} as ${vb?.req.port} (${pb.ms} ms): ${pb.text}`);+ check(!!vb && said(await viaProxy(k, vb.req.port), 'inside B') && said(await viaProxy(k, va.req.port), 'inside A'), `${vb?.req.port} answers from inside B, ${va.req.port} still from inside A`);+ const fromB = await k.inside(b.id, `test -e ${a.run} && echo there || echo absent; test -S ${previewSocketFor(b.run, b.id)} && echo own; curl -s -m 2 127.0.0.1:${APP_PORT}`);+ check(fromB.split('\n').join(' ') === 'absent own inside B', `inside B: A's run directory (and so its preview socket) is ${fromB.split('\n')[0]}, and ${APP_PORT} is B's own (${fromB.split('\n').slice(1).join(', ')})`);+ const file = path.join(k.dataDir, 'state', 'previews.json');+ const table = JSON.parse(readFileSync(file, 'utf8')) as { entries: { virtual: number; id: string; port: number; name?: string }[] };+ check((statSync(file).mode & 0o777) === 0o600 && table.entries.length === 3 && table.entries.some((e) => e.id === b.id && e.port === APP_PORT && e.virtual === vb?.req.port && e.name === 's9-b'),+ `${file} (0600) holds the three: ${JSON.stringify(table.entries)}`);++ // ---- unpreview+ const ua = await toolCall(k, a, 'unpreview', { name: 's9-a' });+ const gone = await viaProxy(k, va.req.port);+ const closed = await viaSocket(a, APP_PORT);+ check(ua.text === '{}' && !('refused' in gone) && gone.status === 403 && 'refused' in closed, `after unpreview (${ua.ms} ms) ${va.req.port} is refused (${show(gone)}) and A's socket no longer carries ${APP_PORT} (${show(closed)})`);+ check(!!vb && said(await viaProxy(k, vb.req.port), 'inside B'), "B's preview is untouched");++ // ---- terminal+ await k.inside(a.id, 'echo only-in-A > /tmp/s9-mark');+ const t0 = Date.now();+ const ta = await k.wire.terminal(a.sessionId, k.member, 'id -u; hostname; pwd; cat /tmp/s9-mark; echo "$SP_RUN" 2>&1');+ check('out' in ta && ta.exitCode === 0 && ta.out.trim().split('\n').join(' ') === `1500 session /workspace only-in-A ${a.run}`,+ `a terminal of A opens inside A's container, as the session's user, in /workspace (${Date.now() - t0} ms): ${JSON.stringify('out' in ta ? ta.out : ta.error)}`);+ const tb = await k.wire.terminal(b.sessionId, k.member, 'cat /tmp/s9-mark 2>&1; echo "$SP_RUN"');+ check('out' in tb && /No such file/.test(tb.out) && tb.out.includes(b.run), `a terminal of B is in B's: ${JSON.stringify('out' in tb ? tb.out : tb.error)}`);+ const tx = await k.wire.terminal(a.sessionId, 'usr_someone_else', 'id');+ check(code(tx)?.code === 'forbidden', `another member is refused a terminal: ${JSON.stringify(code(tx))}`);+ const open = await k.wire.call<{ terminalId: string }>({ t: 'terminal.open', sessionId: a.sessionId, member: k.member, cols: 80, rows: 24, command: 'sleep 600', tty: true });+ const running = await k.until(async () => ((await k.inside(a.id, 'pgrep -f "[s]leep 600" || true')) ? true : undefined), 10_000);+ await k.wire.call({ t: 'terminal.close', terminalId: open.result?.terminalId });+ const hungUp = await k.until(async () => ((await k.inside(a.id, 'pgrep -f "[s]leep 600|[t]erminal-pty" || echo none')) === 'none' ? true : undefined), 15_000);+ check(!!open.result && running === true && hungUp === true, 'a terminal that is closed leaves no process behind in the container');++ // ---- files, both running+ const up = await k.wire.put(a.sessionId, k.member, 's9-notes', tarOf({ 'a.txt': 'pushed to A\n' }));+ check(up.result?.upload.path === 's9-notes' && up.result.upload.files === 1, `an upload to A: ${JSON.stringify(up.result ?? up.error)}`);+ const inA = await k.inside(a.id, 'cat /workspace/s9-notes/a.txt; stat -c %u /workspace/s9-notes/a.txt');+ const inB = await k.inside(b.id, 'test -e /workspace/s9-notes && echo there || echo absent');+ check(inA.split('\n').join(' ') === 'pushed to A 1500', `it is in A's /workspace, the session user's (${JSON.stringify(inA)})`);+ check(inB === 'absent' && !(await list(k, b)).some((p) => p.startsWith('s9-notes')) && (await list(k, a)).includes('s9-notes/a.txt'), `B's /workspace and B's listing do not have it (${inB}); A's listing does`);+ const back = await k.wire.get(a.sessionId, k.member, 's9-notes/a.txt', true);+ const notB = await k.wire.get(b.sessionId, k.member, 's9-notes/a.txt', true);+ check('body' in back && back.body.toString() === 'pushed to A\n' && code(notB)?.code === 'path_not_found', `it reads back from A, and from B it is ${code(notB)?.code}`);+ await k.inside(a.id, 'ln -s /etc/passwd /workspace/s9-link');+ const out = await k.wire.get(a.sessionId, k.member, '../../etc/passwd', true);+ const link = await k.wire.get(a.sessionId, k.member, 's9-link', true);+ check(code(out)?.code === 'invalid_path' && code(link)?.code === 'invalid_path', `a path that leaves the workspace, by name or by symlink, is ${code(out)?.code} / ${code(link)?.code}`);+ const onHost = (await k.asRunner(['/bin/sh', '-c', 'cat "$1/s9-notes/a.txt"; stat -c %U "$1/s9-notes/a.txt"', 'sh', a.workspace]).catch((e) => String(e.message))).trim();+ check(onHost.split('\n').join(' ') === 'pushed to A agent', `the upload to running A is in A's workspace on the host (${a.workspace}), the runners' user's: ${JSON.stringify(onHost)}`);++ // ---- /files scripts that do not run to their end+ await k.inside(a.id, 'truncate -s 90M /workspace/s9-big');+ await filesEnded(k, a, true);++ // ---- a terminal in a worktree+ const tg = await k.wire.terminal(a.sessionId, a.member, 'cd hello && pwd && git rev-parse --show-toplevel && git status --porcelain --branch | head -n 1 && git log -1 --format=%s && echo from-terminal > s9-term && git add s9-term && git -c user.name=check -c [email protected] commit -qm "from the terminal" && git log -1 --format=%s 2>&1');+ check('out' in tg && tg.exitCode === 0 && /^\/workspace\/hello\n\/workspace\/hello\n## sp\/\S+\nsandbox check\nfrom the terminal$/.test(tg.out.trim()),+ `a terminal of A works in its worktree /workspace/hello: git knows the branch and the last commit, and commits: ${JSON.stringify('out' in tg ? tg.out : tg.error)}`);++ // ---- links out of a workspace, to a sibling thread's and to another person's+ await k.inside(q.id, 'echo secret-of-q > /workspace/marker-q');+ await k.inside(b.id, 'echo secret-of-b > /workspace/marker-q');+ await k.inside(a.id, `ln -s ${b.workspace} /workspace/s9-run-to-b; ln -s ${q.workspace} /workspace/s9-run-to-q; ln -s ../../../${path.basename(path.dirname(path.dirname(q.workspace)))}/sessions/${path.basename(q.workspace)} /workspace/s9-run-rel`);+ const outs = await reads(k, a, ['s9-run-to-b', 's9-run-to-q', 's9-run-rel']);+ const byName = await k.wire.get(a.sessionId, a.member, `../${path.basename(b.workspace)}/marker-q`, true);+ check(outs.every(kept) && kept(byName), `from running A, links to the sibling's workspace and to another person's (absolute and relative) lead nowhere, as an archive or a file: ${codes(outs)}; by name: ${code(byName)?.code}`);+ const own = await k.wire.get(q.sessionId, q.member, 'marker-q', true);+ check('body' in own && own.body.toString() === 'secret-of-q\n', "and the other person reads that file through their own session's /files");++ // ---- a session of the API, with its journal mounted: what its runner records+ const tq = await k.wire.terminal(q.sessionId, q.member, 'id -u; pwd; cat marker-q');+ check('out' in tq && tq.out.trim().split('\n').join(' ') === '1500 /workspace secret-of-q', `a terminal of the session ${q.sessionId} (another person's) opens in its container: ${JSON.stringify('out' in tq ? tq.out : tq.error)}`);+ const notMine = await k.wire.terminal(q.sessionId, a.member, 'id');+ check(code(notMine)?.code === 'forbidden', `the first person is refused a terminal of it: ${JSON.stringify(code(notMine))}`);+ const pq = await k.wire.put(q.sessionId, q.member, 's9-q', tarOf({ 'q.txt': 'pushed to Q\n' })) as { result?: { upload: { files: number }; seq?: number | null }; error?: unknown };+ check(pq.result?.upload.files === 1 && typeof pq.result.seq === 'number', `an upload to it is recorded by its runner, which answers the event's seq: ${JSON.stringify(pq.result ?? pq.error)}`);+ const journal = path.join(k.dataDir, 'journals', q.sessionId, `${q.sessionId}.jsonl`);+ const events = (await k.until(async () => {+ const lines = (await k.asRunner(['/bin/cat', journal]).catch(() => '')).split('\n').filter(Boolean).map((l) => JSON.parse(l) as { seq: number; type: string; data?: Record<string, unknown>; actor?: { id?: string } });+ return lines.some((e) => e.type === 'terminal.closed') ? lines : undefined;+ }, 10_000)) ?? [];+ const opened = events.find((e) => e.type === 'terminal.opened');+ const pushed = events.find((e) => e.type === 'files.pushed');+ check(!!opened && opened.actor?.id === q.member && !!pushed && pushed.seq === pq.result?.seq && pushed.data?.path === 's9-q' && events.some((e) => e.type === 'terminal.closed'),+ `its journal ${journal} has terminal.opened (seq ${opened?.seq}), terminal.closed and files.pushed (seq ${pushed?.seq}: ${JSON.stringify(pushed?.data)})`);+ } finally {+ host.close();+ }+}++/** All three threads are stopped (their containers exited). */+export async function reachStopped(k: Kit, a: Thread, b: Thread, q: Thread) {+ const { check } = k;+ const t = await k.wire.terminal(a.sessionId, k.member, 'id');+ check(code(t)?.code === 'conflict' && code(t)?.reason === 'session_not_running' && (await k.status(a.id)) === 'exited',+ `a terminal of a stopped thread is refused and starts nothing: ${JSON.stringify(code(t))}`);++ const t0 = Date.now();+ const up = await k.wire.put(a.sessionId, k.member, 's9-stopped', tarOf({ 'note.txt': 'pushed while stopped\n' }));+ check(up.result?.upload.files === 1, `an upload to stopped A, through a helper container, in ${Date.now() - t0} ms: ${JSON.stringify(up.result ?? up.error)}`);+ const at = (await k.asRunner(['/bin/sh', '-c', 'cat "$1/s9-stopped/note.txt"; stat -c %U "$1/s9-stopped/note.txt"', 'sh', a.workspace]).catch((e) => String(e.message))).trim();+ check(at.split('\n').join(' ') === 'pushed while stopped agent', `it is in A's workspace on the host, the runners' user's: ${JSON.stringify(at)}`);+ const t1 = Date.now();+ const la = await list(k, a);+ const ms = Date.now() - t1;+ const lb = await list(k, b);+ check(la.includes('s9-stopped/note.txt') && !lb.some((p) => p.startsWith('s9-stopped')), `A's listing has it (${ms} ms), B's does not (A: ${JSON.stringify(la)}; B: ${JSON.stringify(lb)})`);+ const back = await k.wire.get(a.sessionId, k.member, 's9-stopped/note.txt', true);+ const tar = await k.wire.get(a.sessionId, k.member, 's9-stopped', false);+ const notB = await k.wire.get(b.sessionId, k.member, 's9-stopped/note.txt', true);+ check('body' in back && back.body.toString() === 'pushed while stopped\n' && 'body' in tar && tar.body.includes('pushed while stopped') && code(notB)?.code === 'path_not_found',+ `it reads back from A as a file and as an archive, and from B it is ${code(notB)?.code}`);+ const earlier = await k.wire.get(a.sessionId, k.member, 's9-notes/a.txt', true);+ const term = await k.wire.get(a.sessionId, k.member, 'hello/s9-term', true);+ check('body' in earlier && earlier.body.toString() === 'pushed to A\n' && 'body' in term && term.body.toString() === 'from-terminal\n',+ `what was uploaded to A while it ran, and what its terminal wrote in the worktree, read back while it is stopped: ${'body' in earlier ? JSON.stringify(earlier.body.toString()) : code(earlier)?.code}, ${'body' in term ? JSON.stringify(term.body.toString()) : code(term)?.code}`);+ await k.asRunner(['/bin/ln', '-s', b.workspace, path.join(a.workspace, 's9-to-b')]);+ await k.asRunner(['/bin/ln', '-s', q.workspace, path.join(a.workspace, 's9-to-q')]);+ const there = (await k.asRunner(['/bin/cat', path.join(a.workspace, 's9-to-b', 'marker-q'), path.join(a.workspace, 's9-to-q', 'marker-q')]).catch((e) => String(e.message))).trim();+ const outs = await reads(k, a, ['s9-to-b', 's9-to-q', 's9-run-to-b', 's9-run-to-q', 's9-run-rel']);+ const out = await k.wire.get(a.sessionId, k.member, '../' + path.basename(b.workspace), false);+ check(there === 'secret-of-b\nsecret-of-q' && outs.every(kept) && kept(out),+ `from stopped A, links that on the host lead to the sibling's workspace and to another person's (made now, and made inside while it ran) lead nowhere in the helper: ${codes(outs)}; by name: ${code(out)?.code}`);+ const pq = await k.wire.put(q.sessionId, q.member, 's9-q-stopped', tarOf({ 'q.txt': 'pushed to stopped Q\n' }));+ const lq = await list(k, q);+ const qa = await k.wire.get(a.sessionId, k.member, 's9-q-stopped/q.txt', true);+ check(pq.result?.upload.files === 1 && lq.includes('s9-q-stopped/q.txt') && lq.includes('s9-q/q.txt') && code(qa)?.code === 'path_not_found',+ `an upload to the other person's stopped session is in their listing, beside the one made while it ran, and from A it is ${code(qa)?.code}: ${JSON.stringify(pq.result ?? pq.error)}`);+ // Q's runner is gone: the host's own writer records the upload in Q's journal (this process is the host's user: it reads the file itself).+ const sq = (pq.result as { seq?: number | null } | undefined)?.seq;+ const journal = path.join(k.dataDir, 'journals', q.sessionId, `${q.sessionId}.jsonl`);+ const logged = await k.until(async () => {+ const lines = readFileSync(journal, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as { seq: number; type: string; data?: Record<string, unknown> });+ return lines.find((e) => e.type === 'files.pushed' && e.data?.path === 's9-q-stopped');+ }, 5000).catch(() => undefined);+ check(typeof sq === 'number' && logged?.seq === sq, `the upload to stopped Q is in its journal, written by the host's writer: seq ${sq}, on file ${JSON.stringify(logged)}`);+ await filesEnded(k, a, false);+ check((await k.status(a.id)) === 'exited' && (await k.status(b.id)) === 'exited' && (await k.status(q.id)) === 'exited', 'none of it started a container');+}++/** `a` runs again; `b` is still stopped. */+export async function reachResumed(k: Kit, a: Thread, b: Thread) {+ const { check } = k;+ const inA = await k.inside(a.id, 'cat /workspace/s9-stopped/note.txt; stat -c %u /workspace/s9-stopped/note.txt; cat /workspace/s9-notes/a.txt');+ const back = await k.wire.get(a.sessionId, k.member, 's9-stopped/note.txt', true);+ check(inA.split('\n').join(' ') === 'pushed while stopped 1500 pushed to A' && 'body' in back && back.body.toString() === 'pushed while stopped\n',+ `what was uploaded to A while it was stopped is in its /workspace now that it runs, the session user's, and reads back through its container: ${JSON.stringify(inA)}`);+ const up = await k.wire.put(a.sessionId, k.member, 's9-stopped', tarOf({ 'note.txt': 'again\n' })) as { result?: { upload: { replaced: unknown } }; error?: unknown };+ const mine = await k.wire.put(a.sessionId, k.member, 'hello', tarOf({ 'note.txt': 'again\n' }));+ check(!!up.result?.upload.replaced && (await k.inside(a.id, 'cat /workspace/s9-stopped/note.txt')) === 'again' && code(mine)?.code === 'path_exists',+ `a second upload of that name, now through the container, replaces it as an upload (${JSON.stringify(up.result ?? up.error)}); one over the worktree is ${code(mine)?.code}`);+ const outs = await reads(k, a, ['s9-to-b', 's9-to-q']);+ check(outs.every(kept) && (await k.status(b.id)) === 'exited', `the links made on the host while it was stopped lead nowhere inside it either: ${codes(outs)}`);+}diff --git a/computer/src/dev/sandbox-check-restart.ts b/computer/src/dev/sandbox-check-restart.tsnew file mode 100644index 00000000..38e28880--- /dev/null+++ b/computer/src/dev/sandbox-check-restart.ts@@ -0,0 +1,298 @@+// The part of sandbox-check.ts about a host that starts again and about what+// it removes (work 103, step 8): previews after a resume, `unpreview` of+// another session's name, a killed host taking its running containers back,+// a runner socket that was replaced, a container without a record and a+// record without a container, the sweep, the image lock held across a+// restart, and Prune. sandbox-check.ts owns the hosts, the fake gateway and+// the threads; this file plants, restarts, and compares. And what the review+// of step 8 found: a preview name another session holds, a record's file that+// does not load, and a message that arrives while its thread is pruned.+//+// Invariants:+// - It kills the host with SIGKILL, never asks it to stop: what is checked is+// what a host that died leaves and what the next one makes of it.+// - Everything it plants has an id of its own, and it removes all of it, pass+// or fail. One container and one volume are planted as another host's (no+// run directory of this one): they must be there at the end, and are then+// removed here.+// - The image lock is the computer's (image-lock.ts), so it is held only when+// its file is already there and readable, and for LOCK_S: every host on the+// computer waits that long for Podman.+// - The second restart runs the host with a sweep age of seconds and a+// retention of seconds; the threads that must survive are delivered to+// throughout, and the two that are to be pruned are left to go idle.++import { type ChildProcess, spawn } from 'node:child_process';+import { accessSync, constants, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import path from 'node:path';+import { randomBytes } from 'node:crypto';+import { IMAGE_LOCK } from '../host/sandbox/image-lock.js';+import type { AsRunner } from '../host/sandbox/podman.js';+import { containerName, unitName, volumeName } from '../host/sandbox/podman-args.js';+import type { SandboxRecord } from '../host/sandbox/records.js';+import { type RunRoot, sandboxRunFor, socketFor } from '../ipc.js';+import type { HostToGateway, Person, SessionSpec } from '../protocol.js';+import type { TelemetryEvent } from '../telemetry/envelope.js';+import { safeKey } from '../workspaces/clones.js';+import { APP_PORT, type Kit, type Thread as Reached, said, serve, show, toolCall, viaProxy } from './sandbox-check-reach.js';++const LOCK_S = 8;+const SWEEP_AGE_MS = 6000;+/** SP_FORK_RETENTION_DAYS for the second restart: 26 s. */+const RETENTION_DAYS = 0.0003;++/** A thread as sandbox-check.ts makes one. */+export interface T {+ key: string;+ owner: Person;+ spec: SessionSpec;+ record(): SandboxRecord | undefined;+ id(): string;+ readonly run: RunRoot;+ workspace: string;+ registry(repo: string): string;+ branch: string;+ deliver(): Promise<{ reply?: { ok: boolean; error?: string }; ms: number }>;+ inspect(format: string): Promise<string>;+ inside(script: string, as_?: string): Promise<string>;+ pid(): Promise<number>;+ askToken(): Promise<string>;+}++export interface Rig {+ kit: Kit;+ as: AsRunner;+ run: string;+ data: string;+ image: string;+ /** Everything the hosts wrote, by line. */+ lines: string[];+ /** SIGKILL the host; resolves once it is gone. */+ kill(): Promise<void>;+ /** Start one, with these variables on top of the check's; how long until its hello, undefined when none came. */+ start(env?: Record<string, string>): Promise<number | undefined>;+ events: HostToGateway[];+ tel: TelemetryEvent[];+ /** The public names the gateway holds, and the `unpreview`s it got. */+ names: Map<string, number>;+ unpreviewed: { from: string; name: string }[];+ welcome(about: string): void;+ /** A person's clone of a repository, on the host. */+ clone(person: string, repo: string): string;+ /** Tell the host a thread's `cs_` id, as a gateway does; the id. */+ known(spec: SessionSpec): Promise<string>;+}++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++/**+ * `a` runs, `b` (the same person's) and `q` (another's) are stopped, `c` and `e` are threads nobody started yet. `b` has the+ * preview `s9-b` of APP_PORT and `a` has `s9-none` of APP_PORT + 1, from sandbox-check-reach.ts. Returns the timings.+ */+export async function restarts(x: Rig, A: T, B: T, Q: T, C: T, E: T) {+ const { kit: k } = x;+ const { check, say, until } = k;+ const podman = (args: string[], timeoutMs = 30_000) => x.as.podman(args, { timeoutMs });+ const has = (kind: 'container' | 'volume', name: string) => podman([kind, 'exists', name]).then(() => true, () => false);+ const reach = (name: string, t: T): Reached => ({ name, spec: t.spec, sessionId: '', id: t.id(), run: t.run, workspace: t.workspace, member: '' });+ const started = async (t: T) => ({ pid: await t.pid(), at: await t.inspect('{{.State.StartedAt}}') });+ const same = async (t: T, was: { pid: number; at: string }) => (await t.pid()) === was.pid && (await t.inspect('{{.State.StartedAt}}')) === was.at;+ const status = (t: T) => t.inspect('{{.State.Status}}');+ const tookBack = (t: T, from: number) => /taken back for \S+ in (\d+) ms/.exec(x.lines.slice(from).find((l) => l.includes(`taken back for ${t.key} `)) ?? '')?.[1];+ const failedUnit = (id: string) => x.as.run(['/usr/bin/systemctl', '--user', 'is-failed', '--quiet', unitName(id)], { timeoutMs: 5000 }).then(() => true, () => false);+ const port = (name: string) => k.asked.find((q) => q.req.name === name)?.req.port ?? 0;+ const table = () => (JSON.parse(readFileSync(path.join(x.data, 'state', 'previews.json'), 'utf8')) as { entries: { id: string; name?: string }[] }).entries;+ /** Threads delivered to every 8 s: none of them leaves for idleness, and none is idle beyond retention. */+ const kept = new Set<T>();+ const keeping = setInterval(() => void Promise.all([...kept].map((t) => t.deliver())), 8000);+ /** One more delivery to each, and none after: a runner counts its idle time from here, across the restart. */+ const quiesce = async () => {+ const last = [...kept];+ kept.clear();+ await Promise.all(last.map((t) => t.deliver()));+ };+ const [X, F, V, W, D, U, R] = Array.from({ length: 7 }, () => randomBytes(8).toString('hex'));+ const dir = (id: string) => sandboxRunFor(x.run, id);+ const planted = path.join(x.run, 'runners', 'planted.sock');+ /** The record of R: a file that is there and does not load. */+ const cut = path.join(x.data, 'state', 'sandboxes', `${R}.json`);+ let holder: ChildProcess | undefined;+ const times: Record<string, number | undefined> = {};++ try {+ // ---- previews after a stop and a resume: the runner is told its ports again+ const asked = k.asked.length;+ const [dB, dC] = await Promise.all([B.deliver(), C.deliver()]);+ times.resume_ms = dB.ms;+ check(!!dB.reply?.ok && !!dC.reply?.ok, `the stopped thread resumes in ${dB.ms} ms, and a new one starts in ${dC.ms} ms (${dB.reply?.error ?? ''}${dC.reply?.error ?? ''})`);+ const [a, b, c] = [reach('A', A), reach('B', B), reach('C', C)];+ kept.add(A).add(B).add(C);+ await serve(k, b, APP_PORT);+ await serve(k, a, APP_PORT + 1);+ const gb = await until(async () => (said(await viaProxy(k, port('s9-b')), 'inside B') ? true : undefined), 15_000);+ await until(async () => (said(await viaProxy(k, port('s9-none')), 'inside A') ? true : undefined), 15_000);+ const ga = await viaProxy(k, port('s9-none'));+ check(!!gb && said(ga, 'inside A') && k.asked.length === asked,+ `after a stop and a resume the previews answer again, B's ${port('s9-b')} and A's ${port('s9-none')} (${show(ga)}), and no runner asked for a preview again`);++ // ---- unpreview: only a session's own names+ const un = await toolCall(k, a, 'unpreview', { name: 's9-b' });+ check(/no preview named s9-b in this session/.test(un.text) && x.names.has('s9-b') && !x.unpreviewed.some((u) => u.name === 's9-b') && said(await viaProxy(k, port('s9-b')), 'inside B'),+ `A's unpreview of B's name is refused (${un.text}), the gateway was not asked, and B's preview still answers`);+ await serve(k, c, APP_PORT);+ const pc = await toolCall(k, c, 'preview', { port: APP_PORT, name: 's8-c' });+ check(pc.json?.listening === true && x.names.has('s8-c'), `C previews its ${APP_PORT} as s8-c (${pc.text})`);+ await C.inside('echo layer > /opt/s8-layer', '0:0');+ const dup = await toolCall(k, a, 'preview', { port: APP_PORT + 2, name: 's8-c' });+ check(/another session has a preview named s8-c; choose another name/.test(dup.text) && !k.asked.some((q) => q.req.name === 's8-c' && q.from !== C.key)+ && table().filter((e) => e.name === 's8-c').every((e) => e.id === c.id) && said(await viaProxy(k, port('s8-c')), 'inside C'),+ `A's preview under the name C holds is refused (${dup.text}), the gateway was not asked, and the name still answers from inside C`);++ // ---- a killed host: two threads run, one is stopped, one runner's socket was replaced, one socket is planted where hosts used to scan+ await quiesce();+ const fake = `const net=require("net"),fs=require("fs"),p=process.argv[1];fs.renameSync(p,p+".real");net.createServer(s=>{s.on("error",()=>{});s.write(JSON.stringify({t:"report",report:{key:${JSON.stringify(A.key)},status:"idle",forkPath:"/workspace"}})+"\\n")}).listen(p,()=>fs.chmodSync(p,432))`;+ await k.detached(c.id, ['node', '-e', fake, socketFor(c.run, c.id)]);+ const old = `const net=require("net"),fs=require("fs"),p=process.argv[1];net.createServer(s=>{fs.writeFileSync(p+".dialed","1");s.on("error",()=>{});s.write(JSON.stringify({t:"report",report:{key:"C_PLANTED:1.1",status:"idle"}})+"\\n")}).listen(p,()=>fs.chmodSync(p,432))`;+ void x.as.run([process.execPath, '-e', old, planted], { timeoutMs: 900_000 }).catch(() => {});+ check(!!(await until(() => (existsSync(`${socketFor(c.run, c.id)}.real`) && existsSync(socketFor(c.run, c.id)) && existsSync(planted) ? true : undefined), 10_000)),+ `planted: C's session put its own listener at its runner's socket, reporting A's thread; and a listener at ${planted}`);+ const was = { A: await started(A), B: await started(B) };+ let mark = x.lines.length;+ await x.kill();+ times.restart_hello_ms = await x.start();+ check(times.restart_hello_ms !== undefined, `the host was killed with two threads running; the next one said hello after ${times.restart_hello_ms} ms`);+ times.adopt_a_ms = Number(await until(() => tookBack(A, mark), 5000));+ times.adopt_b_ms = Number(await until(() => tookBack(B, mark), 5000));+ check((await same(A, was.A)) && (await same(B, was.B)) && times.adopt_a_ms >= 0 && times.adopt_b_ms >= 0,+ `it took both back (${times.adopt_a_ms} and ${times.adopt_b_ms} ms from the inventory) and neither container was restarted: same process, same start time`);+ const hello = x.events.filter((e): e is Extract<HostToGateway, { t: 'hello' }> => e.t === 'hello').at(-1);+ check(hello?.sessions.map((s) => s.key).sort().join() === [A.key, B.key].sort().join(), `its hello names those two sessions and no other: ${hello?.sessions.map((s) => s.key).join()}`);+ const [rA, rB] = await Promise.all([A.deliver(), B.deliver()]);+ check(!!rA.reply?.ok && !!rB.reply?.ok && (await same(A, was.A)) && (await same(B, was.B)), `a delivery reaches each (${rA.ms} and ${rB.ms} ms), in the same containers`);+ kept.add(A).add(B);+ check((await A.askToken()).startsWith('ghs_fake') && said(await viaProxy(k, port('s9-b')), 'inside B') && k.asked.length === asked + 1,+ "A's token socket answers under the new host, and B's preview answers with no new preview");+ check(!!(await until(async () => ((await status(C)) === 'exited' ? true : undefined), 30_000)) && x.lines.slice(mark).some((l) => l.includes(`it reports ${A.key}, not its record's ${C.key}`)),+ "the container whose socket reported A's thread was not taken back: it is stopped, and its record stays");+ check(existsSync(planted) && !existsSync(`${planted}.dialed`), `the listener planted in ${path.dirname(planted)} was never dialed`);+ const qid = Q.id();+ const [rQ, rC, rE] = await Promise.all([Q.deliver(), C.deliver(), E.deliver()]);+ check(!!rQ.reply?.ok && Q.record()?.id === qid && (await status(Q)) === 'running', `the thread that was stopped across the restart resumes in ${rQ.ms} ms (${rQ.reply?.error ?? ''})`);+ check(!!rC.reply?.ok && (await C.inside('cat /opt/s8-layer')) === 'layer', `and the stopped one answers again as its own thread in ${rC.ms} ms, with what root wrote outside its home before the stop (${rC.reply?.error ?? ''})`);+ check(!!rE.reply?.ok && !!E.record()?.repos?.hello, `a fifth thread starts in ${rE.ms} ms, to be pruned while a message for it arrives (${rE.reply?.error ?? ''})`);+ kept.add(Q);++ // ---- planted for the second restart; A, C and E are left to go idle+ kept.delete(A);+ for (const id of [X, V, D, R]) mkdirSync(dir(id));+ const make = (id: string, binds: string[], argv = ['true']) =>+ podman(['create', '--name', containerName(id), '--label', `sp.runner=${id}`, '--userns=keep-id:uid=1500,gid=1500', '-v', `${volumeName(id)}:/home/agent`, ...binds, '--entrypoint', JSON.stringify(argv), x.image], 60_000);+ await make(X, ['-v', `${dir(X)}:${dir(X)}`]); // this host's, by its run directory, and of no record+ await make(F, []); // another host's+ // This host's, running, and of a record whose file was cut short: nothing may remove what that record names.+ await make(R, ['-v', `${dir(R)}:${dir(R)}`], ['/bin/sh', '-c', 'echo kept > /home/agent/s8-cut; trap "exit 0" TERM; sleep 900 & wait']);+ await podman(['start', containerName(R)]);+ check(!!(await until(async () => ((await podman(['exec', containerName(R), 'cat', '/home/agent/s8-cut']).catch(() => '')).trim() === 'kept' ? true : undefined), 10_000)), `planted: a running container ${containerName(R)} of this host, whose record's file is cut short`);+ writeFileSync(cut, `{"id":"${R}","person":"${A.owner.dir}","key":"C_SANDBOX:9`);+ for (const id of [V, W]) await podman(['volume', 'create', volumeName(id)]);+ for (const id of [V, U]) await x.as.run(['/usr/bin/systemd-run', '--user', '--quiet', '--unit', unitName(id), '/bin/false'], { timeoutMs: 10_000 }).catch(() => {});+ check(!!(await until(async () => ((await failedUnit(V)) && (await failedUnit(U)) ? true : undefined), 10_000)), 'planted: a container and a home of no record, a home and a failed unit with a run directory, an empty run directory; and a container, a home and a failed unit of no run directory of this host');+ await Q.inside('echo kept > /home/agent/s8-marker');+ await quiesce();+ const wasB = await started(B);+ const canLock = existsSync(IMAGE_LOCK) && (() => { try { return accessSync(IMAGE_LOCK, constants.R_OK), true; } catch { return false; } })();+ mark = x.lines.length;+ const telMark = x.tel.length;+ await x.kill();+ await podman(['rm', '--force', containerName(qid)]); // a record with no container+ if (canLock) {+ holder = spawn('/usr/bin/flock', ['--exclusive', IMAGE_LOCK, '/usr/bin/sleep', String(LOCK_S)], { stdio: 'ignore' });+ await sleep(300);+ }+ times.restart_locked_hello_ms = await x.start({ SP_SWEEP_AGE_MS: String(SWEEP_AGE_MS), SP_FORK_RETENTION_DAYS: String(RETENTION_DAYS) });+ const [rB2, rQ2] = await Promise.all([B.deliver(), Q.deliver()]);+ kept.add(B).add(Q);+ const back = !!rB2.reply?.ok && (await same(B, wasB)) && tookBack(B, mark) !== undefined;+ if (canLock) check((times.restart_locked_hello_ms ?? 0) >= LOCK_S * 1000 - 1500 && back,+ `a host that starts while provisioning holds the image lock (${LOCK_S} s) waits for it (hello after ${times.restart_locked_hello_ms} ms), then takes B back without restarting it`);+ else {+ say(`SKIP the image lock held across a restart: no readable ${IMAGE_LOCK} here (root: install -m 0640 -g <the host's group> /dev/null ${IMAGE_LOCK})`);+ check(back, `the second host said hello after ${times.restart_locked_hello_ms} ms and took B back without restarting it`);+ }++ // ---- what the start removes, and what a record without a container gets+ check(!!(await until(async () => (!(await has('container', containerName(X))) && !(await has('volume', volumeName(X))) ? true : undefined), 20_000)), 'the container with no record, and its home, are removed at the start');+ const ofR = async () => `container ${await podman(['inspect', '--format', '{{.State.Status}}', containerName(R)]).then((s) => s.trim(), () => 'none')}, home ${(await has('volume', volumeName(R))) ? 'there' : 'gone'}, run directory ${existsSync(dir(R)) ? 'there' : 'gone'}, file ${existsSync(cut) ? 'there' : 'gone'}`;+ const keptR = 'container exited, home there, run directory there, file there';+ check(!!(await until(async () => ((await ofR()) === keptR ? true : undefined), 30_000)) && x.lines.slice(mark).some((l) => l.includes(`sandbox ${R}: its record did not load; kept, stopped`)),+ `the running container whose record's file was cut short is stopped and not removed: ${await ofR()}`);+ check(!!rQ2.reply?.ok && Q.record()?.id === qid && (await Q.inside('cat /home/agent/s8-marker')) === 'kept', `the record whose container was removed gets a new container in ${rQ2.ms} ms, under the same id and with its home (${rQ2.reply?.error ?? ''})`);++ // ---- the sweep+ const sweptAt = Date.now();+ check(!!(await until(async () => (!(await has('volume', volumeName(V))) && ![V, X, D].some((id) => existsSync(dir(id))) && !(await failedUnit(V)) ? true : undefined), 60_000)),+ `the sweep removed the home of no record, the three run directories of no container, and reset the failed unit (${Date.now() - sweptAt} ms after the start's checks; objects older than ${SWEEP_AGE_MS} ms)`);+ const homeR = await podman(['run', '--rm', '--userns=keep-id:uid=1500,gid=1500', '-v', `${volumeName(R)}:/home/agent`, '--entrypoint', '/bin/cat', x.image, '/home/agent/s8-cut'], 60_000).then((s) => s.trim(), (e) => `error: ${e.message}`);+ check((await ofR()) === keptR && homeR === 'kept', `after the sweep too (${await ofR()}), and its home holds what was written in it (${JSON.stringify(homeR)})`);+ check((await has('container', containerName(F))) && (await has('volume', volumeName(F))) && (await has('volume', volumeName(W))) && (await failedUnit(U)),+ 'the container, the homes and the failed unit that have no run directory of this host are untouched');+ const swept = await until(() => x.tel.slice(telMark).find((e) => e.event_name === 'sandbox.swept'), 15_000);+ check(!!swept, `sandbox.swept: ${JSON.stringify(swept?.data)}`);+ const whole = async (t: T) => (await status(t)) === 'running' && (await has('volume', volumeName(t.id()))) && existsSync(t.run) && !!t.record();+ check((await whole(B)) && (await whole(Q)) && (await same(B, wasB)), "the running threads, one of each person, have their containers, homes, run directories and records; B's container never restarted");++ // ---- Prune: C is clean and pushed (nothing was committed), A has a commit on no remote+ const [aid, cid, crun, eid] = [A.id(), C.id(), C.run, E.id()];+ check(!!(await until(async () => ((await status(A)) === 'exited' && (await status(C)) === 'exited' && (await status(E)) === 'exited' ? true : undefined), 90_000)), 'A, C and E went idle and are stopped');+ const pruneAt = Date.now();+ // A message for E the moment its prune shows (its record without repositories, or gone): the delivery waits for the thread's turn.+ let seen = '';+ const raced = (async () => {+ for (const end = Date.now() + 200_000; Date.now() < end; await sleep(5)) {+ const r = E.record();+ if (r?.repos?.hello && r.id === eid) continue;+ seen = r ? 'its record had lost its repositories' : 'its record was gone';+ return E.deliver();+ }+ })();+ // A changed definition starts a housekeeping pass, unless one is running: asked again until it shows.+ for (let n = 0; n < 15 && (C.record() || !seen); n++) {+ x.welcome(`fourth ${n}`);+ await until(() => (C.record() || !seen ? undefined : true), 10_000);+ }+ const rE2 = await raced;+ const inE = await E.inside(`git -C /workspace/hello status --porcelain --branch; node -p "require('/workspace/.fork.json').key"; ls /clones/hello/.git/worktrees`);+ check(!!rE2?.reply?.ok && (await status(E)) === 'running' && !!E.record()?.repos?.hello && inE === [`## ${E.branch}`, E.key, 'hello'].join('\n') && !(await has('container', containerName(eid))),+ `a message that arrives while its thread is pruned (${seen || 'the prune never showed'}) is answered in ${rE2?.ms} ms by a thread that works, in a new container ${E.id()} and a prepared workspace: ${JSON.stringify(inE)} ${rE2?.reply?.error ?? ''}`);+ check(!C.record() && !(await has('container', containerName(cid))) && !(await has('volume', volumeName(cid))) && !existsSync(C.workspace) && !existsSync(path.dirname(C.registry('x'))) && !existsSync(crun),+ `a thread idle beyond retention with nothing unsaved is pruned (${Date.now() - pruneAt} ms after it was seen stopped; retention ${Math.round(RETENTION_DAYS * 86_400)} s): container, home, workspace, registries, run directory, record`);+ const branch = await x.as.run(['/usr/bin/git', '-C', x.clone(C.owner.dir, 'hello'), 'branch', '--list', C.branch], { timeoutMs: 10_000 }).catch((e) => `error: ${e.message}`);+ check(branch.trim() === '', `its branch is forgotten in the person's clone (${JSON.stringify(branch.trim())})`);+ check(!!(await until(() => (!x.names.has('s8-c') && x.unpreviewed.some((u) => u.name === 's8-c' && u.from === C.key) ? true : undefined), 10_000)) && !table().some((e) => e.id === cid),+ `the gateway was told to unpreview s8-c for ${C.key}, and the table holds no port of the removed sandbox`);+ const row = await until(() => x.events.flatMap((e) => (e.t === 'workspace' ? e.status.repos : [])).find((r) => r.name === `sessions/${safeKey(A.key)}`), 30_000);+ check(!!A.record() && !(await has('container', containerName(aid))) && (await has('volume', volumeName(aid))) && existsSync(A.workspace) && /kept: /.test(row?.problem ?? ''),+ `the thread with unsaved work loses only its container; housekeeping reports: ${row?.problem}`);+ check(x.names.has('s9-none') && table().some((e) => e.id === aid && e.name === 's9-none'), 'and its preview stays');+ const rA3 = await A.deliver();+ const inA = await A.inside('cat /home/agent/sandbox-check-marker; git -C /workspace/hello log --format=%s -1');+ check(!!rA3.reply?.ok && A.record()?.id === aid && inA === 'kept\nfrom the terminal', `its next message creates the container again in ${rA3.ms} ms, with its home and its commit (${JSON.stringify(inA)} ${rA3.reply?.error ?? ''})`);+ check((await whole(B)) && (await whole(Q)), 'the threads in use were not pruned');++ // ---- health+ const sample = await until(() => x.tel.slice(telMark).find((e) => e.event_name === 'host.sample' && typeof e.data?.containers_running === 'number'), 70_000);+ check(typeof sample?.data?.data_used_pct === 'number' && typeof sample.data.podman_bytes === 'number', `host.sample carries the containers by state and the disk: ${JSON.stringify(sample?.data)}`);+ } finally {+ clearInterval(keeping);+ holder?.kill();+ const quiet = (p: Promise<unknown>) => p.catch(() => {});+ await quiet(x.as.run(['/usr/bin/pkill', '-f', planted], { timeoutMs: 5000 }));+ for (const f of [planted, `${planted}.dialed`]) rmSync(f, { force: true });+ for (const id of [X, F, R]) await quiet(podman(['rm', '--force', '--time', '0', containerName(id)]));+ for (const id of [X, F, V, W, R]) await quiet(podman(['volume', 'rm', '--force', volumeName(id)]));+ for (const id of [X, V, D, R]) rmSync(dir(id), { recursive: true, force: true });+ rmSync(cut, { force: true });+ await quiet(x.as.run(['/usr/bin/systemctl', '--user', 'reset-failed', unitName(V), unitName(U)], { timeoutMs: 5000 }));+ }+ return times;+}diff --git a/computer/src/dev/sandbox-check-spares.ts b/computer/src/dev/sandbox-check-spares.tsnew file mode 100644index 00000000..d21e37b5--- /dev/null+++ b/computer/src/dev/sandbox-check-spares.ts@@ -0,0 +1,403 @@+// The part of sandbox-check.ts about spares (work 103, step 10; `--spares`):+// containers a `podman` host makes ahead of time, and a new thread's claim of+// one. sandbox-check.ts owns the fake gateway, the collector, the threads and+// the cleanup; this file starts and stops the hosts, asks and compares, and+// prints the timings.+//+// Four hosts, one after the other, on the same directories:+// A SP_POOL_SIZE=0: the first reply of new threads without a spare, with a+// repository and without (the numbers to compare with).+// B SP_POOL_SIZE=2: what an unclaimed spare holds (mounts, environment,+// boot.env, token socket) and costs (its cgroup), the claim (whose+// container, what is mounted, the timings), the pool's size and refill, a+// warm delivery beside a refill, new threads back to back, and a claim+// that fails (the spares are paused): the delivery is answered by a cold+// start under the record's id. Killed, as a crash: its spares keep running.+// C another SP_VERSION and another name for the image: the spares of B are+// removed at its start and never claimed (and, where the image lock's file is there+// and the check may read it, not before the lock it holds for LOCK_S is+// free, nor is a spare made), a thread's container is left alone, the new+// spare is from the new release and image, and it stays through the idle+// time that stops the thread it sits beside. Stopped with SIGTERM while+// the spare's runner is frozen (SIGSTOP), so it can heed no request: the+// host removes the spare's container, home and run directory itself,+// and ends within its stop time.+// D SP_POOL_SIZE=0: finds nothing left of C's spare, and makes none.+//+// Invariants:+// - A first reply is measured only while nothing else starts: the pool is+// full (or off) before each, and the threads of a batch are removed after it.+// - A spare is read by its id, found as a run directory below this check's+// SP_RUN with no record and a running container; a ready one has a Claude+// Code parked in it.+// - What it adds to the runners' user's Podman besides containers is one more+// name for the session image, which it removes.++import { type ChildProcess, spawn } from 'node:child_process';+import { accessSync, constants, existsSync, readdirSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { IMAGE_LOCK } from '../host/sandbox/image-lock.js';+import { containerName, pidArgs, unitName, volumeName } from '../host/sandbox/podman-args.js';+import type { Records } from '../host/sandbox/records.js';+import { sandboxRunFor } from '../ipc.js';+import type { HostToGateway, Person, SessionSpec, TraceContext } from '../protocol.js';+import type { TelemetryEvent } from '../telemetry/envelope.js';++export interface SpareThread {+ key: string;+ spec: SessionSpec;+ id(): string;+ deliver(trace?: TraceContext, text?: string): Promise<{ reply?: { ok?: boolean; error?: string }; ms: number; trace: TraceContext }>;+ inspect(format: string): Promise<string>;+ inside(script: string, as?: string): Promise<string>;+ logs(): Promise<string>;+ askToken(): Promise<string>;+}++export interface SpareKit {+ run: string;+ data: string;+ image: string;+ idleMs: number;+ say(...a: unknown[]): void;+ check(ok: boolean, what: string): void;+ until<T>(f: () => T | undefined | Promise<T | undefined>, ms?: number, every?: number): Promise<T | undefined>;+ sleep(ms: number): Promise<unknown>;+ /** Podman as the runners' user. */+ podman(args: string[], timeoutMs?: number): Promise<string>;+ events: HostToGateway[];+ tel: TelemetryEvent[];+ /** The session keys the gateway was asked a token for. */+ tokenSessions: (string | undefined)[];+ mkTrace(): TraceContext;+ people: [Person, Person];+ records(): Records;+ clone(p: Person, name: string): string;+ thread(owner: Person, n: number): SpareThread;+ /** What the gateway's welcome carries from now on, sent to a connected host at once. */+ welcome(about: string, repos: boolean): void;+ start(env: Record<string, string>): ChildProcess;+}++const N = Number(process.env.SP_CHECK_N ?? 6);+const POOL = 2;+const NEXT_VERSION = 'sandbox-check-next';+const NEXT_IMAGE = 'localhost/sandbox-check-spares:next';+const HEX = /^[0-9a-f]{16}$/;+const LOCK_S = 6;++const sorted = (xs: number[]) => [...xs].sort((a, b) => a - b);+const p50 = (xs: number[]) => sorted(xs)[Math.floor((xs.length - 1) / 2)] ?? NaN;+const row = (xs: number[]) => `p50 ${p50(xs)} ms, min ${Math.min(...xs)}, max ${Math.max(...xs)}, n=${xs.length} [${xs.join(' ')}]`;+const num = (v: unknown) => (typeof v === 'number' ? v : NaN);++export async function spareChecks(k: SpareKit) {+ const { say, check, until, sleep, podman } = k;+ const [PAT] = k.people;+ let n = 100;+ let host: ChildProcess | undefined;+ const newThread = () => k.thread(PAT, n++);++ // ---- hosts+ async function boot(name: string, env: Record<string, string>) {+ const from = k.events.length;+ const at = Date.now();+ host = k.start(env);+ const hello = await until(() => k.events.slice(from).find((e) => e.t === 'hello'), 60_000);+ check(!!hello, `host ${name} (${Object.entries(env).map(([a, b]) => `${a}=${b}`).join(' ')}) said hello in ${Date.now() - at} ms`);+ if (!hello) throw new Error(`host ${name} did not start: nothing more can be checked`);+ return at;+ }+ async function halt(signal: 'SIGTERM' | 'SIGKILL') {+ const h = host;+ if (!h || h.exitCode !== null || h.signalCode) return;+ const gone = new Promise((r) => h.once('exit', r));+ h.kill(signal);+ await Promise.race([gone, sleep(15_000).then(() => h.kill('SIGKILL'))]);+ await gone;+ }++ // ---- containers, by id+ const status = (id: string) => podman(['inspect', '--format', '{{.State.Status}}', containerName(id)]).then((s) => s.trim(), () => 'none');+ const inside = (id: string, script: string) =>+ podman(['exec', '--user', '1500:1500', containerName(id), '/bin/sh', '-c', script], 60_000).then((s) => s.trim(), (e) => `error: ${String(e?.stderr || e?.message).trim()}`);+ const running = async () => new Set((await podman(['ps', '--format', '{{.Names}}'])).split('\n'));+ /** The spares: run directories of this check's SP_RUN with no record and a running container. */+ async function spares(): Promise<string[]> {+ const up = await running();+ const records = k.records();+ let ids: string[] = [];+ try {+ ids = readdirSync(path.join(k.run, 'sandbox'));+ } catch {+ // no container yet+ }+ return ids.filter((id) => HEX.test(id) && !records.get(id) && up.has(containerName(id)));+ }+ /** Parked: a Claude Code runs beside the runner. */+ const parked = async (id: string) => /claude/i.test(await podman(['top', containerName(id), 'args']).catch(() => ''));+ async function ready(): Promise<string[]> {+ const out: string[] = [];+ for (const id of await spares()) if (await parked(id)) out.push(id);+ return out;+ }+ /** Exactly `count` spares, all parked, and still so a moment later (nothing is starting). */+ async function full(count: number, ms = 90_000): Promise<string[]> {+ const got = await until(async () => {+ const a = await ready();+ if (a.length !== count || (await spares()).length !== count) return;+ await sleep(700);+ const b = await ready();+ return b.length === count && b.every((id) => a.includes(id)) ? b : undefined;+ }, ms);+ return got ?? [];+ }+ const ev = (trace: TraceContext, name: string) => k.tel.find((e) => e.trace_id === trace.id && e.event_name === name);+ const evLater = (trace: TraceContext, name: string) => until(() => ev(trace, name), 10_000);+ const started = () => k.tel.filter((e) => e.event_name === 'pool.spare_started');+ /** Remove the containers of measured threads, so that a batch does not run beside the last one's. */+ async function drop(ts: SpareThread[]) {+ for (const t of ts) if (t.id()) await podman(['rm', '--force', '--volumes', containerName(t.id())], 60_000).catch(() => {});+ }+ /** A unit's cgroup, from the container's first process. */+ async function cgroup(id: string) {+ const pid = Number((await podman(pidArgs(id))).trim());+ const line = readFileSync(`/proc/${pid}/cgroup`, 'utf8').trim().split('\n').at(-1) ?? '';+ const unit = unitName(id);+ const dir = path.join('/sys/fs/cgroup', line.split('::')[1].split(unit)[0], unit);+ const read = (f: string) => readFileSync(path.join(dir, f), 'utf8');+ const stat = Object.fromEntries(read('memory.stat').trim().split('\n').map((l) => l.split(' ')));+ const mb = (v: unknown) => Math.round(Number(v) / 2 ** 20);+ const cpuUs = Number(/usage_usec (\d+)/.exec(read('cpu.stat'))?.[1]);+ return { memory: mb(read('memory.current')), anon: mb(stat.anon), file: mb(stat.file), pids: Number(read('pids.current')), cpuUs };+ }++ /** `count` new threads, one at a time, each once the pool is as `pool` says: the first reply, and the host's own timings. */+ async function batch(what: string, count: number, pool: number) {+ const rows = { reply: [] as number[], host: [] as number[], mount: [] as number[], add: [] as number[], create: [] as number[], start: [] as number[], claim: [] as number[] };+ const ts: SpareThread[] = [];+ let claimed = 0;+ for (let i = 0; i < count; i++) {+ if (pool) await full(pool);+ const t = newThread();+ ts.push(t);+ const d = await t.deliver();+ if (!d.reply?.ok) {+ check(false, `${what}: delivery ${i} failed: ${d.reply?.error}`);+ continue;+ }+ const c = pool ? await evLater(d.trace, 'runner.claimed') : undefined;+ const e = c ?? (await evLater(d.trace, 'runner.launched'));+ if (c) claimed++;+ rows.reply.push(d.ms);+ rows.host.push(num(e?.duration_ms));+ rows.mount.push(num(e?.data?.['container.mount_ms']));+ rows.add.push(num(e?.data?.['container.add_ms']));+ if (c) rows.claim.push(num(c.data?.['container.claim_ms']));+ if (!c) rows.create.push(num(e?.data?.['container.create_ms'])), rows.start.push(num(e?.data?.['container.start_ms']));+ }+ say(`TIMING ${what}: first reply ${row(rows.reply)}`);+ say(`TIMING ${what}: ${pool ? 'runner.claimed' : 'runner.launched'} ${row(rows.host)}; mounts ${row(rows.mount)}; worktrees and root files ${row(rows.add)}${rows.create.length ? `; create ${row(rows.create)}; start ${row(rows.start)}` : ''}`);+ if (pool) say(`TIMING ${what}: the claim frame ${row(rows.claim)}; the rest (record, directories, root files, credentials) ${row(rows.host.map((h, i) => h - rows.mount[i] - rows.add[i] - rows.claim[i]))}`);+ check(claimed === (pool ? count : 0), `${what}: ${claimed} of ${count} took a spare`);+ return { ts, rows };+ }++ // ==== host A: no spares+ await boot('A', { SP_POOL_SIZE: '0', SP_IDLE_MS: '600000' });+ const cloneAt = Date.now();+ const clones = k.people.map((p) => path.join(k.clone(p, 'hello'), '.git', 'worktrees'));+ check(!!(await until(() => (clones.every((c) => existsSync(c)) ? true : undefined), 180_000)), `the repository is cloned for both people (${Date.now() - cloneAt} ms)`);+ await sleep(2000); // the workspace is marked prepared after its clones+ const coldRepos = await batch('no spare, 1 repository', N, 0);+ check((await spares()).length === 0 && started().length === 0, 'SP_POOL_SIZE=0: no spare was made');+ await drop(coldRepos.ts);+ k.welcome('no repositories', false);+ await sleep(1500);+ const coldNone = await batch('no spare, no repository', N, 0);+ await drop(coldNone.ts);+ await halt('SIGTERM');++ // ==== host B: two spares+ k.welcome('with a repository', true);+ const bootAt = await boot('B', { SP_POOL_SIZE: String(POOL), SP_IDLE_MS: '600000' });+ const first = await full(POOL, 120_000);+ check(first.length === POOL, `SP_POOL_SIZE=${POOL}: ${first.length} spares parked ${Date.now() - bootAt} ms after the host started (${first.join(', ')})`);+ if (first.length !== POOL) throw new Error('no spares: nothing more can be checked');+ await until(() => (started().length >= POOL ? true : undefined), 10_000);+ say(`TIMING a spare: ${started().map((e) => `create ${e.data?.['container.create_ms']} ms, start ${e.data?.['container.start_ms']} ms`).join('; ')}`);+ check(started().length === POOL && started().every((e) => e.data?.launch_mode === 'podman' && typeof e.data.image === 'string'), `pool.spare_started: ${JSON.stringify(started().map((e) => e.data))}`);++ // ---- what an unclaimed spare holds+ const dataMounts = `grep -c -e ' ${k.data}/' -e ' /workspace ' -e ' /clones' /proc/self/mountinfo`;+ for (const id of first) {+ const run = sandboxRunFor(k.run, id);+ const mounts = (await podman(['inspect', '--format', '{{range .Mounts}}{{.Destination}} {{end}}', containerName(id)])).trim().split(' ').sort();+ check(mounts.length === 4 && mounts.includes('/home/agent') && mounts.includes(run) && !mounts.some((m) => m.startsWith(k.data) || m === '/workspace' || m.startsWith('/clones')),+ `spare ${id} was created with its home, its run directory, the model proxy's API socket and the releases, and nothing else: ${mounts.join(' ')}`);+ const seen = await inside(id, `${dataMounts}; ls -A /workspace 2>&1 | wc -l; ls ${k.data} 2>&1 | grep -c -v 'No such file'; find ${run}/secrets -type f ! -name env.sh ! -name values.sh | wc -l; cat ${run}/secrets/*/values.sh | grep -c =; true`);+ if (id === first[0]) say(`its home: ${(await inside(id, 'LC_ALL=C ls -A /home/agent; find /home/agent -type f | wc -l')).split('\n').join(' ')}`);+ check(seen === '0\n0\n0\n0\n0', `inside it: no mount from ${k.data}, none at /workspace or /clones, an empty /workspace, no ${k.data}, no secret file and no secret value in its run directory (${JSON.stringify(seen)})`);+ const env = JSON.parse(await podman(['inspect', '--format', '{{json .Config.Env}}', containerName(id)])) as string[];+ const names = env.map((e) => e.split('=')[0]);+ check(!names.some((x) => /TOKEN$|KEY|SECRET|PASSWORD|ANTHROPIC|SLACK|GH_|GITHUB/.test(x.replace('SP_TOKEN_SOCKET', ''))), `its environment holds no credential: ${names.join(' ')}`);+ const env0 = readFileSync(path.join(run, 'boot.env'), 'utf8');+ const spec = JSON.parse(/^RUNNER_SPEC='(.*)'$/m.exec(env0)?.[1] ?? '{}');+ check(Object.keys(spec).sort().join() === 'id,socket,version' && spec.id === id, `its boot.env names no session, no API, no journal: RUNNER_SPEC ${JSON.stringify(spec)}; names ${env0.split('\n').map((l) => l.split('=')[0]).filter(Boolean).join(' ')}`);+ check(!k.records().get(id) && !existsSync(path.join(run, 'api')), 'it has no record');+ const before = k.tokenSessions.length;+ const tok = await inside(id, `node -e 'const s=require("net").createConnection(process.env.SP_TOKEN_SOCKET,()=>s.write(JSON.stringify({sessionKey:"C_OTHER:1.1"})+"\\n"));let b="";s.on("data",d=>b+=d).on("end",()=>console.log(b.trim())).on("error",e=>{console.log("error "+e.message)})'`);+ check(!/"token"/.test(tok) && /serves no thread|error/.test(tok) && k.tokenSessions.length === before, `its token socket gives no token, and the gateway is not asked: ${tok}`);+ }+ await sleep(5000);+ for (const id of first) {+ const c0 = await cgroup(id);+ await sleep(5000);+ const c = await cgroup(id);+ const top = (await podman(['top', containerName(id), 'pid', 'rss', 'args'])).trim().split('\n').slice(1);+ say(`TIMING an idle spare ${id}: ${c.memory} MB in its unit's cgroup (anonymous ${c.anon} MB, file ${c.file} MB), ${c.pids} tasks, ${Math.round((c.cpuUs - c0.cpuUs) / 1000)} ms of CPU in 5 s, ${top.length} processes: ${top.map((l) => l.trim().split(/\s+/).slice(1, 4).join(' ').slice(0, 60)).join(' | ')}`);+ }++ // ---- the claim+ const one = newThread();+ const d1 = await one.deliver();+ const c1 = await evLater(d1.trace, 'runner.claimed');+ check(!!d1.reply?.ok && !!c1 && first.includes(one.id()), `a new thread's first delivery → ok in ${d1.ms} ms, in the container of spare ${one.id()} (${d1.reply?.error ?? ''})`);+ check(c1?.data?.launch_mode === 'podman' && typeof c1.data['container.mount_ms'] === 'number' && typeof c1.data['container.add_ms'] === 'number' && !ev(d1.trace, 'runner.launched'),+ `runner.claimed: ${JSON.stringify(c1?.data)} duration ${c1?.duration_ms} ms, and no runner.launched`);+ const rec = k.records().get(one.id());+ check(rec?.key === one.key && rec.person === PAT.dir && !!rec.repos?.hello, `the record under the spare's id is the thread's: ${JSON.stringify(rec)}`);+ const mounted = (await one.inside("awk '{print $5}' /proc/self/mountinfo | grep -E '^/(workspace|clones)' | sort")).split('\n').join(' ');+ check(mounted === '/clones/hello /clones/hello/.git/worktrees /workspace', `mounted into it at the claim: ${mounted}`);+ const wt = await one.inside('cd /workspace/hello && git status --porcelain --branch && LC_ALL=C ls -A /workspace');+ check(wt.startsWith('## sp/') && /\.fork\.json/.test(wt) && /AGENTS\.md/.test(wt), `its worktree and root files are there: ${JSON.stringify(wt)}`);+ check(!!(await until(async () => (/chat\.postMessage .*cwd/.test(await one.logs()) ? true : undefined))), 'the claimed runner answered !status');+ const st = (await one.logs()).split('\n').find((l) => /chat\.postMessage .*cwd/.test(l)) ?? '';+ check(/\/workspace\b/.test(st) && !st.includes(k.data), 'its cwd is /workspace, and it names no host path');+ const tk = await one.askToken();+ check(tk.startsWith('ghs_fake') && k.tokenSessions.at(-1) === one.key, `its token socket now asks for this thread (${tk}, ${k.tokenSessions.at(-1)})`);+ const other = first.find((id) => id !== one.id()) as string;+ check((await inside(other, `${dataMounts}; true`)) === '0' && !k.records().get(other), `the other spare ${other} still has no mount and no record`);+ const d1b = await one.deliver();+ check(!!d1b.reply?.ok, `a second delivery to the claimed thread → ok in ${d1b.ms} ms`);+ const refilled = await full(POOL);+ check(refilled.length === POOL && refilled.includes(other) && !refilled.includes(one.id()), `the pool is ${POOL} again: ${refilled.join(', ')}`);++ // ---- timings: with a repository, then with none and a warm delivery beside each refill+ const warmRepos = await batch('spare, 1 repository', N, POOL);+ await drop(warmRepos.ts);+ k.welcome('no repositories', false);+ await sleep(1500);+ const quiet: number[] = [];+ const beside: number[] = [];+ const reply: number[] = [];+ const made: SpareThread[] = [];+ let took = 0;+ for (let i = 0; i < N; i++) {+ await full(POOL);+ quiet.push((await one.deliver()).ms);+ const t = newThread();+ made.push(t);+ const d = await t.deliver();+ await until(async () => ((await spares()).length === POOL ? true : undefined), 15_000, 50); // the pool is being topped up now+ beside.push((await one.deliver()).ms);+ if (d.reply?.ok) reply.push(d.ms);+ if (await evLater(d.trace, 'runner.claimed')) took++;+ }+ say(`TIMING spare, no repository: first reply ${row(reply)}`);+ say(`TIMING a delivery to a running thread: ${row(quiet)} with the pool full; ${row(beside)} while a spare is made after a claim`);+ check(took === N, `spare, no repository: ${took} of ${N} took a spare`);+ await drop(made);+ k.welcome('with a repository', true);+ await sleep(1500);+ await full(POOL);+ const burst = [newThread(), newThread(), newThread()];+ const out: string[] = [];+ const ds = [];+ for (const t of burst) ds.push(await t.deliver());+ for (const d of ds) out.push(`${d.ms} ms (${(await evLater(d.trace, 'runner.claimed')) ? 'spare' : 'no spare'}${d.reply?.ok ? '' : ` FAILED ${d.reply?.error}`})`);+ say(`TIMING three new threads back to back, 1 repository, pool of ${POOL}: ${out.join(', ')}`);+ await drop(burst);+ const total = started().length;+ const now = await full(POOL);+ check(now.length === POOL && started().length >= total, `the pool is ${POOL}, never more: ${now.join(', ')} (${started().length} spares made in all)`);++ // ---- a claim that fails: the spares are paused, so the one taken cannot be made the thread's+ for (const id of now) await podman(['pause', containerName(id)]);+ const f = newThread();+ const df = await f.deliver();+ for (const id of now) await podman(['unpause', containerName(id)]).catch(() => {}); // the one taken is gone+ const missed = await evLater(df.trace, 'pool.spare_missed');+ const cold = await evLater(df.trace, 'runner.launched');+ check(!!df.reply?.ok && !!missed && !!cold && !ev(df.trace, 'runner.claimed'),+ `a spare that cannot be claimed: the delivery is answered in ${df.ms} ms by a cold start (pool.spare_missed ${JSON.stringify(missed?.data)}, runner.launched ${JSON.stringify(cold?.data)}) ${df.reply?.error ?? ''}`);+ check(now.includes(f.id()) && (await status(f.id())) === 'running' && (await f.inside(dataMounts)) !== '0', `under the id of the spare that was taken (${f.id()}), in a container made anew, with its workspace mounted`);+ const left = now.find((id) => id !== f.id()) as string;+ check((await status(left)) === 'running' && !k.records().get(left), `the spare that was not taken (${left}) is still a spare`);+ const dfb = await f.deliver();+ check(!!dfb.reply?.ok, `the thread goes on: next delivery ok in ${dfb.ms} ms`);+ await drop([one]);++ // ==== host C: another release and image; B is killed, its spares keep running+ const old = await full(POOL);+ await halt('SIGKILL');+ check(old.length === POOL && (await Promise.all(old.map(status))).every((s) => s === 'running') && (await status(f.id())) === 'running', `host B killed: its spares ${old.join(', ')} and the thread's container still run`);+ await podman(['tag', k.image, NEXT_IMAGE]);+ try {+ // ---- the image lock, held as provisioning holds it while it pulls an image+ const lockable = (() => { try { return accessSync(IMAGE_LOCK, constants.R_OK), true; } catch { return false; } })();+ const lock = lockable ? spawn('/usr/bin/flock', ['--exclusive', IMAGE_LOCK, '/usr/bin/sleep', String(LOCK_S)], { stdio: 'ignore' }) : undefined;+ const released = lock && new Promise((r) => lock.once('exit', r));+ if (lock) await sleep(300);+ // This check's own Podman calls wait for the lock as the host's do, so while it is held only files and frames are read.+ const before = { events: k.events.length };+ const madeByNext = () => started().filter((e) => e.service_version === NEXT_VERSION).length; // host B's last event may still be on its way+ // A host takes its containers back before it says hello (sweep.ts `reconcile`), and that waits for the lock too.+ const up = boot('C', { SP_POOL_SIZE: '1', SP_VERSION: NEXT_VERSION, SP_IMAGE: NEXT_IMAGE, SP_IDLE_MS: String(k.idleMs) });+ up.catch(() => {});+ if (lock) {+ await sleep((LOCK_S - 2) * 1000);+ const seen = { held: lock.exitCode === null, hello: k.events.slice(before.events).some((e) => e.t === 'hello'), there: old.filter((id) => existsSync(sandboxRunFor(k.run, id))).length, made: madeByNext() };+ check(seen.held && !seen.hello && seen.there === old.length && seen.made === 0, `the image lock held for ${LOCK_S - 2} s of host C: it has not said hello, no spare was made and none removed (${JSON.stringify(seen)})`);+ await released;+ } else say(`SKIP the image lock: no ${IMAGE_LOCK} this check may read (as root: install -m 640 -g <the host's group> /dev/null ${IMAGE_LOCK})`);+ await up;+ const goneAt = Date.now();+ const vols = () => Promise.all(old.map((id) => podman(['volume', 'exists', volumeName(id)]).then(() => true, () => false)));+ const gone = await until(async () => ((await Promise.all(old.map(status))).every((s) => s === 'none') && !(await vols()).some(Boolean) && !old.some((id) => existsSync(sandboxRunFor(k.run, id))) ? true : undefined), 60_000);+ check(!!gone, `the new host removed the old release's spares, their homes and run directories (${Date.now() - goneAt} ms)`);+ check((await status(f.id())) === 'running' && !!k.records().get(f.id()), "and left the thread's container, which has a record");+ const next = await full(1, 120_000);+ const env1 = next[0] ? readFileSync(path.join(sandboxRunFor(k.run, next[0]), 'boot.env'), 'utf8') : '';+ check(next.length === 1 && !old.includes(next[0]) && env1.includes(`"version":"${NEXT_VERSION}"`) && (await podman(['inspect', '--format', '{{.Config.Image}}', containerName(next[0])])).trim() === NEXT_IMAGE,+ `SP_POOL_SIZE=1: one spare, from the new release and the new image (${next.join(', ')})`);+ const g = newThread();+ const dg = await g.deliver();+ check(!!dg.reply?.ok && g.id() === next[0] && !!(await evLater(dg.trace, 'runner.claimed')), `a new thread takes it: ok in ${dg.ms} ms`);+ // ---- idle: the thread stops, the spare beside it stays+ const stay = await full(1);+ const idleAt = Date.now();+ check(!!(await until(async () => ((await status(g.id())) === 'exited' ? true : undefined), k.idleMs + 40_000)), `idle for ${k.idleMs} ms: the claimed thread's container exited (${Date.now() - idleAt} ms)`);+ await sleep(3000);+ check(stay.length === 1 && (await status(stay[0])) === 'running' && (await parked(stay[0])) && (await spares()).join() === stay[0], `the spare ${stay[0]} outlived the idle time and is still parked, the only one`);+ // ---- the host stops, and its spare's runner answers nothing+ await podman(['exec', '--user', '0:0', containerName(stay[0]), 'pkill', '-STOP', '-f', '[r]unner-boot']).catch((e) => say(`pkill: ${e.message}`));+ const frozen = (await podman(['top', containerName(stay[0]), 'state', 'args'])).split('\n').filter((l) => /runner-boot/.test(l));+ const stopAt = Date.now();+ await halt('SIGTERM');+ const stopMs = Date.now() - stopAt;+ const left = `container ${await status(stay[0])}, home ${(await podman(['volume', 'exists', volumeName(stay[0])]).then(() => 'there', () => 'gone'))}, run directory ${existsSync(sandboxRunFor(k.run, stay[0])) ? 'there' : 'gone'}`;+ check(frozen.length > 0 && frozen.every((l) => /^T/.test(l.trim())) && host?.signalCode !== 'SIGKILL' && left === 'container none, home gone, run directory gone',+ `host C stopped in ${stopMs} ms while its spare's runner was frozen (${frozen.map((l) => l.trim().slice(0, 40)).join(' | ')}): the spare left by its container (${left})`);+ await boot('D', { SP_POOL_SIZE: '0', SP_VERSION: NEXT_VERSION, SP_IMAGE: NEXT_IMAGE, SP_IDLE_MS: String(k.idleMs) });+ check((await status(stay[0])) === 'none' && !existsSync(sandboxRunFor(k.run, stay[0])), 'the next host finds nothing of it');+ await sleep(3000);+ check((await spares()).length === 0, 'and with SP_POOL_SIZE=0 it makes none');+ await halt('SIGTERM');+ } finally {+ await halt('SIGKILL');+ await drop([f]);+ for (const id of await spares().catch(() => [])) await podman(['rm', '--force', '--volumes', containerName(id)]).catch(() => {});+ await podman(['untag', k.image, NEXT_IMAGE]).catch((e) => say(`cleanup: ${e.message}`));+ }+}diff --git a/computer/src/dev/sandbox-check-waits.ts b/computer/src/dev/sandbox-check-waits.tsnew file mode 100644index 00000000..90a96e1f--- /dev/null+++ b/computer/src/dev/sandbox-check-waits.ts@@ -0,0 +1,189 @@+// The part of sandbox-check.ts about what waits for what on a `podman` host+// (work 103; the gaps closed after step 10): a start, a terminal and `/files`+// while provisioning holds the image lock; a download whose session is+// stopped under it; a prune and a `/files` script on one stopped thread; and+// the home volume of an id whose run directory is gone, as after a reboot.+// sandbox-check.ts owns the host, the fake gateway and the threads;+// sandbox-check-restart.ts ran before and left the host that runs here.+//+// Invariants:+// - It runs on the host the restart checks started last: a sweep age of+// seconds and a retention of seconds. A thread it wants whole is delivered+// to; the two it wants pruned are left to go idle.+// - The relay it plays is a new connection: the wire socket of the first host+// went with it.+// - The image lock is the computer's (image-lock.ts): held only when its file+// is there and readable, for LOCK_S, which is longer than a person is kept+// waiting (sandbox/use.ts WAIT_MS) and shorter than a relay's call.+// - The homes it plants have ids of their own, and it removes them, pass or+// fail: one labelled as this host's with no run directory (must go), one+// labelled as another host's with a run directory of this one, and one+// without a label and without a run directory (both must stay).+// - The session of the download is stopped by killing its first process:+// everything in the container goes with it, as at an idle stop.++import { type ChildProcess, execFileSync, spawn } from 'node:child_process';+import { randomBytes } from 'node:crypto';+import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { IMAGE_LOCK } from '../host/sandbox/image-lock.js';+import { containerName, HOME_LABEL, volumeName } from '../host/sandbox/podman-args.js';+import { WAIT_MS } from '../host/sandbox/use.js';+import { UPDATING } from '../host/unavailable.js';+import { sandboxRunFor } from '../ipc.js';+import type { ApiError } from '../protocol.js';+import type { Rig, T } from './sandbox-check-restart.js';+import { wireClient } from './wire-client.js';++const LOCK_S = 16;+/** The second host's retention (sandbox-check-restart.ts), and a little more. */+const RETENTION_MS = 30_000;++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++function tarOf(name: string, bytes: number): Buffer {+ const dir = mkdtempSync(path.join(tmpdir(), 'sandbox-check-'));+ try {+ writeFileSync(path.join(dir, name), randomBytes(bytes));+ return execFileSync('/usr/bin/tar', ['-cf', '-', '-C', dir, name], { maxBuffer: 128 << 20 });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++/** `b` and `e` are two running threads of one person, both with nothing unsaved; `e` is pruned here, `b` loses its container at least. */+export async function waits(x: Rig, b: T, e: T) {+ const { check, say, until } = x.kit;+ const podman = (args: string[], timeoutMs = 30_000) => x.as.podman(args, { timeoutMs });+ const has = (kind: 'container' | 'volume', name: string) => podman([kind, 'exists', name]).then(() => true, () => false);+ const status = (t: T) => t.inspect('{{.State.Status}}');+ const dir = (id: string) => sandboxRunFor(x.run, id);+ const [Y, O, N] = Array.from({ length: 3 }, () => randomBytes(8).toString('hex'));+ const member = b.owner.userId as string;+ const err = (r: object) => ('error' in r ? (r.error as ApiError | undefined) : undefined);+ const brief = (r: object) => (err(r) ? `${err(r)?.code}: ${err(r)?.message}` : 'answered');+ let holder: ChildProcess | undefined;+ let keeping: NodeJS.Timeout | undefined;+ const wire = await wireClient(path.join(x.run, 'wire', 'wire.sock'));++ try {+ // ---- planted: homes of no container and no record, for the sweep to judge by their label+ await podman(['volume', 'create', '--label', `${HOME_LABEL}=${dir(Y)}`, volumeName(Y)]);+ await podman(['volume', 'create', '--label', `${HOME_LABEL}=/run/sandbox-check-elsewhere/sandbox/${O}`, volumeName(O)]);+ await podman(['volume', 'create', volumeName(N)]);+ mkdirSync(dir(O));+ const plantedAt = Date.now();++ const [sb, se] = [await x.known(b.spec), await x.known(e.spec)];+ await Promise.all([b.deliver(), e.deliver()]);+ keeping = setInterval(() => void b.deliver(), 8000);+ const list = (s: string) => wire.call<{ entries: { path: string }[] }>({ t: 'files.list', sessionId: s, member, path: '', depth: 1, limit: 200 });+ const before = await list(sb);+ check(!!before.result, `over a new connection to the wire socket, /files of the running thread answers (${brief(before)})`);++ // ---- the image lock held: a resume waits for it; a terminal and /files wait their own limit and say so+ check(!!(await until(async () => ((await status(e)) === 'exited' ? true : undefined), 60_000)), 'the thread that is not delivered to went idle and is stopped');+ const eid = e.id();+ const canLock = existsSync(IMAGE_LOCK) && (() => { try { return accessSync(IMAGE_LOCK, constants.R_OK), true; } catch { return false; } })();+ if (canLock) {+ holder = spawn('/usr/bin/flock', ['--exclusive', IMAGE_LOCK, '/usr/bin/sleep', String(LOCK_S)], { stdio: 'ignore' });+ await sleep(300);+ const timed = async <R>(p: Promise<R>) => {+ const at = Date.now();+ const r = await p;+ return { r, ms: Date.now() - at };+ };+ const [start, term, files] = await Promise.all([timed(e.deliver()), timed(wire.terminal(sb, member, 'id -u')), timed(list(sb))]);+ const within = (ms: number) => ms >= WAIT_MS - 1500 && ms <= WAIT_MS + 4000;+ check(!!start.r.reply?.ok && start.ms >= LOCK_S * 1000 - 2500 && e.id() === eid && (await status(e)) === 'running',+ `while provisioning holds the image lock (${LOCK_S} s) the start of a stopped thread waits for it: answered in ${start.ms} ms, in the same container (${start.r.reply?.error ?? ''})`);+ check(err(term.r)?.code === 'unavailable' && err(term.r)?.message === UPDATING && err(term.r)?.retryable === true && within(term.ms),+ `a terminal opened meanwhile is refused after ${term.ms} ms: ${brief(term.r)}`);+ check(err(files.r)?.code === 'unavailable' && err(files.r)?.message === UPDATING && within(files.ms), `and so is /files, after ${files.ms} ms: ${brief(files.r)}`);+ const [term2, files2] = [await wire.terminal(sb, member, 'id -u'), await list(sb)];+ check('out' in term2 && term2.out.trim() === '1500' && !!files2.result, `once the lock is released both answer again (${brief(term2)}, ${brief(files2)})`);+ } else {+ say(`SKIP a start, a terminal and /files under the image lock: no readable ${IMAGE_LOCK} here (root: install -m 0640 -g <the host's group> /dev/null ${IMAGE_LOCK})`);+ const r = await e.deliver();+ check(!!r.reply?.ok && e.id() === eid, `the stopped thread resumes in ${r.ms} ms`);+ }++ // ---- a session stopped under a download: the download says so, and the next read is answered from the stopped thread+ const big = await wire.put(se, member, 's11-big', tarOf('big.bin', 48 << 20));+ const dl = await wire.getPaused(se, member, 's11-big/big.bin', true);+ if ('error' in dl) check(false, `a download from the running thread starts (upload: ${brief(big)}; download: ${brief(dl)})`);+ else {+ await sleep(500);+ // Its first process is killed: as at the idle stop, everything in the container goes with it.+ // Its first process is killed, as when a runner leaves. While nobody reads the download the container does not reach+ // `exited`, and `podman kill` gives up waiting for it (measured, Podman 4.9.3): so the reader reads on first.+ const killAt = Date.now();+ const killing = podman(['kill', '--signal', 'KILL', containerName(eid)]).then(() => 'killed', (err_) => `podman kill: ${String(err_.message).split('\n').pop()}`);+ await sleep(1500);+ const end = await dl.rest();+ const gone = await until(async () => ((await status(e)) === 'exited' ? true : undefined), 60_000);+ say(`the container of the download: ${await killing}; ${gone ? 'exited' : 'not exited'} ${Date.now() - killAt} ms after`);+ check(end.error?.code === 'unavailable' && /The session stopped during the download/.test(end.error.message) && end.got < 48 << 20,+ `a download whose session is stopped under it ends after ${end.got} bytes with ${end.error?.code}: ${end.error?.message}`);+ const after = await list(se);+ check(!!after.result?.entries.some((f) => f.path === 's11-big'), `and a listing right after is answered from the stopped thread (${brief(after)})`);+ }++ // ---- a prune and a /files script on one stopped thread+ check(!!(await until(async () => ((await status(e)) === 'exited' ? true : undefined), 30_000)) && !!e.record()?.repos?.hello, 'the thread is stopped, with its record');+ const small = tarOf('a.txt', 2048);+ const held = await wire.putHeld(se, member, 's11-held', small, small.length >> 1);+ check('finish' in held, `an upload to the stopped thread is under way, half sent (${brief(held)})`);+ clearInterval(keeping);+ await b.deliver();+ const idleAt = Date.now();+ check(!!(await until(async () => ((await status(b)) === 'exited' ? true : undefined), 60_000)), 'the other thread went idle too');+ await sleep(Math.max(0, RETENTION_MS - (Date.now() - idleAt)));+ const bName = containerName(b.id());+ // A changed definition starts a housekeeping pass, unless one is running: asked again until it shows.+ for (let n = 0; n < 15 && (await has('container', bName)); n++) {+ x.welcome(`waits ${n}`);+ await until(async () => ((await has('container', bName)) ? undefined : true), 10_000);+ }+ x.welcome('waits again');+ await sleep(10_000);+ const whole = !!e.record()?.repos?.hello && e.id() === eid && (await has('container', containerName(eid))) && (await has('volume', volumeName(eid))) && existsSync(e.workspace);+ check(!(await has('container', bName)) && whole,+ `housekeeping passed over both, idle beyond retention: the other thread's container is gone, and the one with an upload in it is whole (record, container, home, workspace)`);+ const done = 'finish' in held ? await held.finish() : held;+ const back = await wire.get(se, member, 's11-held/a.txt', true);+ check(done && 'result' in done && done.result?.upload.files === 1 && 'body' in back && back.body.length === 2048, `the upload then ends well (${brief(done)}) and what it brought reads back (${brief(back)})`);+ // The moment the removal shows (the record without repositories, or gone), /files is asked once more.+ let seen = '';+ const raced = (async () => {+ for (const end = Date.now() + 200_000; Date.now() < end; await sleep(5)) {+ const r = e.record();+ if (r?.repos?.hello && r.id === eid) continue;+ seen = r ? 'its record had lost its repositories' : 'its record was gone';+ return list(se);+ }+ })();+ for (let n = 0; n < 15 && !seen; n++) {+ x.welcome(`waits more ${n}`);+ await until(() => (seen ? true : undefined), 10_000);+ }+ const refused = await raced;+ check(!!refused && err(refused)?.code === 'unavailable' && /being cleaned up/.test(err(refused)?.message ?? ''),+ `with no upload in it the thread is pruned at a later pass, and /files asked while it is removed (${seen || 'the prune never showed'}) is refused: ${refused ? brief(refused) : 'never asked'}`);+ check(!!(await until(async () => (!e.record() && !(await has('container', containerName(eid))) && !(await has('volume', volumeName(eid))) && !existsSync(e.workspace) ? true : undefined), 30_000)),+ 'and it is gone whole: record, container, home, workspace');++ // ---- the homes planted at the start+ await sleep(Math.max(0, 20_000 - (Date.now() - plantedAt)));+ check(!!(await until(async () => ((await has('volume', volumeName(Y))) ? undefined : true), 30_000)), `the home labelled as this host's, of an id with no run directory (as after a reboot), was removed by the sweep`);+ check((await has('volume', volumeName(O))) && (await has('volume', volumeName(N))),+ `the home labelled as another host's stays, though this host has a run directory for its id; and so does the one without a label and without a run directory`);+ } finally {+ clearInterval(keeping);+ holder?.kill();+ wire.close();+ for (const id of [Y, O, N]) await podman(['volume', 'rm', '--force', volumeName(id)]).catch(() => {});+ rmSync(dir(O), { recursive: true, force: true });+ }+}diff --git a/computer/src/dev/sandbox-check.ts b/computer/src/dev/sandbox-check.tsnew file mode 100644index 00000000..35b0681c--- /dev/null+++ b/computer/src/dev/sandbox-check.ts@@ -0,0 +1,557 @@+// End-to-end check of sessions in containers (work 103), on a computer: the+// host agent with SP_LAUNCH=podman against a fake gateway in this process,+// runners rendering to a fake Slack client (SP_FAKE_SLACK=1, read back with+// `podman logs`). No model call: a delivery is `!status`, or a turn whose+// model is src/dev/fake-model.mjs behind the release's oc-modelproxy, which+// the check runs itself (sandbox-check-model.ts): every runner is bound there+// by its unit, as on a computer, and without a proxy no session starts.+//+// It checks a new thread (record, container, unit, cgroup, run directory,+// token socket, the report's path), a warm delivery, what reaches into a+// running container, a stopped one and a resumed one (step 9: previews,+// terminal, files, in sandbox-check-reach.ts), the idle exit (container+// exited, home and record kept) and the resume under the same id with the home+// intact; and it prints what each start took. Then (step 8, in+// sandbox-check-restart.ts) the host is killed and started again, twice: what+// it takes back, stops, removes, sweeps and prunes.+//+// Workspaces (step 7), with a definition of two public repositories the fake+// gateway sends: the clones a helper container makes, the workspace and the+// worktrees mounted in a thread, its own worktree registry, a commit made+// inside, a second thread of the same person and a thread of another person+// (what each can see), `git worktree prune` in one thread and its sibling,+// ws-add.sh a second time, the mount helper's refusals, a journal directory+// for a session of the API, `checkout`, the definition rewritten for a running+// container, and an idle thread's build directories removed by housekeeping.+// `checkout` is called in this process on the host's own parts, since only a+// model turn makes a runner ask for it.+//+// It needs what deploy/vm/provision.sh sets up (the runners' user and its+// Podman, the session image, the run and state directories) and github.com,+// so it runs on a computer, as the host's user, from a release, and not in CI:+// cd /opt/slack-presence/current && set -a && . ./.sp-version.env && set +a && \+// sudo -u sp-host env SP_RUNNER_USER=agent SP_IMAGE="$SP_IMAGE" SP_IMAGE_ABI="$SP_IMAGE_ABI" \+// node --import tsx src/dev/sandbox-check.ts [--keep]+//+// With `--spares` it runs the checks and timings of step 10 instead (spare+// containers: sandbox-check-spares.ts), on hosts it starts and stops itself.+//+// Invariants:+// - It refuses to run beside a host agent: it is a host itself, on the+// computer's SP_RUN and SP_DATA (or the ones in its environment, set up the+// same way) and on the preview proxy's port.+// - The gateway it plays speaks protocol 4, so the host serves its wire+// socket, and the check is the relay on it. Two threads of one person are+// Slack threads, whose `cs_` ids the host learns from an `api` frame each+// (their runners write no journal); the other person's thread is a session+// of the API: its deliveries carry its `sessionId`, and its runner writes+// its journal.+// - The host is a child of the check, and more than one in a run: `host` is+// the one that runs now, and `hostLines` what all of them wrote.+// - It removes what it made (containers, home volumes, records, run+// directories, the previews table, the person directories `sandbox-check`+// and `sandbox-check-b`, the journal directories, the upload records, the+// definition it saved, every container whose run directory is below its+// SP_RUN: the spares), pass or fail, unless `--keep`.++import { execFileSync, spawn, type ChildProcess } from 'node:child_process';+import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from 'node:fs';+import type net from 'node:net';+import http from 'node:http';+import path from 'node:path';+import { randomBytes, randomUUID } from 'node:crypto';+import { WebSocketServer, type WebSocket } from 'ws';+import { runnerUser } from '../host/runner-user.js';+import { mounts } from '../host/sandbox/mounts.js';+import { asRunner, type PodmanError } from '../host/sandbox/podman.js';+import { containerName, execArgs, mountArgs, pidArgs, unitName, unshareRmArgs, volumeName } from '../host/sandbox/podman-args.js';+import { sandboxRecords } from '../host/sandbox/records.js';+import { type SandboxPlace, sandboxScripts } from '../host/sandbox/scripts.js';+import { sandboxWorkspaces } from '../host/sandbox/workspace.js';+import { runnersDir, sandboxRunFor, secretsFor, socketFor, tokenSocketFor } from '../ipc.js';+import type { GatewayToHost, HostToGateway, Person, PreviewConfig, PreviewRequest, SessionSpec, TraceContext, WorkspaceDefinition } from '../protocol.js';+import { mintId } from '../session-ids.js';+import { createTelemetry } from '../telemetry/emitter.js';+import { type TelemetryEvent, uuidv7 } from '../telemetry/envelope.js';+import { safeKey, useScripts } from '../workspaces/clones.js';+import { gatewayDefinitionPath } from '../workspaces/definition.js';+import { checkModel } from './sandbox-check-model.js';+import { APP_PORT, type Kit, type Thread as Reached, reachResumed, reachRunning, reachStopped } from './sandbox-check-reach.js';+import { spareChecks } from './sandbox-check-spares.js';+import { type Rig, restarts } from './sandbox-check-restart.js';+import { waits } from './sandbox-check-waits.js';+import { type WireClient, wireClient } from './wire-client.js';++const ROOT = path.resolve(import.meta.dirname, '..', '..');+const KEEP = process.argv.includes('--keep');+const SPARES = process.argv.includes('--spares');+const RUN = process.env.SP_RUN ?? '/run/slack-presence';+const DATA = process.env.SP_DATA ?? '/data';+const IDLE_MS = 20_000;+/** Hours a stopped thread's build directories stay: 9 s here, less than a thread's idle time. */+const ARTIFACTS_IDLE_HOURS = 0.0025;+const NOW = Date.now() / 1000;+const SESSION_ID = `cs_${randomUUID().replace(/-/g, '').slice(0, 16)}`;+const definition = (about: string, repos = true): WorkspaceDefinition => ({+ name: 'sandbox-check', about,+ repos: repos ? [+ { name: 'hello', remote: 'https://github.com/octocat/Hello-World' },+ { name: 'spoon', remote: 'https://github.com/octocat/Spoon-Knife', clone: 'lazy', description: 'checked out on demand' },+ ] : [],+});++const t0 = Date.now();+const say = (...a: unknown[]) => console.log(`+${((Date.now() - t0) / 1000).toFixed(1)}s`, ...a);+let failed = 0;+const check = (ok: boolean, what: string) => {+ say(ok ? 'PASS' : 'FAIL', what);+ if (!ok) failed++;+};+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+async function until<T>(f: () => T | undefined | Promise<T | undefined>, ms = 30_000, every = 100): Promise<T | undefined> {+ for (const end = Date.now() + ms; Date.now() < end; await sleep(every)) {+ const v = await f();+ if (v) return v;+ }+}+const refuse = (why: string): never => {+ console.error(`sandbox-check: ${why}`);+ process.exit(2);+};++const user = runnerUser(process.env) ?? refuse('set SP_RUNNER_USER (the runners\' user, `agent` on a computer)');+const IMAGE: string = process.env.SP_IMAGE || refuse('set SP_IMAGE (the release\'s .sp-version.env has it)');+if (!process.env.SP_IMAGE_ABI) refuse("set SP_IMAGE_ABI (the release's .sp-version.env has it)");+if (!existsSync(path.join(ROOT, 'dist/runner-boot.mjs'))) refuse(`${ROOT} has no dist/runner-boot.mjs: run it from a release (node scripts/bundle-runner.mjs builds one)`);+try {+ execFileSync('/usr/bin/systemctl', ['is-active', '--quiet', 'slack-presence-host.service']);+ refuse('slack-presence-host is running here; this check would be a second host on its directories');+} catch {+ // not active: the directories are ours for the run+}+/** The check's own model proxy and model stand-in: the host's SP_MODEL_PROXY and SP_MODEL_SOCKET. */+const model = await checkModel({ root: ROOT, run: RUN }).catch((e) => refuse(`no model proxy: ${e.message}`));+const as = asRunner(user.sudo);+const podman = (args: string[], timeoutMs = 30_000) => as.podman(args, { timeoutMs });+const mnt = mounts({ as, root: ROOT, dataDir: DATA });+/** Read anew at every use: the host writes the records. */+const records = () => sandboxRecords(path.join(DATA, 'state', 'sandboxes'));+const savedDefinition = existsSync(gatewayDefinitionPath()) ? readFileSync(gatewayDefinitionPath(), 'utf8') : undefined;++// ---- fake collector (the host's telemetry) and fake gateway++const tel: TelemetryEvent[] = [];+const collector = http.createServer((req, res) => {+ let body = '';+ req.on('data', (c) => (body += c)).on('end', () => {+ tel.push(...JSON.parse(body).events);+ res.writeHead(202).end();+ });+});+await new Promise<void>((r) => collector.listen(0, '127.0.0.1', r));+function mkTrace(): TraceContext {+ const now = Date.now();+ return { id: uuidv7(now), sentAt: now - 40, receivedAt: now - 20, dispatchedAt: now, surface: 'slack', surfaceWorkspaceId: 'T_CHECK', conversationId: 'C_SANDBOX', personId: 'U_OWNER' };+}+const launched = (trace: TraceContext) => tel.find((e) => e.trace_id === trace.id && e.event_name === 'runner.launched');++const events: HostToGateway[] = [];+const tokenSessions: (string | undefined)[] = [];+let conn: WebSocket | undefined;+const wss = new WebSocketServer({ port: 0, path: '/host', verifyClient: ({ req }: { req: http.IncomingMessage }) => req.headers.authorization === 'Bearer check-token' });+await new Promise((r) => wss.on('listening', r));+const toHost = (m: GatewayToHost) => conn?.send(JSON.stringify(m));+/** `userId`: the member the wire socket knows the person as, who alone may open a terminal in their sessions. */+const person = (dir: string, slackUserId: string, userId: string): Person => ({ slackUserId, userId, dir, gitName: 'Sandbox Check', gitEmail: '[email protected]' });+const PAT = person('sandbox-check', 'U_OWNER', 'usr_sandbox_check');+const QUINN = person('sandbox-check-b', 'U_OTHER', 'usr_sandbox_check_b');+/** The previews this gateway registered: the allow-list holds APP_PORT from the start, which no host with containers may serve. */+const preview: PreviewConfig = { tunnelToken: '', key: randomBytes(32).toString('base64url'), ports: [APP_PORT] };+const asked: { from: string; req: PreviewRequest }[] = [];+const names = new Map<string, number>();+/** No model credential: the welcome's route is the stand-in's profile, whose one variable is a word. */+const credentials = { slackBotToken: 'xoxb-fake', slackBotUserId: 'U_BOT' };+/** What the gateway's welcome carries: with `--spares` the organization's Slack credentials too (a spare parks a Claude Code once it has credentials), and repositories or none. */+const gateway = { spares: SPARES, repos: true };+const unpreviewed: { from: string; name: string }[] = [];+/** Protocol 4: the host serves its wire socket, and a thread with a session id gets a journal (work 084), which its container must have mounted. */+const welcome = (about: string) =>+ toHost({ t: 'welcome', protocol: 4, credentials: gateway.spares ? credentials : { slackBotToken: '', slackBotUserId: '' }, models: { claude: model.route }, people: [PAT, QUINN], definition: definition(about, gateway.repos), preview, wire: { key: preview.key } });+wss.on('connection', (c) => {+ conn = c;+ c.on('message', (d) => {+ const m = JSON.parse(String(d)) as HostToGateway;+ events.push(m);+ if (m.t === 'hello') welcome('first');+ if (m.t === 'preview') {+ asked.push({ from: m.from, req: m.req });+ const name = m.req.name ?? `p${m.req.port}`;+ names.set(name, m.req.port);+ preview.ports = [APP_PORT, ...names.values()];+ toHost({ t: 'previews', preview });+ toHost({ t: 'previewed', id: m.id, result: { url: `https://${name}.opencomputer.app`, name, port: m.req.port } });+ }+ if (m.t === 'unpreview') {+ unpreviewed.push({ from: m.from, name: m.req.name });+ names.delete(m.req.name);+ preview.ports = [APP_PORT, ...names.values()];+ toHost({ t: 'previews', preview });+ toHost({ t: 'previewed', id: m.id, result: { url: '', name: m.req.name, port: 0 } });+ }+ if (m.t === 'token') {+ tokenSessions.push(m.sessionKey);+ toHost({ t: 'token', id: m.id, result: { token: `ghs_fake${tokenSessions.length}`, expiresAt: new Date(Date.now() + 3600_000).toISOString() } });+ }+ });+});+let ts = 1;+/** Tell the host a thread's `cs_` id, as a gateway does with the first API call for a session it does not know. */+async function known(session: SessionSpec): Promise<string> {+ const sessionId = session.sessionId ?? mintId('cs');+ const id = randomUUID();+ const member = session.owner.userId ?? '';+ toHost({ t: 'api', id, sessionId, method: 'sessions.get', params: { sessionId }, actor: { id: member, name: null, via: 'api', client: null }, member, session });+ await until(() => events.find((e) => e.t === 'api-result' && e.id === id), 15_000);+ return sessionId;+}++/** One thread of the check: its spec, and what the check reads of its container. */+function thread(owner: Person, n: number, sessionId?: string) {+ const key = `C_SANDBOX:${(NOW + n).toFixed(3)}`;+ const spec: SessionSpec = { key, kind: 'thread', channel: 'C_SANDBOX', threadTs: key.split(':')[1], owner, title: `sandbox check ${n}`, mode: 'bypassPermissions', ...(sessionId && { sessionId }) };+ const record = () => records().find(owner.dir, key);+ const id = () => record()?.id ?? '';+ const t = {+ key, owner, spec, record, id,+ get run() { return sandboxRunFor(RUN, id()); },+ /** The thread's files, its worktree registry for a repository, on the host. */+ workspace: mnt.workspace({ person: owner.dir, key }),+ registry: (repo: string) => mnt.registry({ person: owner.dir, key }, repo),+ branch: `sp/${safeKey(key)}`,+ async deliver(trace = mkTrace(), text = '!status') {+ const d = randomUUID();+ const at = Date.now();+ toHost({ t: 'deliver', id: d, session: spec, msg: { userId: owner.slackUserId ?? 'U_OWNER', text, ts: `3.${ts++}` }, credentials, trace });+ const reply = await until(() => events.find((e): e is Extract<HostToGateway, { t: 'reply' }> => e.t === 'reply' && e.id === d), 120_000, SPARES ? 5 : 100);+ return { reply, ms: Date.now() - at, trace };+ },+ reports: () => events.flatMap((e) => (e.t === 'session' && e.report.key === key ? [e.report] : [])),+ inspect: (format: string) => podman(['inspect', '--format', format, containerName(id())]).then((s) => s.trim(), () => ''),+ logs: () => podman(['logs', containerName(id())]).catch(() => ''),+ unitActive: () => as.run(['/usr/bin/systemctl', '--user', 'is-active', '--quiet', unitName(id())], { timeoutMs: 5000 }).then(() => true, () => false),+ /** A shell script inside, as the session's user (or root, which is the runners' user outside); what it printed, or `error: …`. */+ inside: (script: string, as_ = '1500:1500') =>+ podman(['exec', '--user', as_, containerName(id()), '/bin/sh', '-c', script], 60_000).then((s) => s.trim(), (e: PodmanError) => `error: ${(e.stderr || e.message).trim()}`),+ pid: async () => Number((await podman(pidArgs(id()))).trim()),+ /** One request on the session's own token socket, from inside its container. */+ askToken: () =>+ t.inside(`node -e 'const s=require("net").createConnection(process.env.SP_TOKEN_SOCKET,()=>s.write(JSON.stringify({sessionKey:"C_OTHER:1.1"})+"\\n"));let b="";s.on("data",d=>b+=d).on("end",()=>console.log(JSON.parse(b).token)).on("error",e=>{console.log("error "+e.message)})'`),+ };+ return t;+}+type Thread = ReturnType<typeof thread>;+const A1 = thread(PAT, 1);+const A2 = thread(PAT, 2);+const B = thread(QUINN, 3, SESSION_ID);+/** Started by the step 8 checks only. */+const C = thread(PAT, 4);+const E = thread(PAT, 5);+const all = [A1, A2, B, C, E];+/** The `cs_` ids the host was told for the Slack threads. */+const sessions: string[] = [];+let wire: WireClient | undefined;+/** A thread as sandbox-check-reach.ts takes one: read once its container is there. */+const reached = (name: string, t: Thread, sessionId: string): Reached => ({ name, spec: t.spec, sessionId, id: t.id(), run: t.run, workspace: t.workspace, member: t.owner.userId as string });++// ---- the host, and the cleanup++const hostLines: string[] = [];+function startHost(extra: Record<string, string> = {}): ChildProcess {+ const { SP_DEFINITION, WORKDIR, SLACK_BOT_TOKEN, ...rest } = process.env;+ const h = spawn(process.execPath, ['--import', 'tsx', 'src/host/main.ts'], {+ cwd: ROOT,+ env: { ...rest, SP_GATEWAY_URL: `ws://127.0.0.1:${(wss.address() as net.AddressInfo).port}/host`, SP_HOST_TOKEN: 'check-token', SP_HOST_ID: 'sandbox-check',+ SP_RUN: RUN, SP_DATA: DATA, SP_IDLE_MS: String(IDLE_MS), SP_LAUNCH: 'podman', SP_POOL_SIZE: '0', SP_FAKE_SLACK: '1', SP_MODEL_PROXY: model.control, SP_MODEL_SOCKET: model.api, SP_ARTIFACTS_IDLE_HOURS: String(ARTIFACTS_IDLE_HOURS),+ SP_TELEMETRY_URL: `http://127.0.0.1:${(collector.address() as net.AddressInfo).port}`, SP_TELEMETRY_CREDENTIAL: 'check-credential', SP_REGION: 'local', SP_SUBSTRATE: 'vm', ...extra },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ for (const s of [h.stdout!, h.stderr!]) s.on('data', (d) => (hostLines.push(...String(d).split('\n').filter(Boolean)), process.stdout.write(String(d).replace(/^(?=.)/gm, ' host| '))));+ return h;+}++async function cleanup() {+ if (KEEP) return say('--keep: left the containers and their files');+ const quiet = (p: Promise<unknown>) => p.catch((e) => say(`cleanup: ${e.message}`));+ rmSync(path.join(DATA, 'state', 'previews.json'), { force: true });+ for (const s of [...sessions, SESSION_ID]) rmSync(path.join(DATA, 'state', 'uploads', `${s}.json`), { force: true });+ for (const s of sessions) rmSync(path.join(DATA, 'journals', s), { recursive: true, force: true });+ // The threads', and what no record names below this check's SP_RUN: the spares.+ const below = (() => { try { return readdirSync(path.join(RUN, 'sandbox')); } catch { return []; } })();+ const spares = below.filter((id) => /^[0-9a-f]{16}$/.test(id) && !records().get(id));+ for (const id of new Set([...all.map((t) => t.id()), ...spares])) {+ if (!id) continue;+ const run = sandboxRunFor(RUN, id);+ await quiet(podman(['rm', '--force', '--volumes', containerName(id)]));+ await quiet(podman(['volume', 'rm', '--force', volumeName(id)]));+ await podman(unshareRmArgs([runnersDir(run), path.dirname(secretsFor(run, id))])).catch(() => {});+ rmSync(run, { recursive: true, force: true });+ records().delete(id);+ }+ // In the user namespace: a session writes there as root and as its own users.+ await quiet(podman(unshareRmArgs([PAT, QUINN].map((p) => path.join(DATA, 'people', p.dir))), 60_000));+ rmSync(path.join(DATA, 'journals', SESSION_ID), { recursive: true, force: true });+ if (savedDefinition === undefined) rmSync(gatewayDefinitionPath(), { force: true });+ else writeFileSync(gatewayDefinitionPath(), savedDefinition);+}++/** Threads delivered to every 8 s, so that none leaves for idleness while it is looked at. */+const kept = new Set<Thread>();+const keeping = setInterval(() => void Promise.all([...kept].map((t) => t.deliver())), 8000);++/** The step 7 checks on running threads: `a` and its sibling `a2` of one person, `b` of another, with a journal. */+async function workspaces(a: Thread, a2: Thread, b: Thread) {+ // ---- what a thread got+ const ra = a.record();+ const hello = ra?.repos?.hello;+ check(!!hello && hello.branch === a.branch && hello.from === 'origin/master' && /^[0-9a-f]{40}$/.test(hello.base) && !ra?.repos?.spoon,+ `the record is the fork's record: ${JSON.stringify(ra?.repos)}`);+ const seen = await a.inside('cd /workspace/hello && git status --porcelain --branch && git rev-parse HEAD && cat .git && LC_ALL=C ls -A /workspace && ls /clones && ls /clones/hello/.git/worktrees && git -C /clones/hello config gc.worktreePruneExpire');+ check(seen === [`## ${a.branch}`, hello?.base, 'gitdir: /clones/hello/.git/worktrees/hello', '.claude', '.fork.json', 'AGENTS.md', 'hello', 'hello', 'hello', 'never'].join('\n'),+ `inside: /workspace/hello is a clean worktree of /clones/hello on ${a.branch}, the registry holds it alone, the clone never prunes: ${JSON.stringify(seen)}`);+ const mounted = (await a.inside("awk '{print $5}' /proc/self/mountinfo | grep -E '^/(workspace|clones)' | sort")).split('\n');+ check(mounted.join(' ') === '/clones/hello /clones/hello/.git/worktrees /workspace', `mounted for it: ${mounted.join(' ')}`);+ const fork = JSON.parse((await a.inside('cat /workspace/.fork.json')) || '{}');+ check(fork.key === a.key && fork.owner === a.owner.dir && fork.repos?.hello?.base === hello?.base, `.fork.json in the workspace is a copy of the record: ${JSON.stringify(fork)}`);+ check(/spoon/.test(await a.inside('cat /workspace/AGENTS.md')), 'AGENTS.md lists the repository that is not checked out');+ check(lstatSync(path.join(a.workspace, 'hello', '.git')).isFile() && lstatSync(path.join(a.registry('hello'), 'hello', 'HEAD')).isFile(),+ `on the host: the worktree is in ${a.workspace}, its registry in ${a.registry('hello')}`);+ const commit = await a.inside('cd /workspace/hello && echo edited >> README && node -e "console.log(require(\'fs\').readFileSync(\'README\',\'utf8\').includes(\'edited\'))" && git -c user.name=check -c [email protected] commit -qam "sandbox check" && git log --format=%s -1 && git status --porcelain | wc -l');+ check(commit === 'true\nsandbox check\n0', `a session edits, runs and commits in its worktree: ${JSON.stringify(commit)}`);++ // ---- a sibling thread of the same person, and another person's+ const [d2, d3] = await Promise.all([a2.deliver(), b.deliver()]);+ kept.add(a2).add(b);+ check(!!d2.reply?.ok && !!d3.reply?.ok, `a second thread of ${a.owner.dir} and one of ${b.owner.dir} → ok in ${d2.ms} and ${d3.ms} ms (${d2.reply?.error ?? ''}${d3.reply?.error ?? ''})`);+ await a.inside('echo secret-of-a > /workspace/marker-a && echo secret-of-a > /workspace/hello/marker-a');+ const view = (t: Thread) => t.inside(`ls -A /workspace /workspace/hello | grep -c marker-a; cat /proc/self/mountinfo | grep -c -e '${safeKey(a.key)}'${t.owner === a.owner ? '' : ` -e '/${a.owner.dir}/'`}; ls -d ${a.workspace} ${path.join(DATA, 'people')} 2>&1 | grep -c -v 'No such file'; ls /clones/hello/.git/worktrees | tr '\\n' ' '`);+ check((await view(a2)) === '0\n0\n0\nhello', `the sibling sees neither the first thread's files nor its registry (${JSON.stringify(await view(a2))})`);+ const other = await b.inside(`${`cat /proc/self/mountinfo | grep -c '/${a.owner.dir}/'`}; timeout 40 find / -name marker-a -not -path '/proc/*' 2>/dev/null | wc -l; ls ${path.join(DATA, 'people')} 2>&1 | grep -c -v 'No such file'; git -C /workspace/hello log --all --format=%s | grep -c 'sandbox check'; true`);+ check(other === '0\n0\n0\n0', `the other person's thread has no mount of ${a.owner.dir}'s, finds no file of theirs anywhere, and its clone has not their commit (${JSON.stringify(other)})`);+ const pruned = await a2.inside('cd /workspace/hello && git worktree prune --expire now -v 2>&1; git -C /clones/hello worktree prune --expire now -v 2>&1; git worktree list | wc -l');+ const sibling = await a.inside('cd /workspace/hello && git status --porcelain --branch && git log --format=%s -1');+ check(pruned === '2' && sibling === `## ${a.branch}\n?? marker-a\nsandbox check` && lstatSync(path.join(a.registry('hello'), 'hello', 'gitdir')).isFile(),+ `git worktree prune in the sibling removes nothing (${JSON.stringify(pruned)}) and the first thread's worktree works (${JSON.stringify(sibling)})`);++ // ---- ws-add.sh again, and the mount helper+ const row = `hello\tok\t${a2.branch}\tmaster\t${a2.record()?.repos?.hello?.base}\t`;+ const again = await podman(execArgs(a2.id(), ['/bin/sh', path.join(ROOT, 'bin/ws-add.sh'), '/clones', '/workspace', a2.branch, '0', 'hello'], { dir: '/' }));+ check(again.trimEnd() === row.trimEnd() && (await a2.inside('git -C /workspace/hello status --porcelain --branch')) === `## ${a2.branch}`, `ws-add.sh a second time answers the same and changes nothing: ${JSON.stringify(again)}`);+ const pid = await a2.pid();+ await a2.inside(`ln -s ${b.workspace} /workspace/link-out; ln -s /etc /tmp/link-etc`);+ const mount = (id: string, p: number, who: string, src: string, dst: string) =>+ as.podman(mountArgs(ROOT, p, id, who, [{ src, dst }]), { timeoutMs: 10_000, env: { SP_DATA: DATA } }).then(() => 'mounted', (e: PodmanError) => `exit ${e.code}: ${e.stderr.trim().split('\n').at(-1)}`);+ const me = a2.owner.dir;+ const refusals: [string, Promise<string>, string][] = [+ ["another person's workspace", mount(a2.id(), pid, me, b.workspace, '/mnt/x'), '2'],+ ['a directory outside the data', mount(a2.id(), pid, me, '/etc', '/mnt/x'), '2'],+ ['a link the session left in its workspace', mount(a2.id(), pid, me, path.join(a2.workspace, 'link-out'), '/mnt/x'), '2'],+ ['a source written with ..', mount(a2.id(), pid, me, `${a2.workspace}/../../../${b.owner.dir}/sessions`, '/mnt/x'), '2'],+ ['a destination through a link in the container', mount(a2.id(), pid, me, a2.workspace, '/tmp/link-etc/x'), '[24]'],+ ["another container's process", mount(a2.id(), await b.pid(), me, a2.workspace, '/mnt/x'), '3'],+ ];+ for (const [what, r, code] of refusals) check(new RegExp(`^exit ${code}: `).test(await r), `the mount helper refuses ${what}: ${await r}`);+ check((await mount(a2.id(), pid, me, a2.workspace, '/workspace')) === 'mounted' && (await a2.inside("grep -c ' /workspace ' /proc/self/mountinfo; ls /mnt | wc -l")) === '1\n0',+ 'mounting what is mounted changes nothing, and nothing refused was mounted');++ // ---- the journal of a session of the API+ const journal = path.join(DATA, 'journals', SESSION_ID);+ const j = await b.inside(`grep -c ' ${journal} ' /proc/self/mountinfo; ls ${journal}; ls ${path.dirname(journal)} | wc -l`);+ check(new RegExp(`^1\\n(.*\\n)*${SESSION_ID}\\.jsonl\\n(.*\\n)*1$`).test(j) && existsSync(path.join(journal, `${SESSION_ID}.jsonl`)), `a session with a journal has its own journal directory mounted at the host's path, and no other (${JSON.stringify(j)})`);++ // ---- checkout, by the host's own parts in this process+ const tm = createTelemetry({ service: 'host', version: 'check', region: 'local', send: async () => {} });+ const scripts = sandboxScripts({ as, sudo: user.sudo, tm, root: ROOT, dataDir: DATA, helperRun: path.join(RUN, 'helper'), image: IMAGE,+ execIn: (id, argv, o) => as.podman(execArgs(id, argv, { dir: o.dir, interactive: o.stdin !== undefined }), { timeoutMs: o.timeoutMs, stdin: o.stdin }),+ enter: () => Promise.reject(new Error('not used')), running: async () => true });+ useScripts((clonesDir) => scripts.helperScripts(path.basename(path.dirname(clonesDir))));+ kept.delete(a2);+ await a2.deliver(); // the host writes the record at a delivery: the last one before the checkout, which the host does not know of+ const ws = sandboxWorkspaces({ as, records: records(), mounts: mnt, scripts: scripts.sessionScripts, pid: () => a2.pid() });+ const at = Date.now();+ const out = await ws.checkout(a2.id(), ['octocat/Spoon-Knife', 'nope', '../hello']);+ const spoon = out.find((r) => r.name === 'spoon');+ check(!!spoon && !spoon.error && spoon.branch === a2.branch && out.filter((r) => r.error).length === 2, `checkout in ${Date.now() - at} ms (cloned by a helper container): ${JSON.stringify(out)}`);+ const co = await a2.inside('git -C /workspace/spoon status --porcelain --branch; ls /clones; ls /clones/spoon/.git/worktrees; node -p "Object.keys(require(\'/workspace/.fork.json\').repos).join()"');+ check(co === `## ${a2.branch}\nhello\nspoon\nspoon\nhello,spoon` && Object.keys(a2.record()?.repos ?? {}).join() === 'hello,spoon', `the repository is mounted and checked out, the record and its copy have it: ${JSON.stringify(co)}`);+ check((await a.inside('ls /clones')) === 'hello', 'the thread that did not ask has no mount of it');++ // ---- the definition changes: a running container reads the new one+ welcome('second');+ const def = () => { try { return JSON.parse(readFileSync(path.join(a2.run, 'definition.json'), 'utf8')).about; } catch { return undefined; } };+ check(!!(await until(() => (def() === 'second' ? true : undefined), 10_000)) && /"about": ?"second"/.test(await a2.inside('cat $SP_DEFINITION')), 'a definition the gateway sends is written again for a running container, which reads it');+}++async function finish(host?: ChildProcess): Promise<never> {+ clearInterval(keeping);+ wire?.close();+ host?.kill('SIGTERM');+ await sleep(1500);+ host?.kill('SIGKILL');+ await cleanup();+ model.stop();+ wss.close();+ collector.close();+ say(failed ? `${failed} check(s) FAILED` : 'all checks passed');+ process.exit(failed ? 1 : 0);+}++if (SPARES) {+ let host: ChildProcess | undefined;+ await spareChecks({+ run: RUN, data: DATA, image: IMAGE, idleMs: IDLE_MS, say, check, until, sleep, podman, events, tel, tokenSessions, mkTrace, people: [PAT, QUINN],+ records, clone: (p, name) => mnt.clone(p.dir, name),+ thread: (owner, n) => { const t = thread(owner, n); all.push(t); return t; },+ welcome: (about, repos) => { gateway.repos = repos; welcome(about); },+ start: (env) => (host = startHost(env)),+ }).catch((e) => check(false, `the check itself failed: ${(e as Error)?.stack ?? e}`));+ await finish(host);+}++let host = startHost();+try {+ check(!!(await until(() => events.find((e) => e.t === 'hello'))), 'host with SP_LAUNCH=podman dialed the gateway and said hello');+ const cloneAt = Date.now();+ const clones = [PAT, QUINN].map((p) => path.join(mnt.clone(p.dir, 'hello'), '.git', 'worktrees'));+ check(!!(await until(() => (clones.every((c) => existsSync(c)) ? true : undefined), 180_000)), `helper containers cloned the eager repository for both people in ${Date.now() - cloneAt} ms`);+ check(!existsSync(mnt.clone(PAT.dir, 'spoon')), 'the lazy repository is not cloned');++ // ---- a new thread+ const d1 = await A1.deliver();+ check(!!d1.reply?.ok, `first delivery → reply ok in ${d1.ms} ms (${d1.reply?.error ?? ''})`);+ const record = await until(A1.record, 5000);+ const id = record?.id;+ check(!!record && record.key === A1.key && record.person === PAT.dir, `the thread has a record: ${JSON.stringify(record)}`);+ if (!id) throw new Error('no record: nothing more can be checked');+ const run = A1.run;+ check((await A1.inspect('{{.State.Status}}')) === 'running' && (await A1.unitActive()), `container ${containerName(id)} runs and its unit ${unitName(id)} is active`);+ const pid = await A1.pid();+ const cgroup = pid ? readFileSync(`/proc/${pid}/cgroup`, 'utf8').trim() : '';+ check(new RegExp(`/${unitName(id).replace(/\./g, '\\.')}/`).test(cgroup), `its first process (${pid}) is in that unit's cgroup: ${cgroup}`);+ check((await A1.inspect('{{.Config.Image}}')) === IMAGE && (await A1.inspect('{{index .Config.Labels "sp.abi"}}')) === process.env.SP_IMAGE_ABI,+ 'it was created from SP_IMAGE and carries SP_IMAGE_ABI');+ check(lstatSync(socketFor(run, id)).isSocket(), `the runner listens on ${socketFor(run, id)}`);+ check(!!(await until(async () => (/chat\.postMessage .*cwd/.test(await A1.logs()) ? true : undefined))), 'the runner answered !status into the fake Slack');+ const status = (await A1.logs()).split('\n').find((l) => /chat\.postMessage .*cwd/.test(l)) ?? '';+ check(/\/workspace\b/.test(status) && !status.includes(DATA), 'its cwd is /workspace, and it names no host path');+ const fp = (await until(() => A1.reports().find((r) => r.status === 'idle')))?.forkPath;+ check(fp === A1.workspace, `the report the gateway got names the host's path: ${fp}`);+ const seen = (await A1.inside('id -u; echo $SP_RUN')).split('\n').join(' ');+ check(seen === `1500 ${run}`, `inside: uid 1500, SP_RUN its own run directory (${seen})`);+ check(readlinkSync(path.join(run, 'token.sock')) === path.relative(run, tokenSocketFor(run, id)), `token.sock in its run directory links to ${path.relative(run, tokenSocketFor(run, id))}`);+ check((await A1.inside(`test -S ${model.api} && test ! -e ${model.control} && echo yes`).catch(() => '')) === 'yes',+ `inside, the model proxy's API socket ${model.api} is there and its control socket is not`);+ const tk = await A1.askToken();+ check(tk.startsWith('ghs_fake') && tokenSessions.at(-1) === A1.key, `a token asked for inside, naming another session, is asked of the gateway for this one (${tk}, ${JSON.stringify(tokenSessions)})`);+ const l1 = launched(d1.trace) ?? (await until(() => launched(d1.trace), 10_000));+ check(l1?.data?.launch_mode === 'podman' && typeof l1.data['container.create_ms'] === 'number' && typeof l1.data['container.start_ms'] === 'number' && l1.data['container.recreated'] === undefined+ && typeof l1.data['container.mount_ms'] === 'number' && typeof l1.data['container.add_ms'] === 'number', `runner.launched: ${JSON.stringify(l1?.data)} duration ${l1?.duration_ms} ms`);+ await A1.inside('echo kept > /home/agent/sandbox-check-marker');++ // ---- workspaces, while the thread runs; then build directories for housekeeping to find once it has stopped+ kept.add(A1);+ await workspaces(A1, A2, B);+ await A1.inside('cd /workspace/hello && mkdir -p node_modules/pkg .venv/bin && echo node_modules > .gitignore');+ await A1.inside('echo x > /workspace/hello/node_modules/pkg/made-by-root && chmod 600 /workspace/hello/node_modules/pkg/made-by-root', '0:0');++ // ---- warm+ const d2 = await A1.deliver();+ check(!!d2.reply?.ok && (await A1.pid()) === pid, `second delivery → ok in ${d2.ms} ms, same container process`);++ // ---- what reaches into a running container (step 9): the two threads of one person+ const dA2 = await A2.deliver();+ kept.add(A2);+ check(!!dA2.reply?.ok && !!A2.id() && A2.id() !== id && (await A2.inspect('{{.State.Status}}')) === 'running', `the second thread of the same person runs in its own container ${containerName(A2.id())}`);+ sessions.push(await known(A1.spec), await known(A2.spec));+ const a = reached('A', A1, sessions[0]);+ const b = reached('B', A2, sessions[1]);+ const q = reached('Q', B, await known(B.spec));+ const wireSocket = path.join(RUN, 'wire', 'wire.sock');+ check(!!(await until(() => existsSync(wireSocket) || undefined, 10_000)), `the host serves its wire socket ${wireSocket}`);+ wire = await wireClient(wireSocket);+ const byId = (cid: string) => all.find((t) => t.id() === cid) ?? refuse(`no thread ${cid}`);+ // Started here as the host starts them; nothing in this process runs a workspace script through it, so it is given no way to.+ // Where a script runs is what the check says the thread is (the host asks its record and its unit, sandbox/use.ts).+ const files = (place: SandboxPlace) => sandboxScripts({ as, sudo: user.sudo, tm: createTelemetry({ service: 'host', version: 'check', region: 'local', send: async () => {} }), root: ROOT, dataDir: DATA,+ helperRun: path.join(RUN, 'helper'), image: IMAGE, execIn: () => Promise.reject(new Error('not used')), enter: async () => ({ place, leave() {} }), running: async () => place.running }).filesPlace(place);+ const kit: Kit = {+ root: ROOT, dataDir: DATA, key: preview.key, member: PAT.userId as string, say, check, until, asked, wire, calls: model.calls,+ inside: (cid, script) => podman(['exec', '--user', '1500:1500', containerName(cid), '/bin/sh', '-c', script]).then((s) => s.trim()),+ detached: (cid, argv) => podman(['exec', '--detach', '--user', '1500:1500', containerName(cid), ...argv]),+ asRunner: (argv) => as.run(argv, { timeoutMs: 10_000 }),+ status: (cid) => byId(cid).inspect('{{.State.Status}}'),+ tell: (t, text) => byId(t.id).deliver(mkTrace(), text),+ filesPlace: (t, running) => files({ id: t.id, person: path.basename(path.dirname(path.dirname(t.workspace))), workspace: t.workspace, running }),+ };+ await reachRunning(kit, a, b, q);++ // ---- idle exit+ kept.clear();+ clearInterval(keeping);+ await A1.deliver();+ const idleAt = Date.now();+ check(!!(await until(async () => ((await A1.inspect('{{.State.Status}}')) === 'exited' ? true : undefined), IDLE_MS + 40_000)),+ `idle for ${IDLE_MS} ms: the runner left and the container is exited (${Date.now() - idleAt} ms after the delivery)`);+ check(!!(await until(async () => ((await A1.unitActive()) ? undefined : true), 10_000)), 'its unit is gone');+ check((await podman(['volume', 'exists', volumeName(id)]).then(() => true, () => false)) && !!A1.record(), 'its home volume and its record stay');+ check(!!(await until(() => A1.reports().find((r) => r.status === 'stopped'))), 'the gateway was told the session stopped');++ // ---- housekeeping: the stopped thread's build directories, asked of git in a helper container+ const modules = path.join(A1.workspace, 'hello', 'node_modules');+ check(existsSync(modules), 'the stopped thread still has the node_modules it made');+ await sleep(Math.max(0, ARTIFACTS_IDLE_HOURS * 3600e3 + 1000 - (Date.now() - idleAt)));+ const keepAt = Date.now();+ // A changed definition starts a housekeeping pass, unless one is running: asked again until it shows.+ for (let n = 0; n < 6 && existsSync(modules); n++) {+ welcome(`third ${n}`);+ await until(() => (existsSync(modules) ? undefined : true), 20_000);+ }+ check(!existsSync(modules) && existsSync(path.join(A1.workspace, 'hello', '.venv')) && existsSync(path.join(A1.workspace, 'hello', 'README')),+ `housekeeping removed the ignored node_modules (with a file root made inside) ${Date.now() - keepAt} ms after it was asked, and kept .venv, which git does not ignore`);++ // ---- what reaches a stopped thread (step 9)+ check(!!(await until(async () => ((await A2.inspect('{{.State.Status}}')) === 'exited' && !(await A2.unitActive()) ? true : undefined), 30_000)), 'the second thread is stopped too');+ check(!!(await until(async () => ((await B.inspect('{{.State.Status}}')) === 'exited' && !(await B.unitActive()) ? true : undefined), 30_000)), "and the other person's");+ await reachStopped(kit, a, b, q);++ // ---- resume+ const d3 = await A1.deliver();+ check(!!d3.reply?.ok, `delivery after the idle exit → ok in ${d3.ms} ms (${d3.reply?.error ?? ''})`);+ check(A1.record()?.id === id && (await A1.inspect('{{.State.Status}}')) === 'running' && (await A1.unitActive()), 'the same container runs again, under the same id');+ check((await A1.inside('cat /home/agent/sandbox-check-marker')) === 'kept', 'a file written in its home before the exit is there');+ const l3 = launched(d3.trace) ?? (await until(() => launched(d3.trace), 10_000));+ check(l3?.data?.['container.recreated'] === false && l3.data['container.create_ms'] === undefined && typeof l3.data['container.mount_ms'] === 'number' && l3.data['container.add_ms'] === undefined,+ `runner.launched of the resume: ${JSON.stringify(l3?.data)} duration ${l3?.duration_ms} ms`);+ check((await A1.askToken()).startsWith('ghs_fake'), 'its token socket answers again');+ const back = await A1.inside('cd /workspace/hello && git log --format=%s -1 && cat /workspace/marker-a && ls /clones/hello/.git/worktrees');+ check(back === 'from the terminal\nsecret-of-a\nhello', `its workspace, its worktree and its registry are mounted again, as it left them (${JSON.stringify(back)})`);+ await reachResumed(kit, a, b);++ // ---- the host killed and started again; the sweep; Prune (step 8)+ const rig: Rig = {+ kit, as, run: RUN, data: DATA, image: IMAGE, events, tel, names, unpreviewed, welcome, clone: mnt.clone, lines: hostLines,+ kill: () => new Promise<void>((r) => (host.once('exit', () => r()), host.kill('SIGKILL'))),+ async start(env) {+ const [at, n] = [Date.now(), events.length];+ host = startHost(env);+ return (await until(() => events.slice(n).find((e) => e.t === 'hello'), 90_000)) ? Date.now() - at : undefined;+ },+ known,+ };+ const times = await restarts(rig, A1, A2, B, C, E);+ say(`timings: ${JSON.stringify(times)}`);+ // ---- what waits for what: the image lock, a prune and a /files script, a session stopped under a download, a home after a reboot+ await waits(rig, A2, E);+} catch (e) {+ check(false, `the check itself failed: ${(e as Error)?.stack ?? e}`);+}+await finish(host);diff --git a/computer/src/dev/wire-client.ts b/computer/src/dev/wire-client.tsnew file mode 100644index 00000000..e4d6a99a--- /dev/null+++ b/computer/src/dev/wire-client.ts@@ -0,0 +1,137 @@+// The relay's side of the host's wire socket, for dev checks (the real one is+// src/wire/host-link.ts): `hello`, calls answered by `result`, a terminal run+// to its exit, and `/files` list, get and put with their one-shot sockets,+// also cut short.+//+// Invariants: it checks nothing a relay would (no member, key or scope): it+// is the trusted peer the host takes a relay for, so what it is refused, the+// host refused. Run it as a user that may open the socket (the host's own).++import net from 'node:net';+import { randomUUID } from 'node:crypto';+import type { ApiError, HostToWire } from '../protocol.js';+import { lines, send } from '../ipc.js';++type Outcome<T> = { result?: T; error?: ApiError };++export interface WireClient {+ call<T = unknown>(m: { t: string } & Record<string, unknown>): Promise<Outcome<T>>;+ /** Run `command` in the session's terminal (no tty) to its exit: what it wrote, or why it did not open. */+ terminal(sessionId: string, member: string, command: string): Promise<{ out: string; exitCode: number | null } | { error: ApiError }>;+ /** Upload a tar as the top-level name `path`. */+ put(sessionId: string, member: string, path: string, tar: Buffer): Promise<Outcome<{ upload: { path: string; files: number; bytes: number } }>>;+ /** One file's bytes (`file`), or a directory's tar. */+ get(sessionId: string, member: string, path: string, file: boolean): Promise<{ body: Buffer } | { error: ApiError }>;+ /** An upload that says `tar.length` bytes come and hangs up after `sent` of them: how the host ended it. */+ putCut(sessionId: string, member: string, path: string, tar: Buffer, sent: number): Promise<Outcome<unknown>>;+ /** A download whose reader hangs up at its first bytes: how many came. */+ getCut(sessionId: string, member: string, path: string, file: boolean): Promise<{ got: number } | { error: ApiError }>;+ /** An upload whose first `sent` bytes are written and whose connection stays open: `finish` sends the rest. */+ putHeld(sessionId: string, member: string, path: string, tar: Buffer, sent: number): Promise<{ finish(): Promise<Outcome<{ upload: { files: number } }>> } | { error: ApiError }>;+ /** A download whose reader stops reading at its first bytes: `rest` reads on, to how the host ended it. */+ getPaused(sessionId: string, member: string, path: string, file: boolean): Promise<{ rest(): Promise<{ got: number; error?: ApiError }> } | { error: ApiError }>;+ close(): void;+}++const drain = (socket: string, write?: Buffer) =>+ new Promise<Buffer>((resolve, reject) => {+ const chunks: Buffer[] = [];+ const c = net.connect(socket, () => write && c.end(write));+ c.on('data', (d: Buffer) => chunks.push(d)).on('close', () => resolve(Buffer.concat(chunks))).on('error', reject);+ });++export async function wireClient(socket: string): Promise<WireClient> {+ const waiting = new Map<string, (m: Outcome<unknown>) => void>();+ const done = new Map<string, (m: Outcome<unknown>) => void>();+ const exits = new Map<string, (code: number | null) => void>();+ const sock = net.connect(socket);+ await new Promise<void>((resolve, reject) => sock.once('connect', resolve).once('error', reject));+ sock.on('error', () => {});+ lines(sock, (m: HostToWire) => {+ if (m.t === 'result') waiting.get(m.id)?.(m);+ else if (m.t === 'files.done') done.get(m.id)?.(m);+ else if (m.t === 'terminal.exited') exits.get(m.terminalId)?.(m.exitCode);+ });+ send(sock, { t: 'hello', version: 'dev-check' });++ function ask<T>(m: { t: string } & Record<string, unknown>, id: string = randomUUID()): Promise<Outcome<T>> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => resolve({ error: { code: 'timeout', message: `no answer to ${m.t} in 60 s`, status: 504 } as ApiError }), 60_000);+ waiting.set(id, (r) => (clearTimeout(timer), waiting.delete(id), resolve(r as Outcome<T>)));+ send(sock, { ...m, id });+ });+ }+ const finished = (id: string) => new Promise<Outcome<unknown>>((resolve) => done.set(id, (r) => (done.delete(id), resolve(r))));++ return {+ call: (m) => ask(m),+ async terminal(sessionId, member, command) {+ const r = await ask<{ terminalId: string; socket: string }>({ t: 'terminal.open', sessionId, member, cols: 80, rows: 24, command, tty: false });+ if (!r.result) return { error: r.error as ApiError };+ const exited = new Promise<number | null>((resolve) => exits.set(r.result!.terminalId, resolve));+ const out = await drain(r.result.socket);+ return { out: out.toString('utf8'), exitCode: await exited };+ },+ async put(sessionId, member, path, tar) {+ const id = randomUUID();+ const end = finished(id);+ const r = await ask<{ socket: string }>({ t: 'files.put', sessionId, member, path, format: 'tar', bytes: tar.length }, id);+ if (!r.result) return { error: r.error };+ await drain(r.result.socket, tar);+ return (await end) as Outcome<{ upload: { path: string; files: number; bytes: number } }>;+ },+ async get(sessionId, member, path, file) {+ const id = randomUUID();+ const end = finished(id);+ const r = await ask<{ socket: string }>({ t: 'files.get', sessionId, member, path, file }, id);+ if (!r.result) return { error: r.error as ApiError };+ const body = await drain(r.result.socket);+ const d = await end;+ return d.error ? { error: d.error } : { body };+ },+ async putCut(sessionId, member, path, tar, sent) {+ const id = randomUUID();+ const end = finished(id);+ const r = await ask<{ socket: string }>({ t: 'files.put', sessionId, member, path, format: 'tar', bytes: tar.length }, id);+ if (!r.result) return { error: r.error };+ const c = net.connect(r.result.socket, () => c.write(tar.subarray(0, sent), () => setTimeout(() => c.destroy(), 1000)));+ c.on('error', () => {});+ return end;+ },+ async getCut(sessionId, member, path, file) {+ const r = await ask<{ socket: string }>({ t: 'files.get', sessionId, member, path, file });+ if (!r.result) return { error: r.error as ApiError };+ const c = net.connect(r.result.socket);+ return new Promise((resolve) => c.once('data', (d: Buffer) => (c.destroy(), resolve({ got: d.length }))).once('error', () => resolve({ got: 0 })).once('end', () => resolve({ got: 0 })));+ },+ async putHeld(sessionId, member, path, tar, sent) {+ const id = randomUUID();+ const end = finished(id);+ const r = await ask<{ socket: string }>({ t: 'files.put', sessionId, member, path, format: 'tar', bytes: tar.length }, id);+ if (!r.result) return { error: r.error as ApiError };+ const c = net.connect(r.result.socket);+ c.on('error', () => {});+ await new Promise<void>((resolve) => c.once('connect', () => c.write(tar.subarray(0, sent), () => resolve())));+ return { finish: () => (c.end(tar.subarray(sent)), end as Promise<Outcome<{ upload: { files: number } }>>) };+ },+ async getPaused(sessionId, member, path, file) {+ const id = randomUUID();+ const end = finished(id);+ const r = await ask<{ socket: string }>({ t: 'files.get', sessionId, member, path, file }, id);+ if (!r.result) return { error: r.error as ApiError };+ const c = net.connect(r.result.socket);+ c.on('error', () => {});+ let got = 0;+ await new Promise<void>((resolve) => c.once('data', (d: Buffer) => ((got += d.length), c.pause(), resolve())).once('close', () => resolve()));+ return {+ async rest() {+ c.on('data', (d: Buffer) => (got += d.length)).resume();+ const d = await end;+ c.destroy();+ return { got, error: d.error };+ },+ };+ },+ close: () => sock.destroy(),+ };+}diff --git a/computer/src/host/api-host-epoch.test.ts b/computer/src/host/api-host-epoch.test.tsindex e96b0ce2..3f57d13c 100644--- a/computer/src/host/api-host-epoch.test.ts+++ b/computer/src/host/api-host-epoch.test.ts@@ -10,8 +10,10 @@ import { afterEach, describe, expect, it } from 'vitest';import { ensureSessionJournalDir, Journal, journalPath, readJournalFile } from '../api/journal.js';import type { ApiClient } from '../api/socket.js';import type { SubscribeOptions } from '../api/writer.js';+import { createTelemetry } from '../telemetry/emitter.js';import type { ApiActor, GatewayToHost, HostToGateway, JournalEvent, SessionSpec } from '../protocol.js';import { apiHost, type ApiHostDeps, type WireLinkLike } from './api-host.js';+import { apiMeter } from './api-meter.js';import { scanJournals } from './session-writer.js';const S = 'cs_0000000000000002';@@ -28,7 +30,8 @@ const until = async (f: () => boolean, ms = 3000) => {const dirs: string[] = [];afterEach(() => {- for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+ // Retried: a writer a test stopped may still be closing a file in it (seen under load: ENOTEMPTY).+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });});/** The SessionLog DO as far as the mirror sees it: stores batches of its epoch, gapless, acks them. */@@ -274,24 +277,33 @@ describe('epoch adoption (recovery-fix)', () => {it('a host whose adoption dies mid-tail reports the old epoch at hello, and the resent frame adopts (review r2 P1-2, P2-7)', async () => {const ref: { t?: Awaited<ReturnType<typeof outage>> } = {};- const t = (ref.t = await outage({ retire: (id) => cooperative(ref.t!)(id) }));+ // What the host's meter hears of adoptions, and nothing else of it: an attempt is over when it is told.+ const attempts: boolean[] = [];+ const real = apiMeter(createTelemetry({ service: 'host', version: 't', region: 'local', send: () => {} }), { journals: path.join(os.tmpdir(), 'apiepoch-none'), intervalMs: 3_600_000 });+ const meter = { ...real, adopted: (x: Parameters<typeof real.adopted>[0]) => (attempts.push(x.ok), real.adopted(x)) };+ const t = (ref.t = await outage({ retire: (id) => cooperative(ref.t!)(id), meter }));const good = t.dO.recover(3);// The write of the tail's second event throws (the crash, a full disk) after its first is on file.const torn = { ...good, tail: [good.tail[0], { ...good.tail[1], data: { bad: 1n } }, ...good.tail.slice(2)] } as never;t.a.onGateway(torn);await until(() => t.moves.length > 0); // the runner's own `down`+ // The attempt has failed, and its backoff is counted from before the clock moves below: on a slow machine it+ // was still running after a fixed wait, the backoff then started at the later time and the resent frame was dropped.+ await until(() => attempts.length === 1);+ expect(attempts).toEqual([false]);await settle();const moves = t.moves.length;// The hello a restarted host would send: still epoch 1, so the gateway sends `epoch` again.expect(t.a.journals()).toEqual([{ sessionId: S, epoch: 1, startSeq: 1, lastSeq: 4 }]);t.clock.now += 60_000;t.a.onGateway(good);- await until(() => readJournalFile(t.file, 0).epoch === 2);- await settle();+ await until(() => attempts.length === 2); // over, the relay told: the epoch on file comes some steps before that+ expect(attempts).toEqual([false, true]);expect(readJournalFile(t.file, 0).events).toEqual(t.dO.log);expect(t.a.journals()).toEqual([{ sessionId: S, epoch: 2, startSeq: 4, lastSeq: 7 }]);expect(t.moves.length).toBe(moves + 1);await t.a.stop();+ real.stop();});it('a journal whose epoch line is ahead of its events is left alone by the boot scan and repaired by the same-epoch frame (review r2 P1-2, P2-7)', async () => {diff --git a/computer/src/host/api-host.test.ts b/computer/src/host/api-host.test.tsindex 0ed3b9c3..583701f9 100644--- a/computer/src/host/api-host.test.ts+++ b/computer/src/host/api-host.test.ts@@ -80,7 +80,7 @@ const dialTo = (w: ReturnType<typeof memWriter>, dialled: string[]) => async (p:const dirs: string[] = [];afterEach(() => {- for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });});function setup(o: Partial<ApiHostDeps> = {}) {@@ -208,6 +208,21 @@ describe('apiHost', () => {await t.a.stop();});+ it('journals an upload to a session whose runner is gone through the host\'s writer, which it opens for it', async () => {+ const t = setup();+ t.a.onGateway(welcome(4));+ t.a.onGateway({ t: 'deliver', id: 'd1', session: spec, msg: { userId: 'U1', text: 'hi', ts: '1' }, epoch: 1, lastSeq: 0 });+ await t.a.mint(spec, 'beef');+ t.a.up('beef');+ await tick(5);+ t.a.down('beef');+ // Nothing has asked for the session since its runner left: no writer of the host's is open.+ expect(t.host.calls).toEqual([]);+ expect(await t.a.hooks.record(S, 'files.pushed', { path: 'notes', files: 1, bytes: 9, replaced: false }, actor)).toBe(1);+ expect(t.host.calls).toEqual([RECORD_METHOD]);+ await t.a.stop();+ });+it('wakes the runner for a send the host writer recorded, as an API delivery', async () => {const t = setup();t.a.onGateway(welcome(4));@@ -252,6 +267,31 @@ describe('apiHost', () => {}});+ it('opens no host writer while a start of the session is in flight, however long it takes; the start\'s end, not a timer, lets it', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ let hooks: WireHooks | undefined;+ const t = setup({ wire: async (h) => ((hooks = h), { setKey() {}, setAccess() {}, setAdmins() {}, revoked() {}, moved() {}, close: async () => {} }) });+ t.a.onGateway(welcome(4, { wire: { key: 'k' } }));+ await vi.advanceTimersByTimeAsync(0);+ await t.a.mint(spec, 'aaaa');+ let where: unknown;+ void Promise.resolve(hooks!.where(S)).then((w) => (where = w));+ // A start may wait 300 s for the image lock (sandbox/image-lock.ts) before its container is even started.+ await vi.advanceTimersByTimeAsync(301_000);+ expect(where).toBeUndefined();+ expect(t.opened).toEqual([]);+ t.a.startEnded(spec); // it failed: no runner registered+ await vi.advanceTimersByTimeAsync(0);+ expect(where).toMatchObject({ writer: 'host' });+ t.a.startEnded(spec); // twice, or for a session with no start: nothing+ t.a.startEnded({ ...spec, sessionId: undefined });+ await t.a.stop();+ } finally {+ vi.useRealTimers();+ }+ });+it('mirrors the runner, then the host writer once it exits; forwards access and revocations to the relay', async () => {const t = setup();t.a.onGateway(welcome(4, { wire: { key: 'k' } }));diff --git a/computer/src/host/api-host.ts b/computer/src/host/api-host.tsindex 2740f135..6f58f9ab 100644--- a/computer/src/host/api-host.ts+++ b/computer/src/host/api-host.ts@@ -12,7 +12,11 @@// before reaches main unchanged. Only `cs_` sessions have a writer.// - One writer per session: the host's session-writer is handed off (lock// released) before a runner is started or claimed for its session, and is-// opened only when no runner serves it and none is starting.+// opened only when no runner serves it and none is starting. "Starting"+// lasts from `mint` until the runner is `up` or main says the start ended+// (`startEnded`, well or not), however long that takes: a start in a+// container may wait minutes for the image lock (work 103), and no timer+// stands in for its end.// - Calvin never writes recovery events for a lost runner (the DO does, under// epoch + 1); the boot scan settles only journals no process holds.// - Only the gateway's `epoch` frame moves a session's epoch (recovery-fix):@@ -40,7 +44,7 @@ import { moveFlatJournals, moveFlatSessionLogged } from './journal-flat-move.js'import { journalReports } from './journal-reports.js';import { type HostWriterOptions, HostSessionWriter, scanJournals } from './session-writer.js';import { isSessionId } from '../session-ids.js';-import { runnersDir as runnersDirOf } from '../ipc.js';+import { type RunRoot, runnersDir as runnersDirOf } from '../ipc.js';import { log } from '../log.js';import { apiBridge, localPort, type WriterPort } from './api-bridge.js';import { mirrorAcks } from './mirror-acks.js';@@ -50,6 +54,7 @@ import { apiWake } from './api-wake.js';import { apiRelay, type WireHooks, type WireLinkLike } from './api-relay.js';import { type ApiMeter, apiMeter } from './api-meter.js';import type { Telemetry } from '../telemetry/emitter.js';+import type { SandboxPlace } from './sandbox/scripts.js';export interface StartOptions {/** A message to deliver once it runs (a send recorded by the host's writer); absent: only start it. */@@ -81,6 +86,8 @@ export interface ApiHostDeps {start(spec: SessionSpec, o: StartOptions): Promise<SessionStatus | undefined>;/** The fork of the session's runner, if it reported one. */forkPath?(key: string): string | undefined;+ /** Present where sessions run in containers (work 103): the session's sandbox, undefined when it has none yet. Its terminal and files are reached only there. */+ sandbox?(spec: SessionSpec): Promise<SandboxPlace | undefined>;/** Serve the relay's local socket (api-wire.ts); absent: no relay on this host. */wire?(hooks: WireHooks): Promise<WireLinkLike>;/** The host's emitter: the API side's telemetry (api-meter.ts: the relay's frames, the mirror's turns, adoptions, api.sample). */@@ -165,9 +172,7 @@ export function apiHost(d: ApiHostDeps) {if (pending.has(sessionId)) return;let resolve = () => {};const done = new Promise<void>((r) => (resolve = r));- const t = setTimeout(() => settle(sessionId), 60_000); // a launch that failed before its runner registered- t.unref?.();- pending.set(sessionId, { done, resolve: () => (clearTimeout(t), resolve()) });+ pending.set(sessionId, { done, resolve });}function settle(sessionId: string) {pending.get(sessionId)?.resolve();@@ -272,10 +277,15 @@ export function apiHost(d: ApiHostDeps) {const spec = specs.get(sessionId);const forkPath = spec && (d.forkPath?.(spec.key) ?? spec.forkPath);const owner = spec?.owner.userId;+ if (d.sandbox) {+ const sandbox = spec && (await d.sandbox(spec));+ return sandbox && owner ? { forkPath: sandbox.workspace, owner, sandbox } : undefined;+ }return forkPath && owner ? { forkPath, owner } : undefined;},async record(sessionId, type, data, actor) {- const w = await writer(sessionId, false);+ // With no runner the host's own writer records it, opened as for any call: an upload to a stopped session is in its log.+ const w = await writer(sessionId, true);const r = await w?.call(RECORD_METHOD, { sessionId, type, data }, { actor, member: actor.id });if (r?.error) log.warn(`${type} not recorded in ${sessionId}: ${r.error.code}`);return (r?.result as { seq?: number } | undefined)?.seq;@@ -461,8 +471,8 @@ export function apiHost(d: ApiHostDeps) {}},- /** Before a runner is launched or claimed for `spec`: its RunnerApi, with the host's writer handed off; undefined off the API. */- async mint(spec: SessionSpec, runnerId: string): Promise<RunnerApi | undefined> {+ /** Before a runner is launched or claimed for `spec`: its RunnerApi, with the host's writer handed off; undefined off the API. `run`: the runner's own run root, when it has one (work 103). */+ async mint(spec: SessionSpec, runnerId: string, run?: RunRoot): Promise<RunnerApi | undefined> {const sessionId = spec.sessionId;if (!v4 || !isSessionId(sessionId)) return undefined;specs.set(sessionId, spec);@@ -474,11 +484,14 @@ export function apiHost(d: ApiHostDeps) {const { epoch, lastSeq } = logOf(sessionId);ensureSessionJournalDir(d.dataDir, sessionId); // the runner opens the journal there and cannot make the directory itselfmoveFlatSessionLogged(d.dataDir, sessionId); // what a runner from before the move left flat (goes in step 12 of work 103)- const api: RunnerApi = { sessionId, journal: journalPath(d.dataDir, sessionId), epoch, lastSeq, socket: apiSocketFor(runnerId, runnersDir), token: mintToken() };+ const api: RunnerApi = { sessionId, journal: journalPath(d.dataDir, sessionId), epoch, lastSeq, socket: apiSocketFor(runnerId, run ? runnersDirOf(run) : runnersDir), token: mintToken() };tokens.set(runnerId, api);return api;},+ /** The start `mint` was called for is over, with a runner or without: whoever waited for it goes on (to the runner's writer, or the host's). */+ startEnded: (spec: SessionSpec) => void (isSessionId(spec.sessionId) && settle(spec.sessionId)),+/** A runner now serves its session (launched, claimed, or found after a restart). */up(runnerId: string) {const api = tokens.get(runnerId);diff --git a/computer/src/host/api-wire.test.ts b/computer/src/host/api-wire.test.tsindex 57148559..ac863f5e 100644--- a/computer/src/host/api-wire.test.ts+++ b/computer/src/host/api-wire.test.ts@@ -4,7 +4,14 @@ import { groupId, wireFor } from './api-wire.js';describe('api-wire', () => {it('serves no relay socket where runners run as the host\'s own user (a host still running as agent, a laptop)', () => {expect(wireFor({ launch: 'systemd', stateDir: '/nonexistent' })).toBeUndefined();- expect(wireFor({ launch: 'systemd', stateDir: '/nonexistent', user: { sudo: [], env: {} } })).toBeTypeOf('function');+ expect(wireFor({ launch: 'systemd', stateDir: '/nonexistent', user: { sudo: [], uid: 1500, env: {} } })).toBeTypeOf('function');+ });++ it('on a podman host it needs where a session\'s files are and how its terminal enters the sandbox', () => {+ const user = { sudo: [], uid: 1500, env: {} };+ const files = () => ({ root: '/workspace', spawn: () => Promise.reject(new Error('not used')) });+ expect(() => wireFor({ launch: 'podman', stateDir: '/nonexistent', user, files })).toThrow(/its terminal/);+ expect(wireFor({ launch: 'podman', stateDir: '/nonexistent', user, files, terminal: { enter: async () => ({ running: true, leave() {} }), hangUp() {} } })).toBeTypeOf('function');});it('reads a group\'s gid, undefined where it does not exist', () => {diff --git a/computer/src/host/api-wire.ts b/computer/src/host/api-wire.tsindex 5eef67f8..29708100 100644--- a/computer/src/host/api-wire.ts+++ b/computer/src/host/api-wire.ts@@ -11,6 +11,9 @@// still running as agent, a laptop) there is no wire socket at all.// - The socket's directory and the terminals' sockets belong to group// `sp-wire`; without that group wire-link chowns nothing and fails closed.+// - On a `podman` host (work 103) a terminal is a shell in the session's+// container and `/files` run inside it, or in a helper container while it+// is stopped (sandbox/scripts.ts `filesPlace`); neither ever runs on the host.// - Upload records live in `stateDir` (HOST_DATA/state/uploads), so a push's// per-name record survives a reboot.@@ -19,10 +22,11 @@ import os from 'node:os';import path from 'node:path';import type { WireHooks, WireLinkLike } from './api-relay.js';import { systemdRunPrefix } from './runner-limits.js';+import type { SandboxPlace } from './sandbox/scripts.js';import type { RunnerUser } from './runner-user.js';-import { createTerminals } from './terminal.js';+import { createTerminals, type TerminalsOptions } from './terminal.js';import { serveWireLink, WIRE_DIR } from './wire-link.js';-import { createWorkspaceFiles } from './workspace-files.js';+import { createWorkspaceFiles, type Place } from './workspace-files.js';export interface WireOptions {launch: string;@@ -34,6 +38,10 @@ export interface WireOptions {/** Upload records (HOST_DATA/state/uploads). */stateDir: string;dir?: string;+ /** On a `podman` host: where a session's `/files` scripts run (sandbox/host.ts `files`). */+ files?(sandbox: SandboxPlace): Place;+ /** On a `podman` host: how a terminal enters a session's sandbox and hangs up in it (sandbox/host.ts `terminal`). */+ terminal?: TerminalsOptions['inside'];}/** The gid of `name`, or undefined where it does not exist. */@@ -49,18 +57,30 @@ export function groupId(name: string, getent = (n: string) => execFileSync('/usr/** How api-host starts the relay's socket on this host, or undefined where it must not (see the header). */export function wireFor(o: WireOptions): ((hooks: WireHooks) => Promise<WireLinkLike>) | undefined {if (!o.user) return undefined;+ const podman = o.launch === 'podman';+ if (podman && !(o.files && o.terminal)) throw new Error('SP_LAUNCH=podman: the wire socket needs the place of a session\'s files and its terminal');+ const user = o.user;return (hooks) => {const dir = o.dir ?? WIRE_DIR;const group = groupId('sp-wire');const terminals = createTerminals({dir: path.join(dir, 'terminals'),- launch: o.launch === 'systemd' ? 'systemd' : 'detached',+ launch: podman ? 'podman' : o.launch === 'systemd' ? 'systemd' : 'detached',user: o.user,systemdRun: o.systemdRun ?? systemdRunPrefix(os.totalmem()),path: o.path,group,+ inside: podman ? o.terminal : undefined,+ });+ const inSandbox = podman ? o.files : undefined;+ const files = createWorkspaceFiles({+ dir: path.join(dir, 'files'), stateDir: o.stateDir, user,+ // On a podman host nothing reads a workspace outside a container: a workspace without a sandbox is an error, not the host's turn.+ place: inSandbox && ((ws) => {+ if (!ws.sandbox) throw new Error(`session ${ws.sessionId} has no sandbox`);+ return inSandbox(ws.sandbox);+ }),});- const files = createWorkspaceFiles({ dir: path.join(dir, 'files'), stateDir: o.stateDir, user: o.user });return serveWireLink(hooks, { dir, group, terminals, files });};}diff --git a/computer/src/host/checked-socket.test.ts b/computer/src/host/checked-socket.test.tsnew file mode 100644index 00000000..c668c9a1--- /dev/null+++ b/computer/src/host/checked-socket.test.ts@@ -0,0 +1,96 @@+import net from 'node:net';+import { mkdtempSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { connectChecked, pinSocket } from './checked-socket.js';+import { checkedDial, remotePort } from './remote-port.js';+import { dialSocket } from './runner-sockets.js';++const servers: net.Server[] = [];+const dir = () => mkdtempSync(path.join(tmpdir(), 'checked-'));+const serve = (p: string, says: string) =>+ new Promise<void>((r) => servers.push(net.createServer((c) => void c.on('error', () => {}).end(says)).listen(p, r)));+const read = (s: net.Socket) =>+ new Promise<string>((resolve, reject) => {+ let out = '';+ s.on('data', (b) => (out += b)).on('end', () => resolve(out)).on('error', reject);+ });+afterEach(() => {+ for (const s of servers.splice(0)) s.close();+});++const linux = process.platform === 'linux';++describe('connectChecked', () => {+ it('connects to a socket', async () => {+ const p = path.join(dir(), 'a.sock');+ await serve(p, 'a');+ expect(await read(connectChecked(p, { uid: process.getuid!() }))).toBe('a');+ });++ it('refuses a link to a socket, a file, and a socket of another user; nothing there is ENOENT', async () => {+ const d = dir();+ await serve(path.join(d, 'a.sock'), 'a');+ symlinkSync(path.join(d, 'a.sock'), path.join(d, 'link.sock'));+ writeFileSync(path.join(d, 'file.sock'), '');+ expect(() => connectChecked(path.join(d, 'link.sock'))).toThrow(/not a socket/);+ expect(() => connectChecked(path.join(d, 'file.sock'))).toThrow(/not a socket/);+ expect(() => connectChecked(path.join(d, 'a.sock'), { uid: process.getuid!() + 1 })).toThrow(/owned by uid/);+ expect(() => connectChecked(path.join(d, 'none.sock'))).toThrow(/ENOENT/);+ });++ it.runIf(linux)('connects to what it checked, whatever the path holds a moment later', async () => {+ const d = dir();+ const a = path.join(d, 'a.sock');+ await serve(a, 'checked');+ await serve(path.join(d, 'other.sock'), 'swapped in');+ const pin = pinSocket(a);+ // The session swaps the path for a link to another socket between the check and the connect.+ symlinkSync(path.join(d, 'other.sock'), path.join(d, 'l'));+ renameSync(path.join(d, 'l'), a);+ expect(await read(net.connect(a))).toBe('swapped in'); // what lstat-then-connect would reach+ expect(await read(net.connect(pin.path))).toBe('checked');+ pin.close();+ pin.close(); // twice is once+ });++ it.runIf(linux)('holds no file descriptor once connected or refused', async () => {+ const d = dir();+ const p = path.join(d, 'a.sock');+ await serve(p, 'a');+ const fds = () => readdirSync('/proc/self/fd').length as number;+ const before = fds();+ for (let i = 0; i < 20; i++) await read(connectChecked(p));+ rmSync(p); // nobody listens at the pinned inode's path any more; the next pin is ENOENT+ expect(() => connectChecked(p)).toThrow(/ENOENT/);+ expect(fds()).toBeLessThanOrEqual(before + 1);+ });+});++describe('the dials built on it', () => {+ const planted = async () => {+ const d = dir();+ await serve(path.join(d, 'real.sock'), '{"t":"hello"}\n');+ symlinkSync(path.join(d, 'real.sock'), path.join(d, 'link.sock'));+ return d;+ };++ it("dialSocket: a runner's socket, never a link a session put in its place, never another user's", async () => {+ const d = await planted();+ const s = await dialSocket(path.join(d, 'real.sock'), { uid: process.getuid!() });+ expect(s).toBeDefined();+ s!.destroy();+ expect(await dialSocket(path.join(d, 'link.sock'))).toBeUndefined();+ expect(await dialSocket(path.join(d, 'real.sock'), { uid: process.getuid!() + 1 })).toBeUndefined();+ expect(await dialSocket(path.join(d, 'none.sock'))).toBeUndefined();+ });++ it("a runner's API socket is dialled the same way, by default", async () => {+ const d = await planted();+ await expect(checkedDial()(path.join(d, 'link.sock'), 'token')).rejects.toThrow(/not a socket/);+ const port = remotePort(path.join(d, 'link.sock'), 'token', { dialMs: 0 });+ await expect(port.call('sessions.get', {}, {} as never)).rejects.toThrow(/not a socket/);+ port.close();+ });+});diff --git a/computer/src/host/checked-socket.ts b/computer/src/host/checked-socket.tsnew file mode 100644index 00000000..2c6dae89--- /dev/null+++ b/computer/src/host/checked-socket.ts@@ -0,0 +1,72 @@+// Connecting to a unix socket in a directory a session can write (work 103,+// trust rule 4): `<run>/runners/<id>.sock` and `<id>.api.sock`. The session+// decides what is at such a path, and may change it at any moment.+//+// Invariants:+// - The host connects to exactly the thing it checked. On Linux the path is+// opened once (`O_PATH | O_NOFOLLOW`: never through a link in its last+// component, nothing is read or connected by the open), the open file is+// checked (`fstat`), and the connection goes to that open file through+// `/proc/self/fd/<n>`. Replacing the path after the check changes nothing.+// - It must be a socket and, when the caller names one, owned by that user.+// - Elsewhere (a laptop: no `O_PATH`, no `/proc`) it is `lstat`, then connect,+// which a session could race; no sandbox runs there.+//+// What this does not do: tell one session's socket from another's (both are+// the runners' user's). That is the directory's work: a run directory is+// mounted into its own container only.++import net from 'node:net';+import { closeSync, constants, fstatSync, lstatSync, openSync } from 'node:fs';++/** Linux's O_PATH, which node:fs does not name. */+const O_PATH = 0o10000000;++export interface SocketCheck {+ /** The user the socket must belong to. */+ uid?: number;+}++export interface Pinned {+ /** Where to connect: the checked file itself, whatever its path holds by now. */+ path: string;+ /** Release it, once connected or given up. */+ close(): void;+}++const refuse = (path: string, why: string) => Object.assign(new Error(`${path}: ${why}`), { code: 'ECONNREFUSED' });++/** Check the socket at `path` and hold on to it. Throws when nothing is there (`ENOENT`) or it is not that (`ECONNREFUSED`). */+export function pinSocket(path: string, o: SocketCheck = {}, platform = process.platform): Pinned {+ if (platform !== 'linux') {+ const st = lstatSync(path);+ if (!st.isSocket()) throw refuse(path, 'not a socket');+ if (o.uid !== undefined && st.uid !== o.uid) throw refuse(path, `owned by uid ${st.uid}, not ${o.uid}`);+ return { path, close: () => {} };+ }+ const fd = openSync(path, O_PATH | constants.O_NOFOLLOW);+ try {+ const st = fstatSync(fd);+ if (!st.isSocket()) throw refuse(path, 'not a socket');+ if (o.uid !== undefined && st.uid !== o.uid) throw refuse(path, `owned by uid ${st.uid}, not ${o.uid}`);+ } catch (e) {+ closeSync(fd);+ throw e;+ }+ let open = true;+ return { path: `/proc/self/fd/${fd}`, close: () => void (open && ((open = false), closeSync(fd))) };+}++/** `net.connect(path)` to a checked socket. Throws as `pinSocket` does; a refused connection is the socket's `error`. */+export function connectChecked(path: string, o: SocketCheck = {}): net.Socket {+ const pin = pinSocket(path, o);+ let sock: net.Socket;+ try {+ sock = net.connect(pin.path);+ } catch (e) {+ pin.close();+ throw e;+ }+ for (const ev of ['connect', 'error', 'close'] as const) sock.once(ev, pin.close);+ return sock;+}diff --git a/computer/src/host/claim.test.ts b/computer/src/host/claim.test.tsindex c81e9c04..7989b498 100644--- a/computer/src/host/claim.test.ts+++ b/computer/src/host/claim.test.ts@@ -8,7 +8,7 @@ describe('claimSpare', () => {log,s: {take: o.take ?? (() => 'spare' as string),- fork: o.fork ?? (async () => (log.push('fork'), '/fork')),+ fork: o.fork ?? (async (r: string) => (log.push(`fork for ${r}`), '/fork')),claim: o.claim ?? (async () => void log.push('claim')),discard: (r: string) => void log.push(`discard ${r}`),release: (r: string) => void log.push(`release ${r}`),@@ -19,7 +19,7 @@ describe('claimSpare', () => {it('forks, then claims the spare into the fork', async () => {const { s, log } = steps();expect(await claimSpare(s)).toEqual({ runner: 'spare', forkPath: '/fork' });- expect(log).toEqual(['fork', 'claim']);+ expect(log).toEqual(['fork for spare', 'claim']);});it('no spare: misses without forking (the cold start forks alongside the launch)', async () => {@@ -31,7 +31,7 @@ describe('claimSpare', () => {it('a refused or unanswered claim discards the spare and keeps the fork for the cold start', async () => {const refused = steps({ claim: () => Promise.reject(new Error('claim refused: option x')) });expect(await claimSpare(refused.s)).toEqual({ missed: 'refused', forkPath: '/fork' });- expect(refused.log).toEqual(['fork', 'discard spare']);+ expect(refused.log).toEqual(['fork for spare', 'discard spare']);const slow = steps({ claim: () => Promise.reject(new Error('runner did not answer claim')) });expect(await claimSpare(slow.s)).toEqual({ missed: 'timeout', forkPath: '/fork' });const dead = steps({ claim: () => Promise.reject(new Error('runner gone')) });diff --git a/computer/src/host/claim.ts b/computer/src/host/claim.tsindex 32297f0d..923c2692 100644--- a/computer/src/host/claim.ts+++ b/computer/src/host/claim.ts@@ -7,7 +7,9 @@// Claude Code reads the fork's AGENTS.md and skills when claimed. A spare that// refused or did not answer is discarded, never offered again: it may have// claimed late, so it is not known to be parked. One whose fork failed was-// never spoken to, so it goes back to the pool.+// never spoken to, so it goes back to the pool; a host that passes no+// `release` (a `podman` one, whose fork step mounts a person's files into the+// spare) discards it instead.import type { MissReason } from './pool.js';@@ -16,8 +18,8 @@ export type ClaimMiss = MissReason | 'refused' | 'timeout' | 'gone';export interface ClaimSteps<R> {/** A parked spare, now ours; else why there is none. */take: () => R | MissReason;- /** Make the session's fork; resolves with its path. */- fork: () => Promise<string>;+ /** Make the session's fork; resolves with its path. A container host makes the spare itself the thread's here (work 103). */+ fork: (r: R) => Promise<string>;/** Claim the spare into the fork; rejects if it refused or did not answer in time. */claim: (r: R, forkPath: string) => Promise<void>;/** Tell a spare that was not claimed to exit. */@@ -38,7 +40,7 @@ export async function claimSpare<R>(s: ClaimSteps<R>): Promise<ClaimOutcome<R>>const r = taken as R;let forkPath: string;try {- forkPath = await s.fork();+ forkPath = await s.fork(r);} catch (e) {(s.release ?? s.discard)(r);throw e;diff --git a/computer/src/host/cold-start.test.ts b/computer/src/host/cold-start.test.tsindex 5175afb8..add06549 100644--- a/computer/src/host/cold-start.test.ts+++ b/computer/src/host/cold-start.test.ts@@ -5,50 +5,63 @@ const later = <T>(ms: number, v: T, log?: string[], what?: string) =>new Promise<T>((r) => setTimeout(() => (what && log?.push(what), r(v)), ms));describe('coldStart', () => {- it('starts the runner while forking and resolves only once both are done', async () => {+ it('brings the runner up, then prepares the fork while waiting for the socket', async () => {const log: string[] = [];const r = await coldStart({- dir: '/f',- fork: () => (log.push('fork start'), later(60, '/f', log, 'fork done')),- start: (dir) => (log.push(`start ${dir}`), later(20, 'runner', log, 'runner up')),- abandon: () => log.push('abandon'),+ up: () => later(5, undefined, log, 'up'),+ prepare: () => (log.push('prepare start'), later(60, undefined, log, 'prepared')),+ ready: () => (log.push('ready start'), later(20, 'runner', log, 'runner up')),+ abandon: async () => void log.push('abandon'),});- expect(r).toEqual({ ready: 'runner', forkPath: '/f' });- // 'runner up' before 'fork done' is the concurrency: sequential, the runner- // couldn't start before the fork finished. (A wall-clock bound flaked on CI.)- expect(log).toEqual(['fork start', 'start /f', 'runner up', 'fork done']);+ expect(r).toBe('runner');+ // 'runner up' before 'prepared' is the concurrency. (A wall-clock bound flaked on CI.)+ expect(log).toEqual(['up', 'ready start', 'prepare start', 'runner up', 'prepared']);});- it('forks first when the directory is not known up front (laptop)', async () => {+ it('only waits for the socket when the fork exists already', async () => {+ expect(await coldStart({ up: async () => {}, ready: async () => 1, abandon: async () => {} })).toBe(1);+ });++ it('a failed `up` fails the start; nothing else runs', async () => {const log: string[] = [];- const r = await coldStart({- fork: () => later(5, '/w', log, 'fork done'),- start: (dir) => (log.push(`start ${dir}`), later(5, 1)),- abandon: () => log.push('abandon'),- });- expect(r).toEqual({ ready: 1, forkPath: '/w' });- expect(log).toEqual(['fork done', 'start /w']);+ await expect(coldStart({+ up: () => Promise.reject(new Error('create')),+ prepare: async () => void log.push('prepare'),+ ready: async () => void log.push('ready'),+ abandon: async () => void log.push('abandon'),+ })).rejects.toThrow('create');+ expect(log).toEqual([]);});- it('only starts when the fork exists already', async () => {- const r = await coldStart({ dir: '/f', start: async (dir) => dir, abandon: () => {} });- expect(r).toEqual({ ready: '/f', forkPath: '/f' });+ it('a failed fork abandons the runner and fails the start', async () => {+ const log: string[] = [];+ await expect(coldStart({+ up: async () => {},+ prepare: () => Promise.reject(new Error('worktree')),+ ready: () => later(5, 'runner'),+ abandon: async () => void log.push('abandon'),+ })).rejects.toThrow('worktree');+ expect(log).toEqual(['abandon']);});- it('a failed fork abandons a runner that came up, and fails the start', async () => {- const abandoned: string[] = [];- await expect(- coldStart({ dir: '/f', fork: () => Promise.reject(new Error('worktree')), start: () => later(5, 'runner'), abandon: (r) => abandoned.push(r) }),- ).rejects.toThrow('worktree');- expect(abandoned).toEqual(['runner']);+ it('a runner that never answers abandons and fails the start', async () => {+ const log: string[] = [];+ await expect(coldStart({+ up: async () => {},+ prepare: () => later(20, undefined, log, 'prepared'),+ ready: () => Promise.reject(new Error('not ready')),+ abandon: async () => void log.push('abandon'),+ })).rejects.toThrow('not ready');+ expect(log).toEqual(['abandon']);});- it('a failed launch fails the start after the fork settles', async () => {- let forked = false;- await expect(- coldStart({ dir: '/f', fork: () => later(10, '/f').then((v) => ((forked = true), v)), start: () => Promise.reject(new Error('launch')), abandon: () => {} }),- ).rejects.toThrow('launch');- expect(forked).toBe(true);+ it('rethrows the first failure, also when abandoning fails', async () => {+ await expect(coldStart({+ up: async () => {},+ prepare: () => later(5, undefined).then(() => Promise.reject(new Error('first'))),+ ready: () => later(30, undefined).then(() => Promise.reject(new Error('second'))),+ abandon: () => Promise.reject(new Error('stop failed')),+ })).rejects.toThrow('first');});});diff --git a/computer/src/host/cold-start.ts b/computer/src/host/cold-start.tsindex 5a37c9ac..ca2146c7 100644--- a/computer/src/host/cold-start.ts+++ b/computer/src/host/cold-start.ts@@ -1,6 +1,6 @@-// A runner's cold start on the host: the session's fork and the runner's-// launch, concurrently when the fork's directory is known up front, then the-// first connection to the runner's socket.+// A runner's cold start on the host, one orchestration for both launch modes+// (work 103): bring the runner's process up, then make the session's fork and+// wait for the runner's socket together.//// Invariant: the fork is complete (every worktree added, .fork.json written)// before `coldStart` resolves, and the host hands the runner its socket@@ -8,8 +8,8 @@// that (host/start-runner.ts `adopt`). The runner process itself may boot inside the// still-empty fork directory: until it has credentials it only listens on its// socket and never reads its cwd, so Claude Code never starts, nor sees the-// fork, before the worktrees exist. If the fork fails, a runner that already-// came up is told to go (`abandon`) and the start fails as before.+// fork, before the worktrees exist. If either step fails, the runner is made+// to go (`abandon`) and the start fails with the first failure.import type { SessionSpec } from '../protocol.js';import type { Telemetry } from '../telemetry/emitter.js';@@ -45,37 +45,25 @@ export async function pollReady<T>(dial: () => Promise<T | undefined>, intervalM}}-export interface ColdStartSteps<T> {- /** The fork's directory when it is known before forking (a workspace fork); the runner launches in it right away. */- dir?: string;- /** Creates (or completes) the fork and returns its path; absent when the fork already exists at `dir`. */- fork?: () => Promise<string>;- /** Starts the runner in `dir` and resolves once it answers on its socket. */- start: (dir: string) => Promise<T>;- /** The fork failed after the runner came up: make it go. */- abandon: (ready: T) => void;+export interface StartSteps<T> {+ /** Bring the runner's process up: launch it (detached), or create/start/mount its container. */+ up: () => Promise<void>;+ /** Make the fork's content; absent when it exists (a resume). */+ prepare?: () => Promise<void>;+ /** Resolves once the runner answers on its socket. */+ ready: () => Promise<T>;+ /** A step failed after `up`: make it go. */+ abandon: () => Promise<void>;}-/** Fork and start the runner, concurrently when `dir` is known; resolves once both are done. */-export async function coldStart<T>(s: ColdStartSteps<T>): Promise<{ ready: T; forkPath: string }> {- if (!s.fork) {- if (s.dir === undefined) throw new Error('cold start without a fork or its directory');- return { ready: await s.start(s.dir), forkPath: s.dir };- }- if (s.dir === undefined) {- const forkPath = await s.fork();- return { ready: await s.start(forkPath), forkPath };- }- const [forked, started] = await Promise.allSettled([s.fork(), s.start(s.dir)]);- if (forked.status === 'rejected') {- if (started.status === 'fulfilled') s.abandon(started.value);- throw forked.reason;- }- if (started.status === 'rejected') throw started.reason;- if (forked.value !== s.dir) {- // Never expected (the fork lands where forkDir says); the runner's cwd would be wrong.- s.abandon(started.value);- throw new Error(`fork landed at ${forked.value}, runner started in ${s.dir}`);+/** `up`, then `prepare` and `ready` together; any rejection abandons and rethrows the first. */+export async function coldStart<T>(s: StartSteps<T>): Promise<T> {+ await s.up(); // a failed `up` leaves nothing behind itself+ try {+ const [ready] = await Promise.all([s.ready(), s.prepare?.()]);+ return ready;+ } catch (e) {+ await s.abandon().catch(() => {}); // the first failure is the one to report+ throw e;}- return { ready: started.value, forkPath: forked.value };}diff --git a/computer/src/host/launch.test.ts b/computer/src/host/launch.test.tsindex 20fece27..25777b8a 100644--- a/computer/src/host/launch.test.ts+++ b/computer/src/host/launch.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { launchCommand, runnerCommand } from './launch.js';+import { launchCommand, runnerCommand, unitFailure } from './launch.js';import { RUNNER_ENV, dropEmpty } from '../runner-env.js';describe('runnerCommand', () => {@@ -54,6 +54,35 @@ describe('launchCommand', () => {});});+describe('launchCommand, podman', () => {+ const rs = { id: 'ab12', socket: '/run/x/runners/ab12.sock', version: 'v' } as never;+ const env = { SP_RUNNER_USER: 'root', SP_SYSTEMD_RUN: 'systemd-run --user --slice=s.slice' };+ const yes = () => true;++ it('starts the container attached, in a unit named by the runner, with no environment and no directory', () => {+ const c = launchCommand(rs, 'podman', env, '/r', yes);+ expect(c.detached).toBe(false);+ expect(c.cmd).toBe('/usr/bin/sudo');+ const at = c.args.indexOf('--');+ expect(c.args.slice(0, at).slice(0, 3)).toEqual(['-n', '-u', 'root']);+ expect(c.args.slice(at + 1)).toEqual([+ 'systemd-run', '--user', '--slice=s.slice',+ '-p', 'Delegate=yes', '-p', 'KillMode=mixed', '-p', 'TimeoutStopSec=20', '-p', 'StandardOutput=null', '-p', 'StandardError=journal',+ '--unit=sp-runner-ab12', '--collect', '--quiet',+ '--', '/usr/bin/podman', 'start', '--attach', 'sp-runner-ab12',+ ]);+ expect(c.args.some((a) => /^--setenv|^--working-directory/.test(a))).toBe(false);+ });++ it('throws without the bundle: a container has no tsx fallback', () => {+ expect(() => launchCommand(rs, 'podman', env, '/r', () => false)).toThrow('/r/dist/runner-boot.mjs');+ });++ it('throws without a runner user, naming what sets one up', () => {+ expect(() => launchCommand(rs, 'podman', { SP_SYSTEMD_RUN: 'systemd-run --user' }, '/r', yes)).toThrow('sp-host.sh');+ });+});+describe('dropEmpty', () => {it('unsets runner variables the host set empty, and only those', () => {const env: NodeJS.ProcessEnv = { SP_CODEX_BIN: '', SP_COMPACT_AT: '0.8', OTHER: '' };@@ -61,3 +90,12 @@ describe('dropEmpty', () => {expect(env).toEqual({ SP_COMPACT_AT: '0.8', OTHER: '' });});});++describe('unitFailure', () => {+ it('says the time only when the time ran out, else what systemd-run said last', () => {+ expect(unitFailure({ timedOut: true, stderr: '' }, 20_000)).toBe('no answer in 20000 ms');+ expect(unitFailure({ timedOut: false, stderr: 'a\nFailed to start transient service unit: no\n', code: 1 }, 20_000)).toBe('Failed to start transient service unit: no');+ expect(unitFailure({ timedOut: false, stderr: '', code: 3 }, 20_000)).toBe('exit 3');+ expect(unitFailure({ timedOut: false, stderr: '' }, 20_000)).toBe('exit by a signal');+ });+});diff --git a/computer/src/host/launch.ts b/computer/src/host/launch.tsindex d3785d48..e0234e86 100644--- a/computer/src/host/launch.ts+++ b/computer/src/host/launch.ts@@ -1,11 +1,15 @@// How the host starts a runner outside its own process tree: a transient-// systemd user unit on Linux, a detached process elsewhere. The one place to+// systemd user unit on Linux (the runner itself, or `podman start --attach`+// of its container, work 103), a detached process elsewhere. The one place to// change how runners are launched.//// Invariants: a runner gets RUNNER_SPEC and every variable in RUNNER_ENV// (runner-env.ts), each set even when empty, never credentials (those go over// its socket); a systemd unit also inherits the user manager's environment,-// which sessions can change, so nothing a runner reads is left to it.+// which sessions can change, so nothing a runner reads is left to it. A+// container's unit carries no environment at all: the container's is fixed at+// its creation and by boot.env (sandbox/boot-env.ts). A `podman` launch never+// falls back to anything else: without the bundle or the runners' user it throws.import os from 'node:os';import path from 'node:path';@@ -18,14 +22,28 @@ import { definitionFile } from '../workspaces/index.js';import { systemdRunPrefix } from './runner-limits.js';import { runnerUser } from './runner-user.js';import { runnerVars } from '../runner-env.js';+import { PODMAN, type PodmanError, runBounded } from './sandbox/podman.js';+import { startArgs, unitName } from './sandbox/podman-args.js';-export type LaunchMode = 'systemd' | 'detached';+export type LaunchMode = 'systemd' | 'podman' | 'detached';const SYSTEMD_RUN = systemdRunPrefix(os.totalmem());const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));/** The command that starts a runner from the release at `root`. */-export function launchCommand(rs: RunnerSpec, how: LaunchMode | string, env: NodeJS.ProcessEnv, root: string) {+export function launchCommand(rs: RunnerSpec, how: LaunchMode | string, env: NodeJS.ProcessEnv, root: string, has: (p: string) => boolean = existsSync) {+ if (how === 'podman') {+ // The container exists already (sandbox/containers.ts); its unit only holds `podman start --attach`.+ const as = runnerUser(env);+ if (!as) throw new Error('podman launch: no runner user (SP_RUNNER_USER); deploy/vm/sp-host.sh sets one up');+ const boot = path.join(root, 'dist/runner-boot.mjs');+ if (!has(boot)) throw new Error(`podman launch: ${boot} is absent, and a container has no tsx fallback`);+ if (!rs.id) throw new Error('podman launch: a runner without an id');+ const [cmd, ...pre] = [...as.sudo, '--', ...(env.SP_SYSTEMD_RUN || SYSTEMD_RUN).trim().split(/\s+/)];+ const args = [...pre, '-p', 'Delegate=yes', '-p', 'KillMode=mixed', '-p', 'TimeoutStopSec=20', '-p', 'StandardOutput=null', '-p', 'StandardError=journal',+ `--unit=${unitName(rs.id).replace(/\.service$/, '')}`, '--collect', '--quiet', '--', PODMAN, ...startArgs(rs.id)];+ return { cmd, args, env: env as Record<string, string>, detached: false };+ }// Every RUNNER_ENV variable, set even when empty: a systemd unit would otherwise take the user manager's, which sessions can change (runner-env.ts).const vars: Record<string, string> = { ...runnerVars(env), RUNNER_SPEC: JSON.stringify(rs), SP_RUN: HOST_RUN };// Linux sets no TMPDIR, and the system prompt points scratch work at $TMPDIR: an empty one@@ -68,18 +86,33 @@ export function runnerCommand(root: string, has: (p: string) => boolean = exists/** The session's fork; a spare (work 069) has none yet and parks its Claude Code elsewhere. */const workingDirectory = (rs: RunnerSpec, env: NodeJS.ProcessEnv) => rs.session?.forkPath ?? env.HOME ?? os.homedir();-/** Start the runner; resolves once it was spawned (not yet listening). */-export async function launch(rs: RunnerSpec, how: LaunchMode | string, env: NodeJS.ProcessEnv, root: string) {+/** Why a container's unit did not start, in a few words: the time it had, or the last thing systemd-run said. */+export const unitFailure = (e: Partial<PodmanError>, timeoutMs: number) =>+ e.timedOut ? `no answer in ${timeoutMs} ms` : String(e.stderr ?? '').trim().split('\n').pop() || `exit ${e.code ?? 'by a signal'}`;++/** Start the runner; resolves once it was spawned (not yet listening). `timeoutMs` bounds each try of a unit's start. */+export async function launch(rs: RunnerSpec, how: LaunchMode | string, env: NodeJS.ProcessEnv, root: string, timeoutMs?: number) {const c = launchCommand(rs, how, env, root);if (!c.detached) {- // A unit named by session (no runner id) may still be held by a runner that just quit.+ // A unit's name repeats (a session's before work 069, a thread's container since work 103): one may still be held by a runner that just quit.+ // cwd: the runners' user cannot enter every directory the host runs in, and sudo keeps it.+ // A container's unit starts under timeout(1) as the runners' user: a signal to sudo would not end systemd-run (sandbox/podman.ts).+ const at = c.args.indexOf('--');+ const start = how === 'podman'+ ? () => runBounded([c.cmd, ...c.args.slice(0, at)], c.args.slice(at + 1), { timeoutMs: timeoutMs ?? 20_000 })+ : () => promisify(execFile)(c.cmd, c.args, { env: c.env, cwd: '/' });for (let i = 0; ; i++)try {- await promisify(execFile)(c.cmd, c.args, { env: c.env });+ await start();return;} catch (e: any) {- if (i >= 10 || !/already/.test(String(e?.stderr ?? e?.message))) throw e;- await sleep(300);+ if (i < 10 && /already/.test(String(e?.stderr ?? e?.message))) {+ await sleep(300);+ continue;+ }+ // execFile's own message is the whole command line; a container's start says why instead (it reaches the gateway's reply).+ if (how !== 'podman') throw e;+ throw new Error(`unit ${unitName(rs.id!)} did not start: ${unitFailure(e, timeoutMs ?? 20_000)}`);}}// Own session and process group, output to a log file: survives the host.@@ -92,14 +125,15 @@ export async function launch(rs: RunnerSpec, how: LaunchMode | string, env: Node/*** Whether runner `id`'s systemd unit still exists (work 097: the model proxy's- * binding for a caller whose unit is gone is released). Detached runners have- * no unit, and any doubt (systemctl failing) answers true: a binding is never- * released on a guess.+ * binding for a caller whose unit is gone is released). A container's unit has+ * its runner's name too (work 103), and is gone while the container is stopped.+ * Detached runners have no unit, and any doubt (systemctl failing) answers+ * true: a binding is never released on a guess.*/export async function unitExists(id: string, how: LaunchMode | string, env: NodeJS.ProcessEnv): Promise<boolean> {- if (how !== 'systemd') return true;+ if (how !== 'systemd' && how !== 'podman') return true;const as = runnerUser(env);- const [cmd, ...args] = [...(as?.sudo ?? []), 'systemctl', '--user', 'show', '-p', 'LoadState', '--value', `sp-runner-${id}.service`];+ const [cmd, ...args] = [...(as?.sudo ?? []), 'systemctl', '--user', 'show', '-p', 'LoadState', '--value', unitName(id)];try {const { stdout } = await promisify(execFile)(cmd, args, { env: { ...env, ...as?.env } as NodeJS.ProcessEnv });return stdout.trim() !== 'not-found';diff --git a/computer/src/host/main.ts b/computer/src/host/main.tsindex 7bffaeec..40b3a74c 100644--- a/computer/src/host/main.ts+++ b/computer/src/host/main.ts@@ -1,15 +1,21 @@// Host agent (work 045): one per machine. Dials the gateway over one// WebSocket, forks sessions, starts runners outside its own process tree,-// forwards deliveries, relays GitHub tokens, and finds its runners again by-// their sockets after a restart. Restarting it never ends a turn.+// forwards deliveries, relays GitHub tokens, and finds its runners again+// after a restart: by their sockets, or on a `podman` host from its records+// and Podman's inventory (sandbox/sweep.ts). Restarting it never ends a turn.//// SP_GATEWAY_URL=ws://…/host SP_HOST_TOKEN=… [SP_HOST_ID] [SP_DATA] [SP_RUN]// [SP_DEFINITION] workspace definition: fork with src/workspaces (VM); unset: ensureWorkdir (laptop).// A definition in the gateway's welcome replaces it (<SP_DATA>/definition.json).// [SP_IDLE_MS=7200000] tell a runner to exit after this long without deliveries-// [SP_LAUNCH=systemd|detached] default systemd on Linux, detached elsewhere+// [SP_LAUNCH=systemd|podman|detached] default systemd on Linux, detached elsewhere. podman (work 103): every+// thread in its own container (sandbox/), spares too; needs SP_RUNNER_USER+// [SP_IMAGE] [SP_IMAGE_ABI] the session image and its ABI, from the release's .sp-version.env; required by podman+// [SP_SWEEP_AGE_MS=600000] podman: how old a container, home or run directory of no thread must be before the+// sweep removes it (sandbox/sweep.ts); the sweep runs every half of it, at most every 5 minutes// [SP_SYSTEMD_RUN="systemd-run --user --slice=slack-presence-runners.slice -p MemoryHigh=12G -p MemoryMax=16G"]-// prefix for the transient unit (--unit, --collect, --setenv are added); the+// prefix for the transient unit (--unit, --collect, --setenv are added; a container's+// unit gets no --setenv); the// default sizes MemoryHigh/MemoryMax from the machine (runner-limits.ts)// [SP_POOL_SIZE=2] spare runners kept parked for new sessions (work 069, pool.ts); 0: off// [SP_VERSION] code version (the release's commit); else `git rev-parse`@@ -17,7 +23,7 @@// [SP_TELEMETRY_CREDENTIAL] the collector credential the gateway signed for this host; a `welcome` renews it// [SP_REGION] [SP_SUBSTRATE] telemetry dimensions (`westus2`, `vm`)// SP_MODEL_PROXY the model proxy's control socket (work 097, model-access.ts); unset: the proxy is down, no session starts-// [SP_MODEL_SOCKET=/run/oc-modelproxy/api.sock] where runners reach the proxy's API (sent to them, C4)+// [SP_MODEL_SOCKET=/run/oc-modelproxy/api.sock] where runners reach the proxy's API (sent to them, C4); a container mounts it// [SP_RUNNER_USER=agent] run runners as this user, through sudo (work 077, runner-user.ts); the host then runs as another// [SP_RUNNER_PATH=...] the PATH runners and workspace commands get then (the host's own has no agent-owned directory)// node --import tsx src/host/main.ts@@ -36,7 +42,7 @@ import type net from 'node:net';import os from 'node:os';import path from 'node:path';import { mkdirSync } from 'node:fs';-import { HOST_DATA, HOST_RUN, HOST_TOKEN_SOCKET, PROTOCOL_VERSION } from '../protocol.js';+import { HOST_DATA, HOST_RUN, HOST_TOKEN_SOCKET, MODEL_SOCKET, PROTOCOL_VERSION } from '../protocol.js';import { codexBin } from '../runner-env.js';import { prereadCodex } from './codex-preread.js';import type {@@ -66,6 +72,7 @@ import {import { send, socketFor } from '../ipc.js';import { log } from '../log.js';import { closed, rediscover, retire } from './runner-sockets.js';+import { checkedDial } from './remote-port.js';import { type Runner, runnerStarts } from './start-runner.js';import { Pool } from './pool.js';import { freshTokenDir, tokenRelay } from './tokens.js';@@ -83,6 +90,7 @@ import { gatewayUpdates } from './gateway-updates.js';import { callRunner as call } from './runner-call.js';import { apiHost, type StartOptions } from './api-host.js';import { wireFor } from './api-wire.js';+import { sandboxHost, sandboxWorkspace } from './sandbox/host.js';const env = process.env;const IDENTITY_FILE = identityFile(HOST_DATA);@@ -111,7 +119,7 @@ observeWorkspaces(workspaceTelemetry(tm, () => forkContext.getStore()));/** The organization's credentials and people, as the gateway last sent them. */const org = gatewayUpdates({ runners: () => runners.values(), spares: () => pool.spares, forRunner: (key, c) => subs.forRunner(key, c),fillPool: () => fillPool(), prepare: (p) => workspacesEnabled() && prepareInBackground(p) });-const subs = hostModelAccess({ controlSocket: env.SP_MODEL_PROXY || undefined, modelSocket: env.SP_MODEL_SOCKET || undefined, single: LAUNCH !== 'systemd',+const subs = hostModelAccess({ controlSocket: env.SP_MODEL_PROXY || undefined, modelSocket: env.SP_MODEL_SOCKET || undefined, single: LAUNCH !== 'systemd' && LAUNCH !== 'podman',toGateway, tm, runner: (key) => runners.get(key), creds: () => org.creds, exit: switchRunner, unitExists: (id) => unitExists(id, LAUNCH, env),rehello: () => link.redial(), codexBin: codexBin(env) });@@ -125,7 +133,7 @@ const pool = new Pool<Runner>({failed: () => tm.emit('pool.spare_failed', {}),evict: (r, reason) => {tm.emit('pool.spare_evicted', { data: { reason } });- exitRunner(r.sock);+ starts.evict(r);},});/** Every connected runner: the sessions' and the spares. */@@ -139,20 +147,31 @@ function exitRunner(sock: net.Socket) {function switchRunner(key: string, r = runners.get(key)) {if (r) (r.switching = true), r.report?.status === 'busy' ? send(r.sock, { t: 'exit' } satisfies HostToRunner) : exitRunner(r.sock);}-/** Its session's epoch moved on (api-host `epoch`): end its turn now, then exit; killed after 10 s. */+/** Its session's epoch moved on (api-host `epoch`): end its turn now, then exit; killed after 10 s (a container: stopped with no grace). */const retireRunner = async (id: string, r = [...runners.values()].find((x) => x.id === id)) =>- r && ((r.exiting = true), retire(r.sock, socketFor(HOST_RUN, r.id), () => void call(r, { t: 'stop' }, 10_000).catch(() => {})));+ r && ((r.exiting = true), retire(r.sock, socketFor(r.sandbox?.run ?? HOST_RUN, r.id), () => void call(r, { t: 'stop' }, 10_000).catch(() => {}),+ { kill: r.sandbox && (() => sandbox!.stop(r.id, 0)) }));/** spawn, secret and thread requests in flight to the gateway, by id: the runner that asked. */const spawning = new Map<string, Runner>();const starting = new Map<string, Promise<Runner>>();/** Set on SIGTERM: runner sockets closing then are the host leaving, not the runners. */let stopping = false;+/** Work 103: on a `podman` host every thread runs in its own container (sandbox/host.ts); `api` and `tokens` below are there by a start. */+const sandbox = LAUNCH === 'podman'+ ? sandboxHost({ env, run: HOST_RUN, data: HOST_DATA, root: ROOT, version: VERSION, tm, modelSocket: env.SP_MODEL_SOCKET || MODEL_SOCKET, models: subs,+ mint: (spec, id, run) => api.mint(spec, id, run), serveTokens: (run, id, session) => tokens.serveRunner(run, id, session),+ serveHelper: (socket, allowed) => tokens.serveHelper(socket, allowed), running: (id) => allRunners().some((r) => r.id === id),+ adopt: (record, run, sock) => starts.adopt(record.id, sock, { verify: true, sandbox: { record, run } }),+ unpreview: (name, from) => previews.forget(name, from), sweepAgeMs: env.SP_SWEEP_AGE_MS ? Number(env.SP_SWEEP_AGE_MS) : undefined })+ : undefined;+/** Starting and adopting runners (start-runner.ts); what it asks for is looked up when used, so `api` and `tokens` below are there by then. */const starts = runnerStarts({tm, launch: { tm, mode: LAUNCH, env, root: ROOT }, run: HOST_RUN, version: VERSION, pool,creds: () => org.creds, models: subs,- mint: (spec, id) => api.mint(spec, id), serveTokens: (id, session) => tokens.serveRunner(HOST_RUN, id, session),+ mint: (spec, id) => api.mint(spec, id), serveTokens: (run, id, session) => tokens.serveRunner(run, id, session),+ sandbox: sandbox?.starts, spares: sandbox?.spares, image: env.SP_IMAGE, stopSandbox: (id) => sandbox!.stop(id, 0),fillPool: () => fillPool(), inFork: (f, fn) => forkContext.run(f, fn),register, closed: runnerClosed, message: onRunner, exit: exitRunner, toGateway,});@@ -172,7 +191,9 @@ function runnerClosed(r: Runner) {if (!stopping) api.down(r.id), subs.closed(r.key, r.id);if (!r.key) {pool.gone(r);- fillPool();+ // A spare that leaves a `podman` host is Removed (sandbox/spares.ts), whatever made it go; the next host removes what this one leaves.+ if (stopping) return;+ void (sandbox?.spares.gone(r.id) ?? Promise.resolve()).then(fillPool);return;}if (runners.get(r.key) !== r) return;@@ -186,6 +207,7 @@ async function onRunner(r: Runner, m: RunnerToHost) {case 'telemetry':return telemetry.relay(m.batch);case 'report':+ if (r.sandbox) m.report.forkPath = sandboxWorkspace(r.sandbox.record); // the runner says /workspace; the gateway keeps seeing host pathsr.report = m.report;// A spare reports as it is claimed, before the host has it as the session's runner (startRunner forwards it then).return runners.get(r.key) === r && toGateway({ t: 'session', report: m.report });@@ -206,15 +228,16 @@ async function onRunner(r: Runner, m: RunnerToHost) {return toGateway({ ...m, from: r.key });}case 'preview': // the host probes the port between the gateway's answer and the runner's (previews.ts)- case 'unpreview': return previews.request(r.key, m).then((a) => send(r.sock, a satisfies HostToRunner));+ case 'unpreview': return previews.request(r.key, m, r.sandbox?.record.id).then((a) => send(r.sock, a satisfies HostToRunner));case 'out-of-credits': return runners.get(r.key) === r && toGateway({ t: 'out-of-credits', sessionKey: r.key });case 'model-denied': return toGateway({ t: 'model-denied', sessionKey: r.key, model: m.model, fallbackTo: m.fallbackTo });case 'checkout': {const forkPath = r.report?.forkPath;const fail = (error: string) => send(r.sock, { t: 'checked-out', id: m.id, error } satisfies HostToRunner);if (!workspacesEnabled()) return fail('this host has no workspace definition; there is nothing to check out');- if (!forkPath) return fail('the session has not reported its fork yet');- return checkoutRepos(forkPath, m.repos).then(+ if (!r.sandbox && !forkPath) return fail('the session has not reported its fork yet');+ // A container's worktrees are added inside it, from its record (sandbox/workspace.ts); the reported path is never used.+ return (r.sandbox ? sandbox!.checkout(r.id, m.repos) : checkoutRepos(forkPath!, m.repos)).then((result) => send(r.sock, { t: 'checked-out', id: m.id, result } satisfies HostToRunner),(e) => fail(String(e?.message ?? e)),);@@ -232,7 +255,8 @@ function ensureRunner(spec: SessionSpec, f: Fields, first?: HostCredentials): Prif (live) return Promise.resolve(live);let p = starting.get(spec.key);if (!p) {- p = starts.startRunner(spec, f, first).finally(() => starting.delete(spec.key));+ // Until here nobody opens the session's journal beside the start (api-host.ts `mint`): its end, whichever, is what frees it.+ p = starts.startRunner(spec, f, first).finally(() => (starting.delete(spec.key), api.startEnded(spec)));starting.set(spec.key, p);}return p;@@ -262,9 +286,11 @@ function toGateway(m: HostToGateway) {link.send(m);}const api = apiHost({ dataDir: HOST_DATA, stateDir: path.join(HOST_DATA, 'host-api'), runDir: path.join(HOST_RUN, 'host-api'),- send: (m) => link.open && (link.send(m), true), buffered: () => link.buffered, start: startSession, retire: retireRunner, forkPath: (key) => runners.get(key)?.report?.forkPath,+ send: (m) => link.open && (link.send(m), true), buffered: () => link.buffered, start: startSession, retire: retireRunner,+ dial: LAUNCH === 'podman' ? checkedDial({ uid: runnerUser(env)?.uid }) : undefined, // a container's sockets are its user's (checked-socket.ts)+ forkPath: (key) => runners.get(key)?.report?.forkPath,wire: wireFor({ launch: LAUNCH, user: runnerUser(env), systemdRun: env.SP_SYSTEMD_RUN || undefined, path: env.SP_RUNNER_PATH,- stateDir: path.join(HOST_DATA, 'state', 'uploads') }), telemetry: tm });+ stateDir: path.join(HOST_DATA, 'state', 'uploads'), files: sandbox?.files, terminal: sandbox?.terminal }), sandbox: sandbox?.place, telemetry: tm });setInterval(() => {const disk = diskReport(HOST_DATA);if (disk) toGateway(disk);@@ -281,9 +307,9 @@ async function onGateway(m: GatewayToHost) {switch (m.t) {case 'welcome':org.welcome(m);- if (m.definition !== undefined && applyGatewayDefinition(m.definition)) housekeeper?.now();+ if (m.definition !== undefined && applyGatewayDefinition(m.definition)) (sandbox?.definitionChanged([...runners.values()].flatMap((r) => (r.sandbox ? r.id : []))), housekeeper?.now());if (m.telemetryCredential) telemetry.renew(m.telemetryCredential, m.telemetryUrl);- previews.configure(m.preview);+ (previews.configure(m.preview), previews.connected());return housekeeping();case 'previews': return previews.configure(m.preview);case 'previewed': return previews.answer(m);@@ -379,11 +405,15 @@ async function deliver(spec: SessionSpec, msg: Delivery, delivered: HostCredenti}// Ahead of the message on the same socket, so the turn starts with them.if (secrets) send(r.sock, { t: 'secrets', secrets } satisfies HostToRunner);+ // A container that started for this delivery serves no preview yet: its runner is told the ports its thread had (work 103, "Previews").+ const ports = cold && r.sandbox ? sandbox!.previews.ports.all().flatMap((e) => (e.id === r.id && e.name ? [{ port: e.port, name: e.name }] : [])) : [];+ if (ports.length) send(r.sock, { t: 'preview-ports', ports } satisfies HostToRunner);r.lastDelivery = Date.now();r.owner = spec.owner;// Retention counts from the latest use; never awaited, so delivery doesn't wait on the disk.const forkPath = r.report?.forkPath ?? spec.forkPath;- if (forkPath && workspacesEnabled()) void touchFork(forkPath);+ if (r.sandbox) sandbox!.touch(r.id); // its record is its fork record+ else if (forkPath && workspacesEnabled()) void touchFork(forkPath);const wasExiting = r.exiting;r.exiting = false;const trace = rx.trace && forwardTrace(rx.trace, cold);@@ -429,14 +459,18 @@ function housekeeping() {freshTokenDir(HOST_RUN); // no runner's token socket outlives the host that served itconst tokens = tokenRelay(link.ask, tm);-const previews = hostPreviews({ ask: link.ask });+const previews = hostPreviews({ ask: link.ask, sandbox: sandbox?.previews });// ---------------------------------------------------------------- startmkdirSync(HOST_RUN, { recursive: true });const tokenServer = tokens.serve(path.join(HOST_RUN, HOST_TOKEN_SOCKET));+const helperTokens = sandbox?.serveHelpers(); // workspace scripts in helper containers (sandbox/scripts.ts)await api.boot(); // settles the journals no runner holds (work 084); none on a host that never had a v4 gateway-api.rediscovered(await rediscover(HOST_RUN, (id, sock) => starts.adopt(id, sock, { verify: true }).then((r) => log.info('rediscovered runner', id, r.key || 'spare'))));+// A `podman` host never scans `runners/`, which its sessions' user can write: it takes back the running containers of its records.+api.rediscovered(sandbox ? await sandbox.reconcile()+ : await rediscover(HOST_RUN, (id, sock) => starts.adopt(id, sock, { verify: true }).then((r) => log.info('rediscovered runner', id, r.key || 'spare'))));+sandbox?.sweeping();log.info(`host ${identity.hostId} (${VERSION}) run=${HOST_RUN} launch=${LAUNCH} ${workspacesEnabled() ? 'workspaces' : 'laptop'} mode, ${runners.size} live runner(s), pool ${POOL_SIZE}`);link.dial();setInterval(fillPool, 30_000).unref();@@ -459,6 +493,7 @@ const emitSample = () =>since_gateway_message_s: link.seenAt ? Math.round((Date.now() - link.seenAt) / 1000) : undefined,telemetry_spooled_bytes: telemetry.spooledBytes,telemetry_dropped: telemetry.dropped,+ ...sandbox?.health(),model_proxy_down_s: subs.downS(),}) });emitSample();@@ -470,12 +505,16 @@ const shutdown = async () => {// Runners keep going; the next host finds them by their sockets.log.info('host stopping');for (const r of allRunners()) r.sock.destroy();+ // A spare's container serves nobody and no host finds it again: each is stopped and Removed, within what the unit's stop allows (15 s in all).+ const spares = sandbox && Promise.race([sandbox.spares.close(), new Promise((r) => setTimeout(r, 8000).unref())]);tokenServer.close();+ helperTokens?.close();previews.stop();subs.stop(); // tokenServer.close() unlinked the socket; the next host replaces it anywayawait api.stop();// One last send within 5 s; what is left stays in the spool for the next start.await telemetry.close(5000);+ await spares;process.exit(0);};process.on('SIGTERM', () => void shutdown());diff --git a/computer/src/host/preview-dial.test.ts b/computer/src/host/preview-dial.test.tsindex e02d5a05..4b2c612f 100644--- a/computer/src/host/preview-dial.test.ts+++ b/computer/src/host/preview-dial.test.ts@@ -1,7 +1,13 @@import net from 'node:net';import { once } from 'node:events';import { afterEach, describe, expect, it } from 'vitest';-import { loopbackDialer } from './preview-dial.js';+import http from 'node:http';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { previewSocketFor } from '../ipc.js';+import { loopbackDialer, nothingListens, sandboxDialer } from './preview-dial.js';+import { probePort } from './preview-probe.js';const servers: net.Server[] = [];afterEach(() => { for (const s of servers.splice(0)) s.close(); });@@ -31,3 +37,109 @@ describe('loopbackDialer', () => {expect((e as NodeJS.ErrnoException).code).toBe('ECONNREFUSED');});});++/**+ * A runner's end of the preview socket (src/runner/preview-socket.ts), as the contract says it: `ports` are+ * connected and answered `ok`, 9 is previewed with nothing listening (`closed`), any other gets no reply.+ */+async function runnerEnd(ports: number[], answer = 'ok\n') {+ const run = mkdtempSync(path.join(os.tmpdir(), 'sp-dial-'));+ mkdirSync(path.join(run, 'runners'));+ const lines: string[] = [];+ const s = net.createServer((c) => {+ c.on('error', () => {});+ c.once('data', (d: Buffer) => {+ const nl = d.indexOf(0x0a);+ const port = Number(d.subarray(0, nl));+ lines.push(d.subarray(0, nl + 1).toString());+ if (port === 9) return void c.end('closed\n');+ if (!ports.includes(port)) return void c.end();+ const up = net.connect(port, '127.0.0.1', () => {+ c.write(answer);+ up.write(d.subarray(nl + 1));+ up.pipe(c).pipe(up);+ });+ up.on('error', () => c.destroy());+ });+ });+ servers.push(s);+ s.listen(previewSocketFor(run, 'r1'));+ await once(s, 'listening');+ return { run, lines };+}++async function app(): Promise<number> {+ const s = http.createServer((req, res) => res.end(`inside ${req.headers.host} ${req.url}`));+ servers.push(s as unknown as net.Server);+ s.listen(0, '127.0.0.1');+ await once(s, 'listening');+ return (s.address() as net.AddressInfo).port;+}++const get = (dial: ReturnType<typeof sandboxDialer>, port: number) =>+ new Promise<string>((resolve, reject) => {+ http.get({ createConnection: () => dial(port) as net.Socket, host: 'demo.example', path: '/x', headers: { host: 'demo.example' } }, (res) => {+ let body = '';+ res.setEncoding('utf8').on('data', (d) => (body += d)).on('end', () => resolve(body));+ }).on('error', reject);+ });++describe('sandboxDialer', () => {+ it('names the port in one line, then carries HTTP once the runner says ok', async () => {+ const port = await app();+ const { run, lines } = await runnerEnd([port]);+ expect(await get(sandboxDialer(run, 'r1'), port)).toBe('inside demo.example /x');+ expect(lines).toEqual([`${port}\n`]);+ expect(await probePort(port, 'demo.example', 2000, sandboxDialer(run, 'r1'))).toMatchObject({ listening: true });+ });++ it('works under a keep-alive agent, as the proxy uses it', async () => {+ const port = await app();+ const { run, lines } = await runnerEnd([port]);+ const agent = new http.Agent({ keepAlive: true, timeout: 5000 });+ const dial = sandboxDialer(run, 'r1');+ agent.createConnection = (o) => dial(Number(o.port));+ const viaAgent = () =>+ new Promise<string>((resolve, reject) => {+ http.get({ agent, host: '127.0.0.1', port, path: '/x', headers: { host: 'demo.example' } }, (res) => {+ let body = '';+ res.setEncoding('utf8').on('data', (d) => (body += d)).on('end', () => resolve(body));+ }).on('error', reject);+ });+ expect(await viaAgent()).toBe('inside demo.example /x');+ expect(await viaAgent()).toBe('inside demo.example /x');+ expect(lines).toEqual([`${port}\n`]); // the second request reused the first one's connection+ agent.destroy();+ });++ it('reports ECONNREFUSED for closed, for no reply, and for any answer that is not ok', async () => {+ const port = await app();+ const { run } = await runnerEnd([]);+ for (const p of [9, port]) await expect(get(sandboxDialer(run, 'r1'), p)).rejects.toMatchObject({ code: 'ECONNREFUSED' });+ expect(await probePort(9, 'demo.example', 300, sandboxDialer(run, 'r1'))).toEqual({ listening: false });+ const liar = await runnerEnd([port], 'okay\nHTTP/1.1 200 OK\r\n\r\n');+ await expect(get(sandboxDialer(liar.run, 'r1'), port)).rejects.toMatchObject({ code: 'ECONNREFUSED' });+ });++ it('refuses when the socket is missing or is not a socket, without connecting', async () => {+ const { run } = await runnerEnd([]);+ const [e] = await once(sandboxDialer(run, 'nobody')(80), 'error');+ expect((e as NodeJS.ErrnoException).code).toBe('ECONNREFUSED');+ writeFileSync(previewSocketFor(run, 'file'), 'x');+ const [e2] = await once(sandboxDialer(run, 'file')(80), 'error');+ expect((e2 as NodeJS.ErrnoException).code).toBe('ECONNREFUSED');+ });++ it("refuses a socket that is not the named user's", async () => {+ const { run } = await runnerEnd([80]);+ const [e] = await once(sandboxDialer(run, 'r1', { uid: process.getuid!() + 1 })(80), 'error');+ expect((e as NodeJS.ErrnoException).code).toBe('ECONNREFUSED');+ });+});++describe('nothingListens', () => {+ it('is ECONNREFUSED', async () => {+ const [e] = await once(nothingListens(80), 'error');+ expect((e as NodeJS.ErrnoException).code).toBe('ECONNREFUSED');+ });+});diff --git a/computer/src/host/preview-dial.ts b/computer/src/host/preview-dial.tsindex 631a72b7..520cceff 100644--- a/computer/src/host/preview-dial.ts+++ b/computer/src/host/preview-dial.ts@@ -1,17 +1,101 @@// How the preview proxy and the listen probe reach a previewed port (work// 103, seam S3). Both take a Dialer, so where the port lives is decided in one-// place: today it is this machine's loopback. Invariants: a Dialer returns its-// connection at once and never throws; the connection emits `connect`, or-// `error` with code ECONNREFUSED when nothing listens on the port. The proxy-// keeps connections alive through an http.Agent, which calls a socket's-// setKeepAlive, setTimeout, ref and unref on them: a Dialer whose connection-// is not a net.Socket has to provide those.+// place: this machine's loopback for a runner that shares it (`detached`), the+// runner's preview socket for one in a container (C9; the other end is+// src/runner/preview-socket.ts).+//+// Invariants:+// - A Dialer returns its connection at once and never throws; the connection+// emits `connect`, or `error` with code ECONNREFUSED when nothing listens on+// the port.+// - The proxy keeps connections alive through an http.Agent, which calls a+// socket's setKeepAlive, setTimeout, ref and unref on them: a Dialer whose+// connection is not a net.Socket provides those.+// - The preview socket is in a directory its session can write: the host+// connects to the socket it checked (checked-socket.ts: a socket, the+// runners' user's, never through a link), and what it answers is believed+// only as far as `ok`: every other answer, or none, is "nothing listens".import net from 'node:net';-import type { Duplex } from 'node:stream';+import { Duplex } from 'node:stream';+import { type RunRoot, previewSocketFor } from '../ipc.js';+import { type SocketCheck, connectChecked } from './checked-socket.js';/** A connection to this port for http.request's `createConnection`: returned at once, emits `connect` or `error` (code ECONNREFUSED when nothing listens). */export type Dialer = (port: number) => Duplex;/** The port on this machine, over IPv4 loopback, as http.request itself would connect. */export const loopbackDialer: Dialer = (port) => net.connect({ host: '127.0.0.1', port, noDelay: true });++const refused = (why: string) => Object.assign(new Error(`connect ECONNREFUSED ${why}`), { code: 'ECONNREFUSED', errno: -111, syscall: 'connect' });++/** The connection of a port nothing can listen on: ECONNREFUSED, as every Dialer reports one. */+export const nothingListens: Dialer = (port) => {+ const out = new Duplex({ read() {}, write: (_c, _e, cb) => cb() });+ process.nextTick(() => out.destroy(refused(`:${port}`)));+ return out;+};+const OK = 'ok\n';++/**+ * The port inside the container of sandbox `id`, through its runner's preview socket below `run`. The runner+ * connects to its own loopback and answers `ok`; a port it never previewed, a closed one and a runner that is not+ * there are all ECONNREFUSED. `check`: the user the socket must belong to.+ */+export function sandboxDialer(run: RunRoot, id: string, check: SocketCheck = {}): Dialer {+ const socketPath = previewSocketFor(run, id);+ return (port) => {+ let sock: net.Socket | undefined;+ let ready = false;+ let head = Buffer.alloc(0);+ const held: (() => void)[] = [];+ const whenReady = (f: () => void) => (ready ? f() : void held.push(f));+ const out: Duplex & { connecting?: boolean } = new Duplex({+ read: () => void sock?.resume(),+ write: (chunk, _enc, cb) => whenReady(() => sock?.write(chunk, cb)),+ final: (cb) => whenReady(() => (sock ? sock.end(cb) : cb())),+ destroy: (err, cb) => (sock?.destroy(), cb(err)),+ });+ out.connecting = true;+ const fail = (why: string) => out.destroyed || out.destroy(refused(why));+ try {+ sock = connectChecked(socketPath, check);+ } catch {+ process.nextTick(fail, `${socketPath} (no preview socket)`);+ }+ // What an http.Agent and http.request call on a socket.+ Object.assign(out, {+ setKeepAlive: () => out,+ setNoDelay: () => out,+ setTimeout: (ms: number, cb?: () => void) => (cb && out.once('timeout', cb), sock?.setTimeout(ms), out),+ ref: () => (sock?.ref(), out),+ unref: () => (sock?.unref(), out),+ });+ if (!sock) return out;+ const s = sock;+ s.on('timeout', () => out.emit('timeout'));+ s.on('connect', () => s.write(`${port}\n`));+ s.on('data', (d: Buffer) => {+ if (ready) return void (out.push(d) || s.pause());+ head = Buffer.concat([head, d]);+ if (head.length < OK.length && OK.startsWith(head.toString('latin1'))) return;+ if (head.subarray(0, OK.length).toString('latin1') !== OK) return void fail(`${id}:${port}`);+ ready = true;+ out.connecting = false;+ const rest = head.subarray(OK.length);+ out.emit('connect');+ if (rest.length && !out.push(rest)) s.pause();+ for (const f of held.splice(0)) f();+ });+ let ended = false;+ s.on('end', () => (ready ? ((ended = true), void out.push(null)) : void fail(`${id}:${port}`)));+ s.on('error', (e) => (ready ? out.destroy(e) : void fail(`${id}:${port}`)));+ s.on('close', () => {+ if (!ready) return void fail(`${id}:${port}`);+ // After a clean end, what was pushed is read first.+ if (ended && !out.readableEnded) out.once('end', () => out.destroy());+ else if (!out.destroyed) out.destroy();+ });+ return out;+ };+}diff --git a/computer/src/host/preview-proxy.test.ts b/computer/src/host/preview-proxy.test.tsindex fc1533e7..c440f979 100644--- a/computer/src/host/preview-proxy.test.ts+++ b/computer/src/host/preview-proxy.test.ts@@ -92,6 +92,19 @@ describe('preview proxy', () => {expect(open).toBe(0);});+ it('with a table of previewed ports, dials only a port the table holds', async () => {+ const app = await echo();+ const dialed: number[] = [];+ const held = new Set([30001]);+ const config = { tunnelToken: 't', key: KEY, ports: [30001, 30002] };+ const at = await listen(previewProxy(() => config, [], (port) => (dialed.push(port), loopbackDialer(app)), (port) => held.has(port)));+ const signed = (port: number) => ({ 'x-preview-port': String(port), 'x-preview-auth': signPreview(KEY, port), 'x-preview-host': 'demo.opencomputer.app' });+ expect((await get(at, signed(30001))).status).toBe(200);+ const r = await get(at, signed(30002)); // signed and allowed by the gateway, but the table lost it+ expect([r.status, r.body.trim()]).toEqual([403, 'port not previewed']);+ expect(dialed).toEqual([30001]);+ });+it('refuses a port not in the allow-list, a host port, and a request without config', async () => {const app = await echo();const { at, signed } = await proxy([app + 1]);diff --git a/computer/src/host/preview-proxy.ts b/computer/src/host/preview-proxy.tsindex 6a2e2f0e..3fad3753 100644--- a/computer/src/host/preview-proxy.ts+++ b/computer/src/host/preview-proxy.ts@@ -6,7 +6,9 @@// Invariants: it dials only through its Dialer (preview-dial.ts; loopback// unless another is passed; the connections are kept alive by an agent of// its own, which ends with it), only a port in the config's allow-list-// that is not one of the host's own, and only for a request whose+// that is not one of the host's own and that `previewed` accepts (on a host+// whose sessions run in containers: a virtual port in the host's table, work+// 103 C9; no other port is ever dialed there), and only for a request whose// X-Preview-Auth verifies (src/signed-header.ts). Every response it produces,// proxied ones too, carries `X-Preview-Origin: computer`, the one signal the// Worker trusts; a closed port is a 503 with `X-Preview-State: closed`, which@@ -29,11 +31,12 @@ const HOP = new Set(['connection', 'keep-alive', 'proxy-connection', 'transfer-etype Check = { port: number; headers: http.OutgoingHttpHeaders } | { status: number; error: string; state?: string };/** Whether the request may reach a port, and the headers the app gets. */-export function checkRequest(req: http.IncomingMessage, config: PreviewConfig | undefined, refused: number[], now = Date.now()): Check {+export function checkRequest(req: http.IncomingMessage, config: PreviewConfig | undefined, refused: number[], now = Date.now(),+ previewed: (port: number) => boolean = () => true): Check {if (!config) return { status: 503, error: 'previews are not configured on this computer' };const raw = String(req.headers['x-preview-port'] ?? '');const port = /^\d{1,5}$/.test(raw) ? Number(raw) : 0;- if (!config.ports.includes(port) || refused.includes(port)) {+ if (!config.ports.includes(port) || refused.includes(port) || !previewed(port)) {log.warn(`preview proxy: refused port ${raw.slice(0, 16) || '(none)'}`);return { status: 403, error: 'port not previewed' };}@@ -89,10 +92,11 @@ function dialAgent(dial: Dialer): http.Agent {}/** The proxy; `config` is read per request, so a `previews` frame applies at once. Closing it closes its idle connections to the apps. */-export function previewProxy(config: () => PreviewConfig | undefined, refused = HOST_PORTS, dial: Dialer = loopbackDialer): http.Server {+export function previewProxy(config: () => PreviewConfig | undefined, refused = HOST_PORTS, dial: Dialer = loopbackDialer,+ previewed?: (port: number) => boolean): http.Server {const agent = dialAgent(dial);const server = http.createServer((req, res) => {- const c = checkRequest(req, config(), refused);+ const c = checkRequest(req, config(), refused, Date.now(), previewed);if ('status' in c) return refuse(res, c);for (const k of HOP) delete c.headers[k];const up = http.request({ host: '127.0.0.1', port: c.port, method: req.method, path: req.url, headers: c.headers, agent }, (ures) => {@@ -108,7 +112,7 @@ export function previewProxy(config: () => PreviewConfig | undefined, refused =server.on('upgrade', (req, socket: Duplex, first: Buffer) => {socket.on('error', () => {});- const c = checkRequest(req, config(), refused);+ const c = checkRequest(req, config(), refused, Date.now(), previewed);if ('status' in c) return refuseSocket(socket, c);const up = http.request({ host: '127.0.0.1', port: c.port, method: req.method, path: req.url, headers: c.headers, agent });up.on('upgrade', (ures, usock, uhead) => {diff --git a/computer/src/host/previews.test.ts b/computer/src/host/previews.test.tsindex ce8cf1a6..46ab254c 100644--- a/computer/src/host/previews.test.ts+++ b/computer/src/host/previews.test.ts@@ -1,7 +1,11 @@+import { mkdtempSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';import { describe, expect, it } from 'vitest';import type { HostToGateway } from '../protocol.js';import type { Cloudflared } from './cloudflared.js';import { hostPreviews } from './previews.js';+import { previewPorts } from './sandbox/preview-ports.js';const tunnel = (): Cloudflared & { tokens: (string | undefined)[] } => {const tokens: (string | undefined)[] = [];@@ -46,4 +50,143 @@ describe('host previews', () => {p.stop();expect(t.tokens).toEqual(['tok', undefined, 'stopped']);});++ describe('on a host whose sessions run in containers', () => {+ const rig = (answer: (m: HostToGateway) => { result?: { url: string; name: string; port: number }; error?: string }) => {+ const asked: HostToGateway[] = [];+ const probed: [number, string][] = [];+ const ports = previewPorts(path.join(mkdtempSync(path.join(os.tmpdir(), 'sp-previews-')), 'previews.json'));+ const p = hostPreviews({+ ask: (m) => (asked.push(m), queueMicrotask(() => p.answer({ id: m.id, ...answer(m) })), true),+ tunnel: tunnel(),+ probe: async (port, host) => (probed.push([port, host]), { listening: true }),+ sandbox: { ports, run: (id) => `/run/x/sandbox/${id}` },+ });+ return { p, asked, probed, ports };+ };+ const named = (m: HostToGateway) => (m.t === 'preview' ? { result: { url: 'https://demo.opencomputer.app', name: 'demo', port: m.req.port } } : { result: { url: '', name: 'demo', port: 0 } });++ it('gives the gateway a virtual port, probes that, and answers the runner with its own', async () => {+ // A gateway gives each thread a name of its own.+ const { p, asked, probed, ports } = rig((m) => (m.t === 'preview' && m.from !== 'C1:1.2' ? { result: { url: 'https://other.opencomputer.app', name: 'other', port: m.req.port } } : named(m)));+ const a = await p.request('C1:1.2', { t: 'preview', id: 'r1', req: { port: 5173 } }, 'aaaa');+ expect(asked).toMatchObject([{ t: 'preview', from: 'C1:1.2', req: { port: 30000 } }]);+ expect(probed).toEqual([[30000, 'demo.opencomputer.app']]);+ expect(a).toEqual({ t: 'previewed', id: 'r1', result: { url: 'https://demo.opencomputer.app', name: 'demo', port: 5173, listening: true } });+ expect(ports.all()).toEqual([{ virtual: 30000, id: 'aaaa', port: 5173, name: 'demo' }]);+ // Another session on the same port has its own number; the same session's port keeps its own.+ await p.request('C1:3.4', { t: 'preview', id: 'r2', req: { port: 5173 } }, 'bbbb');+ await p.request('C1:1.2', { t: 'preview', id: 'r3', req: { port: 5173 } }, 'aaaa');+ expect(asked.map((m) => m.t === 'preview' && m.req.port)).toEqual([30000, 30001, 30000]);+ });++ it('frees the number the gateway refused, and the one whose name is unpreviewed', async () => {+ let refuse = true;+ const { p, ports } = rig((m) => (refuse ? { error: 'demo is taken; try demo-2' } : named(m)));+ expect(await p.request('k', { t: 'preview', id: 'r1', req: { port: 3000, name: 'demo' } }, 'aaaa')).toEqual({ t: 'previewed', id: 'r1', error: 'demo is taken; try demo-2' });+ expect(ports.all()).toEqual([]);+ refuse = false;+ await p.request('k', { t: 'preview', id: 'r2', req: { port: 3000 } }, 'aaaa');+ expect(ports.all()).toHaveLength(1);+ expect(await p.request('k', { t: 'unpreview', id: 'r3', req: { name: 'demo' } }, 'aaaa')).toMatchObject({ result: { listening: false } });+ expect(ports.all()).toEqual([]);+ });++ it('unpreview: only a name of the caller\'s own sandbox; for any other the gateway is not asked and nothing is freed', async () => {+ const { p, asked, ports } = rig(named);+ await p.request('C1:1.2', { t: 'preview', id: 'r1', req: { port: 5173 } }, 'aaaa');+ expect(await p.request('C1:3.4', { t: 'unpreview', id: 'r2', req: { name: 'demo' } }, 'bbbb')).toEqual({ t: 'previewed', id: 'r2', error: 'no preview named demo in this session' });+ expect(await p.request('C1:3.4', { t: 'unpreview', id: 'r3', req: { name: 'never' } }, 'bbbb')).toEqual({ t: 'previewed', id: 'r3', error: 'no preview named never in this session' });+ expect(asked.map((m) => m.t)).toEqual(['preview']);+ expect(ports.all()).toHaveLength(1);+ });++ it('forget: a removed sandbox\'s name is unpreviewed at the gateway by the host itself, and a gateway that is away fails nothing', async () => {+ const { p, asked, ports } = rig(named);+ p.forget('demo', 'C1:1.2');+ expect(asked).toMatchObject([{ t: 'unpreview', from: 'C1:1.2', req: { name: 'demo' } }]);+ await new Promise((r) => setImmediate(r));+ expect(ports.owed()).toEqual([]);+ const away = hostPreviews({ ask: () => false, tunnel: tunnel() });+ expect(() => away.forget('demo', '')).not.toThrow();+ await new Promise((r) => setImmediate(r));+ });++ it('forget with the gateway away: the name is owed, on disk, and asked again each time the gateway is back until it answers', async () => {+ const file = path.join(mkdtempSync(path.join(os.tmpdir(), 'sp-previews-')), 'previews.json');+ const asked: HostToGateway[] = [];+ let there = false;+ let answer: { result?: { url: string; name: string; port: number }; error?: string } = { result: { url: '', name: 'demo', port: 0 } };+ const make = () => {+ const ports = previewPorts(file);+ const p = hostPreviews({ ask: (m) => there && (asked.push(m), queueMicrotask(() => p.answer({ id: m.id, ...answer })), true), tunnel: tunnel(), sandbox: { ports, run: (id) => `/run/x/sandbox/${id}` } });+ return { p, ports };+ };+ const a = make();+ a.p.forget('demo', 'C1:1.2');+ a.p.forget('shop', '');+ await new Promise((r) => setImmediate(r));+ expect(a.ports.owed()).toEqual([{ name: 'demo', from: 'C1:1.2' }, { name: 'shop', from: '' }]);+ // A host restart keeps what is owed; the gateway's welcome sends it.+ const b = make();+ expect(b.ports.owed()).toHaveLength(2);+ there = true;+ b.p.connected();+ b.p.connected(); // a second welcome while the first is unanswered asks nothing twice+ expect(asked).toMatchObject([{ t: 'unpreview', from: 'C1:1.2', req: { name: 'demo' } }, { t: 'unpreview', from: '', req: { name: 'shop' } }]);+ await new Promise((r) => setImmediate(r));+ expect(b.ports.owed()).toEqual([]);+ b.p.connected();+ expect(asked).toHaveLength(2);+ // A gateway that heard and said no is not asked again: its answer would be the same.+ answer = { error: 'no preview named gone' };+ b.p.forget('gone', '');+ await new Promise((r) => setImmediate(r));+ expect(b.ports.owed()).toEqual([]);+ });++ it('a name that is owed and is given to a preview again is not owed any more: the retry would take it from its new session', async () => {+ const { p, ports } = rig(named);+ ports.owe('demo', 'C1:1.2');+ await p.request('C1:3.4', { t: 'preview', id: 'r1', req: { port: 5173 } }, 'bbbb');+ expect(ports.owed()).toEqual([]);+ });++ it('preview: a name another sandbox holds, or is being given, is refused before the gateway is asked; its own name it may ask for again', async () => {+ const { p, asked, ports } = rig((m) => (m.t === 'preview' ? { result: { url: `https://${m.req.name ?? 'demo'}.opencomputer.app`, name: m.req.name ?? 'demo', port: m.req.port } } : { result: { url: '', name: 'demo', port: 0 } }));+ await p.request('C1:1.2', { t: 'preview', id: 'r1', req: { port: 5173 } }, 'aaaa');+ expect(await p.request('C1:3.4', { t: 'preview', id: 'r2', req: { port: 3000, name: 'demo' } }, 'bbbb')).toEqual({ t: 'previewed', id: 'r2', error: 'another session has a preview named demo; choose another name' });+ expect(asked).toHaveLength(1);+ expect(ports.all()).toEqual([{ virtual: 30000, id: 'aaaa', port: 5173, name: 'demo' }]);+ // Two sessions ask for one free name at once: the first to ask has it, whatever order the gateway would answer in.+ const [a, b] = await Promise.all([+ p.request('C1:1.2', { t: 'preview', id: 'r3', req: { port: 8000, name: 'shop' } }, 'aaaa'),+ p.request('C1:3.4', { t: 'preview', id: 'r4', req: { port: 8000, name: 'shop' } }, 'bbbb'),+ ]);+ expect(a).toMatchObject({ result: { name: 'shop' } });+ expect(b).toEqual({ t: 'previewed', id: 'r4', error: 'another session has a preview named shop; choose another name' });+ expect(asked).toHaveLength(2);+ // Its own name, on another port: the gateway is asked, and the name is the new port's alone.+ expect(await p.request('C1:1.2', { t: 'preview', id: 'r5', req: { port: 9000, name: 'demo' } }, 'aaaa')).toMatchObject({ result: { name: 'demo', port: 9000 } });+ expect(ports.all().filter((e) => e.name === 'demo')).toEqual([{ virtual: 30002, id: 'aaaa', port: 9000, name: 'demo' }]);+ // A request that failed holds no name.+ const refused = rig(() => ({ error: 'no' }));+ await refused.p.request('k', { t: 'preview', id: 'r1', req: { port: 1, name: 'x' } }, 'aaaa');+ expect(await refused.p.request('k', { t: 'preview', id: 'r2', req: { port: 1, name: 'x' } }, 'bbbb')).toEqual({ t: 'previewed', id: 'r2', error: 'no' });+ });++ it('a session that has as many previews as it may is told so, and the gateway is not asked', async () => {+ const { p, asked, ports } = rig(named);+ for (let n = 0; n < 32; n++) ports.assign('aaaa', 4000 + n);+ expect(await p.request('k', { t: 'preview', id: 'r1', req: { port: 5173 } }, 'aaaa')).toEqual({ t: 'previewed', id: 'r1', error: 'this session has 32 previews, the most it can have; unpreview one first' });+ expect(asked).toEqual([]);+ expect(await p.request('k', { t: 'preview', id: 'r2', req: { port: 5173 } }, 'bbbb')).toMatchObject({ result: { port: 5173 } });+ });++ it('never previews a port of the host: a request that names no sandbox is refused before the gateway hears of it', async () => {+ const { p, asked } = rig(named);+ expect(await p.request('k', { t: 'preview', id: 'r1', req: { port: 22 } })).toEqual({ t: 'previewed', id: 'r1', error: 'this computer previews only sessions that run in a container' });+ expect(asked).toEqual([]);+ });+ });});diff --git a/computer/src/host/previews.ts b/computer/src/host/previews.tsindex cf1574ea..dfd5ba7c 100644--- a/computer/src/host/previews.ts+++ b/computer/src/host/previews.ts@@ -8,13 +8,33 @@// sends `previews` before the `previewed` it causes, so the allow-list already// has a port when its URL reaches the model. The proxy starts with the first// config, so a laptop host never binds its port.+//+// On a host whose sessions run in containers (work 103, C9; `sandbox` is+// passed) a session's port is not the host's: each previewed `(sandbox, port)`+// has a virtual port (sandbox/preview-ports.ts). The gateway, the Worker and+// the proxy's allow-list see only the virtual number; the proxy and the probe+// reach the session through its runner's preview socket (preview-dial.ts+// `sandboxDialer`), and the runner is answered with its own port. There the+// host's loopback is never dialed: a request that names no sandbox is+// refused, and a port outside the table is "port not previewed". A name is+// its sandbox's: `unpreview` is answered only for a name the table holds under+// the caller's id, and a sandbox that is removed has its names unpreviewed at+// the gateway by the host (`forget`): the name is owed, in the table's file,+// until the gateway answered for it, and what is owed is asked again each+// time the gateway is back (`connected`); only a gateway that was not there+// or did not answer leaves a name owed. A `preview` that asks for a name another+// sandbox holds, or asked for first and is not answered yet, is refused before+// the gateway hears of it: the gateway would point the name at the caller.import { randomUUID } from 'node:crypto';import type http from 'node:http';import type { HostToGateway, HostToRunner, PreviewConfig, PreviewResult, RunnerToHost } from '../protocol.js';import { log } from '../log.js';import { type Cloudflared, cloudflared } from './cloudflared.js';-import { PREVIEW_PROXY_PORT, previewProxy } from './preview-proxy.js';+import type { RunRoot } from '../ipc.js';+import { type Dialer, nothingListens, sandboxDialer } from './preview-dial.js';+import { HOST_PORTS, PREVIEW_PROXY_PORT, previewProxy } from './preview-proxy.js';+import type { PreviewEntry, PreviewPorts } from './sandbox/preview-ports.js';import { probePort } from './preview-probe.js';type Ask = Extract<RunnerToHost, { t: 'preview' | 'unpreview' }>;@@ -25,8 +45,12 @@ const GATEWAY_WAIT_MS = 45_000;export interface HostPreviews {/** A `welcome` (absent: no tunnel yet) or `previews` frame. */configure(config: PreviewConfig | undefined): void;- /** A runner's `preview` or `unpreview`; resolves with the frame to send back, never rejects. */- request(from: string, m: Ask): Promise<Answer>;+ /** A runner's `preview` or `unpreview`; resolves with the frame to send back, never rejects. `sandboxId`: the runner's, when it runs in a container. */+ request(from: string, m: Ask, sandboxId?: string): Promise<Answer>;+ /** Work 103: a sandbox was removed and `name` was its preview: tell the gateway, so the public name does not outlive the container; owed until it answered. Never throws; a failure is logged. */+ forget(name: string, from: string): void;+ /** The gateway is connected again (`welcome`): ask for every name still owed. */+ connected(): void;/** The gateway's `previewed`. */answer(m: { id: string; result?: PreviewResult; error?: string }): void;stop(): void;@@ -34,24 +58,85 @@ export interface HostPreviews {/** `ask` sends to the gateway and returns false when it is not connected. */export function hostPreviews(o: { ask: (m: Extract<HostToGateway, { t: 'preview' | 'unpreview' }>) => boolean; tunnel?: Cloudflared;- probe?: typeof probePort; proxyPort?: number }): HostPreviews {+ probe?: typeof probePort; proxyPort?: number;+ /** Set on a host whose sessions run in containers: the virtual port table, each sandbox's run root, and the user its preview socket must belong to. */+ sandbox?: { ports: PreviewPorts; run(id: string): RunRoot; uid?: number } }): HostPreviews {let config: PreviewConfig | undefined;let proxy: http.Server | undefined;const tunnel = o.tunnel ?? cloudflared();const probe = o.probe ?? probePort;const waiters = new Map<string, (m: { result?: PreviewResult; error?: string }) => void>();+ const sb = o.sandbox;+ /** Names asked of the gateway and not answered yet: the sandbox that asked first. */+ const asking = new Map<string, string>();+ /** Owed names whose `unpreview` is at the gateway now. */+ const forgetting = new Set<string>();+ /** The gateway was not there, or did not answer: it may never have heard. */+ class Unheard extends Error {}++ /** Ask the gateway to take an owed name away; it stays owed only when the gateway did not hear. */+ function unowe(name: string, from: string) {+ if (forgetting.has(name)) return;+ forgetting.add(name);+ gateway(from, { t: 'unpreview', id: '', req: { name } })+ .then(+ () => sb?.ports.settle(name),+ (e) => {+ const kept = e instanceof Unheard && !!sb;+ if (!kept) sb?.ports.settle(name);+ log.warn(`preview ${name} of a removed sandbox not unpreviewed: ${e?.message ?? e}${kept ? '; asked again when the gateway is back' : ''}`);+ },+ )+ .finally(() => forgetting.delete(name));+ }+ /** A virtual port's session, through its runner; a number the table lost meanwhile is a closed port. */+ const dialVirtual: Dialer = (virtual) => {+ const e = sb?.ports.get(virtual);+ return sb && e ? sandboxDialer(sb.run(e.id), e.id, { uid: sb.uid })(e.port) : nothingListens(virtual);+ };++ /** `preview` and `unpreview` of a runner in a container. */+ async function sandboxed(ports: PreviewPorts, from: string, m: Ask, id: string): Promise<Answer['result']> {+ if (m.t === 'unpreview') {+ // A name is its sandbox's: another session's, or nobody's, is not asked of the gateway.+ const e = ports.byName(m.req.name);+ if (e?.id !== id) throw new Error(`no preview named ${m.req.name} in this session`);+ const result = await gateway(from, m);+ ports.release(e.virtual);+ return { ...result, listening: false };+ }+ // A name another sandbox holds, or was the first to ask for, is not asked of the gateway: it would point the name here.+ const name = m.req.name;+ if (name !== undefined && (ports.byName(name) ?? { id: asking.get(name) ?? id }).id !== id) throw new Error(`another session has a preview named ${name}; choose another name`);+ const mine = name !== undefined && !asking.has(name);+ if (mine) asking.set(name, id);+ let entry: PreviewEntry | undefined;+ let fresh = false;+ let result: PreviewResult;+ try {+ ({ entry, fresh } = ports.assign(id, m.req.port));+ result = await gateway(from, { ...m, req: { ...m.req, port: entry.virtual } });+ } catch (e) {+ if (entry && fresh) ports.release(entry.virtual); // the gateway never heard of it, or refused it+ throw e;+ } finally {+ if (mine) asking.delete(name);+ }+ ports.setName(entry.virtual, result.name);+ return { ...result, port: m.req.port, ...(await probe(entry.virtual, new URL(result.url).host, undefined, dialVirtual)) };+ }function gateway(from: string, m: Ask): Promise<PreviewResult> {const id = randomUUID();return new Promise((resolve, reject) => {- const timer = setTimeout(() => (waiters.delete(id), reject(new Error('no answer from the gateway within 45 s'))), GATEWAY_WAIT_MS);+ const timer = setTimeout(() => (waiters.delete(id), reject(new Unheard('no answer from the gateway within 45 s'))), GATEWAY_WAIT_MS);waiters.set(id, (a) => {clearTimeout(timer);waiters.delete(id);a.result ? resolve(a.result) : reject(new Error(a.error ?? 'no answer'));});const sent = m.t === 'preview' ? o.ask({ t: 'preview', id, from, req: m.req }) : o.ask({ t: 'unpreview', id, from, req: m.req });- if (!sent) waiters.get(id)?.({ error: 'gateway not connected' });+ if (!sent) (clearTimeout(timer), waiters.delete(id), reject(new Unheard('gateway not connected')));});}@@ -60,14 +145,18 @@ export function hostPreviews(o: { ask: (m: Extract<HostToGateway, { t: 'preview'config = next;tunnel.set(next?.tunnelToken);if (next && !proxy) {- proxy = previewProxy(() => config);+ proxy = sb ? previewProxy(() => config, HOST_PORTS, dialVirtual, (port) => !!sb.ports.get(port)) : previewProxy(() => config);// A failed bind (the previous host still holds the port) is retried on the next config, not after a restart.proxy.on('error', (e) => (log.error(`preview proxy: ${e.message}`), proxy?.close(), (proxy = undefined)));proxy.listen(o.proxyPort ?? PREVIEW_PROXY_PORT, '127.0.0.1');}},- async request(from, m) {+ async request(from, m, sandboxId) {try {+ if (sb) {+ if (!sandboxId) throw new Error('this computer previews only sessions that run in a container');+ return { t: 'previewed', id: m.id, result: await sandboxed(sb.ports, from, m, sandboxId) };+ }const result = await gateway(from, m);if (m.t === 'unpreview') return { t: 'previewed', id: m.id, result: { ...result, listening: false } };return { t: 'previewed', id: m.id, result: { ...result, ...(await probe(result.port, new URL(result.url).host)) } };@@ -75,6 +164,17 @@ export function hostPreviews(o: { ask: (m: Extract<HostToGateway, { t: 'preview'return { t: 'previewed', id: m.id, error: e instanceof Error ? e.message : String(e) };}},+ forget(name, from) {+ try {+ sb?.ports.owe(name, from);+ } catch (e) {+ log.warn(`preview ${name} of a removed sandbox not noted as owed: ${(e as Error)?.message ?? e}`);+ }+ unowe(name, from);+ },+ connected() {+ for (const x of sb?.ports.owed() ?? []) unowe(x.name, x.from);+ },answer: (m) => waiters.get(m.id)?.(m),stop() {tunnel.stop();diff --git a/computer/src/host/remote-port.ts b/computer/src/host/remote-port.tsindex 20cc366a..cfdcdf5d 100644--- a/computer/src/host/remote-port.ts+++ b/computer/src/host/remote-port.ts@@ -10,14 +10,20 @@// whichever writes next.// - A runner listens on its API socket a moment after its control socket:// dialling retries for up to `dialMs`.+// - The socket is in a directory its session can write: it is connected to+// as the runner's control socket is (checked-socket.ts), never plainly.import { type ApiClient, dialApi } from '../api/socket.js';import type { WriterPort } from './api-bridge.js';+import { type SocketCheck, connectChecked } from './checked-socket.js';export type Dial = (path: string, token: string) => Promise<ApiClient>;+/** `dialApi` for a runner's API socket: only a socket (of `check.uid`, when given), and the very file that was checked. */+export const checkedDial = (check: SocketCheck = {}): Dial => (path, token) => dialApi(path, token, (p) => connectChecked(p, check));+export function remotePort(socket: string, token: string, o: { dial?: Dial; dialMs?: number } = {}): WriterPort & { close(): void } {- const dial = o.dial ?? dialApi;+ const dial = o.dial ?? checkedDial();const dialMs = o.dialMs ?? 10_000;let shared: Promise<ApiClient> | undefined;const subs = new Set<ApiClient>();diff --git a/computer/src/host/runner-sockets.test.ts b/computer/src/host/runner-sockets.test.tsnew file mode 100644index 00000000..4a6eada0--- /dev/null+++ b/computer/src/host/runner-sockets.test.ts@@ -0,0 +1,46 @@+import net from 'node:net';+import { spawn } from 'node:child_process';+import { mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import { pidFileFor } from '../ipc.js';+import { retire } from './runner-sockets.js';++/** A runner that ignores `exit`: the host's end of its socket, and what it was sent. */+async function deaf() {+ const p = path.join(mkdtempSync(path.join(tmpdir(), 'retire-')), 'r.sock');+ const got: string[] = [];+ const server = net.createServer((c) => void c.on('data', (b) => got.push(String(b))).on('error', () => {}));+ await new Promise<void>((r) => server.listen(p, r));+ const sock = net.connect(p);+ await new Promise((r) => sock.once('connect', r));+ return { sock, socket: p, got, close: () => server.close() };+}++describe('retire', () => {+ it("a container's runner that ignores exit is stopped by `kill`; the pid file, which its session can write, is never used", async () => {+ const r = await deaf();+ // What a session could plant: the pid of something the host must not kill.+ const bystander = spawn('/bin/sleep', ['30'], { stdio: 'ignore' });+ writeFileSync(pidFileFor(r.socket), String(bystander.pid));+ const did: string[] = [];+ const went = await retire(r.sock, r.socket, () => void did.push('stop'), { ms: 30, kill: async () => void (did.push('kill'), r.sock.destroy()) });+ expect(went).toBe(true);+ expect(did).toEqual(['stop', 'kill']);+ expect(r.got.join('')).toContain('"t":"exit"');+ expect(bystander.exitCode).toBeNull();+ expect(bystander.signalCode).toBeNull();+ bystander.kill();+ r.close();+ });++ it('a runner that goes on `exit` is not killed', async () => {+ const r = await deaf();+ const did: string[] = [];+ setTimeout(() => r.sock.destroy(), 5);+ expect(await retire(r.sock, r.socket, () => {}, { ms: 2000, kill: async () => void did.push('kill') })).toBe(true);+ expect(did).toEqual([]);+ r.close();+ });+});diff --git a/computer/src/host/runner-sockets.ts b/computer/src/host/runner-sockets.tsindex 2483a765..11efa772 100644--- a/computer/src/host/runner-sockets.ts+++ b/computer/src/host/runner-sockets.ts@@ -20,6 +20,7 @@ import { launch } from './launch.js';import { pollReady } from './cold-start.js';import { rm } from '../workspaces/as-runner.js';import { API_SOCK } from './runner-api.js';+import { type SocketCheck, connectChecked } from './checked-socket.js';/** Open a connection to a runner's socket; rejects if nothing listens there. */export function dialRunner(socket: string): Promise<net.Socket> {@@ -34,19 +35,55 @@ export function dialRunner(socket: string): Promise<net.Socket> {});}-/** Launch a runner (`runner.launched`) and connect to it once it listens (`runner.ready`). */-export async function launchRunner(rs: RunnerSpec, o: { tm: Telemetry; mode: string; env: NodeJS.ProcessEnv; root: string; f?: Dimensions }) {- const { tm, f = {} } = o;+/**+ * `dialRunner` for a socket in a directory a session can write (work 103): connected to only when it is a socket+ * (of `check.uid`, when given), never through a link the session put there, and to the very file that was checked+ * (checked-socket.ts). Undefined when nothing is there or nothing answers.+ */+export function dialSocket(socket: string, check: SocketCheck = {}): Promise<net.Socket | undefined> {+ return new Promise((resolve) => {+ let sock: net.Socket;+ try {+ sock = connectChecked(socket, check);+ } catch {+ return resolve(undefined);+ }+ sock.once('error', () => resolve(undefined));+ sock.once('connect', () => {+ sock.on('error', (e) => log.warn('runner socket', path.basename(socket), e.message));+ resolve(sock);+ });+ });+}++export interface LaunchOptions { tm: Telemetry; mode: string; env: NodeJS.ProcessEnv; root: string; f?: Dimensions }++/** Launch a runner's process (`runner.launched`); resolves once it was spawned, with when the launch began. */+export async function launchProcess(rs: RunnerSpec, o: LaunchOptions): Promise<number> {const t0 = Date.now();- const launched = tm.start('runner.launched', { ...f, data: { launch_mode: o.mode } });+ const launched = o.tm.start('runner.launched', { ...o.f, data: { launch_mode: o.mode } });await launch(rs, o.mode, o.env, o.root).catch((e) => {launched.end({ outcome: 'failed', error_type: 'launch' });throw e;});launched.end({ outcome: 'completed' });- const { value: sock, polls } = await pollReady(() => dialRunner(rs.socket).catch(() => undefined));+ return t0;+}++/**+ * Connect to a launched runner once it listens (`runner.ready`), 30 s at most. `t0`: when its launch began.+ * `dial`: how its socket is reached, when not plainly; `late`: called for one that never listened, before the+ * error, which is always the same one line (it reaches the gateway's reply; a diagnosis belongs in the host's log).+ */+export async function awaitRunner(+ rs: RunnerSpec,+ o: { tm: Telemetry; f?: Dimensions; t0: number; dial?: () => Promise<net.Socket | undefined>; late?: () => Promise<unknown> },+): Promise<net.Socket> {+ const { tm, f = {}, t0 } = o;+ const { value: sock, polls } = await pollReady(o.dial ?? (() => dialRunner(rs.socket).catch(() => undefined)));if (!sock) {tm.emit('runner.ready', { ...f, outcome: 'timed_out', error_type: 'launch', duration_ms: Date.now() - t0, data: { polls } });+ await o.late?.().catch((e) => log.warn(`runner ${rs.id} never listened, and no diagnosis: ${e?.message ?? e}`));throw new Error('runner did not start within 30 s');}const launchMs = Date.now() - t0;@@ -55,6 +92,9 @@ export async function launchRunner(rs: RunnerSpec, o: { tm: Telemetry; mode: strreturn sock;}+/** Launch a runner and connect to it once it listens. */+export const launchRunner = async (rs: RunnerSpec, o: LaunchOptions) => awaitRunner(rs, { ...o, t0: await launchProcess(rs, o) });+/*** After a restart: connect to every runner still listening and hand it to `adopt` (by its socket's* name); clear what the dead ones left. Resolves with the names of the runners adopted.@@ -105,17 +145,22 @@ export async function rediscover(run: RunRoot, adopt: (id: string, sock: net.Soc/*** Stop a runner now: `stop` (its turn), `exit` with a deadline (the runner quits by itself after it, ending its own- * harness: the host may not be allowed to signal it); SIGKILL from its pid file if its socket is still open after `ms`.- * True when it went.+ * harness: the host may not be allowed to signal it); if its socket is still open after `ms`, SIGKILL from its pid file,+ * or `kill` for a runner in a container (work 103: Stop with no grace; its pid file is the session's to write and is+ * never read). True when it went.*/-export async function retire(sock: net.Socket, socket: string, stop: () => void, ms = 10_000): Promise<boolean> {+export async function retire(sock: net.Socket, socket: string, stop: () => void, o: { ms?: number; kill?: () => Promise<unknown> } = {}): Promise<boolean> {+ const ms = o.ms ?? 10_000;stop();send(sock, { t: 'exit', ms: Math.max(0, ms - 2_000) } satisfies HostToRunner);await Promise.race([closed(sock), new Promise((t) => setTimeout(t, ms).unref())]);if (sock.destroyed) return true;try {- const pid = Number(readFileSync(pidFileFor(socket), 'utf8'));- if (pid > 1) process.kill(pid, 'SIGKILL');+ if (o.kill) await o.kill();+ else {+ const pid = Number(readFileSync(pidFileFor(socket), 'utf8'));+ if (pid > 1) process.kill(pid, 'SIGKILL');+ }} catch (e) {log.warn(`runner ${path.basename(socket)} did not exit and could not be killed: ${(e as Error)?.message ?? e}`);}diff --git a/computer/src/host/runner-user.ts b/computer/src/host/runner-user.tsindex 786ab534..5bbe9312 100644--- a/computer/src/host/runner-user.ts+++ b/computer/src/host/runner-user.ts@@ -9,6 +9,8 @@ import { execFileSync } from 'node:child_process';export interface RunnerUser {/** Goes before systemd-run. */sudo: string[];+ /** Their uid: what a socket of theirs belongs to. */+ uid: number;/** The user's own HOME, USER, SHELL (and PATH, when the host's differs), over the host's. */env: Record<string, string>;}@@ -35,6 +37,7 @@ export function runnerUser(env: RunnerUserEnv, passwd = (n: string) => execFileSconst run = `/run/user/${uid}`;// sudoers keeps these two (env_keep), so systemd-run --user finds agent's manager.u = {+ uid: Number(uid),sudo: [SUDO, '-n', '-u', name, `XDG_RUNTIME_DIR=${run}`, `DBUS_SESSION_BUS_ADDRESS=unix:path=${run}/bus`],env: { HOME: home, USER: name, SHELL: shell || '/bin/bash', ...(env.SP_RUNNER_PATH ? { PATH: env.SP_RUNNER_PATH } : {}) },};diff --git a/computer/src/host/sample.ts b/computer/src/host/sample.tsindex 8c83b295..c27857fb 100644--- a/computer/src/host/sample.ts+++ b/computer/src/host/sample.ts@@ -18,6 +18,13 @@ export interface HostFigures {since_gateway_message_s?: number;telemetry_spooled_bytes: number;telemetry_dropped: number;+ /** Work 103, a `podman` host as of its last sweep (sandbox/sweep.ts `SandboxHealth`). */+ containers_running?: number;+ containers_exited?: number;+ containers_created?: number;+ containers_other?: number;+ data_used_pct?: number;+ podman_bytes?: number;/** Seconds the model proxy's control socket has been down (work 097); 0 while up. A host's health fails past 30. */model_proxy_down_s?: number;}diff --git a/computer/src/host/sandbox/artifacts.test.ts b/computer/src/host/sandbox/artifacts.test.tsnew file mode 100644index 00000000..5f3f4fde--- /dev/null+++ b/computer/src/host/sandbox/artifacts.test.ts@@ -0,0 +1,176 @@+import { lutimesSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import type { ScriptRunner } from '../../workspaces/script-runner.js';+import { sandboxArtifacts } from './artifacts.js';+import { mounts } from './mounts.js';+import type { AsRunner } from './podman.js';+import type { Bind } from './podman-args.js';+import { type SandboxRecord, sandboxRecords } from './records.js';+import { threadLocks } from './thread-lock.js';+import { sandboxUses } from './use.js';++const HOUR = 3600e3;+const ago = (ms: number) => new Date(Date.now() - ms);+/** As git would answer: of the lines asked, the one that names node_modules. */+const ignoredLine = (stdin: string) => stdin.split('\n').indexOf('1\tnode_modules') + 1;+const repos = { alpha: { branch: 'sp/k', from: 'origin/main', base: 'abc' } };++/** One person's stopped thread with a worktree `alpha` holding node_modules (ignored) and .venv (tracked). */+function rig(o: { usedHoursAgo?: number; answer?: string; running?: () => boolean; asked?: () => void } = {}) {+ const locks = threadLocks();+ const data = mkdtempSync(path.join(os.tmpdir(), 'sp-art-'));+ const log: string[] = [];+ const helped: { person: string; binds: Bind[]; args: string[]; stdin?: string | Buffer }[] = [];+ const as: AsRunner = { settled: async () => {}, run: async () => '', podman: async (args) => (log.push(`podman ${args.join(' ').replaceAll(data, '')}`), '') };+ const m = mounts({ as, root: '/opt/r1', dataDir: data });+ const records = sandboxRecords(path.join(data, 'records'));+ const record: SandboxRecord = { id: '00aa11bb22cc33dd', person: 'pat', key: 'C1:1.1', createdAt: '', usedAt: ago((o.usedHoursAgo ?? 48) * HOUR).toISOString(), repos };+ records.write(record);+ const wt = path.join(m.workspace(record), 'alpha');+ for (const d of ['node_modules', '.venv', 'src']) mkdirSync(path.join(wt, d), { recursive: true });+ writeFileSync(path.join(wt, '.git'), 'gitdir: /clones/alpha/.git/worktrees/alpha\n');+ const admin = path.join(m.registry(record, 'alpha'), 'alpha');+ mkdirSync(path.join(admin, 'logs'), { recursive: true });+ for (const f of ['index', 'logs/HEAD']) {+ writeFileSync(path.join(admin, f), '');+ utimesSync(path.join(admin, f), ago(72 * HOUR), ago(72 * HOUR));+ }+ const helper = (person: string, binds: Bind[]): ScriptRunner => ({+ clones: '/clones', workspace: () => '/workspace',+ run: async (script, args, r) => (helped.push({ person, binds, args: [script, ...args], stdin: r.stdin }), o.asked?.(), o.answer ?? `1\tok\t-\t-\t-\t-\t${ignoredLine(String(r.stdin))}\n`),+ });+ const uses = sandboxUses({ as, records, workspace: m.workspace, unitActive: async () => false });+ const a = sandboxArtifacts({ as, records, locks, mounts: m, helper, running: o.running ?? (() => false), claim: uses.claim });+ return { a, uses, log, helped, record, records, locks, wt, admin, data };+}++describe('artifacts of a sandboxed thread (work 103, without host git)', () => {+ it('last use: the record, or a worktree\'s index or HEAD log in the thread\'s registry, whichever is latest', async () => {+ const t = rig();+ expect(await t.a.lastUsed(t.record)).toBe(Date.parse(t.record.usedAt));+ const recent = ago(HOUR);+ utimesSync(path.join(t.admin, 'logs', 'HEAD'), recent, recent);+ expect(await t.a.lastUsed(t.record)).toBe(recent.getTime());+ expect(await t.a.lastUsed({ ...t.record, repos: undefined })).toBe(Date.parse(t.record.usedAt));+ });++ it('last use follows no link a session left in a registry', async () => {+ const t = rig();+ const elsewhere = path.join(t.data, 'elsewhere');+ writeFileSync(elsewhere, '');+ const link = path.join(t.admin, 'index');+ const old = ago(96 * HOUR);+ rmSync(link);+ symlinkSync(elsewhere, link);+ lutimesSync(link, old, old);+ expect(await t.a.lastUsed(t.record)).toBe(Date.parse(t.record.usedAt)); // the link's own time, not its target's (now)+ });++ it('git is asked in a helper that sees the workspace read-only and the thread\'s registries; only what it calls ignored is removed, in the user namespace', async () => {+ const t = rig();+ const removed = await t.a.pruneArtifacts(t.record);+ expect(removed).toEqual([path.join(t.wt, 'node_modules')]);+ expect(t.helped).toEqual([{+ person: 'pat',+ binds: [+ { src: path.join(t.data, 'people/pat/sessions/C1-1-1'), dst: '/workspace', ro: true },+ { src: path.join(t.data, 'people/pat/wt/C1-1-1/alpha'), dst: '/clones/alpha/.git/worktrees' },+ ],+ args: ['ws-inspect.sh', '--only=ignored', '/clones', '/workspace', 'alpha'],+ stdin: expect.any(String),+ }]);+ expect(String(t.helped[0].stdin).split('\n').sort()).toEqual(['', '1\t.venv', '1\tnode_modules']);+ expect(t.log).toEqual(['podman unshare rm -rf -- /people/pat/sessions/C1-1-1/alpha/node_modules']);+ });++ it('a .wt that links to another workspace: nothing there is listed, asked about or removed', async () => {+ const t = rig();+ const other = path.join(t.data, 'people/quinn/sessions/C2-2-2');+ mkdirSync(path.join(other, 'theirs', 'node_modules'), { recursive: true });+ writeFileSync(path.join(other, 'theirs', '.git'), 'gitdir: /clones/theirs/.git/worktrees/theirs\n');+ symlinkSync(other, path.join(path.dirname(t.wt), '.wt'));+ expect(await t.a.pruneArtifacts(t.record)).toEqual([path.join(t.wt, 'node_modules')]);+ expect(t.helped[0].args).toEqual(['ws-inspect.sh', '--only=ignored', '/clones', '/workspace', 'alpha']);+ expect(t.log).toEqual(['podman unshare rm -rf -- /people/pat/sessions/C1-1-1/alpha/node_modules']);+ });++ it('a directory that became a link while git was asked is not removed', async () => {+ const t = rig();+ const other = path.join(t.data, 'people/quinn/sessions/C2-2-2/theirs');+ mkdirSync(path.join(other, 'node_modules'), { recursive: true });+ const a = sandboxArtifacts({+ as: { settled: async () => {}, run: async () => '', podman: async (args) => (t.log.push(args.join(' ')), '') }, records: t.records, locks: t.locks, mounts: mounts({ as: { settled: async () => {}, run: async () => '', podman: async () => '' }, root: '/opt/r1', dataDir: t.data }),+ helper: () => ({ clones: '/clones', workspace: () => '/workspace', run: async (_s, _a, r) => {+ rmSync(t.wt, { recursive: true });+ symlinkSync(other, t.wt);+ return `1\tok\t-\t-\t-\t-\t${ignoredLine(String(r.stdin))}\n`;+ } }), running: () => false, claim: () => () => {},+ });+ expect(await a.pruneArtifacts(t.record)).toEqual([]);+ expect(t.log).toEqual([]);+ });++ it('nothing is removed when git ignores nothing, or when the thread got a runner while git was asked', async () => {+ const none = rig({ answer: '1\tok\t-\t-\t-\t-\n' });+ expect(await none.a.pruneArtifacts(none.record)).toEqual([]);+ let asked = 0;+ const started = rig({ running: () => asked++ > 0 });+ await started.a.pruneIdle('pat');+ expect(started.helped.length).toBe(1);+ expect([none.log, started.log]).toEqual([[], []]);+ });++ it('nothing is removed under a /files script, nor after one that ran since git was asked (C13)', async () => {+ const reading = rig();+ const use = await reading.uses.enter(reading.record.id);+ expect(await reading.a.pruneArtifacts(reading.record)).toEqual([]);+ use.leave();+ let t: ReturnType<typeof rig>;+ const since = (t = rig({ asked: () => void t.uses.enter(t.record.id).then((u) => u.leave()) }));+ expect(await since.a.pruneArtifacts(since.record)).toEqual([]);+ expect([reading.log, since.log]).toEqual([[], []]);+ });++ it('nothing is removed while a start has the thread\'s turn, nor after it: the start wrote the record', async () => {+ let end: (() => void) | undefined;+ const t = rig({ asked: () => void t.locks.run('pat', 'C1:1.1', () => new Promise<void>((r) => (end = () => (t.records.write({ ...t.record, usedAt: new Date().toISOString() }), r())))) });+ const done = t.a.pruneArtifacts(t.record);+ // Git is asked after the worktrees were read from disk: however long that takes.+ while (!end) await new Promise((r) => setTimeout(r, 5));+ await new Promise((r) => setTimeout(r, 20));+ expect(t.log).toEqual([]);+ end();+ expect(await done).toEqual([]);+ expect(t.log).toEqual([]);+ });++ it('pruneIdle: only this person\'s threads, idle long enough, without a runner, and each once per use', async () => {+ const fresh = rig({ usedHoursAgo: 1 });+ await fresh.a.pruneIdle('pat');+ const running = rig({ running: () => true });+ await running.a.pruneIdle('pat');+ const other = rig();+ await other.a.pruneIdle('quinn');+ expect([fresh.helped, running.helped, other.helped]).toEqual([[], [], []]);+ const idle = rig();+ await idle.a.pruneIdle('pat');+ await idle.a.pruneIdle('pat');+ expect(idle.helped.length).toBe(1);+ expect(idle.log.length).toBe(1);+ idle.records.write({ ...idle.record, usedAt: ago(30 * HOUR).toISOString() });+ await idle.a.pruneIdle('pat');+ expect(idle.helped.length).toBe(2);+ });++ it('a helper that fails removes nothing and does not stop the others', async () => {+ const t = rig();+ const a = sandboxArtifacts({+ as: { settled: async () => {}, run: async () => '', podman: async (args) => (t.log.push(args.join(' ')), '') }, records: t.records, locks: t.locks, mounts: mounts({ as: { settled: async () => {}, run: async () => '', podman: async () => '' }, root: '/opt/r1', dataDir: t.data }),+ helper: () => ({ clones: '/clones', workspace: () => '/workspace', run: async () => Promise.reject(new Error('ws-inspect.sh: timed out')) }), running: () => false, claim: () => () => {},+ });+ await a.pruneIdle('pat');+ expect(t.log).toEqual([]);+ });+});diff --git a/computer/src/host/sandbox/artifacts.ts b/computer/src/host/sandbox/artifacts.tsnew file mode 100644index 00000000..a2e42940--- /dev/null+++ b/computer/src/host/sandbox/artifacts.ts@@ -0,0 +1,110 @@+// When a sandboxed thread was last used, and pruning the build and dependency+// directories of idle ones (work 071, for work 103): what workspaces/idle.ts+// does for a fork on the host, without the host running git or a shell on+// anything a session wrote.+//+// Invariants:+// - The host only lists (readdir) and looks (lstat) in a workspace and a+// registry, and follows no link there: idle.ts walks only directories that+// lstat says are no links, and `stillInside` resolves what is to be removed+// once more after git answered. Git is asked in a helper container+// that sees the workspace read-only, with no network.+// - Directories are removed inside Podman's user namespace (`podman unshare+// rm -rf`): what a session made as root belongs to subordinate uids.+// - Only a thread with no runner is pruned, and its directories are removed+// in the thread's turn (thread-lock.ts): a thread that has a runner then, or+// whose record a start wrote since git was asked, loses nothing, and a start+// that arrives during the removal waits for it. Neither does one a `/files`+// script or a terminal is in, or was since git was asked, and none enters+// during the removal (use.ts `claim`).+// - A thread is looked at again only once it was used again.++import { lstat } from 'node:fs/promises';+import path from 'node:path';+import { log } from '../../log.js';+import { artifactQuestion, artifactsIdle, ignoredArtifacts, stillInside } from '../../workspaces/idle.js';+import type { ScriptRunner } from '../../workspaces/script-runner.js';+import { CLONES, type Mounts, WORKSPACE } from './mounts.js';+import type { AsRunner } from './podman.js';+import { type Bind, unshareRmArgs } from './podman-args.js';+import type { Records, SandboxRecord } from './records.js';+import type { ThreadLocks } from './thread-lock.js';++const INSPECT_TIMEOUT_MS = 60_000;+const REMOVE_TIMEOUT_MS = 120_000;++export interface ArtifactsDeps {+ as: AsRunner;+ records: Records;+ /** The threads' turns, shared with the starts. */+ locks: ThreadLocks;+ mounts: Mounts;+ /** `sandboxScripts.helperScripts`. */+ helper(person: string, binds: Bind[]): ScriptRunner;+ /** True while the thread of this record has a runner. */+ running(id: string): boolean;+ /** `sandboxUses.claim`: the thread, free of `/files` scripts and terminals since `since`, until the function returned is called. */+ claim(id: string, since: number): (() => void) | undefined;+}++export type SandboxArtifacts = ReturnType<typeof sandboxArtifacts>;++const mtime = async (p: string) => (await lstat(p).catch(() => undefined))?.mtimeMs ?? 0;++export function sandboxArtifacts(d: ArtifactsDeps) {+ const { mounts: m } = d;+ /** Threads already pruned, by their last use then. */+ const pruned = new Map<string, number>();++ /** Latest use: the record (every start and delivery) and each worktree's index and HEAD log, which live in the thread's registries. */+ async function lastUsed(r: SandboxRecord): Promise<number> {+ const times = [Date.parse(r.usedAt) || 0];+ for (const name of Object.keys(r.repos ?? {})) {+ const admin = path.join(m.registry(r, name), name);+ times.push(await mtime(path.join(admin, 'index')), await mtime(path.join(admin, 'logs', 'HEAD')));+ }+ return Math.max(...times);+ }++ /** Remove the git-ignored build and dependency directories of a stopped thread's worktrees. Returns the directories removed, as host paths. */+ async function pruneArtifacts(r: SandboxRecord): Promise<string[]> {+ const ws = m.workspace(r);+ const asked = Date.now();+ const q = await artifactQuestion(ws);+ if (!q.asked.length) return [];+ const binds: Bind[] = [+ { src: ws, dst: WORKSPACE, ro: true },+ ...Object.keys(r.repos ?? {}).map((name) => ({ src: m.registry(r, name), dst: `${CLONES}/${name}/.git/worktrees` })),+ ];+ const out = await d.helper(r.person, binds).run('ws-inspect.sh', ['--only=ignored', CLONES, WORKSPACE, ...q.names], { stdin: q.lines, timeoutMs: INSPECT_TIMEOUT_MS });+ return d.locks.run(r.person, r.key, async () => {+ // No runner and no start since git was asked first, then the paths: a thread that is not running cannot move them after they were resolved.+ if (d.running(r.id) || d.records.get(r.id)?.usedAt !== r.usedAt) return [];+ const free = d.claim(r.id, asked);+ if (!free) return [];+ try {+ const ignored = await stillInside(ws, ignoredArtifacts(q, out));+ if (!ignored.length) return [];+ await d.as.podman(unshareRmArgs(ignored), { timeoutMs: REMOVE_TIMEOUT_MS });+ return ignored;+ } finally {+ free();+ }+ });+ }++ /** Prune the build and dependency directories of `person`'s threads idle for SP_ARTIFACTS_IDLE_HOURS, except those with a runner. */+ async function pruneIdle(person: string): Promise<void> {+ for (const r of d.records.all()) {+ if (r.person !== person || d.running(r.id)) continue;+ const used = await lastUsed(r);+ if (Date.now() - used < artifactsIdle() || pruned.get(r.id) === used) continue;+ const ws = m.workspace(r);+ const removed = await pruneArtifacts(r).catch((e) => (log.warn(`workspaces: artifacts of ${ws}: ${(e as Error)?.message ?? e}`), [] as string[]));+ if (removed.length) log.info(`workspaces: removed ${removed.length} build/dependency dirs from idle thread ${r.key} (${r.person}): ${removed.map((x) => path.relative(ws, x)).join(', ')}`);+ pruned.set(r.id, used);+ }+ }++ return { lastUsed, pruneArtifacts, pruneIdle };+}diff --git a/computer/src/host/sandbox/boot-env.test.ts b/computer/src/host/sandbox/boot-env.test.tsnew file mode 100644index 00000000..f4569792--- /dev/null+++ b/computer/src/host/sandbox/boot-env.test.ts@@ -0,0 +1,46 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import { RUNNER_ENV, runnerVars } from '../../runner-env.js';+import { BOOT_ENV, HOST_ONLY, bootEnv } from './boot-env.js';++const spec = { id: 'abc', socket: '/run/x/runners/abc.sock', version: 'v1', session: { key: "it's", forkPath: '/workspace' } } as never;++describe('boot.env', () => {+ it('every runner variable is in exactly one of the two lists', () => {+ const both = [...BOOT_ENV, ...HOST_ONLY] as string[];+ expect(new Set(both).size).toBe(both.length);+ expect([...both].sort()).toEqual([...RUNNER_ENV].sort());+ });++ it('is SP_ROOT, RUNNER_SPEC, then the variables in order, empty ones left out', () => {+ const text = bootEnv({ root: '/opt/slack-presence/releases/abc', spec, vars: runnerVars({ MODEL: 'm', SP_VERSION: 'v1', PATH: '/host/bin', HTTPS_PROXY: 'http://p' }) });+ expect(text.split('\n').map((l) => l.split('=')[0])).toEqual(['SP_ROOT', 'RUNNER_SPEC', 'SP_VERSION', 'MODEL', 'SP_CODEX_PEER_CHECK', 'HTTPS_PROXY', '']);+ expect(text).toContain("SP_ROOT='/opt/slack-presence/releases/abc'\n");+ expect(text).toContain("SP_CODEX_PEER_CHECK='on'\n");+ expect(text).not.toContain('PATH=');+ });++ it('never writes a host-only name, whatever the host has', () => {+ const all = Object.fromEntries(RUNNER_ENV.map((k) => [k, `/host/${k}`]));+ const names = bootEnv({ root: '/r', spec, vars: all }).trimEnd().split('\n').map((l) => l.slice(0, l.indexOf('=')));+ expect(names).toEqual(['SP_ROOT', 'RUNNER_SPEC', ...BOOT_ENV]);+ });++ it('a shell reads back exactly what was written', () => {+ const dir = mkdtempSync(path.join(os.tmpdir(), 'boot-env-'));+ try {+ const nasty = `a'b"c $(id) \`id\` \\ $HOME; x`;+ const file = path.join(dir, 'boot.env');+ writeFileSync(file, bootEnv({ root: '/r', spec, vars: { MODEL: nasty } }));+ const out = execFileSync('/bin/sh', ['-c', 'set -a; . "$1"; set +a; printf "%s\\n%s" "$MODEL" "$RUNNER_SPEC"', 'sh', file], { encoding: 'utf8', env: {} });+ const [model, ...rest] = out.split('\n');+ expect(model).toBe(nasty);+ expect(JSON.parse(rest.join('\n'))).toEqual(spec);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/computer/src/host/sandbox/boot-env.ts b/computer/src/host/sandbox/boot-env.tsnew file mode 100644index 00000000..08bb1909--- /dev/null+++ b/computer/src/host/sandbox/boot-env.ts@@ -0,0 +1,47 @@+// boot.env (work 103, C4): what a start may change for a runner in a+// container, written by the host before every start and sourced by the image's+// entrypoint (deploy/image/sp-session-init). `podman start` cannot change a+// container's environment, and a resumed runner needs a new RUNNER_SPEC and+// possibly a new release.+//+// Invariants:+// - One `NAME='value'` per line, in the order of BOOT_ENV after SP_ROOT and+// RUNNER_SPEC; a name whose value is empty is left out.+// - No credential (the invariant of runner-env.ts stands), and no name in+// HOST_ONLY: those are host paths, loader settings, or owned by the image+// or by Create.+// - Every name in RUNNER_ENV is in exactly one of BOOT_ENV and HOST_ONLY.++import type { RunnerSpec } from '../../protocol.js';++/** The runner variables a start passes on, in the file's order. */+export const BOOT_ENV = [+ 'SP_VERSION', 'SP_COMMITTER_NAME', 'SP_COMMITTER_EMAIL', 'SP_FAKE_SLACK', 'SP_SLACK_API_URL', 'MODEL', 'FOLD_AT', 'PERMISSION_MODE',+ 'SP_REGION', 'SP_SUBSTRATE', 'SP_PROMPT_CACHE_TTL', 'SP_CONTEXT_WINDOW', 'SP_COMPACT_AT', 'SP_PROMPT_GUARD', 'SP_CODEX_PEER_CHECK',+ 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy',+] as const;++/** Never written: the value is a host path, a loader setting, or owned by the image or the Create command. */+export const HOST_ONLY = [+ 'PATH', 'HOME', 'USER', 'SHELL', 'LANG', 'TMPDIR', 'CLAUDE_CONFIG_DIR', 'SP_RUN', 'SP_DATA', 'SP_DEFINITION', 'SP_REAL_GH', 'SP_REAL_OPENCOMPUTER',+ 'SP_CODEX_BIN', 'SP_PREVIEW_SOCKET', 'DISABLE_AUTOUPDATER', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM', 'WORKDIR',+ 'NODE_OPTIONS', 'NODE_PATH', 'NODE_EXTRA_CA_CERTS', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'BASH_ENV',+] as const;++/** A value for a POSIX shell's `.`: single-quoted, `'` written as `'\''`. */+const quote = (v: string) => `'${v.replace(/'/g, `'\\''`)}'`;++export interface BootVars {+ /** The release the runner starts from: the host's own. */+ root: string;+ spec: RunnerSpec;+ /** `runnerVars(env)` (runner-env.ts). */+ vars: Record<string, string>;+}++/** The file's text. */+export function bootEnv(b: BootVars): string {+ const out: [string, string][] = [['SP_ROOT', b.root], ['RUNNER_SPEC', JSON.stringify(b.spec)]];+ for (const k of BOOT_ENV) if (b.vars[k]) out.push([k, b.vars[k]]);+ return out.map(([k, v]) => `${k}=${quote(v)}\n`).join('');+}diff --git a/computer/src/host/sandbox/containers.test.ts b/computer/src/host/sandbox/containers.test.tsnew file mode 100644index 00000000..d72513d7--- /dev/null+++ b/computer/src/host/sandbox/containers.test.ts@@ -0,0 +1,295 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import { type ContainersDeps, TIMEOUTS, containers } from './containers.js';+import { type AsRunner, PodmanError } from './podman.js';++const ID = '00aa11bb22cc33dd';+const rs = { id: ID, socket: '/s', version: 'v', session: { key: 'C1:1.1', forkPath: '/workspace' } } as never;+const record = { id: ID, person: 'p', key: 'C1:1.1', createdAt: '', usedAt: '' };++/** A fake runners' user: every command is recorded, `answer` says what it prints or throws. */+function rig(answer: (argv: string[]) => string | Error = () => '', over: Partial<ContainersDeps> = {}) {+ const root = mkdtempSync(path.join(tmpdir(), 'containers-'));+ const calls: { argv: string[]; timeoutMs: number; repeatable?: boolean }[] = [];+ const log: string[] = [];+ const run = async (argv: string[], o: { timeoutMs: number; repeatable?: boolean }) => {+ calls.push({ argv, timeoutMs: o.timeoutMs, ...(o.repeatable && { repeatable: true }) });+ log.push(argv.slice(0, 3).join(' '));+ const a = answer(argv);+ if (a instanceof Error) throw a;+ return a;+ };+ const as: AsRunner = { settled: async (ms) => void log.push(`settled ${ms ?? ''}`.trim()), run, podman: (args, o) => run(['podman', ...args], o) };+ const c = containers({+ as, runRoot: (id) => path.join(root, id), dataDir: '/data', root: '/opt/slack-presence/releases/r1', image: 'img:tag', abi: '1', modelSocket: '/run/oc-modelproxy/api.sock',+ start: async () => void log.push('start'), vars: () => ({ SP_VERSION: 'v1', PATH: '/host/bin' }), definition: () => undefined,+ serveTokens: (_run, id, session) => (log.push(`tokens ${id} ${session()}`), { close: () => void log.push('tokens closed') }),+ sleep: async () => {}, ...over,+ });+ return { c, calls, log, run: path.join(root, ID), find: (word: string) => calls.filter((x) => x.argv.join(' ').includes(word)) };+}+const fail = (stderr: string, timedOut = false) => new PodmanError('failed', timedOut ? undefined : 125, stderr, timedOut);+const mode = (p: string) => statSync(p).mode & 0o7777;++describe('containers', () => {+ it('creates within 60 s, with the run directory there first', async () => {+ const t = rig();+ await t.c.create(ID);+ expect(mode(t.run)).toBe(0o2750);+ const [create] = t.find('podman create');+ expect(create.timeoutMs).toBe(TIMEOUTS.create);+ expect(create.argv).toEqual(expect.arrayContaining(['--name', `sp-runner-${ID}`, '--label', 'sp.abi=1', 'img:tag']));+ });++ it('create: the home is made first, labelled with this host\'s run directory for the id (Podman labels no volume a container names)', async () => {+ const t = rig();+ await t.c.create(ID);+ expect(t.calls.map((x) => x.argv.slice(1, 3).join(' '))).toEqual(['volume create', 'create --name']);+ expect(t.calls[0]).toEqual({ argv: ['podman', 'volume', 'create', '--ignore', '--label', `sp.run=${t.run}`, `sp-home-${ID}`], timeoutMs: TIMEOUTS.create, repeatable: true });+ const bad = rig((a) => (a[1] === 'volume' ? fail('no space') : ''));+ await expect(bad.c.create(ID)).rejects.toThrow();+ expect(bad.find('podman create')).toEqual([]);+ });++ it('up: empties what the session wrote, writes the run directory, serves tokens, starts, then asks the pid', async () => {+ const def = path.join(mkdtempSync(path.join(tmpdir(), 'def-')), 'definition.json');+ writeFileSync(def, '{"name":"d"}');+ const t = rig((a) => (a[1] === 'inspect' ? '4242\n' : ''), { definition: () => def });+ const up = await t.c.up(ID, rs, record);+ expect(up.pid).toBe(4242);+ // Its unit's `podman start` is no `as.podman` call: the image lock is waited for before it, with no bound of a person's.+ expect(t.log).toEqual(['podman unshare find', 'tokens 00aa11bb22cc33dd C1:1.1', 'settled', 'start', 'podman inspect --format', '/usr/bin/systemctl --user is-active']);+ expect(t.calls[0].argv).toEqual(['podman', 'unshare', 'find', `${t.run}/runners`, `${t.run}/secrets`, '-mindepth', '1', '-delete']);+ expect([t.run, `${t.run}/runners`, `${t.run}/secrets`, `${t.run}/tokens`].map(mode)).toEqual([0o2750, 0o2770, 0o2770, 0o2750]);+ expect(readFileSync(`${t.run}/definition.json`, 'utf8')).toBe('{"name":"d"}');+ const boot = readFileSync(`${t.run}/boot.env`, 'utf8');+ expect(boot).toContain("SP_ROOT='/opt/slack-presence/releases/r1'\n");+ expect(boot).toContain('"forkPath":"/workspace"');+ expect(boot).toContain("SP_VERSION='v1'");+ expect(boot).not.toContain('PATH='); // a host path: the image's own stands+ expect(mode(`${t.run}/boot.env`)).toBe(0o640);+ });++ it('diagnose: waits for the image lock before the shell that runs podman logs', async () => {+ const t = rig(() => ' unit failed \n');+ expect(await t.c.diagnose(ID)).toBe('unit failed');+ expect(t.log).toEqual(['settled', '/bin/sh -c /usr/bin/systemctl --user status --no-pager --lines=0 "$1" 2>&1 | cut -c1-200; echo \'--- podman logs\'; /usr/bin/podman logs --tail 50 "$2" 2>&1; true']);+ });++ it('up: a first start has nothing to empty; any other failure to empty stops it', async () => {+ const none = rig((a) => (a[2] === 'find' ? fail("find: '/x/runners': No such file or directory\nfind: '/x/secrets': No such file or directory\n") : a[1] === 'inspect' ? '7' : ''));+ await expect(none.c.up(ID, rs)).resolves.toMatchObject({ pid: 7 });+ const denied = rig((a) => (a[2] === 'find' ? fail('find: cannot delete: Permission denied\n') : ''));+ await expect(denied.c.up(ID, rs)).rejects.toThrow();+ expect(denied.log).not.toContain('start');+ });++ it('up: the mounts are part of the start, given the pid; a container that could not get them is stopped', async () => {+ const t = rig((a) => (a[1] === 'inspect' ? '4242\n' : ''));+ const up = await t.c.up(ID, rs, record, async (pid) => void t.log.push(`mount ${pid}`));+ expect(t.log.slice(-2)).toEqual(['/usr/bin/systemctl --user is-active', 'mount 4242']);+ expect(up.mountMs).toBeGreaterThanOrEqual(0);+ expect((await t.c.up(ID, rs, record)).mountMs).toBeUndefined();+ const bad = rig((a) => (a[1] === 'inspect' ? '4242\n' : ''));+ await expect(bad.c.up(ID, rs, record, () => Promise.reject(new Error('sandbox-mount: refused')))).rejects.toThrow('sandbox-mount: refused');+ expect(bad.log.slice(-2)).toEqual(['podman stop --time', 'tokens closed']);+ });++ it('the definition in effect is written again for a running container, and removed when there is none', () => {+ const def = path.join(mkdtempSync(path.join(tmpdir(), 'def-')), 'definition.json');+ writeFileSync(def, '{"name":"one"}');+ let file: string | undefined = def;+ const t = rig(() => '', { definition: () => file });+ mkdirSync(t.run, { recursive: true });+ t.c.rewriteDefinition(ID);+ expect(readFileSync(`${t.run}/definition.json`, 'utf8')).toBe('{"name":"one"}');+ writeFileSync(def, '{"name":"two"}');+ t.c.rewriteDefinition(ID);+ expect(readFileSync(`${t.run}/definition.json`, 'utf8')).toBe('{"name":"two"}');+ expect(mode(`${t.run}/definition.json`)).toBe(0o640);+ file = undefined;+ t.c.rewriteDefinition(ID);+ expect(existsSync(`${t.run}/definition.json`)).toBe(false);+ });++ it('up: a spare names no session on its token socket', async () => {+ const t = rig((a) => (a[1] === 'inspect' ? '7' : ''));+ await t.c.up(ID, { id: ID, socket: '/s', version: 'v' });+ expect(t.log).toContain(`tokens ${ID} undefined`);+ });++ it('up: a start that fails stops the container and closes its token socket', async () => {+ const t = rig(() => '', { start: () => Promise.reject(new Error('start timed out')) });+ await expect(t.c.up(ID, rs, record)).rejects.toThrow('start timed out');+ expect(t.log.slice(-2)).toEqual(['podman stop --time', 'tokens closed']);+ });++ it('up: no pid within 5 s fails, and so does a pid whose unit is not active', async () => {+ const nopid = rig((a) => (a[1] === 'inspect' ? '0\n' : ''));+ const realNow = Date.now;+ let now = realNow();+ Date.now = () => (now += 1000);+ try {+ await expect(nopid.c.up(ID, rs, record)).rejects.toThrow('has no process');+ } finally {+ Date.now = realNow;+ }+ expect(nopid.log).toContain('tokens closed');+ // Podman keeps the last run's pid when the unit never came up.+ const inactive = rig((a) => (a[1] === 'inspect' ? '99' : a.includes('is-active') ? fail('', false) : ''));+ await expect(inactive.c.up(ID, rs, record)).rejects.toThrow('not active');+ expect(inactive.find('podman stop')).toHaveLength(1);+ });++ it('stop: 15 s for Podman; a container Podman does not know is down', async () => {+ const t = rig();+ await t.c.stop(ID);+ expect(t.calls).toEqual([{ argv: ['podman', 'stop', '--time', '10', `sp-runner-${ID}`], timeoutMs: TIMEOUTS.stop, repeatable: true }]);+ const gone = rig(() => fail('Error: no container with name or ID "sp-runner-x" found: no such container'));+ await gone.c.stop(ID);+ expect(gone.calls).toHaveLength(1);+ });++ it("stop: past its timeout, kills the payload's cgroup as the runners' user and never signals the unit", async () => {+ const cg = `/user.slice/user-1500.slice/[email protected]/slack.slice/slack-presence.slice/slack-presence-runners.slice/sp-runner-${ID}.service`;+ let active = 2;+ const t = rig((a) => (a[1] === 'stop' ? fail('', true) : a.includes('show') ? `${cg}\n` : a.includes('is-active') && active-- <= 0 ? fail('') : ''));+ await t.c.stop(ID);+ const sh = t.calls.find((x) => x.argv[0] === '/bin/sh')!;+ expect(sh.argv[2]).toContain('libpod-payload-*');+ expect(sh.argv[2]).toContain('cgroup.kill');+ expect(sh.argv.at(-1)).toBe(`/sys/fs/cgroup${cg}`);+ expect(t.calls.some((x) => x.argv.includes('kill'))).toBe(false);+ expect(t.find('is-active').length).toBeGreaterThan(1); // waited for the unit to go+ });++ it('stop: rejects, in one line, when the unit is still active after its cgroup was killed', async () => {+ const cg = `/user.slice/user-1500.slice/[email protected]/sp-runner-${ID}.service`;+ const realNow = Date.now;+ let now = realNow();+ Date.now = () => (now += 1000);+ try {+ const t = rig((a) => (a[1] === 'stop' ? fail('', true) : a.includes('show') ? `${cg}\n` : ''));+ const e = await t.c.stop(ID).catch((e) => e);+ expect(e).toBeInstanceOf(Error);+ expect(e.message).toBe(`container sp-runner-${ID} did not stop: its unit is still active after its cgroup was killed`);+ } finally {+ Date.now = realNow;+ }+ });++ it('stop: with no unit there is no cgroup to kill', async () => {+ const t = rig((a) => (a[1] === 'stop' ? fail('', true) : ''));+ await t.c.stop(ID);+ expect(t.calls.some((x) => x.argv[0] === '/bin/sh')).toBe(false);+ });++ it('remove: the container, then its home, 30 s each; never rejects', async () => {+ const t = rig();+ expect(await t.c.remove(ID)).toBe(true);+ expect(t.calls.map((x) => x.argv.slice(1))).toEqual([['rm', '--force', '--volumes', `sp-runner-${ID}`], ['volume', 'rm', '--force', `sp-home-${ID}`]]);+ expect(t.calls.every((x) => x.timeoutMs === TIMEOUTS.remove)).toBe(true);+ const bad = rig(() => fail('', true));+ expect(await bad.c.remove(ID)).toBe(false);+ expect(bad.calls).toHaveLength(2); // the volume is tried all the same+ });++ it('remove: says so, for what else the host keeps by the id (its preview ports)', async () => {+ const gone: string[] = [];+ const t = rig(() => '', { removed: (id) => void gone.push(id) });+ await t.c.remove(ID);+ expect(gone).toEqual([ID]);+ // A container Podman did not remove is still there, with its previews: nothing is said. A home that stayed alone changes nothing.+ await rig((a) => (a[1] === 'rm' ? fail('', true) : ''), { removed: (id) => void gone.push(`${id} while its container stays`) }).c.remove(ID);+ await rig((a) => (a[1] === 'volume' ? fail('in use') : ''), { removed: (id) => void gone.push(`${id} home stays`) }).c.remove(ID);+ expect(gone).toEqual([ID, `${ID} home stays`]);+ });++ it('only what changes nothing when made twice is repeatable after a wait for the image lock: stop, rm, the lists; never create, an exec, or what empties a run directory', async () => {+ const t = rig((a) => (a[1] === 'inspect' ? '7\n' : a[1] === 'ps' || a[1] === 'volume' ? '[]' : ''));+ await t.c.create(ID);+ await t.c.up(ID, rs, record);+ await t.c.execIn(ID, ['/bin/true'], { dir: '/', timeoutMs: 1000 });+ await t.c.stop(ID);+ await t.c.inventory();+ await t.c.recreate(ID);+ await t.c.remove(ID);+ const verbs = (repeatable: boolean) => [...new Set(t.calls.filter((x) => x.argv[0] === 'podman' && !!x.repeatable === repeatable).map((x) => x.argv[1]))].sort();+ expect(verbs(true)).toEqual(['ps', 'rm', 'stop', 'volume']);+ expect(verbs(false)).toEqual(['create', 'exec', 'inspect', 'unshare']);+ });++ it('recreate: the container alone goes; its home stays for the new one', async () => {+ const t = rig();+ await t.c.recreate(ID);+ expect(t.calls.map((x) => x.argv.slice(1, 3).join(' '))).toEqual(['rm --force', 'volume create', 'create --name']);+ expect(t.calls[0].argv).not.toContain('--volumes');+ });++ it('inventory: what Podman has under our label and names and on our run directories, 10 s each', async () => {+ const t = rig((a) => (a[1] === 'ps' ? ps() : a[1] === 'volume' ? vols : ''));+ const OTHER = 'ffee11bb22cc33dd';+ const ps = () => JSON.stringify([+ { Names: [`sp-runner-${ID}`], State: 'running', Labels: { 'sp.runner': ID, 'sp.abi': '1' }, Image: 'img:tag', Created: 1_700_000_000, Mounts: ['/home/agent', t.run] },+ { Names: ['other'], State: 'running', Labels: { 'sp.runner': ID }, Mounts: [t.run] }, // the label alone does not make it ours+ // Another host of this computer (another SP_RUN) made this one under the same Podman user: seen, never ours.+ { Names: [`sp-runner-${OTHER}`], State: 'running', Labels: { 'sp.runner': OTHER, 'sp.abi': '1' }, Mounts: ['/home/agent', `/run/elsewhere/sandbox/${OTHER}`] },+ ]);+ const [V1, V2, V3] = ['1111111111111111', '2222222222222222', '3333333333333333'];+ const at = '2026-11-12T10:00:00Z';+ const vols = JSON.stringify([+ { Name: `sp-home-${ID}`, CreatedAt: at, Labels: { 'sp.run': t.run } },+ { Name: `sp-home-${V1}`, CreatedAt: at, Labels: { 'sp.run': `/run/elsewhere/sandbox/${V1}` } }, // another host's+ { Name: `sp-home-${V2}`, CreatedAt: at, Labels: { 'sp.run': t.run } }, // another id's directory: not this host's for this id+ { Name: `sp-home-${V3}`, CreatedAt: at, Labels: {} }, // made before homes had the label+ { Name: 'unrelated' },+ ]);+ expect(await t.c.inventory()).toEqual({+ containers: [{ id: ID, state: 'running', abi: '1', image: 'img:tag', createdAt: 1_700_000_000_000 }],+ volumes: [{ id: ID, createdAt: Date.parse(at), mine: true }, { id: V1, createdAt: Date.parse(at), mine: false }, { id: V2, createdAt: Date.parse(at), mine: false }, { id: V3, createdAt: Date.parse(at) }],+ foreign: [OTHER],+ });+ expect(t.calls.every((x) => x.timeoutMs === TIMEOUTS.inventory)).toBe(true);+ await expect(rig(() => fail('', true)).c.inventory()).rejects.toThrow();+ });++ it('inventory: an id is sixteen hex digits; a label or a volume name that is anything else is nobody\'s, and reaches no path and no argv', async () => {+ const bad = ['../../etc', '--all', 'AAAAAAAAAAAAAAAA', `${ID}0`, `${ID}/..`, 'a b', ''];+ const t = rig((a) => (a[1] === 'ps'+ ? JSON.stringify(bad.flatMap((id) => [+ { Names: [`sp-runner-${id}`], State: 'running', Labels: { 'sp.runner': id, 'sp.abi': '1' }, Mounts: [path.join(path.dirname(t.run), id)] },+ { Names: [`sp-runner-${id}`], State: 'running', Labels: { 'sp.runner': id, 'sp.abi': '1' }, Mounts: ['/elsewhere'] },+ ]))+ : JSON.stringify(bad.map((id) => ({ Name: `sp-home-${id}`, CreatedAt: '2026-11-12T10:00:00Z' })))));+ expect(await t.c.inventory()).toEqual({ containers: [], volumes: [], foreign: [] });+ });++ const info = { id: ID, state: 'running', abi: '1', image: '', createdAt: 0 };+ const at = { runRoot: (id: string) => `/r/${id}` };+ const ps = (state: string) => JSON.stringify([{ Names: [`sp-runner-${ID}`], State: state, Labels: { 'sp.runner': ID, 'sp.abi': '1' }, Mounts: [`/r/${ID}`] }]);++ it('stale: Podman says running while the unit is not active, and still says so when asked again', async () => {+ const inactive = (state: string) => rig((a) => (a.includes('is-active') ? fail('') : a[1] === 'ps' ? ps(state) : ''), at);+ expect(await inactive('running').c.stale(info)).toBe(true);+ expect(await inactive('stopping').c.stale(info)).toBe(true);+ expect(await rig().c.stale(info)).toBe(false);+ expect(await inactive('running').c.stale({ ...info, state: 'exited' })).toBe(false);+ });++ it('stale: not a container that ended by itself since the inventory, nor one whose unit gave no answer', async () => {+ // Listed as running, then it exited (its idle exit, say): the unit is inactive and Podman says exited by now.+ const ended = rig((a) => (a.includes('is-active') ? fail('') : a[1] === 'ps' ? ps('exited') : ''), at);+ expect(await ended.c.stale(info)).toBe(false);+ const gone = rig((a) => (a.includes('is-active') ? fail('') : a[1] === 'ps' ? '[]' : ''));+ expect(await gone.c.stale(info)).toBe(false);+ await expect(rig((a) => (a.includes('is-active') ? fail('', true) : '')).c.stale(info)).rejects.toMatchObject({ timedOut: true });+ });++ it('execIn: as the session, in a directory, with stdin only when given', async () => {+ const t = rig(() => 'out');+ expect(await t.c.execIn(ID, ['/bin/true'], { dir: '/workspace', timeoutMs: 5 })).toBe('out');+ expect(t.calls[0].argv).toEqual(['podman', 'exec', '--user', '1500:1500', '--workdir', '/workspace', `sp-runner-${ID}`, '/bin/true']);+ });+});diff --git a/computer/src/host/sandbox/containers.ts b/computer/src/host/sandbox/containers.tsnew file mode 100644index 00000000..20e60fb3--- /dev/null+++ b/computer/src/host/sandbox/containers.ts@@ -0,0 +1,317 @@+// A thread's container through its life (work 103): create, bring up, stop,+// remove, recreate, list. Every Podman call is an argv from podman-args.ts,+// run as the runners' user (podman.ts) with the timeout of the spec's+// "Timeouts and failures" table, which TIMEOUTS holds.+//+// Invariants:+// - The host writes only the root of a run directory and its `tokens/`+// (sessions can write neither), by temporary file and rename; what a session+// may write (`runners/`, `secrets/`) is emptied before every start.+// - A start that fails after Start leaves no container running: `up` stops it+// and closes its token socket before it rejects. Its mounts are part of the+// start: a container that could not be given them does not stay up.+// - `definition.json` in a run directory is the definition in effect: written+// at every start, and again for a running container when it changes.+// - Stop never signals the unit (`systemctl --user kill` takes conmon with the+// payload, and Podman then says `running` for ever): past its timeout it+// kills the payload's cgroup.+// - A container whose unit is not active is not running, whatever Podman says:+// `stale` is how callers ask, and they recreate it. Recreating costs the+// container what it installed, so `stale` is never said of one that only+// ended between two looks.+// - `stop` resolves only for a container that is down: one that outlived+// Podman's stop and the kill of its cgroup rejects.+// - Stop, Remove, a home's creation and the lists are `repeatable` behind the+// image lock (podman.ts): each leaves the same behind made twice. Create, an exec, Pid+// (polled anyway) and what empties a run directory are made once.+// - An id the Inventory gives is sixteen hex digits: a label or a volume name+// that is anything else is left out, before it reaches a path or an argv.+// - A container is this host's only when it is mounted on this host's run+// directory for its id (Create mounts it at its own path). The runners'+// user's Podman is one per computer, and another host of the computer (other+// SP_RUN) has its containers there too: the Inventory names those `foreign`+// and nothing here, the restart or the sweep ever touches them.+// - A home says the same of itself: Create makes it first, with the label+// `sp.run` holding that run directory (Podman labels no volume a container+// only names), and the Inventory says `mine` of it by that label. A home+// made before the label has none, and gets none: `volume create --ignore`+// leaves an existing home as it is.++import path from 'node:path';+import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import type { RunnerSpec } from '../../protocol.js';+import { type RunRoot, runnersDir, secretsFor, tokenSocketFor } from '../../ipc.js';+import { log } from '../../log.js';+import { bootEnv } from './boot-env.js';+import type { AsRunner } from './podman.js';+import {+ HOME_LABEL, containerName, createArgs, emptyRunArgs, execArgs, homeArgs, inventoryArgs, logsArgs, pidArgs, recreateRemoveArgs, removeArgs, stopArgs, unitName,+} from './podman-args.js';+import type { SandboxRecord } from './records.js';++/** Milliseconds, from the spec's table. `start` bounds the unit's start, `pid` the wait for the container's first process after it. */+export const TIMEOUTS = { create: 60_000, start: 20_000, pid: 5_000, stop: 15_000, remove: 30_000, inventory: 10_000, unit: 5_000 } as const;+const PID_POLL_MS = 20;+const SYSTEMCTL = '/usr/bin/systemctl';++export interface ContainerInfo {+ /** The runner id (label `sp.runner`). */+ id: string;+ /** Podman's word: created, running, stopping, exited, … */+ state: string;+ /** The image ABI it was created under (label `sp.abi`). */+ abi: string;+ image: string;+ /** Unix milliseconds. */+ createdAt: number;+}++export interface Inventory {+ containers: ContainerInfo[];+ /** Home volumes, by runner id. `mine`: what its label says (true: this host's run directory for the id; false: another's); absent for a home without the label. */+ volumes: { id: string; createdAt: number; mine?: boolean }[];+ /** Runner ids of sandbox containers of the same Podman that are another host's (not on this host's run directories). */+ foreign: string[];+}++export interface ContainersDeps {+ as: AsRunner;+ /** Start the container's unit (launch.ts, the `podman` branch); resolves once the unit is started. */+ start(id: string, timeoutMs: number): Promise<void>;+ /** A runner's run root (`sandboxRunFor`). */+ runRoot(id: string): RunRoot;+ /** The host's SP_DATA, release, and the image and ABI of that release. */+ dataDir: string;+ root: string;+ image: string;+ abi: string;+ /** The model proxy's API socket, mounted into every container. */+ modelSocket: string;+ /** `runnerVars(env)`, read at every start. */+ vars(): Record<string, string>;+ /** The definition file in effect, if any (`definitionFile`). */+ definition(): string | undefined;+ /** `tokens.serveRunner`. */+ serveTokens(run: RunRoot, id: string, session: () => string | undefined): { close(): void };+ /** A sandbox's container was removed: what else the host keeps by its id goes too (its preview ports, C9). Not called while Podman still has the container. */+ removed?(id: string): void;+ sleep?: (ms: number) => Promise<void>;+}++export interface Up {+ /** The container's first process, as the host sees it. */+ pid: number;+ /** Its token socket, open since before the start; the caller closes it when the runner is gone. */+ tokens: { close(): void };+ /** Start until Pid. */+ startMs: number;+ /** The mounts, when `up` was given any. */+ mountMs?: number;+}++export type Containers = ReturnType<typeof containers>;++/** Write `file` whole: a temporary file beside it, then a rename. */+function writeWhole(file: string, text: string, mode: number) {+ const tmp = `${file}.${process.pid}.tmp`;+ writeFileSync(tmp, text, { mode });+ chmodSync(tmp, mode); // the umask may have taken bits+ renameSync(tmp, file);+}++function dir(p: string, mode: number) {+ mkdirSync(p, { recursive: true });+ chmodSync(p, mode);+}++/** A sandbox id as the host makes one (start.ts): what Podman lists under any other is not ours, and never becomes a path or an argument. */+const SANDBOX_ID = /^[0-9a-f]{16}$/;+const absent = (e: unknown) => /no such container|no container with name or ID/i.test(String((e as { stderr?: string })?.stderr ?? ''));++export function containers(d: ContainersDeps) {+ const { as } = d;+ const sleep = d.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));++ /** Create the container (60 s), its home before it (60 s). Its run directory is a mount source, so it exists first. Resolves with the time taken. */+ async function create(id: string): Promise<number> {+ const t0 = Date.now();+ const run = d.runRoot(id);+ dir(run, 0o2750);+ await as.podman(homeArgs(id, run), { timeoutMs: TIMEOUTS.create, repeatable: true });+ await as.podman(createArgs({ id, run, dataDir: d.dataDir, image: d.image, abi: d.abi, modelSocket: d.modelSocket }), { timeoutMs: TIMEOUTS.create });+ return Date.now() - t0;+ }++ /** True when the container's unit is active. */+ const unitActive = (id: string) =>+ as.run([SYSTEMCTL, '--user', 'is-active', '--quiet', unitName(id)], { timeoutMs: TIMEOUTS.unit }).then(() => true, () => false);++ /** The definition in effect, into the run directory (its root is the host's alone to write). The runner reads it at every use. */+ function rewriteDefinition(id: string) {+ const file = path.join(d.runRoot(id), 'definition.json');+ const def = d.definition();+ if (def) writeWhole(file, readFileSync(def, 'utf8'), 0o640);+ else rmSync(file, { force: true });+ }++ /** The run directory as a start needs it: what the session wrote gone, the host's files current. */+ async function prepareRun(id: string, spec: RunnerSpec) {+ const run = d.runRoot(id);+ await as.podman(emptyRunArgs(run), { timeoutMs: TIMEOUTS.remove }).catch((e) => {+ const lines = String(e?.stderr ?? '').trim().split('\n').filter(Boolean);+ if (!lines.length || !lines.every((l) => /No such file or directory/.test(l))) throw e; // a first start has neither directory+ });+ dir(run, 0o2750);+ dir(runnersDir(run), 0o2770);+ dir(path.dirname(secretsFor(run, id)), 0o2770);+ dir(path.dirname(tokenSocketFor(run, id)), 0o2750);+ rewriteDefinition(id);+ writeWhole(path.join(run, 'boot.env'), bootEnv({ root: d.root, spec, vars: d.vars() }), 0o640);+ return run;+ }++ /** The container's first process once it has one (polled every 20 ms, 5 s in all). */+ async function pid(id: string): Promise<number> {+ const end = Date.now() + TIMEOUTS.pid;+ for (;;) {+ const left = end - Date.now();+ const out = left > 0 ? await as.podman(pidArgs(id), { timeoutMs: left }).catch(() => '') : '';+ const n = Number(out.trim());+ if (Number.isInteger(n) && n > 0) return n;+ if (Date.now() + PID_POLL_MS >= end) throw new Error(`container ${containerName(id)} has no process ${TIMEOUTS.pid} ms after its start`);+ await sleep(PID_POLL_MS);+ }+ }++ /**+ * Bring the created container up for `spec`: its run directory, its token socket, Start, then Pid.+ * `record`: the thread it serves; none for a container that serves no thread yet.+ * `mount`: what gives the running container its mounts (mounts.ts), from its first process; part of the start.+ */+ async function up(id: string, spec: RunnerSpec, record?: SandboxRecord, mount?: (pid: number) => Promise<void>): Promise<Up> {+ const run = await prepareRun(id, spec);+ const tokens = d.serveTokens(run, id, () => record?.key);+ const t0 = Date.now();+ try {+ // The unit's `podman start` is not `as.podman`'s: behind the image lock it would run out of the unit's time, not wait.+ await as.settled();+ await d.start(id, TIMEOUTS.start);+ const p = await pid(id);+ // Podman's pid is the previous run's when the unit never came up: never trusted while the unit is inactive.+ if (!(await unitActive(id))) throw new Error(`unit ${unitName(id)} is not active after its start`);+ const startMs = Date.now() - t0;+ if (!mount) return { pid: p, tokens, startMs };+ await mount(p);+ return { pid: p, tokens, startMs, mountMs: Date.now() - t0 - startMs };+ } catch (e) {+ await stop(id).catch((x) => log.warn(`container ${id} not stopped after a failed start: ${x?.message ?? x}`));+ tokens.close();+ throw e;+ }+ }++ /** Kill the payload's cgroup, as the runners' user, and wait for the unit to go (5 s). True when nothing runs in the unit any more. */+ async function killPayload(id: string): Promise<boolean> {+ const cgroup = (await as.run([SYSTEMCTL, '--user', 'show', '-p', 'ControlGroup', '--value', unitName(id)], { timeoutMs: TIMEOUTS.unit })).trim();+ if (!cgroup.startsWith('/') || !cgroup.endsWith(`/${unitName(id)}`)) return true; // no such unit: nothing is running in it+ await as.run(['/bin/sh', '-c', 'for d in "$1"/libpod-payload-*; do [ -e "$d/cgroup.kill" ] && echo 1 > "$d/cgroup.kill"; done; true', 'sh', `/sys/fs/cgroup${cgroup}`],+ { timeoutMs: TIMEOUTS.unit });+ for (const end = Date.now() + TIMEOUTS.unit; ; await sleep(100)) {+ if (!(await unitActive(id))) return true;+ if (Date.now() >= end) return false;+ }+ }++ /**+ * Stop the container: SIGTERM, SIGKILL after `seconds` (15 s in all), then the payload's cgroup if Podman did not manage.+ * Resolves when it is down or was never there; rejects, in one line, when its unit is still active after all that.+ */+ async function stop(id: string, seconds = 10): Promise<void> {+ try {+ await as.podman(stopArgs(id, seconds), { timeoutMs: TIMEOUTS.stop, repeatable: true });+ } catch (e) {+ if (absent(e)) return;+ log.warn(`podman stop ${containerName(id)} failed (${(e as Error)?.message ?? e}); killing its cgroup`);+ if (!(await killPayload(id))) throw new Error(`container ${containerName(id)} did not stop: its unit is still active after its cgroup was killed`);+ }+ }++ /** Remove the container and its home (30 s each). Never rejects: what stays is logged and the sweep's. True when both went. */+ async function remove(id: string): Promise<boolean> {+ const [container, ...rest] = removeArgs(id);+ const rm = (args: string[]) => as.podman(args, { timeoutMs: TIMEOUTS.remove, repeatable: true }).then(() => true, (e) => (log.warn(`sandbox ${id} not removed: ${e?.message ?? e}`), false));+ const gone = await rm(container);+ let ok = gone;+ for (const args of rest) ok = (await rm(args)) && ok;+ // A container that stayed still has its previews; whoever removes it later says so then.+ if (gone) d.removed?.(id);+ return ok;+ }++ /** Remove the container alone and create it again from the current image; the home volume stays. Resolves with the time taken. */+ async function recreate(id: string): Promise<number> {+ const t0 = Date.now();+ await as.podman(recreateRemoveArgs(id), { timeoutMs: TIMEOUTS.remove, repeatable: true });+ await create(id);+ return Date.now() - t0;+ }++ /** Every sandbox container and home volume Podman has (10 s each). */+ async function inventory(): Promise<Inventory> {+ const args = inventoryArgs();+ const list = { timeoutMs: TIMEOUTS.inventory, repeatable: true };+ const [cs, vs] = await Promise.all([as.podman(args.containers, list), as.podman(args.volumes, list)]);+ const parse = (text: string): { Labels?: Record<string, string>; Names?: string[]; Name?: string; State?: string; Image?: string; Created?: number; CreatedAt?: string; Mounts?: string[] }[] => {+ const v = JSON.parse(text.trim() || '[]');+ if (!Array.isArray(v)) throw new Error('podman: not a list');+ return v;+ };+ const foreign: string[] = [];+ return {+ containers: parse(cs).flatMap((c) => {+ const id = c?.Labels?.['sp.runner'];+ // The label and the name agree for every container the host made; anything else is not ours to touch.+ if (typeof id !== 'string' || !SANDBOX_ID.test(id) || !c.Names?.includes?.(containerName(id))) return [];+ if (!Array.isArray(c.Mounts) || !c.Mounts.includes(d.runRoot(id))) return (foreign.push(id), []);+ return [{ id, state: String(c.State ?? ''), abi: String(c.Labels?.['sp.abi'] ?? ''), image: String(c.Image ?? ''), createdAt: Number(c.Created ?? 0) * 1000 }];+ }),+ volumes: parse(vs).flatMap((v) => {+ const m = /^sp-home-([0-9a-f]{16})$/.exec(String(v?.Name ?? ''));+ if (!m) return [];+ const label = v.Labels?.[HOME_LABEL];+ return [{ id: m[1], createdAt: Date.parse(String(v.CreatedAt ?? '')) || 0, ...(typeof label === 'string' && { mine: label === d.runRoot(m[1]) }) }];+ }),+ foreign,+ };+ }++ const runs = (state: string | undefined) => state === 'running' || state === 'stopping';++ /**+ * Podman says it runs, its unit says nothing does: the unit was killed from outside. `podman start` does nothing to it and `podman stop` never ends.+ * `c` is a moment old, and a container that ends by itself is `exited` to Podman before its unit is gone: so Podman is asked again once the unit+ * is seen inactive, and only one it still calls running is stale. A unit whose state could not be read (no answer) rejects: that is not "inactive".+ */+ async function stale(c: ContainerInfo): Promise<boolean> {+ if (!runs(c.state)) return false;+ const inactive = await as.run([SYSTEMCTL, '--user', 'is-active', '--quiet', unitName(c.id)], { timeoutMs: TIMEOUTS.unit }).then(+ () => false,+ (e) => {+ if ((e as { timedOut?: boolean })?.timedOut) throw e;+ return true;+ },+ );+ return inactive && runs((await inventory()).containers.find((x) => x.id === c.id)?.state);+ }++ /** A command in the running container, as the session's user: its stdout. */+ const execIn = (id: string, argv: string[], o: { dir: string; timeoutMs: number; stdin?: string | Buffer }) =>+ as.podman(execArgs(id, argv, { dir: o.dir, interactive: o.stdin !== undefined }), { timeoutMs: o.timeoutMs, stdin: o.stdin });++ /** For the error of a start that never became ready: the unit's status and the last 50 lines the container wrote. */+ const diagnose = (id: string) =>+ as.settled().then(() => as.run(['/bin/sh', '-c', `${SYSTEMCTL} --user status --no-pager --lines=0 "$1" 2>&1 | cut -c1-200; echo '--- podman logs'; /usr/bin/podman ${logsArgs(id).slice(0, -1).join(' ')} "$2" 2>&1; true`,+ 'sh', unitName(id), containerName(id)], { timeoutMs: TIMEOUTS.inventory })).then((s) => s.trim(), (e) => `no diagnosis: ${e?.message ?? e}`);++ return { create, up, pid, rewriteDefinition, stop, remove, recreate, inventory, execIn, stale, unitActive, diagnose };+}diff --git a/computer/src/host/sandbox/host.test.ts b/computer/src/host/sandbox/host.test.tsnew file mode 100644index 00000000..04761b51--- /dev/null+++ b/computer/src/host/sandbox/host.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';+import type { Telemetry } from '../../telemetry/emitter.js';+import { sandboxHost } from './host.js';++const deps = (env: NodeJS.ProcessEnv) => ({+ env, run: '/nonexistent/run', data: '/nonexistent/data', root: '/nonexistent/root', version: 'v', tm: {} as Telemetry, modelSocket: '/run/oc-modelproxy/api.sock', models: { spare: async () => {}, closed: () => {} },+ mint: async () => undefined, serveTokens: () => ({ close() {} }), serveHelper: () => ({}) as never, running: () => false, adopt: async () => undefined, unpreview: () => {},+});++describe('sandboxHost', () => {+ it('does not start without a runner user: sessions would run as the host', () => {+ expect(() => sandboxHost(deps({ SP_IMAGE: 'i:1', SP_IMAGE_ABI: '1' }))).toThrow(/needs a runner user/);+ });++ it('does not start without the image and its ABI', () => {+ expect(() => sandboxHost(deps({ SP_RUNNER_USER: 'root', SP_IMAGE_ABI: '1' }))).toThrow(/needs SP_IMAGE and SP_IMAGE_ABI/);+ expect(() => sandboxHost(deps({ SP_RUNNER_USER: 'root', SP_IMAGE: 'i:1' }))).toThrow(/needs SP_IMAGE and SP_IMAGE_ABI/);+ });+});diff --git a/computer/src/host/sandbox/host.ts b/computer/src/host/sandbox/host.tsnew file mode 100644index 00000000..eedebadc--- /dev/null+++ b/computer/src/host/sandbox/host.ts@@ -0,0 +1,183 @@+// What a `podman` host is made of (work 103): the runners' user, the image of+// its release, the records, the containers, the starts, the virtual preview+// ports, the spares and where a session's terminal and files are, put together+// from the host's environment. host/main.ts makes one when SP_LAUNCH=podman and+// asks it for nothing else.+//+// It also turns the workspaces' two seams its way, once, when it is made: the+// scripts that work on a person's clones with no session run in a helper+// container (scripts.ts), and housekeeping prunes a thread's build+// directories without host git (artifacts.ts), then prunes the threads idle+// beyond retention (prune.ts).+//+// Invariant: a sandbox whose container was removed, by whichever path, has+// its named previews unpreviewed at the gateway before its virtual ports are+// freed; a name the gateway did not hear of stays owed (previews.ts). While+// Podman still has the container (a Remove that failed) it keeps both.+//+// Invariant: a `podman` host that cannot sandbox every session does not start.+// Without a runners' user it would run sessions as itself, without SP_IMAGE+// and SP_IMAGE_ABI it has nothing to run them in; each of these throws here,+// at boot, never at a first message.+//+// Invariant: a container's token socket asks for the thread of its record,+// whatever the runner behind it is taken for, and a container with no record+// (a spare, step 10) is refused: with no session named, the gateway would+// answer with a token of the organization.+//+// Invariant: the helpers' token socket gives GitHub tokens for the+// definition's repositories only, for no session (tokens.ts `serveHelper`).++import type net from 'node:net';+import path from 'node:path';+import type { Person, SessionSpec } from '../../protocol.js';+import type { RunnerApi } from '../../protocol-api.js';+import { type RunRoot, sandboxRunFor, socketFor } from '../../ipc.js';+import { log } from '../../log.js';+import { runnerVars } from '../../runner-env.js';+import type { Telemetry } from '../../telemetry/emitter.js';+import { definitionFile, forkDir, loadDefinition, repoSlug, useForkKeeper, useScripts, workspacesEnabled } from '../../workspaces/index.js';+import { launch } from '../launch.js';+import { dialSocket } from '../runner-sockets.js';+import { runnerUser } from '../runner-user.js';+import { sandboxArtifacts } from './artifacts.js';+import { containers } from './containers.js';+import { mounts } from './mounts.js';+import { asRunner } from './podman.js';+import { terminalHangUpArgs } from './podman-args.js';+import { previewPorts } from './preview-ports.js';+import { type SandboxRecord, sandboxRecords } from './records.js';+import { type SandboxPlace, sandboxScripts } from './scripts.js';+import { type SpareDeps, sandboxSpares } from './spares.js';+import { sandboxPrune } from './prune.js';+import { sandboxStarts } from './start.js';+import { SWEEP_AGE_MS, sandboxSweep } from './sweep.js';+import { threadLocks } from './thread-lock.js';+import { sandboxUses } from './use.js';+import { sandboxWorkspaces } from './workspace.js';++export interface SandboxHostDeps {+ env: NodeJS.ProcessEnv;+ /** HOST_RUN and HOST_DATA. */+ run: string;+ data: string;+ /** The release the host runs from, and its version. */+ root: string;+ version: string;+ /** Where runners reach the model proxy's API (SP_MODEL_SOCKET or its default). */+ modelSocket: string;+ /** The host's model access (model-access.ts): a spare is bound at the model proxy before its container starts. */+ models: SpareDeps['models'];+ tm: Telemetry;+ /** Both are asked for at a start, not here: the host builds what answers them after this. */+ mint(spec: SessionSpec, runnerId: string, run: RunRoot): Promise<RunnerApi | undefined>;+ serveTokens(run: RunRoot, id: string, session: () => string | undefined): { close(): void };+ /** `tokens.serveHelper`. */+ serveHelper(socket: string, allowed: () => string[]): net.Server;+ /** True while the runner with this id is connected. */+ running(id: string): boolean;+ /** Take a runner found running at the host's start on as its record's (start-runner.ts `adopt`, verified). */+ adopt(record: SandboxRecord, run: RunRoot, sock: net.Socket): Promise<unknown>;+ /** A removed sandbox's preview name: tell the gateway (previews.ts `forget`). `from`: its thread, '' when it had no record. */+ unpreview(name: string, from: string): void;+ /** SP_SWEEP_AGE_MS: how old an object without a thread must be for the sweep (10 minutes). */+ sweepAgeMs?: number;+}++/** A sandboxed thread's workspace on the host, from its record: the runner itself knows it as `/workspace`. */+export const sandboxWorkspace = (r: SandboxRecord) => forkDir({ dir: r.person } as Person, r.key);++/** On a `podman` host every thread runs in its own container, and nothing runs outside one. */+export function sandboxHost(d: SandboxHostDeps) {+ const { env } = d;+ const user = runnerUser(env);+ if (!user) throw new Error('SP_LAUNCH=podman needs a runner user (SP_RUNNER_USER): this host would run sessions as itself. deploy/vm/sp-host.sh sets one up.');+ const { SP_IMAGE: image, SP_IMAGE_ABI: abi } = env;+ if (!image || !abi) throw new Error("SP_LAUNCH=podman needs SP_IMAGE and SP_IMAGE_ABI; the release's .sp-version.env sets both");+ const runRoot = (id: string) => sandboxRunFor(d.run, id);+ const records = sandboxRecords(path.join(d.data, 'state', 'sandboxes'));+ const locks = threadLocks();+ const ports = previewPorts(path.join(d.data, 'state', 'previews.json'));+ const as = asRunner(user.sudo);+ // A container's token socket asks for its record's thread; one with no record (a spare) is refused.+ const serveTokens: SandboxHostDeps['serveTokens'] = (run, id, session) => d.serveTokens(run, id, () => {+ const key = session() || records.get(id)?.key;+ if (!key) throw new Error('this runner serves no thread'); // a spare: nothing to ask a token for+ return key;+ });+ const all = containers({+ as, runRoot, dataDir: d.data, root: d.root, image, abi, modelSocket: d.modelSocket,+ start: (id, ms) => launch({ id, socket: socketFor(runRoot(id), id), version: d.version }, 'podman', env, d.root, ms),+ vars: () => runnerVars(env), definition: definitionFile,+ serveTokens,+ removed: (id) => {+ for (const e of ports.all()) if (e.id === id && e.name) d.unpreview(e.name, records.get(id)?.key ?? '');+ ports.releaseAll(id);+ },+ });+ const helperRun = path.join(d.run, 'helper');+ const mnt = mounts({ as, root: d.root, dataDir: d.data });+ const uses = sandboxUses({ as, records, workspace: mnt.workspace, unitActive: all.unitActive });+ const scripts = sandboxScripts({ as, sudo: user.sudo, tm: d.tm, root: d.root, dataDir: d.data, helperRun, image, execIn: all.execIn, enter: uses.enter, running: all.unitActive });+ const workspace = sandboxWorkspaces({ as, records, mounts: mnt, scripts: scripts.sessionScripts, pid: all.pid });+ const artifacts = sandboxArtifacts({ as, records, locks, mounts: mnt, helper: scripts.helperScripts, running: d.running, claim: uses.claim });+ // A clones directory is `<people>/<person>/ws`: the helper is that person's.+ useScripts((clonesDir) => scripts.helperScripts(path.basename(path.dirname(clonesDir))));+ const dial = (socket: string) => dialSocket(socket, { uid: user.uid });+ const sweep = sandboxSweep({ as, tm: d.tm, records, locks, containers: all, runDir: path.join(d.run, 'sandbox'), runRoot, dataDir: d.data,+ serveTokens, dial, adopt: d.adopt, ageMs: d.sweepAgeMs,+ // A spare is this host's from before its Create, though its runner connects only seconds later: never swept meanwhile.+ running: (id) => d.running(id) || spares.has(id) });+ /** Step 10: spares are containers too (spares.ts); pool.ts decides how many. */+ const spares = sandboxSpares({ tm: d.tm, records, locks, containers: all, models: d.models, runRoot, version: d.version, mint: d.mint, workspace, dial, deleteRun: sweep.deleteRun });+ const prune = sandboxPrune({ as, records, locks, mounts: mnt, helper: scripts.helperScripts, running: d.running, claim: uses.claim, lastUsed: artifacts.lastUsed,+ remove: all.remove, deleteRun: sweep.deleteRun });+ useForkKeeper(async (person) => (await artifacts.pruneIdle(person.dir), prune.pruneIdle(person.dir)));+ return {+ stop: all.stop,+ spares,+ starts: sandboxStarts({ tm: d.tm, records, locks, containers: all, runRoot, image, abi, version: d.version, mint: d.mint, workspace, workspaces: workspacesEnabled, dial }),+ /** Host restart: the running containers taken back, by id (sweep.ts). */+ reconcile: sweep.reconcile,+ /** One sweep of what belongs to no thread; never rejects. */+ sweep: sweep.sweep,+ /** Containers by state and the disk, as of the last sweep (`host.sample`). */+ health: sweep.health,+ /** Sweep now and from then on, one pass at a time: every half of the age an object must have, at most every 5 minutes. */+ sweeping() {+ let busy = false;+ const pass = () => !busy && ((busy = true), void sweep.sweep().finally(() => (busy = false)));+ pass();+ return setInterval(pass, Math.min(5 * 60_000, Math.max(1000, (d.sweepAgeMs ?? SWEEP_AGE_MS) / 2))).unref();+ },+ /** Where a session's terminal and files are (api-host `sandbox`): from its record, never from what a runner said. */+ async place(spec: SessionSpec): Promise<SandboxPlace | undefined> {+ const r = records.find(spec.owner.dir, spec.key);+ return r && { id: r.id, person: r.person, workspace: mnt.workspace(r), running: await all.unitActive(r.id) };+ },+ /** Where the `/files` scripts of a place run (api-wire.ts). */+ files: scripts.filesPlace,+ /** How a terminal enters a session's sandbox, and hangs up a helper its unit left there (terminal.ts `inside`). */+ terminal: {+ enter: (id: string) => uses.enter(id).then((u) => ({ running: u.place.running, leave: u.leave })),+ hangUp: (id: string, unit: string) => void as.podman(terminalHangUpArgs(id, unit), { timeoutMs: 20_000 }).catch(() => {}),+ },+ /** The virtual ports, and how a container's preview socket is reached (previews.ts). */+ previews: { ports, run: runRoot, uid: user.uid },+ /** `checkout_repo` of a sandboxed session, by its runner id. */+ checkout: workspace.checkout,+ /** A delivery to a sandboxed session: its record is used now. */+ touch: workspace.touch,+ /** The definition in effect changed: every running container reads the new one. `ids`: the runners connected. */+ definitionChanged(ids: string[]) {+ for (const id of ids)+ try {+ all.rewriteDefinition(id);+ } catch (e) {+ log.warn(`sandbox ${id}: definition not rewritten: ${(e as Error)?.message ?? e}`);+ }+ },+ /** Open the helpers' token socket; the caller closes it when the host stops. */+ serveHelpers: () => d.serveHelper(path.join(helperRun, 'token.sock'), () => (workspacesEnabled() ? loadDefinition().repos.map((r) => repoSlug(r.remote)) : [])),+ };+}diff --git a/computer/src/host/sandbox/image-lock.test.ts b/computer/src/host/sandbox/image-lock.test.tsnew file mode 100644index 00000000..17885ef7--- /dev/null+++ b/computer/src/host/sandbox/image-lock.test.ts@@ -0,0 +1,145 @@+import { execFile, spawn } from 'node:child_process';+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import { imageBusy, imageSettled } from './image-lock.js';+import { asRunner, type Exec, PodmanError } from './podman.js';++describe('imageSettled', () => {+ it('costs nothing where provisioning never took the lock', async () => {+ const flock = vi.fn(async () => 0);+ expect(await imageSettled({ exists: () => false, flock })).toBe(true);+ expect(flock).not.toHaveBeenCalled();+ });++ it('takes a shared lock with a bound, and goes on when the bound passes or flock cannot run', async () => {+ const flock = vi.fn(async (_: string[]) => 1 as number | undefined);+ // Still held after the bound: it says so, and who called decides (podman.ts).+ await expect(imageSettled({ lock: '/run/x.lock', waitS: 7, exists: () => true, flock })).resolves.toBe(false);+ expect(flock.mock.calls[0][0]).toEqual(['--shared', '--timeout', '7', '/run/x.lock', '/usr/bin/true']);+ await expect(imageSettled({ exists: () => true, flock: async () => undefined })).resolves.toBe(true);+ });++ it('after a wait that was a real one, waits for a run queued behind it too; within the one bound', async () => {+ let t = 0;+ const waits = [40_000, 30_000, 5];+ const flock = vi.fn(async (_: string[]) => ((t += waits.shift() ?? 0), 0));+ await imageSettled({ waitS: 100, exists: () => true, flock, now: () => t, nextMs: 1 });+ expect(flock.mock.calls.map((c) => c[0][2])).toEqual(['100', '60', '30']);+ // The file left behind by a run that died: one flock, no second look.+ const left = vi.fn(async () => 0);+ await imageSettled({ exists: () => true, flock: left, now: () => 0, nextMs: 1 });+ expect(left).toHaveBeenCalledTimes(1);+ // The bound is for all of it.+ t = 0;+ const long = vi.fn(async (_: string[]) => ((t += 60_000), 0));+ await imageSettled({ waitS: 100, exists: () => true, flock: long, now: () => t, nextMs: 1 });+ expect(long).toHaveBeenCalledTimes(2);+ });++ it('busy: only while the file is there and held', async () => {+ expect(await imageBusy({ exists: () => false })).toBe(false);+ expect(await imageBusy({ exists: () => true, flock: async () => 0 })).toBe(false);+ expect(await imageBusy({ exists: () => true, flock: async () => undefined })).toBe(false);+ const flock = vi.fn(async (_: string[]) => 1);+ expect(await imageBusy({ lock: '/run/x.lock', exists: () => true, flock })).toBe(true);+ expect(flock.mock.calls[0][0]).toEqual(['--shared', '--nonblock', '/run/x.lock', '/usr/bin/true']);+ });++ it.runIf(existsSync('/usr/bin/flock'))('waits for as long as the lock is held', async () => {+ const dir = mkdtempSync(path.join(os.tmpdir(), 'image-lock-'));+ const lock = path.join(dir, 'lock');+ writeFileSync(lock, '');+ // Free: at once.+ let t0 = Date.now();+ await imageSettled({ lock });+ expect(Date.now() - t0).toBeLessThan(400);+ const holder = spawn('/usr/bin/flock', ['--exclusive', lock, '/usr/bin/sleep', '0.6'], { stdio: 'ignore' });+ await new Promise((r) => setTimeout(r, 150));+ t0 = Date.now();+ await imageSettled({ lock });+ expect(Date.now() - t0).toBeGreaterThanOrEqual(300);+ // A holder that died holds nothing.+ const dead = spawn('/usr/bin/flock', ['--exclusive', lock, '/usr/bin/sleep', '30'], { stdio: 'ignore' });+ await new Promise((r) => setTimeout(r, 150));+ await new Promise<void>((r) => execFile('/usr/bin/pkill', ['-KILL', '-P', String(dead.pid)], () => (dead.kill('SIGKILL'), r())));+ t0 = Date.now();+ await imageSettled({ lock });+ expect(Date.now() - t0).toBeLessThan(1000);+ holder.kill();+ rmSync(dir, { recursive: true, force: true });+ });+});++describe('asRunner with the image lock', () => {+ it('settled: with no bound it waits as podman() does and goes on; with one it refuses when the lock is still held then', async () => {+ const asked: (number | undefined)[] = [];+ const exec = (() => ({})) as unknown as Exec;+ const held = asRunner(['/usr/bin/sudo'], exec, async (d) => (asked.push(d?.waitS), false));+ await expect(held.settled()).resolves.toBeUndefined();+ const e = await held.settled(10_000).catch((x) => x);+ expect([e.name, e.message, e.retryable]).toEqual(['Unavailable', 'The computer is updating, try again in a few minutes.', true]);+ expect(asked).toEqual([undefined, 10]);+ await expect(asRunner(['/usr/bin/sudo'], exec, async () => true).settled(10_000)).resolves.toBeUndefined();+ });++ it('starts no Podman call before provisioning is done, and other commands at once', async () => {+ const started: string[] = [];+ const exec = ((_cmd: string, args: string[], _o: unknown, cb: (e: null, out: string, err: string) => void) => {+ started.push(args.includes('/usr/bin/podman') ? 'podman' : 'other');+ queueMicrotask(() => cb(null, '', ''));+ return {};+ }) as unknown as Exec;+ let free!: () => void;+ const settled = new Promise<void>((r) => (free = r));+ const as = asRunner(['/usr/bin/sudo'], exec, () => settled);+ const call = as.podman(['ps'], { timeoutMs: 1000 });+ await as.run(['/usr/bin/systemctl', '--user', 'is-active', 'x'], { timeoutMs: 1000 });+ expect(started).toEqual(['other']);+ free();+ await call;+ expect(started).toEqual(['other', 'podman']);+ });++ it('a Podman call that ran out of time while provisioning holds the lock is made once more, after the wait, only when its caller called it repeatable', async () => {+ const rig = (busy: boolean, fail: (n: number) => Error | null) => {+ const log: string[] = [];+ let n = 0;+ const exec = ((_cmd: string, _args: string[], _o: unknown, cb: (e: Error | null, out: string, err: string) => void) => {+ log.push('podman');+ const e = fail(n++);+ if (e) queueMicrotask(() => cb(e, '', ''));+ else queueMicrotask(() => cb(null, 'ok', ''));+ return { kill: () => {} };+ }) as unknown as Exec;+ return { log, as: asRunner(['/usr/bin/sudo'], exec, async () => void log.push('settled'), async () => (log.push('busy?'), busy)) };+ };+ const failed = rig(true, () => Object.assign(new Error('exit 125'), { code: 125 }));+ await expect(failed.as.podman(['ps'], { timeoutMs: 1000, repeatable: true })).rejects.toThrow(PodmanError);+ expect(failed.log).toEqual(['settled', 'podman']);+ // Timing out is the host's own timer: 20 ms, and a command that ends only when it is killed.+ const slow = (busy: boolean) => {+ const log: string[] = [];+ let n = 0;+ const exec = ((_cmd: string, _args: string[], _o: unknown, cb: (e: Error | null, out: string, err: string) => void) => {+ log.push('podman');+ if (n++) queueMicrotask(() => cb(null, 'ok', ''));+ return { kill: () => cb(new Error('killed'), '', '') };+ }) as unknown as Exec;+ return { log, as: asRunner(['/usr/bin/sudo'], exec, async () => void log.push('settled'), async () => (log.push('busy?'), busy)) };+ };+ const held = slow(true);+ expect(await held.as.podman(['ps'], { timeoutMs: 20, repeatable: true })).toBe('ok');+ expect(held.log).toEqual(['settled', 'podman', 'busy?', 'settled', 'podman']);+ const free = slow(false);+ await expect(free.as.podman(['ps'], { timeoutMs: 20, repeatable: true })).rejects.toMatchObject({ timedOut: true });+ expect(free.log).toEqual(['settled', 'podman', 'busy?']);+ // Whatever the verb: a call nobody called repeatable (a script's exec, a create, a mount) timed out, lock or no lock, and ran once.+ for (const args of [['exec', 'sp-runner-x', '/bin/sh', 'ws-add.sh'], ['create', '--name', 'x'], ['unshare', 'rm', '-rf', '--', '/x'], ['ps']]) {+ const once = slow(true);+ await expect(once.as.podman(args, { timeoutMs: 20 })).rejects.toMatchObject({ timedOut: true });+ expect(once.log).toEqual(['settled', 'podman']);+ }+ });+});diff --git a/computer/src/host/sandbox/image-lock.ts b/computer/src/host/sandbox/image-lock.tsnew file mode 100644index 00000000..a54806c1--- /dev/null+++ b/computer/src/host/sandbox/image-lock.ts@@ -0,0 +1,92 @@+// Waiting for provisioning to finish with Podman's storage (work 103). While+// deploy/vm/sandbox.sh pulls an image and warms its user-namespace copy, the+// storage lock holds every other Podman call of the runners' user: measured on+// Podman 4.9.3 with a 3.78 GB image on 2 vCPU, `exec`, `stop`, `start`,+// `create`, `rm`, `ps`, `inspect`, `volume ls` and `image exists` each waited+// the whole 124 s of the warm-up, and up to 13 s while a 300 MB layer was+// applied. A self-update does that with sessions alive, and a call that waits+// that long runs out of its own time and fails a person's message.+//+// So sandbox.sh holds an exclusive flock(2) on IMAGE_LOCK for as long as it+// does either, and the host takes a shared one for an instant before each of+// its Podman calls: it waits instead of timing out. A call somebody is+// waiting for at a browser or a command line (a terminal open, `/files`)+// waits a few seconds only and is then refused with words for that person.+//+// Invariants:+// - A session cannot hold the lock: the file is root's, 0640, group the+// host's, in /run, and flock needs it open.+// - The wait never rejects and is bounded (WAIT_S, or what its caller says):+// it answers whether the storage is free. Past WAIT_S, or without flock(1),+// a call goes ahead and is bounded by its own timeout as before; a caller+// that named its own bound refuses instead (podman.ts `settled`).+// - A lock is its holder's: provisioning that died holds nothing, and leaves+// only the file. sandbox.sh removes the file as it finishes, so a call+// normally pays one stat; with a file left behind, one flock(1) (7 ms+// measured) until the next run.+// - A provisioning run queued behind another takes a new file once the first+// removed its own (sandbox.sh). So after a wait that was a real one the host+// looks at the path again, NEXT_MS later, and waits for that run too; all+// within the one bound.+// - A call already running when provisioning takes the lock waits inside+// Podman and may run out of its time: podman.ts asks `imageBusy` then, and+// makes the call once more after the wait when its caller called it+// `repeatable`; any other fails as a timeout does.+// - Every command of the host that runs Podman waits here first, through+// `AsRunner.settled` (podman.ts names them all). Not covered: what a helper+// or a session's unit does once it was started.++import { execFile } from 'node:child_process';+import { existsSync } from 'node:fs';+import { log } from '../../log.js';++/** The same path in deploy/vm/sandbox.sh. One per computer, like the runners' Podman store. */+export const IMAGE_LOCK = '/run/slack-presence-image.lock';+const FLOCK = '/usr/bin/flock';+/** Longer than a pull and a warm-up take (181 to 214 s measured for both, work 103 "Provisioning"). */+export const WAIT_S = 300;+/** A wait this long was for a holder (a free lock answers in 7 ms). */+const HELD_MS = 500;+/** How long a provisioning run that waited for another needs to take its own lock: it wakes, makes the file and locks it. */+const NEXT_MS = 200;++export interface ImageLockDeps {+ lock?: string;+ waitS?: number;+ exists?: (p: string) => boolean;+ /** Runs flock(1); resolves with its exit code, or undefined when it could not run. */+ flock?: (args: string[]) => Promise<number | undefined>;+ now?: () => number;+ nextMs?: number;+}++const run = (args: string[]) =>+ new Promise<number | undefined>((resolve) => execFile(FLOCK, args, (e) => resolve(!e ? 0 : typeof e.code === 'number' ? e.code : undefined)));++/** Resolves once provisioning is not pulling or warming an image (true), or after `waitS` with the lock still held (false). Without the file, nobody is. */+export async function imageSettled(d: ImageLockDeps = {}): Promise<boolean> {+ const { lock = IMAGE_LOCK, waitS = WAIT_S, exists = existsSync, flock = run, now = Date.now, nextMs = NEXT_MS } = d;+ if (!exists(lock)) return true;+ const t0 = now();+ for (;;) {+ const left = Math.ceil(waitS - (now() - t0) / 1000);+ if (left <= 0) break;+ const r0 = now();+ // Exit 1 is flock's "still held"; anything else that is not 0 (a file it may not open) is nobody holding it.+ const code = await flock(['--shared', '--timeout', String(left), lock, '/usr/bin/true']);+ if (code === 1) return log.warn(`podman: provisioning still holds ${lock} after ${waitS} s`), false;+ if (code !== 0 || now() - r0 < HELD_MS) break;+ // It was held, and is free: a run queued behind that one takes its own file now.+ await new Promise((r) => setTimeout(r, nextMs));+ if (!exists(lock)) break;+ }+ const ms = now() - t0;+ if (ms >= 1000) log.info(`podman: waited ${ms} ms for provisioning to finish with an image`);+ return true;+}++/** True while provisioning holds the lock at this moment. */+export async function imageBusy(d: Pick<ImageLockDeps, 'lock' | 'exists' | 'flock'> = {}): Promise<boolean> {+ const { lock = IMAGE_LOCK, exists = existsSync, flock = run } = d;+ return exists(lock) && (await flock(['--shared', '--nonblock', lock, '/usr/bin/true'])) === 1;+}diff --git a/computer/src/host/sandbox/mounts.test.ts b/computer/src/host/sandbox/mounts.test.tsnew file mode 100644index 00000000..80ae7786--- /dev/null+++ b/computer/src/host/sandbox/mounts.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';+import { mounts } from './mounts.js';+import type { AsRunner, RunOptions } from './podman.js';++const ID = '00aa11bb22cc33dd';+const r = { person: 'pat', key: 'C1:1.1' };++function rig() {+ const calls: { args: string[]; o: RunOptions }[] = [];+ const as: AsRunner = { settled: async () => {}, run: async () => '', podman: async (args, o) => (calls.push({ args, o }), '') };+ return { m: mounts({ as, root: '/opt/slack-presence/releases/r1', dataDir: '/data' }), calls };+}++describe('mounts (work 103, "Mount helper")', () => {+ it('a thread\'s paths are below its person, named by the safe key', () => {+ const { m } = rig();+ expect(m.workspace(r)).toBe('/data/people/pat/sessions/C1-1-1');+ expect(m.clones('pat')).toBe('/data/people/pat/ws');+ expect(m.clone('pat', 'alpha')).toBe('/data/people/pat/ws/alpha');+ expect(m.registry(r, 'alpha')).toBe('/data/people/pat/wt/C1-1-1/alpha');+ });++ it('order: the workspace, every clone, every registry inside its clone, the journal last at its own path', () => {+ const { m } = rig();+ expect(m.bindsFor(r, ['alpha', 'beta'], '/data/journals/cs_1')).toEqual([+ { src: '/data/people/pat/sessions/C1-1-1', dst: '/workspace' },+ { src: '/data/people/pat/ws/alpha', dst: '/clones/alpha' },+ { src: '/data/people/pat/ws/beta', dst: '/clones/beta' },+ { src: '/data/people/pat/wt/C1-1-1/alpha', dst: '/clones/alpha/.git/worktrees' },+ { src: '/data/people/pat/wt/C1-1-1/beta', dst: '/clones/beta/.git/worktrees' },+ { src: '/data/journals/cs_1', dst: '/data/journals/cs_1' },+ ]);+ expect(m.bindsFor(r, [])).toEqual([{ src: '/data/people/pat/sessions/C1-1-1', dst: '/workspace' }]);+ expect(m.repoBinds(r, ['alpha']).map((b) => b.dst)).toEqual(['/clones/alpha', '/clones/alpha/.git/worktrees']);+ });++ it('a name that is not one path component names nothing', () => {+ const { m } = rig();+ for (const bad of ['..', '.', '', 'a/b', '.git', '-x', 'a b']) {+ expect(() => m.clone('pat', bad)).toThrow('bad repository name');+ expect(() => m.registry(r, bad)).toThrow('bad repository name');+ }+ expect(() => m.workspace({ person: '../quinn', key: 'k' })).toThrow('bad person name');+ expect(() => m.clones('')).toThrow('bad person name');+ });++ it('applyMounts hands the pairs to the helper with the host\'s SP_DATA, within 10 s; nothing to mount runs nothing', async () => {+ const { m, calls } = rig();+ await m.applyMounts(ID, 4242, 'pat', []);+ expect(calls).toEqual([]);+ await m.applyMounts(ID, 4242, 'pat', m.repoBinds(r, ['alpha']));+ expect(calls[0].args).toEqual([+ 'unshare', 'python3', '-I', '/opt/slack-presence/releases/r1/bin/sandbox-mount.py', '4242', ID, 'pat',+ '/data/people/pat/ws/alpha:/clones/alpha', '/data/people/pat/wt/C1-1-1/alpha:/clones/alpha/.git/worktrees',+ ]);+ expect(calls[0].o).toEqual({ timeoutMs: 10_000, env: { SP_DATA: '/data' } });+ await expect(m.applyMounts(ID, 4242, '../quinn', m.repoBinds(r, ['alpha']))).rejects.toThrow('bad person name');+ });+});diff --git a/computer/src/host/sandbox/mounts.ts b/computer/src/host/sandbox/mounts.tsnew file mode 100644index 00000000..b6e5f3ad--- /dev/null+++ b/computer/src/host/sandbox/mounts.ts@@ -0,0 +1,76 @@+// What a thread's container gets mounted after every start (work 103, "Mount+// helper"): its workspace, the person's clones it uses, its own worktree+// registry over each clone's, and its journal directory. `bindsFor` is the+// ordered list; `applyMounts` hands it to bin/sandbox-mount.py, which runs as+// the runners' user inside Podman's user namespace.+//+// Invariants:+// - Every source is below the record's person directory, or is the journal+// directory; the names in it come from the record and the definition, never+// from a session. The helper checks the same again and follows no link.+// - Order: the workspace, every clone, then every registry (a registry is+// mounted inside its clone), the journal last.+// - A thread sees only its own registry at `/clones/<r>/.git/worktrees`, so+// `git worktree prune` in one thread cannot forget another's worktrees.+// - Mounts do not survive a stop: the caller applies them after every start.+// A destination already mounted is left alone, so applying twice is safe.++import path from 'node:path';+import { safeKey } from '../../workspaces/clones.js';+import type { AsRunner } from './podman.js';+import { type Bind, mountArgs } from './podman-args.js';+import type { SandboxRecord } from './records.js';++/** The workspace and the clones, as a session and a helper container see them. */+export const WORKSPACE = '/workspace';+export const CLONES = '/clones';+const MOUNT_TIMEOUT_MS = 10_000;+const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;++export interface MountsDeps {+ as: AsRunner;+ /** The host's release, which holds bin/sandbox-mount.py. */+ root: string;+ /** The host's SP_DATA. */+ dataDir: string;+}++export type Mounts = ReturnType<typeof mounts>;++const named = (kind: string, name: string) => {+ if (!NAME.test(name) || name === '.git') throw new Error(`bad ${kind} name: ${name}`);+ return name;+};++export function mounts(d: MountsDeps) {+ const people = path.join(d.dataDir, 'people');+ const personDir = (person: string) => path.join(people, named('person', person));+ /** `<people>/<p>/ws`, a helper container's `/clones`. */+ const clones = (person: string) => path.join(personDir(person), 'ws');+ const clone = (person: string, repo: string) => path.join(clones(person), named('repository', repo));+ /** The thread's files on the host: its `/workspace`. */+ const workspace = (r: Pick<SandboxRecord, 'person' | 'key'>) => path.join(personDir(r.person), 'sessions', safeKey(r.key));+ /** The thread's own worktree registry for one clone. */+ const registry = (r: Pick<SandboxRecord, 'person' | 'key'>, repo: string) => path.join(personDir(r.person), 'wt', safeKey(r.key), named('repository', repo));++ /** The clone and the registry of each repository, clones first: what `checkout` adds to a running container. */+ const repoBinds = (r: Pick<SandboxRecord, 'person' | 'key'>, repos: string[]): Bind[] => [+ ...repos.map((name) => ({ src: clone(r.person, name), dst: `${CLONES}/${name}` })),+ ...repos.map((name) => ({ src: registry(r, name), dst: `${CLONES}/${name}/.git/worktrees` })),+ ];++ /** The ordered bind list of a thread's container. `journalDir`: the session's journal directory, when it has one. */+ const bindsFor = (r: Pick<SandboxRecord, 'person' | 'key'>, repos: string[], journalDir?: string): Bind[] => [+ { src: workspace(r), dst: WORKSPACE },+ ...repoBinds(r, repos),+ ...(journalDir ? [{ src: journalDir, dst: journalDir }] : []),+ ];++ /** Mount `binds` into the running container whose first process is `pid` (10 s). Rejects with the helper's own line. */+ async function applyMounts(id: string, pid: number, person: string, binds: Bind[]): Promise<void> {+ if (!binds.length) return;+ await d.as.podman(mountArgs(d.root, pid, id, named('person', person), binds), { timeoutMs: MOUNT_TIMEOUT_MS, env: { SP_DATA: d.dataDir } });+ }++ return { people, clones, clone, workspace, registry, repoBinds, bindsFor, applyMounts };+}diff --git a/computer/src/host/sandbox/podman-args.test.ts b/computer/src/host/sandbox/podman-args.test.tsnew file mode 100644index 00000000..4f38133d--- /dev/null+++ b/computer/src/host/sandbox/podman-args.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it } from 'vitest';+import {+ createArgs, emptyRunArgs, execArgs, HELPER_SCOPE, helperArgs, homeArgs, inventoryArgs, logsArgs, mountArgs, pidArgs, recreateRemoveArgs, removeArgs, startArgs, stopArgs,+ terminalArgs, terminalHangUpArgs, unshareRmArgs,+} from './podman-args.js';++const id = '0123456789abcdef';+const run = `/run/slack-presence/sandbox/${id}`;++describe('podman argv (work 103, "Podman commands")', () => {+ it('create is the specified command, word for word', () => {+ expect(createArgs({ id, run, dataDir: '/data', image: 'ghcr.io/diggerhq/computer-session:abc', abi: '1', modelSocket: '/run/oc-modelproxy/api.sock' }).join('\n')).toBe(`create+--name+sp-runner-${id}+--hostname+session+--label+sp.runner=${id}+--label+sp.abi=1+--cgroups=split+--userns=keep-id:uid=1500,gid=1500+--user+1500:1500+--network=pasta+--pids-limit=4096+--sysctl+net.ipv4.ip_unprivileged_port_start=0+--sysctl+net.ipv4.ping_group_range=0 65536+--security-opt+unmask=/proc/*+--device+/dev/fuse+--device+/dev/net/tun+--log-driver=k8s-file+--log-opt+max-size=10m+--stop-timeout=10+--env+SP_RUN=${run}+--env+SP_DATA=/data+--env+SP_DEFINITION=${run}/definition.json+--env+SP_TOKEN_SOCKET=${run}/tokens/${id}.sock+--env+SP_PREVIEW_SOCKET=${run}/runners/${id}.preview.sock+-v+sp-home-${id}:/home/agent+-v+${run}:${run}+-v+/run/oc-modelproxy/api.sock:/run/oc-modelproxy/api.sock+-v+/opt/slack-presence:/opt/slack-presence:ro+ghcr.io/diggerhq/computer-session:abc`);+ });++ it('create mounts no workspace, no clone and nothing else of the model proxy', () => {+ const binds = createArgs({ id, run, dataDir: '/data', image: 'i', abi: '2', modelSocket: '/run/oc-modelproxy/api.sock' }).flatMap((a, i, all) => (all[i - 1] === '-v' ? [a] : []));+ expect(binds).toHaveLength(4);+ expect(binds.some((b) => /people|sessions|control\.sock|bindings/.test(b))).toBe(false);+ });++ it('start, pid, stop', () => {+ expect(startArgs(id)).toEqual(['start', '--attach', `sp-runner-${id}`]);+ expect(pidArgs(id)).toEqual(['inspect', '--format', '{{.State.Pid}}', `sp-runner-${id}`]);+ expect(stopArgs(id, 10)).toEqual(['stop', '--time', '10', `sp-runner-${id}`]);+ expect(stopArgs(id, 0)).toEqual(['stop', '--time', '0', `sp-runner-${id}`]);+ });++ it('exec runs as the session user in a directory, with no environment of its own', () => {+ expect(execArgs(id, ['sh', '-c', 'true'], { dir: '/workspace' })).toEqual(['exec', '--user', '1500:1500', '--workdir', '/workspace', `sp-runner-${id}`, 'sh', '-c', 'true']);+ expect(execArgs(id, ['cat'], { dir: '/', interactive: true }).slice(0, 2)).toEqual(['exec', '--interactive']);+ expect(execArgs(id, ['x'], { dir: '/' })).not.toContain('--env');+ });++ it('remove takes the home volume, recreate keeps it', () => {+ expect(removeArgs(id)).toEqual([['rm', '--force', '--volumes', `sp-runner-${id}`], ['volume', 'rm', '--force', `sp-home-${id}`]]);+ expect(recreateRemoveArgs(id)).toEqual(['rm', '--force', `sp-runner-${id}`]);+ });++ it('a home is made before its container, with a label that names its host by the run directory; made twice it is the one home', () => {+ expect(homeArgs(id, `/run/slack-presence/sandbox/${id}`)).toEqual(['volume', 'create', '--ignore', '--label', `sp.run=/run/slack-presence/sandbox/${id}`, `sp-home-${id}`]);+ });++ it('inventory lists by label and by volume name', () => {+ expect(inventoryArgs()).toEqual({+ containers: ['ps', '--all', '--filter', 'label=sp.runner', '--format', 'json'],+ volumes: ['volume', 'ls', '--filter', 'name=sp-home-', '--format', 'json'],+ });+ });++ it('the mount helper runs inside the user namespace, isolated, with the pid, the runner, the person and the pairs in order', () => {+ expect(mountArgs('/opt/slack-presence/releases/r1', 4242, id, 'pat', [{ src: '/data/people/pat/sessions/k', dst: '/workspace' }, { src: '/data/people/pat/ws/a', dst: '/clones/a' }])).toEqual([+ 'unshare', 'python3', '-I', '/opt/slack-presence/releases/r1/bin/sandbox-mount.py', '4242', id, 'pat',+ '/data/people/pat/sessions/k:/workspace', '/data/people/pat/ws/a:/clones/a',+ ]);+ });++ it('a helper container sees one person\'s clones, no home, a network only when asked, and is ended by Podman', () => {+ const h = { person: 'pat', people: '/data/people', run: '/run/sp/helper', image: 'img:1', network: false, timeoutS: 60, sh: ['/opt/slack-presence/releases/r1/bin/ws-inspect.sh', '--only=state', '/clones', '/workspace', 'a'] };+ const a = helperArgs({ ...h, binds: [{ src: '/data/people/pat/sessions/k', dst: '/workspace', ro: true }, { src: '/data/people/pat/wt/k/a', dst: '/clones/a/.git/worktrees' }] });+ expect(a.slice(0, 2)).toEqual(['run', '--rm']);+ expect(a).toEqual(expect.arrayContaining(['--label', 'sp.helper=pat', '--user', '1500:1500', '--network=none', '--timeout', '60', '--log-driver=none', '--env', 'SP_TOKEN_SOCKET=/run/sp/helper/token.sock', '--env', 'HOME=/tmp']));+ expect(a.filter((x, i) => a[i - 1] === '-v')).toEqual([+ '/data/people/pat/ws:/clones', '/run/sp/helper:/run/sp/helper', '/opt/slack-presence:/opt/slack-presence:ro',+ '/data/people/pat/sessions/k:/workspace:ro', '/data/people/pat/wt/k/a:/clones/a/.git/worktrees',+ ]);+ expect(a.slice(-8)).toEqual(['--entrypoint', '/bin/sh', 'img:1', ...h.sh]);+ expect(a).not.toContain('--interactive');+ expect(a).not.toContain('--name');+ expect(helperArgs({ ...h, name: 'sp-files-ab12' }).slice(0, 4)).toEqual(['run', '--rm', '--name', 'sp-files-ab12']);+ const net = helperArgs({ ...h, network: true, stdin: true });+ expect(net).toContain('--network=pasta');+ expect(net[2]).toBe('--interactive');+ expect(HELPER_SCOPE.slice(0, 3)).toEqual(['/usr/bin/systemd-run', '--user', '--scope']);+ });++ it('session-made files are removed inside the user namespace', () => {+ expect(unshareRmArgs(['/a', '/b c'])).toEqual(['unshare', 'rm', '-rf', '--', '/a', '/b c']);+ expect(emptyRunArgs(run)).toEqual(['unshare', 'find', `${run}/runners`, `${run}/secrets`, '-mindepth', '1', '-delete']);+ expect(logsArgs(id)).toEqual(['logs', '--tail', '50', `sp-runner-${id}`]);+ });++ it('a terminal is the PTY helper in the container: as the session, in the workspace, TERM and nothing else', () => {+ expect(terminalArgs(id, '/workspace', 'xterm-256color', ['python3', '/opt/slack-presence/releases/r1/src/host/terminal-pty.py', 'sp-term-ab12'])).toEqual([+ 'exec', '--interactive', '--user', '1500:1500', '--workdir', '/workspace', '--env', 'TERM=xterm-256color', `sp-runner-${id}`,+ 'python3', '/opt/slack-presence/releases/r1/src/host/terminal-pty.py', 'sp-term-ab12',+ ]);+ });++ it('hanging a terminal up signals its own helper, not every terminal of the session', () => {+ const args = terminalHangUpArgs(id, 'sp-term-ab12');+ expect(args).toEqual(['exec', '--user', '1500:1500', `sp-runner-${id}`, 'pkill', '-HUP', '-f', 'terminal-pty\\.py sp-term-ab12$']);+ const pattern = new RegExp(args.at(-1) as string);+ expect(pattern.test('python3 /opt/slack-presence/releases/r1/src/host/terminal-pty.py sp-term-ab12')).toBe(true);+ expect(pattern.test('python3 /opt/slack-presence/releases/r1/src/host/terminal-pty.py sp-term-ab123')).toBe(false);+ });+});diff --git a/computer/src/host/sandbox/podman-args.ts b/computer/src/host/sandbox/podman-args.tsnew file mode 100644index 00000000..cbad3996--- /dev/null+++ b/computer/src/host/sandbox/podman-args.ts@@ -0,0 +1,193 @@+// Every Podman argv the host runs for a thread's sandbox (work 103, "Podman+// commands"), as pure functions: the arguments after `podman`. One container+// `sp-runner-<id>`, one volume `sp-home-<id>`, one run directory per runner id.+//+// Invariants:+// - Nothing here runs anything or reads the environment; containers.ts runs+// these through podman.ts, as the runners' user.+// - Create is the same for a spare, a new thread and a recreation: what a+// start may change goes through boot.env (boot-env.ts), never through argv.+// - The paths are the same inside and outside the container; the workspace,+// the clones and their worktree registries are the exceptions, and Create+// mounts none of them: the mount helper does, after every start (mounts.ts).+// - A helper container sees one person's clones, the helpers' run directory+// and the releases, and whatever its caller binds besides; never another+// person's files.+// - Of the model proxy a container gets its API socket alone, the file and+// not its directory: the control socket beside it stays outside. Create+// fails while that socket is absent, and without the proxy no session starts.++import path from 'node:path';+import { type RunRoot, previewSocketFor, tokenSocketFor } from '../../ipc.js';++/** The user every session runs as, inside and outside (the image's `agent`). */+export const SESSION_USER = '1500:1500';+/** Where releases live, mounted read-only at the same path. */+export const RELEASES_DIR = '/opt/slack-presence';++export const containerName = (id: string) => `sp-runner-${id}`;+export const volumeName = (id: string) => `sp-home-${id}`;+/** The transient unit a container runs in; the model proxy tells sessions apart by it. */+export const unitName = (id: string) => `sp-runner-${id}.service`;++export interface CreateSpec {+ id: string;+ /** The runner's run root, `$SP_RUN/sandbox/<id>`. */+ run: RunRoot;+ /** The host's SP_DATA. */+ dataDir: string;+ /** SP_IMAGE and SP_IMAGE_ABI. */+ image: string;+ abi: string;+ /** The model proxy's API socket (the host's SP_MODEL_SOCKET): the one thing of the proxy's a session sees. */+ modelSocket: string;+}++export function createArgs(c: CreateSpec): string[] {+ return [+ 'create', '--name', containerName(c.id), '--hostname', 'session',+ '--label', `sp.runner=${c.id}`, '--label', `sp.abi=${c.abi}`,+ '--cgroups=split', '--userns=keep-id:uid=1500,gid=1500', '--user', SESSION_USER,+ '--network=pasta', '--pids-limit=4096',+ '--sysctl', 'net.ipv4.ip_unprivileged_port_start=0',+ // An upper bound outside the user namespace's mapping fails every start (podman#28180).+ '--sysctl', 'net.ipv4.ping_group_range=0 65536',+ // These three are for containers inside the session (rootless Podman in Podman).+ '--security-opt', 'unmask=/proc/*',+ '--device', '/dev/fuse', '--device', '/dev/net/tun',+ '--log-driver=k8s-file', '--log-opt', 'max-size=10m',+ '--stop-timeout=10',+ '--env', `SP_RUN=${c.run}`, '--env', `SP_DATA=${c.dataDir}`,+ '--env', `SP_DEFINITION=${path.join(c.run, 'definition.json')}`,+ '--env', `SP_TOKEN_SOCKET=${tokenSocketFor(c.run, c.id)}`,+ '--env', `SP_PREVIEW_SOCKET=${previewSocketFor(c.run, c.id)}`,+ '-v', `${volumeName(c.id)}:/home/agent`,+ '-v', `${c.run}:${c.run}`,+ '-v', `${c.modelSocket}:${c.modelSocket}`,+ '-v', `${RELEASES_DIR}:${RELEASES_DIR}:ro`,+ c.image,+ ];+}++/** The label of a home volume: the run root of its id on the host that made it, which is what says whose it is once that directory is gone (`/run` is emptied by a reboot). */+export const HOME_LABEL = 'sp.run';++/**+ * A thread's home, before its container (Create): Podman 4.9.3 gives a volume that `create --volume` names no label (measured).+ * `--ignore`: one that exists stays as it is, labels and all, so this is made at every Create and may be made twice.+ */+export const homeArgs = (id: string, run: RunRoot) => ['volume', 'create', '--ignore', '--label', `${HOME_LABEL}=${run}`, volumeName(id)];++/** What the container's unit runs (launch.ts): attached, so the unit lives as long as the container. */+export const startArgs = (id: string) => ['start', '--attach', containerName(id)];++/** The container's first process as the host sees it; 0 while it has none. */+export const pidArgs = (id: string) => ['inspect', '--format', '{{.State.Pid}}', containerName(id)];++/** A command in the running container. No `--env`: the container's own environment is complete. */+export const execArgs = (id: string, argv: string[], o: { dir: string; interactive?: boolean }) =>+ ['exec', ...(o.interactive ? ['--interactive'] : []), '--user', SESSION_USER, '--workdir', o.dir, containerName(id), ...argv];++/**+ * A terminal's helper in the running container (terminal.ts): `helper` is `python3 <ROOT>/src/host/terminal-pty.py`+ * and the terminal's unit name, which the helper ignores and `terminalHangUpArgs` matches.+ */+export const terminalArgs = (id: string, dir: string, term: string, helper: string[]) =>+ ['exec', '--interactive', '--user', SESSION_USER, '--workdir', dir, '--env', `TERM=${term}`, containerName(id), ...helper];++/** SIGHUP to the helper of one terminal (`unit`: `sp-term-<hex>`), whose `podman exec` is gone. */+export const terminalHangUpArgs = (id: string, unit: string) =>+ ['exec', '--user', SESSION_USER, containerName(id), 'pkill', '-HUP', '-f', `terminal-pty\\.py ${unit}$`];++/** What a `/files` script in the running container is started through, so that `filesEndArgs` finds it: `env` becomes the script's shell, and the tag stays in the command line of the `timeout` before it. */+export const filesTagged = (tag: string) => ['/usr/bin/env', `OPC_FILES=${tag}`];++/** SIGTERM to the `timeout` of one `/files` script, whose `podman exec` is gone: it ends its whole process group (and kills it, `--kill-after`). */+export const filesEndArgs = (id: string, tag: string) =>+ ['exec', '--user', SESSION_USER, containerName(id), 'pkill', '-TERM', '-f', `^/usr/bin/timeout .* OPC_FILES=${tag} `];++/** A helper container by its name, whose `podman run` is gone: SIGTERM, which a script with a handler acts on, then SIGKILL. */+export const helperStopArgs = (name: string) => ['stop', '--ignore', '--time', '2', name];++/** `seconds`: how long the runner gets after SIGTERM before SIGKILL. */+export const stopArgs = (id: string, seconds: number) => ['stop', '--time', String(seconds), containerName(id)];++/** The container with its anonymous volumes, then its home: two commands, in this order. */+export const removeArgs = (id: string) => [+ ['rm', '--force', '--volumes', containerName(id)],+ ['volume', 'rm', '--force', volumeName(id)],+];++/** The container alone; its home volume stays for the one created next (Recreate). */+export const recreateRemoveArgs = (id: string) => ['rm', '--force', containerName(id)];++/** A home alone, for one no container uses (the sweep): without `--force`, which removes the containers that use a volume with it. */+export const volumeRmArgs = (id: string) => ['volume', 'rm', volumeName(id)];++export const inventoryArgs = () => ({+ containers: ['ps', '--all', '--filter', 'label=sp.runner', '--format', 'json'],+ volumes: ['volume', 'ls', '--filter', 'name=sp-home-', '--format', 'json'],+});++/** Files a session made belong to subordinate uids when it made them as root: removed inside the user namespace. */+export const unshareRmArgs = (paths: string[]) => ['unshare', 'rm', '-rf', '--', ...paths];++/** Empties what a session may write in its run directory (`up`, step 1). */+export const emptyRunArgs = (run: RunRoot) => ['unshare', 'find', path.join(run, 'runners'), path.join(run, 'secrets'), '-mindepth', '1', '-delete'];++/** The end of what the container wrote to its output, for a start that never became ready. */+export const logsArgs = (id: string, lines = 50) => ['logs', '--tail', String(lines), containerName(id)];++/** A directory of the host at a path in a container. */+export interface Bind {+ src: string;+ dst: string;+ ro?: boolean;+}++/** The mount helper, inside Podman's user namespace; SP_DATA reaches it through the sudo prefix (podman.ts `env`). */+export const mountArgs = (root: string, pid: number, id: string, person: string, binds: Bind[]) =>+ ['unshare', 'python3', '-I', path.join(root, 'bin', 'sandbox-mount.py'), String(pid), id, person, ...binds.map((b) => `${b.src}:${b.dst}`)];++/** What a helper container's `podman run` is wrapped in: Podman needs a delegated cgroup of the runners' user (the host's own is not one), and it lands in the runners' slice. */+export const HELPER_SCOPE = ['/usr/bin/systemd-run', '--user', '--scope', '--quiet', '--slice=slack-presence-runners.slice', '-p', 'Delegate=yes', '--'];++export interface HelperSpec {+ /** The person whose clones it sees, as `/clones`. */+ person: string;+ /** `<SP_DATA>/people`. */+ people: string;+ /** The helpers' run directory, `$SP_RUN/helper`: its token socket. */+ run: string;+ image: string;+ /** With a network (a script that fetches), or none. */+ network: boolean;+ /** Seconds after which Podman kills it. */+ timeoutS: number;+ /** Whether the script reads its stdin. */+ stdin?: boolean;+ /** What a script on a stopped thread's files needs besides: its workspace, its worktree registries. */+ binds?: Bind[];+ /** A name of its own, for a caller that may have to stop it (`helperStopArgs`). */+ name?: string;+ /** What `/bin/sh` is given: a script by its path in the release and its arguments, or `-c`, a script's text and its arguments. */+ sh: string[];+}++/** One run of a script on one person's clones, with no session. */+export function helperArgs(h: HelperSpec): string[] {+ return [+ 'run', '--rm', ...(h.name ? ['--name', h.name] : []), ...(h.stdin ? ['--interactive'] : []), '--label', `sp.helper=${h.person}`, '--cgroups=split',+ '--userns=keep-id:uid=1500,gid=1500', '--user', SESSION_USER, `--network=${h.network ? 'pasta' : 'none'}`, '--pids-limit=1024',+ // The script is the container's first process, which ignores a signal it has no handler for: Podman ends it.+ '--timeout', String(h.timeoutS),+ // What it prints goes to whoever started it and nowhere else: a workspace's archive is not kept in a log.+ '--log-driver=none',+ '--env', `SP_RUN=${h.run}`, '--env', `SP_TOKEN_SOCKET=${path.join(h.run, 'token.sock')}`, '--env', 'HOME=/tmp',+ '-v', `${path.join(h.people, h.person, 'ws')}:/clones`,+ '-v', `${h.run}:${h.run}`,+ '-v', `${RELEASES_DIR}:${RELEASES_DIR}:ro`,+ ...(h.binds ?? []).flatMap((b) => ['-v', `${b.src}:${b.dst}${b.ro ? ':ro' : ''}`]),+ '--entrypoint', '/bin/sh', h.image, ...h.sh,+ ];+}diff --git a/computer/src/host/sandbox/podman.test.ts b/computer/src/host/sandbox/podman.test.tsnew file mode 100644index 00000000..ea8a3af0--- /dev/null+++ b/computer/src/host/sandbox/podman.test.ts@@ -0,0 +1,101 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { type Exec, PodmanError, asRunner, bounded } from './podman.js';++const sudo = ['/usr/bin/sudo', '-n', '-u', 'agent', 'XDG_RUNTIME_DIR=/run/user/1500'];++type Done = Parameters<Exec>[3];++/** `result`: what the command ends with by itself; none = it runs until `finish` is called. */+function fake(result?: { err?: object; stdout?: string; stderr?: string }) {+ const calls: { cmd: string; args: string[]; opts: object; stdin?: string }[] = [];+ const signals: string[] = [];+ let finish: Done = () => {};+ const exec: Exec = (cmd, args, o, done) => {+ const call: (typeof calls)[number] = { cmd, args, opts: o };+ calls.push(call);+ finish = done;+ if (result) queueMicrotask(() => done((result.err as never) ?? null, result.stdout ?? '', result.stderr ?? ''));+ return { stdin: { end: (d?: string | Buffer) => void (call.stdin = d as string) }, kill: (s) => void signals.push(s) };+ };+ return { exec, calls, signals, finish: (...a: Parameters<Done>) => finish(...a) };+}++afterEach(() => vi.useRealTimers());++describe('asRunner', () => {+ it('runs podman through the sudo prefix under timeout(1), and returns stdout', async () => {+ const f = fake({ stdout: '42\n' });+ expect(await asRunner(sudo, f.exec).podman(['inspect', 'x'], { timeoutMs: 5000 })).toBe('42\n');+ expect(f.calls).toEqual([{+ cmd: '/usr/bin/sudo',+ args: ['-n', '-u', 'agent', 'XDG_RUNTIME_DIR=/run/user/1500', '--', '/usr/bin/timeout', '--kill-after=2', '5.000', '/usr/bin/podman', 'inspect', 'x'],+ opts: { cwd: '/', maxBuffer: 16 * 2 ** 20, encoding: 'utf8' }, // no timeout of execFile's: its SIGKILL would stop at sudo+ stdin: undefined,+ }]);+ });++ it('a variable for the command goes into the sudo prefix, and stdin may be bytes', async () => {+ const f = fake({ stdout: '' });+ await asRunner(sudo, f.exec).podman(['unshare', 'true'], { timeoutMs: 1000, env: { SP_DATA: '/data' }, stdin: Buffer.from('x') });+ expect(f.calls[0].args.slice(3, 7)).toEqual(['XDG_RUNTIME_DIR=/run/user/1500', 'SP_DATA=/data', '--', '/usr/bin/timeout']);+ expect(String(f.calls[0].stdin)).toBe('x');+ });++ it('timeout(1) never gets 0, which would mean no limit', () => {+ expect(bounded(['/bin/true'], 0)[2]).toBe('0.001');+ expect(bounded(['/bin/true'], 0.2)[2]).toBe('0.001');+ expect(bounded(['/bin/true'], 1500)[2]).toBe('1.500');+ });++ it('passes stdin', async () => {+ const f = fake({});+ await asRunner(sudo, f.exec).run(['/bin/cat'], { timeoutMs: 1000, stdin: 'in' });+ expect(f.calls[0].stdin).toBe('in');+ });++ it('a non-zero exit rejects with the code and stderr', async () => {+ const f = fake({ err: Object.assign(new Error('Command failed'), { code: 125 }), stderr: 'warning\nError: no such container\n' });+ const e = await asRunner(sudo, f.exec).podman(['rm', 'x'], { timeoutMs: 1000 }).catch((e) => e);+ expect(e).toBeInstanceOf(PodmanError);+ expect(e).toMatchObject({ code: 125, timedOut: false, stderr: 'warning\nError: no such container\n' });+ expect(e.message).toBe('/usr/bin/podman rm x: Error: no such container');+ });++ it('at the timeout sudo gets SIGTERM, which it relays, and the call rejects as timed out once the command is gone', async () => {+ vi.useFakeTimers();+ const f = fake();+ const p = asRunner(sudo, f.exec).podman(['stop', 'x'], { timeoutMs: 15000 }).catch((e) => e);+ await vi.advanceTimersByTimeAsync(14_999);+ expect(f.signals).toEqual([]);+ await vi.advanceTimersByTimeAsync(1);+ expect(f.signals).toEqual(['SIGTERM']);+ f.finish(Object.assign(new Error('Command failed'), { code: 124 }), '', '');+ const e = await p;+ expect(e).toMatchObject({ timedOut: true, code: undefined });+ expect(e.message).toBe('/usr/bin/podman stop x: timed out after 15000 ms');+ await vi.advanceTimersByTimeAsync(10_000);+ expect(f.signals).toEqual(['SIGTERM']); // no SIGKILL for a command that went+ });++ it('a command whose output outlives it is given up 3 s after the timeout', async () => {+ vi.useFakeTimers();+ const f = fake();+ const p = asRunner(sudo, f.exec).podman(['stop', 'x'], { timeoutMs: 1000 }).catch((e) => e);+ await vi.advanceTimersByTimeAsync(4000);+ expect(f.signals).toEqual(['SIGTERM', 'SIGKILL']);+ expect(await p).toMatchObject({ timedOut: true });+ });++ it('a command killed for anything but its time (too much output, a signal) did not time out', async () => {+ const big = Object.assign(new Error('stdout maxBuffer length exceeded'), { killed: true, code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' });+ const e = await asRunner(sudo, fake({ err: big }).exec).podman(['logs', 'x'], { timeoutMs: 15000 }).catch((e) => e);+ expect(e).toMatchObject({ timedOut: false, code: undefined });+ expect(e.message).toBe('/usr/bin/podman logs x: stdout maxBuffer length exceeded');+ });++ it('refuses a command that is not an absolute path', async () => {+ const f = fake({});+ await expect(asRunner(sudo, f.exec).run(['podman'], { timeoutMs: 1 })).rejects.toThrow(/absolute/);+ expect(f.calls).toHaveLength(0);+ });+});diff --git a/computer/src/host/sandbox/podman.ts b/computer/src/host/sandbox/podman.tsnew file mode 100644index 00000000..902f7cda--- /dev/null+++ b/computer/src/host/sandbox/podman.ts@@ -0,0 +1,147 @@+// Running Podman, and the few other commands a sandbox needs, as the runners'+// user (work 103): `[...runnerUser.sudo, '--', '/usr/bin/timeout', ..., '/usr/bin/podman', ...args]`.+// The host itself never holds Podman's state; every call is one process that+// ends, bounded by the caller's timeout.+//+// A timeout must end the command, not only sudo: SIGKILL to sudo leaves the+// command running (measured: sudo cannot relay it). So every command runs+// under timeout(1) as the runners' user, which ends it by itself; the host's+// own timer sends sudo SIGTERM, which it relays, and decides `timedOut`.+//+// Invariants:+// - Commands are absolute paths and argv arrays: no shell, and the host's PATH+// never decides what runs as the runners' user.+// - Every command runs in `/`: Podman refuses to start in a directory its+// user cannot enter, and the host's own may be one.+// - A call that fails or runs out of time rejects with PodmanError, which+// carries the exit code and stderr. Nothing is retried here but a Podman+// call its caller called `repeatable` that ran out of time while+// provisioning holds the image lock: it was waiting inside Podman for the+// storage, so it is made once more after the wait (image-lock.ts).+// - `repeatable` is said where the call is made, never worked out from its+// words, and only of a call that leaves the same behind when it ran twice,+// or half and then whole: a stop, an `rm --force`, a list. Never of a+// script's `exec`, a `create`, the mount helper or an `unshare`: those may+// have got as far as they did, and a timeout while the lock is held fails+// them as any timeout does.+// - `timedOut` is true only when the caller's time ran out: never for output+// past the limit or a command something else killed.+// - A call that timed out rejects once its command is gone (SIGTERM, SIGKILL+// 2 s later), or 3 s after the timeout at the latest.+// - Whatever of the host runs Podman waits for the image lock first, by+// `settled` here and nowhere else: `podman()` by itself, and before their+// own command a container's Start (containers.ts `up`), its diagnosis+// (`diagnose`), a helper container (scripts.ts), a `/files` script and a+// terminal's `podman exec` (use.ts). The last two name a bound, since a+// person waits for them, and are refused with Unavailable past it.+// - `env` goes into the sudo prefix, the only way a variable reaches the+// command: sudo resets the rest. Only the mount helper is given one.++import { execFile as nodeExecFile } from 'node:child_process';+import { log } from '../../log.js';+import { Unavailable, UPDATING } from '../unavailable.js';+import { imageBusy, imageSettled } from './image-lock.js';++export const PODMAN = '/usr/bin/podman';++export class PodmanError extends Error {+ constructor(+ message: string,+ /** The exit code; undefined when the command was killed or never ran. */+ readonly code: number | undefined,+ readonly stderr: string,+ /** It ran past its timeout and was killed. */+ readonly timedOut: boolean,+ ) {+ super(message);+ this.name = 'PodmanError';+ }+}++export interface RunOptions {+ timeoutMs: number;+ stdin?: string | Buffer;+ /** Variables for the command, added to the sudo prefix. */+ env?: Record<string, string>;+ /** `podman()` only: making this call twice leaves what making it once does, so one that ran out of time behind the image lock is made once more. Absent: never. */+ repeatable?: boolean;+}++/** `execFile` as this file uses it; tests pass their own. No `timeout` of its: its signal would stop at sudo. */+export type Exec = (+ cmd: string,+ args: string[],+ o: { cwd: string; maxBuffer: number; encoding: 'utf8' },+ done: (err: (Error & { code?: number | string | null }) | null, stdout: string, stderr: string) => void,+) => { stdin?: { end(data?: string | Buffer): void } | null; kill?(signal: 'SIGTERM' | 'SIGKILL'): unknown };++export interface AsRunner {+ /** `podman <args>` as the runners' user: its stdout. */+ podman(args: string[], o: RunOptions): Promise<string>;+ /** Any other command, by absolute path, as the runners' user. */+ run(argv: string[], o: RunOptions): Promise<string>;+ /**+ * Wait until provisioning is not holding Podman's storage (image-lock.ts): before a command that runs Podman and is+ * not `podman()`'s. Without `withinMs` it waits as `podman()` does and never rejects; with it, it rejects with+ * Unavailable when the storage is still held then.+ */+ settled(withinMs?: number): Promise<void>;+}++const words = (argv: string[]) => argv.slice(0, 3).join(' ');++export const TIMEOUT = '/usr/bin/timeout';+/** Seconds between a command's SIGTERM and its SIGKILL once its time is up. */+export const KILL_AFTER_S = 2;++/** `argv` under timeout(1): SIGTERM after `timeoutMs`, SIGKILL to its whole process group `KILL_AFTER_S` later; also when timeout(1) itself gets SIGTERM. */+export const bounded = (argv: string[], timeoutMs: number) => [TIMEOUT, `--kill-after=${KILL_AFTER_S}`, Math.max(0.001, timeoutMs / 1000).toFixed(3), ...argv];++/** `argv` as the runners' user, bounded as above: its stdout. `asRunner` for a command that is not Podman's and may be found on sudo's PATH (launch.ts). */+export function runBounded(sudo: string[], argv: string[], o: RunOptions, exec: Exec = nodeExecFile as unknown as Exec): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ const [cmd, ...args] = [...sudo, ...Object.entries(o.env ?? {}).map(([k, v]) => `${k}=${v}`), '--', ...bounded(argv, o.timeoutMs)];+ // Only this timer says "timed out": a command killed for its output, or by anyone else, did not.+ let timedOut = false;+ const late = () => new PodmanError(`${words(argv)}: timed out after ${o.timeoutMs} ms`, undefined, '', true);+ const child = exec(cmd, args, { cwd: '/', maxBuffer: 16 * 2 ** 20, encoding: 'utf8' }, (err, stdout, stderr) => {+ clearTimeout(term);+ clearTimeout(kill);+ if (timedOut) return reject(late());+ if (!err) return resolve(stdout);+ const code = typeof err.code === 'number' ? err.code : undefined;+ reject(new PodmanError(`${words(argv)}: ${stderr.trim().split('\n').pop() || err.message}`, code, stderr, false));+ });+ // sudo relays SIGTERM and timeout(1) turns it into SIGTERM, then SIGKILL, for the command's process group.+ const term = setTimeout(() => {+ timedOut = true;+ child.kill?.('SIGTERM');+ }, o.timeoutMs);+ // Past that, something still holds the output: the caller waits no longer. sudo cannot relay this one.+ const kill = setTimeout(() => {+ child.kill?.('SIGKILL');+ reject(late());+ }, o.timeoutMs + (KILL_AFTER_S + 1) * 1000);+ child.stdin?.end(o.stdin);+ });+}++/** `sudo`: `runnerUser(env).sudo`, the prefix that makes a command the runners' user's. */+export function asRunner(sudo: string[], exec?: Exec, settled: (d?: { waitS?: number }) => Promise<boolean | void> = imageSettled, busy: () => Promise<boolean> = imageBusy): AsRunner {+ const run = (argv: string[], o: RunOptions) =>+ argv[0]?.startsWith('/') ? runBounded(sudo, argv, o, exec) : Promise.reject(new PodmanError(`not an absolute command: ${argv[0]}`, undefined, '', false));+ // A Podman call's time starts once provisioning is not holding the storage (image-lock.ts).+ const podman = (args: string[], o: RunOptions) => settled().then(() => run([PODMAN, ...args], o));+ return {+ run,+ async settled(withinMs) {+ const free = await settled(withinMs === undefined ? undefined : { waitS: withinMs / 1000 });+ if (withinMs !== undefined && free === false) throw new Unavailable(UPDATING);+ },+ podman: (args, o) => podman(args, o).catch(async (e) => {+ if (!o.repeatable || !(e instanceof PodmanError && e.timedOut) || !(await busy())) throw e;+ log.info(`podman ${words(args)}: ran out of time while provisioning holds the storage; once more after it`);+ return podman(args, o);+ }),+ };+}diff --git a/computer/src/host/sandbox/preview-ports.test.ts b/computer/src/host/sandbox/preview-ports.test.tsnew file mode 100644index 00000000..4bb0946f--- /dev/null+++ b/computer/src/host/sandbox/preview-ports.test.ts@@ -0,0 +1,103 @@+import { mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import { HOST_PORTS, PREVIEW_PROXY_PORT } from '../preview-proxy.js';+import { PREVIEWS_PER_SANDBOX, VIRTUAL_PORTS, previewPorts } from './preview-ports.js';++const file = () => path.join(mkdtempSync(path.join(os.tmpdir(), 'sp-ports-')), 'state', 'previews.json');++describe('virtual preview ports', () => {+ it('has a range that holds none of the host\'s own ports', () => {+ for (const p of [...HOST_PORTS, PREVIEW_PROXY_PORT]) expect(p < VIRTUAL_PORTS.first || p > VIRTUAL_PORTS.last, String(p)).toBe(true);+ expect(VIRTUAL_PORTS).toEqual({ first: 30000, last: 39999 });+ });++ it('gives two sessions on the same port a number each, and the same pair its own again', () => {+ const t = previewPorts(file());+ const a = t.assign('aaaa', 5173);+ const b = t.assign('bbbb', 5173);+ expect(a).toEqual({ entry: { virtual: 30000, id: 'aaaa', port: 5173 }, fresh: true });+ expect(b.entry.virtual).toBe(30001);+ expect(t.assign('aaaa', 5173)).toEqual({ entry: a.entry, fresh: false });+ expect(t.get(30001)).toMatchObject({ id: 'bbbb', port: 5173 });+ expect(t.get(30002)).toBeUndefined();+ });++ it('goes round the range: a freed number is not the next one given', () => {+ const t = previewPorts(file(), { first: 100, last: 102 });+ expect(t.assign('a', 1).entry.virtual).toBe(100);+ expect(t.assign('a', 2).entry.virtual).toBe(101);+ t.release(100);+ expect(t.assign('b', 1).entry.virtual).toBe(102);+ expect(t.assign('b', 2).entry.virtual).toBe(100); // wrapped+ expect(() => t.assign('c', 1)).toThrow(/every preview port/);+ t.release(101);+ expect(t.assign('c', 1).entry.virtual).toBe(101);+ });++ it('setName: a name is one entry\'s; an entry that held it is freed, on disk too', () => {+ const f = file();+ const t = previewPorts(f);+ const a = t.assign('aaaa', 5173).entry;+ const b = t.assign('bbbb', 3000).entry;+ t.setName(a.virtual, 'demo');+ t.setName(b.virtual, 'demo');+ expect(t.all()).toEqual([{ virtual: b.virtual, id: 'bbbb', port: 3000, name: 'demo' }]);+ expect(t.byName('demo')?.id).toBe('bbbb');+ expect(previewPorts(f).all()).toEqual(t.all());+ t.setName(b.virtual, 'demo'); // its own again: nothing changes+ expect(t.all()).toHaveLength(1);+ });++ it('gives one sandbox at most PREVIEWS_PER_SANDBOX numbers, whatever the others hold', () => {+ const t = previewPorts(file());+ expect(PREVIEWS_PER_SANDBOX).toBe(32);+ for (let p = 1; p <= PREVIEWS_PER_SANDBOX; p++) t.assign('a', 3000 + p);+ expect(() => t.assign('a', 4000)).toThrow('this session has 32 previews, the most it can have; unpreview one first');+ expect(t.all().length).toBe(32);+ // One it has already is still its own, and another sandbox is not held back.+ expect(t.assign('a', 3001).fresh).toBe(false);+ expect(t.assign('b', 4000).fresh).toBe(true);+ t.release(t.assign('a', 3002).entry.virtual);+ expect(t.assign('a', 4000).fresh).toBe(true);+ });++ it('finds and frees by name, and frees all of a sandbox', () => {+ const t = previewPorts(file());+ const a = t.assign('a', 3000).entry;+ t.assign('a', 3001);+ const b = t.assign('b', 3000).entry;+ t.setName(a.virtual, 'demo');+ expect(t.byName('demo')).toMatchObject({ id: 'a', port: 3000 });+ expect(t.byName('none')).toBeUndefined();+ expect(t.releaseAll('a')).toBe(2);+ expect(t.all()).toEqual([b]);+ expect(t.releaseAll('a')).toBe(0);+ });++ it('keeps the table and its place in the round across a restart, in a 0600 file', () => {+ const f = file();+ const t = previewPorts(f);+ const a = t.assign('a', 3000).entry;+ t.setName(a.virtual, 'demo');+ t.assign('b', 3000);+ t.release(30001);+ expect(statSync(f).mode & 0o777).toBe(0o600);+ const again = previewPorts(f);+ expect(again.all()).toEqual([{ virtual: 30000, id: 'a', port: 3000, name: 'demo' }]);+ expect(again.assign('c', 80).entry.virtual).toBe(30002);+ expect(JSON.parse(readFileSync(f, 'utf8'))).toMatchObject({ next: 30003 });+ });++ it('reads a file that does not parse, or holds a bad entry, as empty', () => {+ const f = file();+ previewPorts(f);+ writeFileSync(f, '{"entries":[{"virtual":7070,"id":"a","port":80}]}');+ expect(previewPorts(f).all()).toEqual([]);+ writeFileSync(f, 'not json');+ const t = previewPorts(f);+ expect(t.all()).toEqual([]);+ expect(t.assign('a', 80).entry.virtual).toBe(30000);+ });+});diff --git a/computer/src/host/sandbox/preview-ports.ts b/computer/src/host/sandbox/preview-ports.tsnew file mode 100644index 00000000..6a145552--- /dev/null+++ b/computer/src/host/sandbox/preview-ports.ts@@ -0,0 +1,161 @@+// Virtual preview ports (work 103, C9): the gateway and the previews Worker+// key a preview by its port, and two sessions in containers can both serve+// 5173. So the host gives each previewed `(sandbox id, port)` a number of its+// own in 30000–39999, tells the gateway that number, and the proxy maps it+// back to the session and its port (previews.ts).+//+// Invariants:+// - One number per `(id, port)`, and one entry per number.+// - One entry per name: giving an entry a name frees the entry that had it+// (the gateway points a name at one number). Whether a sandbox may ask for+// a name is previews.ts's to decide, before the gateway is asked.+// - A new number is the next free one after the last handed out, wrapping+// round: never the lowest free, so a number just freed is not given to+// another session while a public name may still point at it. The place in+// the round is saved with the entries, so a host restart keeps it.+// - One sandbox holds at most PREVIEWS_PER_SANDBOX numbers, so no session can+// use the range up for the others: one preview more fails, and says so.+// - The table is in memory and in `$SP_DATA/state/previews.json` (0600,+// written whole to a temporary file and renamed). A file that does not+// parse is logged and read as empty: the names it held answer "port not+// previewed" until their sessions call `preview` again.+// - `owed` are the names of removed sandboxes the gateway has not been heard+// to take away yet (previews.ts `forget`), each with the thread it was+// for: kept in the same file, so neither a gateway that is away nor a host+// restart leaves a public name behind. A name given to an entry again is+// not owed any more.+// - The range holds none of the host's own ports (preview-proxy.ts+// `HOST_PORTS`); the unit test asserts it.++import path from 'node:path';+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { log } from '../../log.js';++export const VIRTUAL_PORTS = { first: 30000, last: 39999 } as const;+/** The most numbers one sandbox holds at a time. */+export const PREVIEWS_PER_SANDBOX = 32;++export interface PreviewEntry {+ /** What the gateway, the Worker and the proxy's `X-Preview-Port` call this preview. */+ virtual: number;+ /** The sandbox (its runner's id). */+ id: string;+ /** The port inside that sandbox. */+ port: number;+ /** The public name, once the gateway gave one. */+ name?: string;+}++export interface PreviewPorts {+ /** The entry of `(id, port)`: its own when it has one (`fresh` false), else a new number. Throws when `id` has as many as it may, or the range is used up. */+ assign(id: string, port: number): { entry: PreviewEntry; fresh: boolean };+ get(virtual: number): PreviewEntry | undefined;+ byName(name: string): PreviewEntry | undefined;+ /** `name` is this entry's from now on; an entry that held it is freed. */+ setName(virtual: number, name: string): void;+ release(virtual: number): void;+ /** Free every entry of a sandbox (Remove); how many there were. */+ releaseAll(id: string): number;+ all(): PreviewEntry[];+ /** The gateway is to be told `name` is gone, for the thread `from` ('' when there was no record). */+ owe(name: string, from: string): void;+ /** The gateway heard it, or the name is some entry's again. */+ settle(name: string): void;+ owed(): Owed[];+}++/** A removed sandbox's preview name, and the thread to say it for. */+export interface Owed { name: string; from: string }++const inRange = (n: unknown, r: { first: number; last: number }): n is number => Number.isInteger(n) && (n as number) >= r.first && (n as number) <= r.last;++function read(file: string, range: { first: number; last: number }): { next: number; entries: PreviewEntry[]; owed: Owed[] } {+ let text: string;+ try {+ text = readFileSync(file, 'utf8');+ } catch {+ return { next: range.first, entries: [], owed: [] }; // no file yet+ }+ try {+ const j = JSON.parse(text) as { next?: unknown; entries?: unknown; owed?: unknown };+ if (!Array.isArray(j.entries)) throw new Error('no entries');+ const entries: PreviewEntry[] = [];+ for (const e of j.entries as Partial<PreviewEntry>[]) {+ if (!inRange(e?.virtual, range) || typeof e.id !== 'string' || !inRange(e.port, { first: 1, last: 65535 })) throw new Error('a bad entry');+ entries.push({ virtual: e.virtual, id: e.id, port: e.port, ...(typeof e.name === 'string' && { name: e.name }) });+ }+ const owed = (Array.isArray(j.owed) ? (j.owed as Partial<Owed>[]) : []).flatMap((x) => (typeof x?.name === 'string' && typeof x.from === 'string' ? [{ name: x.name, from: x.from }] : []));+ return { next: inRange(j.next, range) ? j.next : range.first, entries, owed };+ } catch (e) {+ log.warn(`preview ports: ${file} not read (${(e as Error)?.message ?? e}); starting empty`);+ return { next: range.first, entries: [], owed: [] };+ }+}++/** The table kept in `file`, read now. `range`: tests pass a small one. */+export function previewPorts(file: string, range: { first: number; last: number } = VIRTUAL_PORTS): PreviewPorts {+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });+ const loaded = read(file, range);+ let next = loaded.next;+ const byVirtual = new Map<number, PreviewEntry>();+ for (const e of loaded.entries) byVirtual.set(e.virtual, e);+ const owed = new Map(loaded.owed.map((x) => [x.name, x.from]));+ const list = () => [...owed].map(([name, from]) => ({ name, from }));++ function save() {+ const tmp = `${file}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify({ next, entries: [...byVirtual.values()], ...(owed.size > 0 && { owed: list() }) }, null, 1) + '\n', { mode: 0o600 });+ renameSync(tmp, file);+ }+ const find = (f: (e: PreviewEntry) => boolean) => [...byVirtual.values()].find(f);++ return {+ assign(id, port) {+ const have = find((e) => e.id === id && e.port === port);+ if (have) return { entry: have, fresh: false };+ let mine = 0;+ for (const e of byVirtual.values()) if (e.id === id) mine++;+ if (mine >= PREVIEWS_PER_SANDBOX) throw new Error(`this session has ${mine} previews, the most it can have; unpreview one first`);+ const size = range.last - range.first + 1;+ for (let i = 0; i < size; i++) {+ const virtual = range.first + ((next - range.first + i) % size);+ if (byVirtual.has(virtual)) continue;+ const entry: PreviewEntry = { virtual, id, port };+ byVirtual.set(virtual, entry);+ next = virtual === range.last ? range.first : virtual + 1;+ save();+ return { entry, fresh: true };+ }+ throw new Error(`every preview port of this computer is in use (${size}); unpreview one first`);+ },+ get: (virtual) => byVirtual.get(virtual),+ byName: (name) => find((e) => e.name === name),+ setName(virtual, name) {+ const e = byVirtual.get(virtual);+ if (!e || e.name === name) return;+ // The gateway points a name at one number: whatever held it before points nowhere now.+ for (const x of [...byVirtual.values()]) if (x.name === name) byVirtual.delete(x.virtual);+ e.name = name;+ owed.delete(name);+ save();+ },+ release(virtual) {+ if (byVirtual.delete(virtual)) save();+ },+ releaseAll(id) {+ const mine = [...byVirtual.values()].filter((e) => e.id === id);+ for (const e of mine) byVirtual.delete(e.virtual);+ if (mine.length) save();+ return mine.length;+ },+ all: () => [...byVirtual.values()],+ owe(name, from) {+ owed.set(name, from);+ save();+ },+ settle(name) {+ if (owed.delete(name)) save();+ },+ owed: list,+ };+}diff --git a/computer/src/host/sandbox/prune.test.ts b/computer/src/host/sandbox/prune.test.tsnew file mode 100644index 00000000..9785cb14--- /dev/null+++ b/computer/src/host/sandbox/prune.test.ts@@ -0,0 +1,217 @@+import { existsSync, mkdirSync, mkdtempSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import type { ScriptRunner } from '../../workspaces/script-runner.js';+import { mounts } from './mounts.js';+import type { AsRunner } from './podman.js';+import type { Bind } from './podman-args.js';+import { sandboxPrune } from './prune.js';+import { type SandboxRecord, sandboxRecords } from './records.js';+import { threadLocks } from './thread-lock.js';+import { sandboxUses } from './use.js';++const DAY = 24 * 3600e3;+const ID = '00aa11bb22cc33dd';+const repos = { alpha: { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc' }, beta: { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc' } };+const CLEAN = '1\tok\tclean\t0\tsp/C1-1-1\t/x\n2\tok\tclean\t0\tsp/C1-1-1\t/y\n';++/** One person's stopped thread, last used `usedDaysAgo` days ago, with two worktrees. Everything done is in `log`, in order. */+function rig(o: { usedDaysAgo?: number; state?: string | Error; running?: () => boolean; remove?: boolean; repos?: SandboxRecord['repos'] | null; during?: () => void;+ /** Called at each Podman call and at Remove. */+ at?: (what: string) => unknown; rm?: Error } = {}) {+ const data = mkdtempSync(path.join(os.tmpdir(), 'sp-prune-'));+ const log: string[] = [];+ const helped: { person: string; binds?: Bind[]; args: string[] }[] = [];+ const locks = threadLocks();+ const as: AsRunner = { settled: async () => {}, run: async () => '', podman: async (args) => {+ log.push(`podman ${args.join(' ').replaceAll(data, '')}`);+ await o.at?.(args[0]);+ if (o.rm && args[0] === 'unshare') throw o.rm;+ return '';+ } };+ const m = mounts({ as, root: '/opt/r1', dataDir: data });+ const records = sandboxRecords(path.join(data, 'records'));+ const real = records.delete;+ records.delete = (id) => (log.push(`record deleted ${id}`), real(id));+ const used = Date.now() - (o.usedDaysAgo ?? 15) * DAY;+ const record: SandboxRecord = { id: ID, person: 'pat', key: 'C1:1.1', createdAt: '', usedAt: new Date(used).toISOString(), ...(o.repos !== null && { repos: o.repos ?? repos }) };+ records.write(record);+ mkdirSync(m.workspace(record), { recursive: true });+ const helper = (person: string, binds?: Bind[]): ScriptRunner => ({+ clones: '/clones', workspace: () => '/workspace',+ run: async (script, args) => {+ helped.push({ person, binds, args: [script, ...args] });+ log.push(script);+ if (script !== 'ws-inspect.sh') return '';+ o.during?.();+ if (o.state instanceof Error) throw o.state;+ return o.state ?? CLEAN;+ },+ });+ let clock = Date.now();+ const uses = sandboxUses({ as, records, workspace: m.workspace, unitActive: async () => false });+ const p = sandboxPrune({+ claim: uses.claim,+ as, records, mounts: m, helper, locks, running: o.running ?? (() => false), lastUsed: async (r) => Date.parse(r.usedAt),+ remove: async (id) => (log.push(`remove ${id}`), o.at?.('remove'), o.remove ?? true), deleteRun: async (id) => (log.push(`run deleted ${id}`), true), now: () => clock,+ });+ return { p, uses, log, helped, record, records, m, data, locks, later: (ms: number) => void (clock += ms) };+}++describe('pruning a sandboxed thread (work 103, Prune)', () => {+ it('clean and pushed: Remove, the workspace and its registries, the branch, the run directory, and the record last', async () => {+ const t = rig();+ expect(await t.p.pruneIdle('pat')).toEqual([]);+ expect(t.log).toEqual([+ 'ws-inspect.sh', `remove ${ID}`, 'podman unshare rm -rf -- /people/pat/sessions/C1-1-1 /people/pat/wt/C1-1-1', 'ws-forget.sh', `run deleted ${ID}`, `record deleted ${ID}`,+ ]);+ expect(t.records.get(ID)).toBeUndefined();+ const [inspect, forget] = t.helped;+ expect(inspect.args).toEqual(['ws-inspect.sh', '--only=state', '/clones', '/workspace', 'alpha', 'beta']);+ expect(inspect.binds).toEqual([+ { src: t.m.workspace(t.record), dst: '/workspace', ro: true },+ { src: t.m.registry(t.record, 'alpha'), dst: '/clones/alpha/.git/worktrees' },+ { src: t.m.registry(t.record, 'beta'), dst: '/clones/beta/.git/worktrees' },+ ]);+ expect(forget).toEqual({ person: 'pat', binds: undefined, args: ['ws-forget.sh', '/clones', 'sp/C1-1-1', 'alpha', 'beta'] });+ });++ it('not clean: only the container goes, and the reason is reported', async () => {+ const t = rig({ state: '1\tok\tdirty\t0\tsp/C1-1-1\t/x\n2\tok\tclean\t2\tsp/C1-1-1\t/y\n' });+ expect(await t.p.pruneIdle('pat')).toEqual([{ name: 'sessions/C1-1-1', problem: 'idle beyond retention, kept: alpha has uncommitted changes, beta has 2 unpushed commits' }]);+ expect(t.log).toEqual(['ws-inspect.sh', `podman rm --force sp-runner-${ID}`]);+ expect(t.records.get(ID)).toBeDefined();+ expect(existsSync(t.m.workspace(t.record))).toBe(true);+ });++ it('a count git could not make keeps the thread too', async () => {+ const t = rig({ state: '1\tok\tclean\t-1\tsp/C1-1-1\t/x\n2\tok\tclean\t0\tsp/C1-1-1\t/y\n' });+ expect((await t.p.pruneIdle('pat'))[0].problem).toContain('alpha: cannot count unpushed commits');+ // Only a number of digits is a count: a field that is empty, missing, or anything else keeps the thread.+ for (const field of ['', 'NaN', 'none', '1e2', ' 0', '0x0']) {+ const odd = rig({ state: `1\tok\tclean\t${field}\tsp/C1-1-1\t/x\n2\tok\tclean\t0\tsp/C1-1-1\t/y\n` });+ expect((await odd.p.pruneIdle('pat'))[0]?.problem, JSON.stringify(field)).toContain('alpha: cannot count unpushed commits');+ expect(odd.records.get(ID)).toBeDefined();+ }+ const short = rig({ state: '1\tok\tclean\n2\tok\tclean\t0\tsp/C1-1-1\t/y\n' });+ expect((await short.p.pruneIdle('pat'))[0]?.problem).toContain('alpha: cannot count unpushed commits');+ });++ it('a thread whose files somebody reads, or read since git was asked, is left whole; while one is removed nobody enters it (C13)', async () => {+ // A `/files` script that runs while the turn comes.+ const reading = rig();+ const use = await reading.uses.enter(ID);+ expect(await reading.p.pruneIdle('pat')).toEqual([]);+ expect(reading.log).toEqual(['ws-inspect.sh']);+ // One that ran, and may have written, after git said the thread was clean.+ let t: ReturnType<typeof rig>;+ const wrote = (t = rig({ during: () => void t.uses.enter(ID).then((u) => u.leave()) }));+ expect(await wrote.p.pruneIdle('pat')).toEqual([]);+ expect(wrote.log).toEqual(['ws-inspect.sh']);+ expect(wrote.records.get(ID)).toBeDefined();+ // Left: the next pass prunes.+ use.leave();+ await new Promise((r) => setTimeout(r, 5));+ const refused: unknown[] = [];+ const gone = (t = rig({ at: (what) => what === 'remove' && t.uses.enter(ID).catch((e) => refused.push(e.message)) }));+ expect(await gone.p.pruneIdle('pat')).toEqual([]);+ expect(gone.records.get(ID)).toBeUndefined();+ expect(refused).toEqual([expect.stringMatching(/being cleaned up/)]);+ });++ it('a kept thread is reported at every pass, and asked about again only after an hour or a use', async () => {+ const t = rig({ state: '1\tok\tdirty\t0\tb\t/x\n2\tok\tclean\t0\tb\t/y\n' });+ await t.p.pruneIdle('pat');+ expect(await t.p.pruneIdle('pat')).toHaveLength(1);+ expect(t.log.filter((l) => l === 'ws-inspect.sh')).toHaveLength(1);+ t.later(3600e3);+ expect(await t.p.pruneIdle('pat')).toHaveLength(1);+ expect(t.log.filter((l) => l === 'ws-inspect.sh')).toHaveLength(2);+ });++ it('leaves a thread used within the retention, one with a runner, and another person\'s', async () => {+ for (const t of [rig({ usedDaysAgo: 13 }), rig({ running: () => true })]) {+ expect(await t.p.pruneIdle('pat')).toEqual([]);+ expect(t.log).toEqual([]);+ }+ const other = rig();+ await other.p.pruneIdle('quinn');+ expect(other.log).toEqual([]);+ });++ it('a thread that got a runner, or was used, while git was asked is left whole', async () => {+ let running = false;+ const t = rig({ running: () => running, during: () => void (running = true) });+ expect(await t.p.pruneIdle('pat')).toEqual([]);+ expect(t.log).toEqual(['ws-inspect.sh']);+ const used = rig({ during: () => used.records.write({ ...used.record, usedAt: new Date().toISOString() }) });+ expect(await used.p.pruneIdle('pat')).toEqual([]);+ expect(used.log).toEqual(['ws-inspect.sh']);+ });++ it('a start that arrives while a thread is removed waits until all of it went, the record too', async () => {+ let started: Promise<unknown> | undefined;+ const t = rig({ at: (what) => what === 'remove' && (started = t.locks.run('pat', 'C1:1.1', async () => void t.log.push(`start finds ${t.records.find('pat', 'C1:1.1')?.id ?? 'no record'}`))) });+ await t.p.pruneIdle('pat');+ await started;+ expect(t.log.slice(-3)).toEqual([`run deleted ${ID}`, `record deleted ${ID}`, 'start finds no record']);+ });++ it('a start that arrives while a kept thread\'s container is removed waits for that', async () => {+ let started: Promise<unknown> | undefined;+ const t = rig({ state: '1\tok\tdirty\t0\tb\t/x\n2\tok\tclean\t0\tb\t/y\n', at: async (what) => {+ if (what !== 'rm') return;+ started = t.locks.run('pat', 'C1:1.1', async () => void t.log.push('start'));+ await new Promise((r) => setTimeout(r, 10));+ t.log.push('rm ended');+ } });+ await t.p.pruneIdle('pat');+ await started;+ expect(t.log).toEqual(['ws-inspect.sh', `podman rm --force sp-runner-${ID}`, 'rm ended', 'start']);+ });++ it('a thread that is starting when its turn comes is left whole: nothing is removed while a start has the turn', async () => {+ // The start took the turn while git was asked, and writes its record as every start does.+ let end!: () => void;+ const t = rig({ during: () => void t.locks.run('pat', 'C1:1.1', () => new Promise<void>((r) => (end = () => (t.records.write({ ...t.record, usedAt: new Date().toISOString() }), r())))) });+ const done = t.p.pruneIdle('pat');+ await new Promise((r) => setTimeout(r, 20));+ expect(t.log).toEqual(['ws-inspect.sh']);+ end();+ expect(await done).toEqual([]);+ expect(t.log).toEqual(['ws-inspect.sh']);+ });++ it('a removal that fails half way leaves a record without `repos`: the next start prepares the workspace again, and the next pass goes on', async () => {+ const t = rig({ rm: new Error('rm: timed out') });+ expect((await t.p.pruneIdle('pat'))[0].problem).toContain('prune failed: rm: timed out');+ expect(t.records.get(ID)).toBeDefined();+ expect(t.records.get(ID)?.repos).toBeUndefined();+ expect(t.records.get(ID)?.usedAt).toBe(t.record.usedAt);+ });++ it('a failed inspection or a failed Remove keeps everything, says so, and is tried again at the next pass', async () => {+ const t = rig({ state: new Error('helper timed out') });+ expect(await t.p.pruneIdle('pat')).toEqual([{ name: 'sessions/C1-1-1', problem: 'idle beyond retention, kept: prune failed: helper timed out' }]);+ await t.p.pruneIdle('pat');+ expect(t.log).toEqual(['ws-inspect.sh', 'ws-inspect.sh']);+ const stuck = rig({ remove: false });+ expect((await stuck.p.pruneIdle('pat'))[0].problem).toContain('prune failed: its container or its home was not removed');+ expect(stuck.log).toEqual(['ws-inspect.sh', `remove ${ID}`]);+ expect(stuck.records.get(ID)).toBeDefined();+ });++ it('a thread with no repositories has nothing git could say: it goes, and no branch is forgotten', async () => {+ const t = rig({ repos: null });+ expect(await t.p.pruneIdle('pat')).toEqual([]);+ expect(t.log).toEqual([`remove ${ID}`, 'podman unshare rm -rf -- /people/pat/sessions/C1-1-1 /people/pat/wt/C1-1-1', `run deleted ${ID}`, `record deleted ${ID}`]);+ });++ it('a branch the host did not make is not forgotten', async () => {+ const t = rig({ repos: { alpha: { branch: 'main', from: 'origin/main', base: 'abc' } }, state: '1\tok\tclean\t0\tmain\t/x\n' });+ await t.p.pruneIdle('pat');+ expect(t.log).not.toContain('ws-forget.sh');+ expect(t.records.get(ID)).toBeUndefined();+ });+});diff --git a/computer/src/host/sandbox/prune.ts b/computer/src/host/sandbox/prune.tsnew file mode 100644index 00000000..1722c1bd--- /dev/null+++ b/computer/src/host/sandbox/prune.ts@@ -0,0 +1,167 @@+// Removing a sandboxed thread nobody used for SP_FORK_RETENTION_DAYS (work+// 103, "Sequences", Prune): what workspaces/prune.ts does for a fork on the+// host, without the host running git on anything a session wrote. It is the+// second half of a `podman` host's fork keeper (host.ts); artifacts.ts is the+// first.+//+// Invariants:+// - A thread with uncommitted changes or commits on no remote is never+// removed. Only its container goes (`podman rm --force`, which releases the+// image and the writable layer); its home, workspace and record stay, and+// the next message creates the container again. Why it was kept is reported.+// - Git is asked in a helper container that sees the workspace read-only, for+// the repositories the record names; the branch forgotten is the record's.+// - Only a thread with no runner is pruned, and nothing of it is removed but+// in the thread's turn (thread-lock.ts), which every start takes too. Git is+// asked before the turn; in the turn the thread is left whole if it has a+// runner or its record was written since (every start writes it), or if a+// `/files` script or a terminal is in it or was since git was asked; while+// it is removed none enters (use.ts `claim`). A start+// that arrives while the thread is removed waits for all of it, the record+// included, and then starts a new thread; while a kept thread's container+// is removed, it waits and resumes, creating the container again.+// - Before the workspace is touched the record loses its `repos` (workspace.ts:+// a record has them only while the workspace is whole). So a removal that+// fails half way leaves a thread whose next start prepares its workspace+// again, and whose next pass here goes on removing.+// - The record is deleted last, and only when the container and the home went:+// until then the next pass finds the thread and tries again.+// - A thread that was kept is asked about again when it was used, or an hour+// later (a helper container per thread is not free).++import { lstat } from 'node:fs/promises';+import path from 'node:path';+import { log } from '../../log.js';+import type { WorkspaceStatus } from '../../protocol.js';+import { retention, safeKey } from '../../workspaces/clones.js';+import { type ScriptRunner, row } from '../../workspaces/script-runner.js';+import { CLONES, type Mounts, WORKSPACE } from './mounts.js';+import type { AsRunner } from './podman.js';+import { type Bind, recreateRemoveArgs, unshareRmArgs } from './podman-args.js';+import type { Records, SandboxRecord } from './records.js';+import type { ThreadLocks } from './thread-lock.js';++type RepoStatus = WorkspaceStatus['repos'][number];++const INSPECT_TIMEOUT_MS = 60_000;+const FORGET_TIMEOUT_MS = 30_000;+const REMOVE_TIMEOUT_MS = 120_000;+const ASK_AGAIN_MS = 3600e3;++export interface PruneDeps {+ as: AsRunner;+ records: Records;+ /** The threads' turns, shared with the starts. */+ locks: ThreadLocks;+ mounts: Mounts;+ /** `sandboxScripts.helperScripts`. */+ helper(person: string, binds?: Bind[]): ScriptRunner;+ /** True while the thread of this record has a runner. */+ running(id: string): boolean;+ /** `sandboxUses.claim`: the thread, free of `/files` scripts and terminals since `since`, until the function returned is called. */+ claim(id: string, since: number): (() => void) | undefined;+ /** When the thread was last used (artifacts.ts). */+ lastUsed(r: SandboxRecord): Promise<number>;+ /** Remove: the container and its home, and what the host keeps by the id; true when both went (containers.ts). */+ remove(id: string): Promise<boolean>;+ /** Delete the thread's run directory (sweep.ts); true when it is gone. */+ deleteRun(id: string): Promise<boolean>;+ now?: () => number;+}++export type SandboxPrune = ReturnType<typeof sandboxPrune>;++const msg = (e: unknown) => (e as Error)?.message ?? String(e);++export function sandboxPrune(d: PruneDeps) {+ const { mounts: m } = d;+ const now = d.now ?? Date.now;+ /** Threads that were kept: their last use then, why, and when git was asked. */+ const kept = new Map<string, { used: number; why: string; at: number }>();++ /** Why the thread's work is not all on a remote; undefined when it is. */+ async function unsaved(r: SandboxRecord): Promise<string | undefined> {+ const ws = m.workspace(r);+ const names = Object.keys(r.repos ?? {});+ // Nothing of it on disk (a start that never made it): nothing to lose.+ if (!names.length || !(await lstat(ws).catch(() => undefined))) return undefined;+ const binds: Bind[] = [{ src: ws, dst: WORKSPACE, ro: true }, ...names.map((name) => ({ src: m.registry(r, name), dst: `${CLONES}/${name}/.git/worktrees` }))];+ const out = await d.helper(r.person, binds).run('ws-inspect.sh', ['--only=state', CLONES, WORKSPACE, ...names], { timeoutMs: INSPECT_TIMEOUT_MS });+ const reasons: string[] = [];+ names.forEach((name, i) => {+ // Answered by position, from 1.+ const [dirty, unpushed] = row(out, String(i + 1));+ // Only digits are a count: anything else (`-1`, nothing, a field the script did not print) is not zero.+ const n = /^\d+$/.test(unpushed ?? '') ? Number(unpushed) : -1;+ if (dirty !== 'clean') reasons.push(`${name} has uncommitted changes`);+ else if (n) reasons.push(n > 0 ? `${name} has ${n} unpushed commit${n > 1 ? 's' : ''}` : `${name}: cannot count unpushed commits`);+ });+ return reasons.length ? reasons.join(', ') : undefined;+ }++ const inUse = (r: SandboxRecord) => d.running(r.id) || d.records.get(r.id)?.usedAt !== r.usedAt;++ /** Prune one thread. Returns why it was kept; undefined when it is gone, or in use again. */+ async function prune(r: SandboxRecord): Promise<string | undefined> {+ const asked = Date.now();+ const why = await unsaved(r);+ return d.locks.run(r.person, r.key, async () => {+ // A start had the turn since git was asked (it wrote the record), or the thread runs: what git said is old.+ if (inUse(r)) return undefined;+ // So it is when a `/files` script ran since; and from here none starts until this is over.+ const free = d.claim(r.id, asked);+ if (!free) return undefined;+ return remove(r, why).finally(free);+ });+ }++ /** In the thread's turn, the thread claimed. */+ async function remove(r: SandboxRecord, why: string | undefined): Promise<string | undefined> {+ if (why) {+ await d.as.podman(recreateRemoveArgs(r.id), { timeoutMs: REMOVE_TIMEOUT_MS, repeatable: true });+ return why;+ }+ if (!(await d.remove(r.id))) throw new Error('its container or its home was not removed');+ // From here the workspace is not whole: a start that finds this record prepares it again.+ const { repos, ...bare } = r;+ if (repos) d.records.write(bare);+ await d.as.podman(unshareRmArgs([m.workspace(r), path.dirname(m.registry(r, 'x'))]), { timeoutMs: REMOVE_TIMEOUT_MS });+ // One branch per thread, normally; a branch the session did not get from the host (`sp/…`) is not the host's to delete.+ const byBranch = new Map<string, string[]>();+ for (const [name, repo] of Object.entries(repos ?? {})) if (repo.branch.startsWith('sp/')) byBranch.set(repo.branch, [...(byBranch.get(repo.branch) ?? []), name]);+ for (const [branch, names] of byBranch)+ await d.helper(r.person).run('ws-forget.sh', [CLONES, branch, ...names], { timeoutMs: FORGET_TIMEOUT_MS }).catch((e) => log.warn(`workspaces: branch ${branch} of ${r.key} not forgotten: ${msg(e)}`));+ await d.deleteRun(r.id);+ d.records.delete(r.id);+ log.info(`workspaces: pruned thread ${r.key} (${r.person}), sandbox ${r.id}`);+ return undefined;+ }++ /** Prune `person`'s threads unused for SP_FORK_RETENTION_DAYS, except those with a runner. Returns the ones kept, as housekeeping reports them. */+ async function pruneIdle(person: string): Promise<RepoStatus[]> {+ const rows: RepoStatus[] = [];+ for (const r of d.records.all()) {+ if (r.person !== person || d.running(r.id)) continue;+ const used = await d.lastUsed(r);+ if (now() - used < retention()) {+ kept.delete(r.id);+ continue;+ }+ const before = kept.get(r.id);+ let why = before && before.used === used && now() - before.at < ASK_AGAIN_MS ? before.why : undefined;+ if (!why) {+ kept.delete(r.id);+ try {+ why = await prune(r);+ if (why) kept.set(r.id, { used, why, at: now() });+ } catch (e) {+ why = `prune failed: ${msg(e)}`; // tried again at the next pass+ }+ }+ if (why) rows.push({ name: `sessions/${safeKey(r.key)}`, problem: `idle beyond retention, kept: ${why}` });+ }+ return rows;+ }++ return { prune, pruneIdle };+}diff --git a/computer/src/host/sandbox/records.test.ts b/computer/src/host/sandbox/records.test.tsnew file mode 100644index 00000000..ef22246a--- /dev/null+++ b/computer/src/host/sandbox/records.test.ts@@ -0,0 +1,72 @@+import { mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { type SandboxRecord, sandboxRecords } from './records.js';++let dir: string;+beforeEach(() => void (dir = path.join(mkdtempSync(path.join(os.tmpdir(), 'records-')), 'sandboxes')));+afterEach(() => rmSync(path.dirname(dir), { recursive: true, force: true }));++const rec = (id: string, over: Partial<SandboxRecord> = {}): SandboxRecord =>+ ({ id, person: 'U1', key: 'slack:C1:1.2', createdAt: '2026-11-12T00:00:00.000Z', usedAt: '2026-11-12T00:00:00.000Z', ...over });+const A = '00000000000000aa';+const B = '00000000000000bb';++describe('sandbox records', () => {+ it('makes its directory for the host alone', () => {+ sandboxRecords(dir);+ expect(statSync(dir).mode & 0o777).toBe(0o700);+ });++ it('finds a thread by person and key, and survives a restart', () => {+ const r = sandboxRecords(dir);+ r.write(rec(A));+ r.write(rec(B, { person: 'U2' }));+ expect(r.find('U1', 'slack:C1:1.2')?.id).toBe(A);+ expect(r.find('U2', 'slack:C1:1.2')?.id).toBe(B);+ expect(r.find('U1', 'other')).toBeUndefined();+ const again = sandboxRecords(dir);+ expect(again.all().map((x) => x.id).sort()).toEqual([A, B]);+ expect(again.get(A)).toEqual(rec(A));+ });++ it('writes by rename and leaves no temporary file', () => {+ const r = sandboxRecords(dir);+ r.write(rec(A));+ r.write(rec(A, { usedAt: '2026-11-13T00:00:00.000Z', repos: { web: { branch: 'sp/x', from: 'abc', base: 'main' } } }));+ expect(readdirSync(dir)).toEqual([`${A}.json`]);+ expect(statSync(path.join(dir, `${A}.json`)).mode & 0o777).toBe(0o600);+ expect(sandboxRecords(dir).get(A)?.repos?.web.base).toBe('main');+ });++ it('deletes', () => {+ const r = sandboxRecords(dir);+ r.write(rec(A));+ r.delete(A);+ expect(r.get(A)).toBeUndefined();+ expect(readdirSync(dir)).toEqual([]);+ });++ it('ignores what is not a record, and refuses an id that is not one', () => {+ const r0 = sandboxRecords(dir);+ writeFileSync(path.join(dir, `${A}.json`), '{"id":"other"}');+ writeFileSync(path.join(dir, `${B}.json.123.tmp`), '{');+ writeFileSync(path.join(dir, 'notes.json'), '{}');+ expect(sandboxRecords(dir).all()).toEqual([]);+ expect(() => r0.write(rec('../x'))).toThrow(/bad sandbox id/);+ });++ it('says which record files are there but did not load, until one is written again', () => {+ sandboxRecords(dir);+ writeFileSync(path.join(dir, `${A}.json`), '{"id":"00000000000000aa","person":"U1","ke');+ writeFileSync(path.join(dir, `${B}.json`), '');+ writeFileSync(path.join(dir, 'notes.json'), '{');+ const r = sandboxRecords(dir);+ expect(r.all()).toEqual([]);+ expect(r.get(A)).toBeUndefined();+ expect(r.unread().sort()).toEqual([A, B]);+ r.write(rec(A));+ expect(r.unread()).toEqual([B]);+ });+});diff --git a/computer/src/host/sandbox/records.ts b/computer/src/host/sandbox/records.tsnew file mode 100644index 00000000..8df46878--- /dev/null+++ b/computer/src/host/sandbox/records.ts@@ -0,0 +1,98 @@+// The host's record of a thread's sandbox (work 103, C2): one file per+// thread, `$SP_DATA/state/sandboxes/<id>.json`, in a directory only the host+// can read. It says which container, volume and run directory (all named by+// `id`) belong to which person's thread.+//+// Invariants:+// - What the host knows of a sandboxed thread comes from here, never from the+// workspace, the runner's report or a socket's name (trust rule 2).+// - Written whole to a temporary file and renamed; all read into memory when+// the store is opened (host start). Deleted only when the thread is pruned.+// - At most one record per person and key: `find` is how a thread gets its+// sandbox back.+// - A record's file that is there but did not load is still a record of its+// id: `unread` names it, and whoever removes what has no record (sweep.ts)+// asks it too. Which thread it was is not known, so a start refuses a+// thread that has files and no record while there is one (start.ts).++import path from 'node:path';+import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { log } from '../../log.js';++export interface SandboxRecord {+ /** The runner id: the suffix of the container, the volume and the run directory. */+ id: string;+ /** `person.dir`. */+ person: string;+ /** The session key, as `SessionSpec.key`. */+ key: string;+ /** ISO 8601. */+ createdAt: string;+ /** ISO 8601; set at every start. */+ usedAt: string;+ /** The fork's repositories (`ForkInfo.repos`). Absent until they were first added. */+ repos?: Record<string, { branch: string; from: string; base: string; fetchError?: string }>;+ /**+ * Step 10: the container under this id was a spare, bound to the thread, and its claim is not known to have been answered+ * (spares.ts). Whatever is under this id is then not the thread's runner: it is never taken back and never started again;+ * the thread's next start removes it, home and all, and creates anew (start.ts). Gone once the claim was answered.+ */+ unclaimed?: true;+}++export interface Records {+ all(): SandboxRecord[];+ get(id: string): SandboxRecord | undefined;+ find(person: string, key: string): SandboxRecord | undefined;+ /** Replace the record with this id, on disk and in memory. */+ write(r: SandboxRecord): void;+ delete(id: string): void;+ /** The ids whose file is there and is not a record that loaded: nothing of theirs is anyone's to remove. */+ unread(): string[];+}++const ID = /^[0-9a-f]{16}$/;+const valid = (r: Partial<SandboxRecord> | null, id: string): r is SandboxRecord =>+ !!r && r.id === id && typeof r.person === 'string' && typeof r.key === 'string' && typeof r.createdAt === 'string' && typeof r.usedAt === 'string';++/** The records in `dir` (`$SP_DATA/state/sandboxes`), read now. A file that is not a record is logged, left alone and counted (`unread`). */+export function sandboxRecords(dir: string): Records {+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ const byId = new Map<string, SandboxRecord>();+ const unread = new Set<string>();+ for (const f of readdirSync(dir)) {+ const id = f.replace(/\.json$/, '');+ if (!f.endsWith('.json') || !ID.test(id)) continue; // a temporary file a killed host left, or not ours+ try {+ const r = JSON.parse(readFileSync(path.join(dir, f), 'utf8'));+ if (!valid(r, id)) throw new Error('not a sandbox record');+ byId.set(id, r);+ } catch (e) {+ unread.add(id);+ log.warn(`sandbox record ${f} not read: ${(e as Error)?.message ?? e}; its container and home are kept`);+ }+ }+ const file = (id: string) => {+ if (!ID.test(id)) throw new Error(`bad sandbox id: ${id}`);+ return path.join(dir, `${id}.json`);+ };+ return {+ all: () => [...byId.values()],+ get: (id) => byId.get(id),+ find: (person, key) => [...byId.values()].find((r) => r.person === person && r.key === key),+ write(r) {+ const to = file(r.id);+ const tmp = `${to}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(r, null, 1) + '\n', { mode: 0o600 });+ renameSync(tmp, to);+ byId.set(r.id, r);+ unread.delete(r.id);+ },+ delete(id) {+ rmSync(file(id), { force: true });+ byId.delete(id);+ unread.delete(id);+ },+ unread: () => [...unread],+ };+}diff --git a/computer/src/host/sandbox/scripts.test.ts b/computer/src/host/sandbox/scripts.test.tsnew file mode 100644index 00000000..83b34adc--- /dev/null+++ b/computer/src/host/sandbox/scripts.test.ts@@ -0,0 +1,271 @@+import type { ChildProcess } from 'node:child_process';+import { EventEmitter } from 'node:events';+import { describe, expect, it, vi } from 'vitest';+import { createTelemetry } from '../../telemetry/emitter.js';+import type { TelemetryEvent } from '../../telemetry/envelope.js';+import { ScriptError } from '../../workspaces/script-runner.js';+import { type AsRunner, PodmanError, type RunOptions } from './podman.js';+import { Unavailable, UPDATING } from '../unavailable.js';+import { HELPER_SECONDS, sandboxScripts } from './scripts.js';++const ID = '00aa11bb22cc33dd';+const BIN = '/opt/slack-presence/releases/r1/bin';++function rig(answer: () => string | Error = () => 'out') {+ const execs: { id: string; argv: string[]; o: { dir: string; timeoutMs: number; stdin?: string | Buffer } }[] = [];+ const runs: { argv: string[]; o: RunOptions }[] = [];+ const sent: TelemetryEvent[] = [];+ const tm = createTelemetry({ service: 'host', version: 'v', region: 'r', send: (b) => void sent.push(...b.events) });+ const reply = async () => {+ const a = answer();+ if (a instanceof Error) throw a;+ return a;+ };+ const podmans: string[][] = [];+ /** What the thread is when a `/files` script enters it, and how often one entered and left. */+ const state = { running: true, held: false, entered: 0, left: 0, order: [] as string[] };+ const as: AsRunner = {+ settled: async () => void state.order.push('settled'),+ run: (argv, o) => (state.order.push('run'), runs.push({ argv, o }), reply()),+ podman: (args) => (podmans.push(args), reply()),+ };+ const started: string[][] = [];+ const children: EventEmitter[] = [];+ const s = sandboxScripts({+ as, sudo: ['/usr/bin/sudo', '-n', '-u', 'agent'], tm, root: '/opt/slack-presence/releases/r1', dataDir: '/data', helperRun: '/run/sp/helper', image: 'img:1',+ execIn: (id, argv, o) => (execs.push({ id, argv, o }), reply()),+ running: async () => state.running, lostWaitMs: 1,+ enter: async (id) => {+ if (state.held) throw new Unavailable(UPDATING);+ state.entered += 1;+ let left = false;+ return { place: { id, person: 'pat', workspace: '/data/people/pat/sessions/k', running: state.running }, leave: () => void (left || ((left = true), (state.left += 1))) };+ },+ spawn: (cmd, args) => {+ started.push([cmd, ...args]);+ const child = Object.assign(new EventEmitter(), { kill: () => true });+ children.push(child);+ return child as ChildProcess;+ },+ });+ return { s, state, execs, runs, podmans, started, children, tm, events: async () => (await tm.flush(), sent) };+}++describe('workspace scripts in containers (work 103, C12)', () => {+ it('a session script runs in the thread\'s container, ended there by timeout, the host waiting a little longer', async () => {+ const t = rig();+ const sc = t.s.sessionScripts(ID);+ expect([sc.clones, sc.workspace('ignored')]).toEqual(['/clones', '/workspace']);+ expect(await sc.run('ws-add.sh', ['/clones', '/workspace', 'sp/k', '1', 'alpha'], { timeoutMs: 60_000, stdin: 'tar' })).toBe('out');+ expect(t.execs).toEqual([{+ id: ID,+ argv: ['/usr/bin/timeout', '--kill-after=5', '60', '/bin/sh', `${BIN}/ws-add.sh`, '/clones', '/workspace', 'sp/k', '1', 'alpha'],+ o: { dir: '/', timeoutMs: 75_000, stdin: 'tar' },+ }]);+ });++ it('only a workspace script of the release is run', async () => {+ const t = rig();+ for (const bad of ['../x.sh', 'ws-add.sh; rm', 'sandbox-mount.py', '/bin/sh']) {+ await expect(t.s.sessionScripts(ID).run(bad, [], { timeoutMs: 1000 })).rejects.toThrow('not a workspace script');+ }+ await expect(t.s.helperScripts('pat').run('ws-add.sh', [], { timeoutMs: 1000 })).rejects.toThrow('does not run in a helper container');+ expect([t.execs, t.runs]).toEqual([[], []]);+ });++ it('a helper is a container of its own in a scope, never longer than the table says, with a network only to fetch', async () => {+ const t = rig();+ // A clone has the caller's limit, 30 min for itself and for each setup command, and no cap of its own.+ await t.s.helperScripts('pat').run('ws-clone.sh', ['/clones', 'alpha', 'https://x/a.git', '', ''], { timeoutMs: 3 * 1_800_000 });+ await t.s.helperScripts('pat', [{ src: '/data/people/pat/sessions/k', dst: '/workspace', ro: true }]).run('ws-inspect.sh', ['--only=state', '/clones', '/workspace', 'alpha'], { timeoutMs: 5_000, stdin: '1\tx\n' });+ const [clone, inspect] = t.runs;+ expect(clone.argv.slice(0, 3)).toEqual(['/usr/bin/systemd-run', '--user', '--scope']);+ expect(clone.argv).toEqual(expect.arrayContaining(['/usr/bin/podman', 'run', '--rm', '--network=pasta', '--timeout', '5400', '/data/people/pat/ws:/clones']));+ expect(clone.argv).not.toContain('--interactive');+ expect(clone.argv.slice(-6)).toEqual([`${BIN}/ws-clone.sh`, '/clones', 'alpha', 'https://x/a.git', '', '']);+ expect(clone.o.timeoutMs).toBe(5_415_000);+ expect(HELPER_SECONDS['ws-sync.sh']).toBe(120);+ expect(inspect.argv).toEqual(expect.arrayContaining(['--network=none', '--interactive', '--timeout', '5', '/data/people/pat/sessions/k:/workspace:ro']));+ expect(inspect.o).toEqual({ timeoutMs: 20_000, stdin: '1\tx\n' });+ // A helper is `podman run` outside `as.podman`: it waits for the image lock by itself, as long as any Podman call.+ expect(t.state.order).toEqual(['settled', 'run', 'settled', 'run']);+ const events = (await t.events()).filter((e) => e.event_name === 'sandbox.helper');+ expect(events.map((e) => [e.data?.script, e.outcome])).toEqual([['ws-clone.sh', 'completed'], ['ws-inspect.sh', 'completed']]);+ expect(t.tm.dropped).toEqual({});+ });++ it('a failure is a ScriptError with the script\'s own words; one that ran out of time says so', async () => {+ const said = rig(() => new PodmanError('failed', 1, 'alpha: no remote branch\n', false));+ const e1 = await said.s.sessionScripts(ID).run('ws-add.sh', [], { timeoutMs: 60_000 }).catch((e) => e);+ expect(e1).toBeInstanceOf(ScriptError);+ expect([e1.killed, e1.message]).toEqual([false, expect.stringContaining('no remote branch')]);+ for (const err of [new PodmanError('failed', 124, '', false), new PodmanError('failed', undefined, '', true)]) {+ const late = rig(() => err);+ const e2 = await late.s.helperScripts('pat').run('ws-sync.sh', [], { timeoutMs: 0 }).catch((e) => e);+ expect([e2.killed, e2.message, e2.stderr]).toEqual([true, 'ws-sync.sh: timed out', 'timed out after 120 s']);+ expect((await late.events()).filter((e) => e.event_name === 'sandbox.helper').map((e) => [e.outcome, e.error_type])).toEqual([['failed', 'timeout']]);+ }+ });++ it('a helper Podman ended at its --timeout (exit 255, no word) ran out of time; the same exit sooner did not', async () => {+ const quick = rig(() => new PodmanError('failed', 255, '', false));+ const e1 = await quick.s.helperScripts('pat').run('ws-sync.sh', [], { timeoutMs: 0 }).catch((e) => e);+ expect(e1.killed).toBe(false);+ const real = Date.now;+ let t = real();+ const now = vi.spyOn(Date, 'now').mockImplementation(() => (t += 130_000));+ try {+ const slow = rig(() => new PodmanError('failed', 255, '', false));+ const e2 = await slow.s.helperScripts('pat').run('ws-sync.sh', [], { timeoutMs: 0 }).catch((e) => e);+ expect([e2.killed, e2.stderr]).toEqual([true, 'timed out after 120 s']);+ } finally {+ now.mockRestore();+ }+ });++ describe('where the /files scripts of a thread run (C13)', () => {+ const sb = { id: ID, person: 'pat', workspace: '/data/people/pat/sessions/k', running: true };+ const AS = ['/usr/bin/sudo', '-n', '-u', 'agent', '--', '/usr/bin/timeout', '--kill-after=2'];++ it('a running thread: podman exec in its container, as the session, in /workspace, ended there by timeout', async () => {+ const t = rig();+ const place = t.s.filesPlace(sb);+ expect(place.root).toBe('/workspace');+ await place.spawn(['/bin/sh', '-c', 'x', 'sh', '/workspace'], { seconds: 30 });+ await place.spawn(['/bin/sh', '-c', 'x'], { stdin: true, write: true });+ const tag = t.started[0].at(-6)?.slice('OPC_FILES='.length);+ expect(tag).toMatch(/^[0-9a-f]{16}$/);+ expect(t.started[0]).toEqual([+ ...AS, '45.000', '/usr/bin/podman', 'exec', '--user', '1500:1500', '--workdir', '/workspace', `sp-runner-${ID}`,+ '/usr/bin/timeout', '--kill-after=5', '30', '/usr/bin/env', `OPC_FILES=${tag}`, '/bin/sh', '-c', 'x', 'sh', '/workspace',+ ]);+ expect(t.started[1].slice(7, 11)).toEqual(['3615.000', '/usr/bin/podman', 'exec', '--interactive']);+ expect(t.started[1].slice(-8, -5)).toEqual(['/usr/bin/timeout', '--kill-after=5', '3600']);+ expect(t.started[1].slice(-3)).toEqual(['/bin/sh', '-c', 'x']);+ expect(t.started[1].at(-4)).not.toBe(`OPC_FILES=${tag}`);+ expect([t.execs, t.runs]).toEqual([[], []]);+ });++ it('a stopped thread: the same helper as a workspace script, its workspace bound read-only unless the script writes, never a network', async () => {+ const t = rig();+ t.state.running = false;+ const place = t.s.filesPlace(sb);+ await place.spawn(['/bin/sh', '-c', 'x', 'sh', '/workspace'], { seconds: 30 });+ await place.spawn(['/bin/sh', '-c', 'x'], { write: true, stdin: true });+ const [read, write] = t.started;+ expect(read.slice(0, 18)).toEqual([...AS, '45.000', '/usr/bin/systemd-run', '--user', '--scope', '--quiet', '--slice=slack-presence-runners.slice', '-p', 'Delegate=yes', '--', '/usr/bin/podman', 'run']);+ expect(read).toEqual(expect.arrayContaining(['--network=none', '--timeout', '30', '--log-driver=none', '/data/people/pat/ws:/clones', `${sb.workspace}:/workspace:ro`]));+ expect(read).not.toContain('--interactive');+ expect(read).not.toContain(`sp-runner-${ID}`);+ expect(read.slice(-7)).toEqual(['--entrypoint', '/bin/sh', 'img:1', '-c', 'x', 'sh', '/workspace']);+ expect(write).toEqual(expect.arrayContaining(['--network=none', '--interactive', '--timeout', '3600', `${sb.workspace}:/workspace`]));+ // A script's own exit is an answer; an exit of timeout(1) or of Podman is the helper's failure.+ t.children[0].emit('close', 3);+ t.children[1].emit('close', 125);+ expect((await t.events()).filter((e) => e.event_name === 'sandbox.helper').map((e) => [e.data?.script, e.outcome])).toEqual([['files', 'completed'], ['files', 'failed']]);+ expect(t.tm.dropped).toEqual({});+ });++ it('a running thread: a script whose command was ended, not over by itself, is ended in the container too', async () => {+ const t = rig();+ const place = t.s.filesPlace(sb);+ const ps = await Promise.all([0, 1, 2, 3, 4].map(() => place.spawn(['/bin/sh', '-c', 'x'], {})));+ const tags = t.started.map((a) => a.at(-4)?.slice('OPC_FILES='.length));+ // The script's own exits: nothing of it is left. Ended by a signal, by timeout(1), or never started: its timeout in the container is told to end it.+ t.children[0].emit('close', 0);+ t.children[1].emit('close', 3);+ t.children[2].emit('close', null);+ t.children[2].emit('close', null);+ t.children[3].emit('close', 124);+ // `podman exec` that is told to end exits 0 (measured, Podman 4.9.3): being told is what counts, not the code.+ expect(ps[4].kill('SIGTERM')).toBe(true);+ t.children[4].emit('close', 0);+ expect(t.podmans).toEqual([2, 3, 4].map((i) => ['exec', '--user', '1500:1500', `sp-runner-${ID}`, 'pkill', '-TERM', '-f', `^/usr/bin/timeout .* OPC_FILES=${tags[i]} `]));+ const pattern = new RegExp(t.podmans[0].at(-1) as string);+ expect(pattern.test(t.started[2].slice(-8).join(' '))).toBe(true);+ expect(pattern.test(t.started[3].slice(-8).join(' '))).toBe(false);+ // What it runs (env has become the shell) is not what is signalled: timeout(1) ends its whole group.+ expect(pattern.test('/bin/sh -c x')).toBe(false);+ });++ it('a stopped thread: a helper whose command was ended, not over by itself, is stopped', async () => {+ const t = rig();+ t.state.running = false;+ const place = t.s.filesPlace(sb);+ const ps = await Promise.all([0, 1, 2, 3].map(() => place.spawn(['/bin/sh', '-c', 'x'], {})));+ const names = t.started.map((a) => a[a.indexOf('--name') + 1]);+ expect(names[0]).toMatch(/^sp-files-[0-9a-f]{16}$/);+ expect(new Set(names).size).toBe(4);+ t.children[0].emit('close', 1);+ t.children[1].emit('close', null);+ t.children[2].emit('close', 143);+ ps[3].kill();+ t.children[3].emit('close', 0);+ expect(t.podmans).toEqual([1, 2, 3].map((i) => ['stop', '--ignore', '--time', '2', names[i]]));+ });++ it('a place that fails to end what is left says so and goes on', async () => {+ const t = rig(() => new PodmanError('failed', 125, 'no such container', false));+ await t.s.filesPlace(sb).spawn(['/bin/sh', '-c', 'x'], {});+ t.children[0].emit('close', null);+ await new Promise((r) => setImmediate(r));+ expect(t.podmans.length).toBe(1);+ });++ it('only a shell script is started', async () => {+ const t = rig();+ await expect(t.s.filesPlace(sb).spawn(['/usr/bin/git', 'status'], {})).rejects.toThrow('not a shell script');+ expect(t.started).toEqual([]);+ });++ it('where it runs is what the thread is when the script starts, whatever its caller was told before', async () => {+ const t = rig();+ const place = t.s.filesPlace({ ...sb, running: false }); // what the request knew+ await place.spawn(['/bin/sh', '-c', 'x'], {});+ t.state.running = false; // idle stop+ await place.spawn(['/bin/sh', '-c', 'x'], {});+ expect(t.started.map((a) => a[a.indexOf('/usr/bin/podman') + 1])).toEqual(['exec', 'run']);+ });++ it('lost: a script in the container whose command failed, untold, and whose container is no longer running then', async () => {+ const t = rig();+ const place = t.s.filesPlace(sb);+ const ps = await Promise.all([0, 1, 2, 3, 4].map(() => place.spawn(['/bin/sh', '-c', 'x'], {})));+ t.state.running = false; // the idle stop+ t.children[0].emit('close', 137); // killed with its container+ t.children[1].emit('close', 255); // `podman exec` found the container stopped+ t.children[2].emit('close', 44); // the script's own answer+ ps[3].kill('SIGTERM'); // the host ended it+ t.children[3].emit('close', 137);+ expect(await Promise.all(ps.map((p) => place.lost?.(p)))).toEqual([true, true, false, false, false]); // the last has not closed+ // A helper is nobody's container to stop: its failure is its own.+ const helper = await place.spawn(['/bin/sh', '-c', 'x'], {});+ t.children[5].emit('close', 255);+ expect(await place.lost?.(helper)).toBe(false);+ // The container still runs: whatever ended the script, it was not the stop.+ const up = rig();+ const p = await up.s.filesPlace(sb).spawn(['/bin/sh', '-c', 'x'], {});+ up.children[0].emit('close', 137);+ expect(await up.s.filesPlace(sb).lost?.(p)).toBe(false);+ });++ it('while provisioning holds the image lock nothing is started, and the caller is told the computer is updating', async () => {+ const t = rig();+ t.state.held = true;+ await expect(t.s.filesPlace(sb).spawn(['/bin/sh', '-c', 'x'], {})).rejects.toThrow(/The computer is updating, try again/);+ expect([t.started, t.podmans]).toEqual([[], []]);+ });++ it('a script has left its sandbox once its command closed, or never started', async () => {+ const t = rig();+ await t.s.filesPlace(sb).spawn(['/bin/sh', '-c', 'x'], {});+ expect([t.state.entered, t.state.left]).toEqual([1, 0]);+ t.children[0].emit('close', 0);+ expect(t.state.left).toBe(1);+ await t.s.filesPlace(sb).spawn(['/bin/sh', '-c', 'x'], {});+ t.children[1].emit('error', new Error('spawn ENOENT'));+ t.children[1].emit('close', null);+ expect([t.state.entered, t.state.left]).toEqual([2, 2]);+ });+ });+});diff --git a/computer/src/host/sandbox/scripts.ts b/computer/src/host/sandbox/scripts.tsnew file mode 100644index 00000000..89542bd6--- /dev/null+++ b/computer/src/host/sandbox/scripts.ts@@ -0,0 +1,249 @@+// The one way a `podman` host runs a script on a person's files (work 103,+// C12 and C13): in the thread's running container, as the session's user,+// where the workspace is `/workspace` and the clones `/clones`; or in a helper+// container made for that run, which sees that person's clones, what its+// caller binds, and nothing of anybody else.+//+// `sessionScripts(id)` and `helperScripts(person, binds?)` are the two+// ScriptRunners of the workspace scripts (bin/ws-*.sh): a script runs to its+// end and its output is the answer. `filesPlace(thread)` is where the `/files`+// scripts run (workspace-files.ts `Place`): the same two commands, started and+// handed back, since a file or an archive is a stream; in the container while+// the thread runs, else in a helper with its workspace bound at `/workspace`,+// read-only unless the script writes, and never with a network.+//+// Invariants:+// - The host never runs git, and never opens a workspace file: on a `podman`+// host every script goes through here.+// - A helper gets a network only for a script that fetches, and never runs+// longer than the spec's table says (HELPER_SECONDS; a clone: as long as+// its caller says), whatever its caller asked: Podman ends it, since the+// script is its first process.+// - A script in a session's container is ended inside the container+// (`timeout`), so nothing of it is left running there when its time is up.+// - A `/files` script whose command on the host ended any other way than by+// the script's own exit (its reader went away, its time was up, the host+// ended it: the child's `kill`) is ended where it runs as well: ending+// `podman exec` or `podman run` leaves a process that neither reads nor+// writes running in the container (measured, Podman 4.9.3). So the host+// signals the script's `timeout` in the session's container, and stops the+// helper by its name.+// - Failures of a ScriptRunner are ScriptError, as from the host's runner, so+// callers are the same. A `/files` script's exit code is its caller's to read.+// - A helper container and a `/files` script start only once provisioning is+// not holding Podman's storage (image-lock.ts): a helper waits as any+// Podman call does, a `/files` script as long as a person may be kept+// waiting, and is refused past that (use.ts).+// - Where a `/files` script runs is decided when it starts, from what the+// thread is then (use.ts `enter`), not from the SandboxPlace its caller+// holds. A container that stops after that (the idle stop) makes `podman+// exec` fail, or kills the script with it; nothing falls back to the host.+// `lost` tells that end from a failure of the script, and the caller runs+// the script again, where the thread is then, only when it changes nothing+// (workspace-files.ts).++import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process';+import { randomBytes } from 'node:crypto';+import path from 'node:path';+import { ScriptError, type ScriptRunner } from '../../workspaces/script-runner.js';+import type { Telemetry } from '../../telemetry/emitter.js';+import type { Place } from '../workspace-files.js';+import { CLONES, WORKSPACE } from './mounts.js';+import { type AsRunner, bounded, PODMAN, PodmanError, TIMEOUT } from './podman.js';+import type { Use } from './use.js';+import { type Bind, execArgs, filesEndArgs, filesTagged, HELPER_SCOPE, helperArgs, helperStopArgs } from './podman-args.js';++/**+ * Seconds a helper may run, by script (the spec's "Helper run"): the most its caller can ask, and what it gets when the+ * caller names no limit. A clone's is the second only: its caller's limit (30 min for the clone and for each setup+ * command, src/workspaces/clones.ts) applies whole.+ */+export const HELPER_SECONDS: Record<string, number> = { 'ws-clone.sh': 1800, 'ws-sync.sh': 120, 'ws-fetch.sh': 120, 'ws-inspect.sh': 60, 'ws-forget.sh': 30 };+/** The scripts whose caller's limit is not capped. */+const UNCAPPED = new Set(['ws-clone.sh']);+/** The scripts that reach a remote. */+const FETCHES = new Set(['ws-clone.sh', 'ws-sync.sh', 'ws-fetch.sh']);+/** What the host waits past a script's own limit before it gives up on the command. */+const GRACE_MS = 15_000;+/** Seconds a `/files` script may run at most: one that carries an archive of 1 GiB out, or an upload in. */+export const FILES_SECONDS = 3600;++/** What ending the rest of a `/files` script in its container may take. */+const LEFT_MS = 20_000;++/** A thread's sandbox as its terminal and its `/files` need it; sandbox/host.ts fills it from the thread's record. */+export interface SandboxPlace {+ /** The sandbox id (`sp-runner-<id>`). */+ id: string;+ /** `person.dir`. */+ person: string;+ /** The workspace on the host: what is mounted at `/workspace` while the thread runs. */+ workspace: string;+ /** The thread's container is running. */+ running: boolean;+}++export interface ScriptsDeps {+ as: AsRunner;+ /** `runnerUser(env).sudo`: for a script whose output is a stream, which `as` does not start. */+ sudo: string[];+ /** Starts such a script; tests pass their own. */+ spawn?: (cmd: string, args: string[]) => ChildProcess;+ tm: Telemetry;+ /** The host's release (its `bin/` holds the scripts) and SP_DATA. */+ root: string;+ dataDir: string;+ /** The helpers' run directory, `$SP_RUN/helper`. */+ helperRun: string;+ image: string;+ /** `sandboxUses.enter`: before a `/files` script starts. */+ enter(id: string): Promise<Use>;+ /** The thread's container is running now (`unitActive`). */+ running(id: string): Promise<boolean>;+ /** How long `lost` waits for a container that is stopping to have stopped (3 s); tests pass less. */+ lostWaitMs?: number;+ /** `containers.execIn`. */+ execIn(id: string, argv: string[], o: { dir: string; timeoutMs: number; stdin?: string | Buffer }): Promise<string>;+}++export type SandboxScripts = ReturnType<typeof sandboxScripts>;++/** `ranOut`: the command failed no sooner than its limit. `podman run --timeout` ends a container with exit 255 and says nothing (measured, Podman 4.9.3), so only the time tells. */+const failed = (script: string, e: unknown, seconds: number, ranOut = false) => {+ if (!(e instanceof PodmanError)) return e;+ // 124: timeout(1) ended it.+ const killed = e.timedOut || e.code === 124 || ranOut;+ return new ScriptError(script, e.code ?? null, killed ? `timed out after ${seconds} s` : e.stderr, killed);+};++export function sandboxScripts(d: ScriptsDeps) {+ const bin = (script: string) => {+ if (!/^ws-[a-z]+\.sh$/.test(script)) throw new Error(`not a workspace script: ${script}`);+ return path.join(d.root, 'bin', script);+ };++ /** `/bin/sh <sh…>` for a thread's running container, ended there after `seconds` (0: never). */+ const inSession = (sh: string[], seconds: number) => [...(seconds > 0 ? [TIMEOUT, '--kill-after=5', String(seconds)] : []), '/bin/sh', ...sh];+ /** `/bin/sh <sh…>` in a container of its own on `person`'s clones, ended by Podman after `seconds`: the whole command, for the runners' user. */+ const inHelper = (person: string, sh: string[], o: { network: boolean; seconds: number; stdin: boolean; binds: Bind[]; name?: string }) => [+ ...HELPER_SCOPE, PODMAN,+ ...helperArgs({ name: o.name, person, people: path.join(d.dataDir, 'people'), run: d.helperRun, image: d.image, network: o.network, timeoutS: o.seconds, stdin: o.stdin, binds: o.binds, sh }),+ ];++ /** In the thread's running container. */+ function sessionScripts(id: string): ScriptRunner {+ return {+ clones: CLONES,+ workspace: () => WORKSPACE,+ async run(script, args, o) {+ const seconds = Math.max(1, Math.ceil(o.timeoutMs / 1000));+ const argv = inSession([bin(script), ...args], o.timeoutMs > 0 ? seconds : 0);+ return d.execIn(id, argv, { dir: '/', timeoutMs: o.timeoutMs > 0 ? o.timeoutMs + GRACE_MS : 0, stdin: o.stdin }).catch((e) => {+ throw failed(script, e, seconds);+ });+ },+ };+ }++ /** In a container of its own, on `person`'s clones. `binds`: a stopped thread's workspace and registries, for a script that reads them. */+ function helperScripts(person: string, binds: Bind[] = []): ScriptRunner {+ return {+ clones: CLONES,+ workspace: () => WORKSPACE,+ async run(script, args, o) {+ const cap = HELPER_SECONDS[script];+ if (!cap) throw new Error(`${script} does not run in a helper container`);+ const asked = Math.max(1, Math.ceil(o.timeoutMs / 1000));+ const seconds = o.timeoutMs > 0 ? (UNCAPPED.has(script) ? asked : Math.min(cap, asked)) : cap;+ const argv = inHelper(person, [bin(script), ...args], { network: FETCHES.has(script), seconds, stdin: o.stdin !== undefined, binds });+ const span = d.tm.start('sandbox.helper', { data: { script } });+ const t0 = Date.now();+ try {+ await d.as.settled();+ const out = await d.as.run(argv, { timeoutMs: seconds * 1000 + GRACE_MS, stdin: o.stdin });+ span.end({ outcome: 'completed' });+ return out;+ } catch (e) {+ const err = failed(script, e, seconds, Date.now() - t0 >= seconds * 1000);+ span.end({ outcome: 'failed', error_type: (err as ScriptError).killed ? 'timeout' : 'unknown' });+ throw err;+ }+ },+ };+ }++ const start = d.spawn ?? ((cmd, args) => nodeSpawn(cmd, args, { cwd: '/', stdio: ['pipe', 'pipe', 'pipe'] }));++ /** The `/files` scripts started in a thread's container: how each ended, for `lost`. */+ const inContainer = new WeakMap<ChildProcess, { id: string; told: boolean; code?: number | null }>();+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++ /** Where the `/files` scripts of a thread run: started, not waited for; what the process prints and how it exits is the caller's. */+ function filesPlace(place: SandboxPlace): Place {+ return {+ root: WORKSPACE,+ async spawn(argv, mode) {+ const [shell, ...sh] = argv;+ if (shell !== '/bin/sh') throw new Error(`not a shell script: ${shell}`);+ const use = await d.enter(place.id);+ // What the thread is now: it may have stopped, or started, since the request came in.+ const sb = use.place;+ const seconds = Math.min(FILES_SECONDS, Math.max(1, Math.ceil(mode.seconds ?? FILES_SECONDS)));+ const tag = randomBytes(8).toString('hex');+ const command = sb.running+ ? [PODMAN, ...execArgs(sb.id, [TIMEOUT, '--kill-after=5', String(seconds), ...filesTagged(tag), '/bin/sh', ...sh], { dir: WORKSPACE, interactive: mode.stdin })]+ : inHelper(sb.person, sh, { name: `sp-files-${tag}`, network: false, seconds, stdin: !!mode.stdin, binds: [{ src: sb.workspace, dst: WORKSPACE, ro: !mode.write }] });+ // The same bound as `as.run` puts on a command (podman.ts): past it timeout(1) ends what sudo started.+ const [cmd, ...args] = [...d.sudo, '--', ...bounded(command, seconds * 1000 + GRACE_MS)];+ let p: ChildProcess;+ try {+ p = start(cmd, args);+ } catch (e) {+ use.leave();+ throw e;+ }+ const span = sb.running ? undefined : d.tm.start('sandbox.helper', { data: { script: 'files' } });+ const t0 = Date.now();+ p.once('error', () => (use.leave(), span?.end({ outcome: 'failed', error_type: 'unknown' })));+ // Whoever tells the command to end is noted: `podman exec` that was told exits 0, as if its script had (measured, Podman 4.9.3).+ let told = false;+ const ran = sb.running ? { id: sb.id, told: false, code: undefined as number | null | undefined } : undefined;+ if (ran) inContainer.set(p, ran);+ const kill = p.kill.bind(p);+ p.kill = (signal) => {+ told = true;+ if (ran) ran.told = true;+ return kill(signal);+ };+ p.once('close', (code: number | null) => {+ use.leave();+ if (ran) ran.code = code;+ // The script's own exits (a path that is not there, or leaves the workspace) are answers, not failures of the helper.+ const own = code !== null && code < 124;+ span?.end(own ? { outcome: 'completed' } : { outcome: 'failed', error_type: Date.now() - t0 >= seconds * 1000 ? 'timeout' : 'unknown' });+ if (own && !told) return;+ // Ended, not over: what it ran may still be there. Nothing to end is the usual answer, and a failure here has nobody to tell.+ d.as.podman(sb.running ? filesEndArgs(sb.id, tag) : helperStopArgs(`sp-files-${tag}`), { timeoutMs: LEFT_MS }).catch(() => {});+ });+ return p;+ },+ /**+ * The script ended because its container stopped under it: it ran in the container, nobody told it to end, its+ * command did not end as the script does (255: `podman exec` on a stopped container; 137: killed with it; measured,+ * Podman 4.9.3), and the container is not running. The exec may fail a moment before the unit is over, hence the wait.+ */+ async lost(p) {+ const ran = inContainer.get(p);+ if (!ran || ran.told || ran.code === undefined || (ran.code !== null && ran.code < 124)) return false;+ const until = Date.now() + (d.lostWaitMs ?? 3000);+ for (;;) {+ if (!(await d.running(ran.id).catch(() => true))) return true;+ if (Date.now() >= until) return false;+ await sleep(Math.min(200, d.lostWaitMs ?? 3000));+ }+ },+ };+ }++ return { sessionScripts, helperScripts, filesPlace };+}diff --git a/computer/src/host/sandbox/spares.test.ts b/computer/src/host/sandbox/spares.test.tsnew file mode 100644index 00000000..7e1a96de--- /dev/null+++ b/computer/src/host/sandbox/spares.test.ts@@ -0,0 +1,329 @@+import type net from 'node:net';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import type { RunnerSpec, SessionSpec } from '../../protocol.js';+import type { RunnerApi } from '../../protocol-api.js';+import { createTelemetry } from '../../telemetry/emitter.js';+import { containers } from './containers.js';+import { type Exec, asRunner } from './podman.js';+import { sandboxRecords } from './records.js';+import { type SpareDeps, sandboxSpares } from './spares.js';+import { threadLocks } from './thread-lock.js';++const owner = { dir: 'pat', gitName: 'Pat', gitEmail: '[email protected]' };+const spec: SessionSpec = { key: 'C1:1.1', kind: 'thread', owner, title: 't', mode: 'default', sdkSessionId: 'old', forkPath: '/data/people/pat/sessions/C1-1.1' };+const sock = { destroyed: false, destroy: () => {} } as unknown as net.Socket;+const tick = () => new Promise((r) => setTimeout(r, 5));++function rig(o: { settleMs?: number; deferMs?: number; fail?: Partial<Record<'create' | 'up' | 'pid' | 'mount' | 'prepare' | 'mint', Error>>; dial?: () => Promise<net.Socket | undefined>; api?: boolean; stays?: boolean; unbound?: boolean } = {}) {+ const log: string[] = [];+ /** What the model proxy was asked, with how much of `log` there was then. */+ const proxy: string[] = [];+ const ups: { rs: RunnerSpec; record: unknown; mount: unknown }[] = [];+ const tm = createTelemetry({ service: 'host', version: 'v', region: 'r', send: () => {} });+ const records = sandboxRecords(mkdtempSync(path.join(tmpdir(), 'records-')));+ const runs = mkdtempSync(path.join(tmpdir(), 'run-'));+ const runRoot = (id: string) => path.join(runs, id);+ const step = async <T>(name: string, v: T): Promise<T> => {+ log.push(name.replaceAll(runs, 'RUN'));+ const e = o.fail?.[name.split(' ')[0] as 'create'];+ if (e) throw e;+ return v;+ };+ const locks = threadLocks();+ const d: SpareDeps = {+ tm, records, locks, runRoot, version: 'v9',+ models: {+ spare: async (id) => {+ proxy.push(`spare ${id} after ${log.length}`);+ if (o.unbound) throw new Error('not bound');+ },+ closed: (key, id) => void proxy.push(`closed '${key}' ${id}`),+ },+ deleteRun: async (id) => (rmSync(runRoot(id), { recursive: true, force: true }), step(`deleteRun ${id}`, true)),+ containers: {+ create: async (id) => (mkdirSync(runRoot(id), { recursive: true }), writeFileSync(path.join(runRoot(id), 'boot.env'), ''), step(`create ${id}`, 11)),+ up: async (id, rs, record, mount) => {+ ups.push({ rs, record, mount });+ return step(`up ${id}`, { pid: 5, startMs: 33, tokens: { close: () => void log.push('tokens closed') } });+ },+ pid: (id) => step(`pid ${id}`, 7),+ remove: (id) => step(`remove ${id}`, !o.stays),+ stop: (id, seconds) => step(`stop ${id} ${seconds}`, undefined),+ diagnose: async () => 'boom',+ },+ mint: async (s, id, run) => (await step(`mint ${id} ${run} sdk=${s.sdkSessionId ?? '-'} fork=${s.forkPath ?? '-'}`, 0), o.api ? ({ journal: '/data/journals/s1/journal.jsonl', token: 'tok' } as RunnerApi) : undefined),+ workspace: {+ repos: () => ['hello'],+ dirs: async (r, names) => void log.push(`dirs ${r.key} ${names.join(',')}`),+ binds: (r, names, journal) => [{ src: `ws:${r.key}`, dst: '/workspace' }, ...names.map((n) => ({ src: n, dst: `/clones/${n}` })), ...(journal ? [{ src: journal, dst: journal }] : [])],+ mount: (id, pid, person, b) => step(`mount ${id} ${pid} ${person} ${b.map((x) => x.dst).join(' ')}`, undefined),+ prepare: async (id, names) => {+ await step(`prepare ${id} ${names.join(',')}`, undefined);+ const record = { ...records.get(id)!, repos: Object.fromEntries(names.map((n) => [n, { branch: 'b', from: 'origin/main', base: 'abc' }])) };+ records.write(record);+ return { record, addMs: 7 };+ },+ },+ dial: o.dial ?? (async () => sock),+ settleMs: o.settleMs ?? 0,+ deferMs: o.deferMs,+ };+ return { ...sandboxSpares(d), log, proxy, ups, records, locks, runRoot, tm };+}++describe('a spare container', () => {+ it('is made with nothing of anyone: no record, no mount, a boot spec with no session and no API', async () => {+ const t = rig();+ const s = await t.launch();+ expect(s.id).toMatch(/^[0-9a-f]{16}$/);+ expect(t.log).toEqual([`create ${s.id}`, `up ${s.id}`]); // no directories of a person, no mint, no mount, no worktree+ expect(t.proxy).toEqual([`spare ${s.id} after 0`]); // bound at the model proxy before its container is made, and kept+ expect(t.ups).toEqual([{ rs: { id: s.id, socket: path.join(t.runRoot(s.id), 'runners', `${s.id}.sock`), version: 'v9' }, record: undefined, mount: undefined }]);+ expect(t.records.all()).toEqual([]);+ expect(s).toMatchObject({ sock, run: t.runRoot(s.id), createMs: 11, startMs: 33 });+ expect(t.ids()).toEqual([s.id]);+ expect(t.has(s.id)).toBe(true); // the sweep leaves it alone+ expect(t.tm.dropped).toEqual({});+ });++ it.each(['create', 'up'] as const)('that fails at %s leaves no container and no run directory', async (at) => {+ const t = rig({ fail: { [at]: new Error('boom') } });+ await expect(t.launch()).rejects.toThrow('boom');+ const id = /^create (\w+)/.exec(t.log[0])![1];+ expect(t.log.slice(-2)).toEqual([`remove ${id}`, `deleteRun ${id}`]);+ expect(existsSync(t.runRoot(id))).toBe(false);+ expect(t.ids()).toEqual([]);+ expect(t.proxy).toEqual([`spare ${id} after 0`, `closed '' ${id}`]); // released at the model proxy+ });++ it('the model proxy did not bind is not made', async () => {+ const t = rig({ unbound: true });+ await expect(t.launch()).rejects.toThrow('not bound');+ expect(t.log.some((l) => /^(create|up) /.test(l))).toBe(false);+ expect(t.proxy).toHaveLength(1); // model-access.ts `spare` released it itself+ expect(t.ids()).toEqual([]);+ });++ it('whose runner never listens is removed, and its token socket closed', async () => {+ const t = rig({ dial: async () => undefined });+ // pollReady's 30 s: the test only needs the order of what follows it.+ vi.useFakeTimers();+ const p = t.launch().catch((e) => e);+ await vi.advanceTimersByTimeAsync(31_000);+ vi.useRealTimers();+ expect(String(await p)).toMatch(/did not start within 30 s/);+ expect(t.log.filter((l) => /tokens closed|^remove/.test(l))).toEqual(['tokens closed', expect.stringMatching(/^remove /)]);+ });++ it('is bound to one thread: the record under its id, then the mounts with the journal, then the worktrees', async () => {+ const t = rig({ api: true });+ const { id } = await t.launch();+ t.log.length = 0;+ const b = await t.bind(id, spec, {});+ expect(t.log).toEqual([+ 'dirs C1:1.1 hello',+ `mint ${id} RUN/${id} sdk=- fork=-`, // a new thread: no transcript, no host path+ `pid ${id}`,+ `mount ${id} 7 pat /workspace /clones/hello /data/journals/s1`,+ `prepare ${id} hello`,+ ]);+ // Until its claim is answered the record says so: whatever is found under this id is not known to be the thread's runner.+ expect(t.records.find('pat', 'C1:1.1')).toMatchObject({ id, person: 'pat', key: 'C1:1.1', repos: { hello: {} }, unclaimed: true });+ expect(b.record.unclaimed).toBe(true);+ expect(t.claimed(id)).not.toHaveProperty('unclaimed');+ expect(t.records.get(id)).not.toHaveProperty('unclaimed');+ expect(t.records.get(id)).toMatchObject({ id, key: 'C1:1.1', repos: { hello: {} } });+ expect(b).toMatchObject({ record: { id, key: 'C1:1.1' }, run: t.runRoot(id), api: { token: 'tok' }, addMs: 7 });+ expect(b.session).not.toHaveProperty('sdkSessionId');+ expect(b.session).not.toHaveProperty('forkPath');+ expect(t.ids()).toEqual([]);+ // Bound once: not to a second thread. And its thread is known from now on: it takes no second spare (start-runner.ts asks).+ await expect(t.bind(id, { ...spec, key: 'C1:2.2' }, {})).rejects.toThrow(/not a spare/);+ expect(t.known(spec)).toBe(true);+ expect(t.known({ ...spec, key: 'C1:2.2' })).toBe(false);+ expect(t.records.all().map((r) => r.id)).toEqual([id]);+ });++ it('is made a thread\'s in the thread\'s turn, the one a start and a prune take: it waits for whoever has it', async () => {+ const t = rig();+ const { id } = await t.launch();+ t.log.length = 0;+ let end!: () => void;+ const prune = t.locks.run('pat', 'C1:1.1', () => new Promise<void>((r) => (end = r)));+ const claim = t.turn(spec, () => t.bind(id, spec, {}));+ await tick();+ expect(t.log).toEqual([]);+ expect(t.records.all()).toEqual([]);+ end();+ await prune;+ expect((await claim).record.id).toBe(id);+ });++ it('the record is written before anything of the person is mounted', async () => {+ const t = rig({ fail: { mount: new Error('mount refused') } });+ const { id } = await t.launch();+ await expect(t.bind(id, spec, {})).rejects.toThrow('mount refused');+ expect(t.records.get(id)).toMatchObject({ key: 'C1:1.1' });+ expect(t.records.get(id)).not.toHaveProperty('repos');+ });++ it('that could not be bound is removed, and its record and run directory stay for the cold start under the same id', async () => {+ const t = rig({ fail: { prepare: new Error('no worktree') } });+ const { id } = await t.launch();+ await expect(t.bind(id, spec, {})).rejects.toThrow('no worktree');+ t.log.length = 0;+ await t.discard(id);+ expect(t.log).toEqual([`stop ${id} 0`, `remove ${id}`]);+ expect(t.records.find('pat', 'C1:1.1')?.id).toBe(id);+ expect(t.records.get(id)).not.toHaveProperty('unclaimed'); // nothing half-bound is left under the id+ expect(existsSync(t.runRoot(id))).toBe(true);+ });++ it('that could not be removed was stopped with no grace before: nothing of a half-bound spare keeps running, and its record says it was never claimed', async () => {+ const t = rig({ fail: { prepare: new Error('no worktree') }, stays: true });+ const { id } = await t.launch();+ await expect(t.bind(id, spec, {})).rejects.toThrow('no worktree');+ t.log.length = 0;+ await t.discard(id);+ expect(t.log).toEqual([`stop ${id} 0`, `remove ${id}`]);+ expect(t.records.get(id)).toMatchObject({ key: 'C1:1.1', unclaimed: true });+ });++ it('whose connection closed is removed with its run directory; a bound one is its thread\'s and stays', async () => {+ const t = rig();+ const a = await t.launch();+ const b = await t.launch();+ await t.bind(b.id, spec, {});+ t.log.length = 0;+ await Promise.all([t.gone(a.id), t.gone(a.id), t.gone(b.id)]);+ // By container, with no grace: a spare is never waited for, whether or not it heard an `exit`.+ expect(t.log).toEqual([`stop ${a.id} 0`, `remove ${a.id}`, `deleteRun ${a.id}`]); // once+ expect(existsSync(t.runRoot(a.id))).toBe(false);+ expect(existsSync(t.runRoot(b.id))).toBe(true);+ });++ it('the host stops: every spare is stopped and removed by container, the one being made too, and none is made after', async () => {+ let up!: () => void;+ const t = rig({ dial: () => new Promise((r) => (up = () => r(sock))) });+ const a = t.launch();+ await vi.waitFor(() => expect(up).toBeDefined());+ up();+ const { id } = await a;+ const b = t.launch(); // in flight when the host stops+ await vi.waitFor(() => expect(t.ids().length).toBe(2));+ const other = t.ids().find((x) => x !== id)!;+ t.log.length = 0;+ const closed = t.close();+ up();+ await expect(b).rejects.toThrow('the host is stopping');+ await closed;+ expect(t.log.filter((l) => l.startsWith('remove')).sort()).toEqual([`remove ${id}`, `remove ${other}`].sort());+ expect(t.log.filter((l) => l.startsWith('stop')).sort()).toEqual([`stop ${id} 0`, `stop ${other} 0`].sort());+ expect(t.ids()).toEqual([]);+ await expect(t.launch()).rejects.toThrow('the host is stopping');+ expect(t.log.filter((l) => l.startsWith('create'))).toEqual([]);+ });++ it('is not made while a thread starts, and one at a time', async () => {+ const t = rig();+ let done!: () => void;+ const start = t.during(() => new Promise<void>((r) => (done = r)));+ const first = t.launch();+ const second = t.launch();+ await tick();+ expect(t.log).toEqual([]);+ done();+ await start;+ const [a, b] = await Promise.all([first, second]);+ expect(t.log).toEqual([`create ${a.id}`, `up ${a.id}`, `create ${b.id}`, `up ${b.id}`]);+ });++ it('while the pool has a spare, is not made until a while after the last thread start ended', async () => {+ const t = rig({ settleMs: 60 });+ await t.launch();+ t.log.length = 0;+ await t.during(async () => {});+ const second = t.launch();+ await tick();+ await t.during(async () => {}); // another thread: the wait starts again+ await new Promise((r) => setTimeout(r, 40));+ expect(t.log).toEqual([]);+ await second;+ expect(t.log).toHaveLength(2);+ });++ it('when the pool is empty, is made as soon as no thread starts: the next thread would start cold', async () => {+ const t = rig({ settleMs: 60_000 });+ let done!: () => void;+ const start = t.during(() => new Promise<void>((r) => (done = r)));+ const first = t.launch();+ await tick();+ expect(t.log).toEqual([]);+ done();+ await start;+ await first; // not 60 s later+ expect(t.log).toHaveLength(2);+ });++ it('the pool empties while a refill waits for the settle: the wait ends with the start that took the last spare', async () => {+ const t = rig({ settleMs: 60_000 });+ const { id } = await t.launch();+ await t.during(async () => {});+ const second = t.launch(); // waits: the pool has a spare+ await tick();+ t.log.length = 0;+ await t.during(() => t.bind(id, spec, {}));+ const s = await second;+ expect(t.log.slice(-2)).toEqual([`create ${s.id}`, `up ${s.id}`]);+ });++ it('under a steady stream of thread starts it is made all the same, once it has waited long enough', async () => {+ for (const spares of [0, 1]) {+ const t = rig({ settleMs: 60_000, deferMs: 50 });+ if (spares) await t.launch();+ t.log.length = 0;+ // Starts that overlap, so that one is in flight for as long as the test runs.+ let more = true;+ const stream = (async () => {+ const all: Promise<unknown>[] = [];+ while (more) all.push(t.during(() => new Promise((r) => setTimeout(r, 12)))), await tick();+ await Promise.all(all);+ })();+ await tick();+ const t0 = Date.now();+ const s = await t.launch();+ more = false;+ expect(Date.now() - t0).toBeGreaterThanOrEqual(45);+ expect(Date.now() - t0).toBeLessThan(1000);+ expect(t.log).toEqual([`create ${s.id}`, `up ${s.id}`]);+ await stream;+ }+ });++ it('waits for the image lock before the first call of a Create', async () => {+ let settle!: () => void;+ const settled = new Promise<void>((r) => (settle = r));+ const calls: string[] = [];+ const exec: Exec = (_cmd, args, _o, done) => {+ calls.push(args.slice(args.indexOf('/usr/bin/podman') + 1, args.indexOf('/usr/bin/podman') + 2).join(' '));+ queueMicrotask(() => done(Object.assign(new Error('no podman here'), { code: 125 }), '', 'no podman here'));+ return {};+ };+ const as = asRunner(['sudo'], exec, () => settled);+ const runs = mkdtempSync(path.join(tmpdir(), 'run-'));+ const all = containers({ as, runRoot: (id) => path.join(runs, id), dataDir: '/data', root: '/root', image: 'i:1', abi: '1', start: async () => {}, vars: () => ({}), definition: () => undefined,+ serveTokens: () => ({ close() {} }), modelSocket: '/run/oc-modelproxy/api.sock' });+ const t = rig();+ const spares = sandboxSpares({ tm: t.tm, records: t.records, locks: t.locks, deleteRun: async () => true, containers: all, runRoot: (id) => path.join(runs, id), version: 'v', mint: async () => undefined, workspace: {} as SpareDeps['workspace'],+ models: { spare: async () => {}, closed: () => {} } });+ const p = spares.launch().catch((e) => e);+ await tick();+ expect(calls).toEqual([]); // provisioning holds the storage: nothing ran+ settle();+ expect(String(await p)).toMatch(/no podman here/);+ expect(calls[0]).toBe('volume'); // the home, the first call of a Create+ });+});diff --git a/computer/src/host/sandbox/spares.ts b/computer/src/host/sandbox/spares.tsnew file mode 100644index 00000000..7f8c300a--- /dev/null+++ b/computer/src/host/sandbox/spares.ts@@ -0,0 +1,317 @@+// Spares on a `podman` host (work 103, step 10): containers made ahead of+// time, each with a runner that parks a Claude Code, so a new thread's first+// message skips Create, Start and the harness's start. `launch` tops the pool+// up (pool.ts decides when), `bind` makes a taken spare one thread's (the+// claim's "fork" step, claim.ts), `gone` and `discard` are "a spare leaves".+//+// Invariants:+// - A spare holds nothing of anyone until it is bound: no record, no mount+// besides those of Create (its own empty home and run directory, the model+// proxy's API socket, the releases read-only), a boot spec with no+// session and no API, no journal, and a token socket that answers nobody+// (host.ts: a container with no record has no session to ask for).+// - A spare is bound at the model proxy under its id before its container is+// created (work 097, model-access.ts `spare`), as a spare outside a+// container is before its launch: the proxy names it by its unit, which has+// the id. One that was not bound is not made; one that did not come up is+// released there (`closed`). Once adopted, its closing releases it+// (host/main.ts), and its claim binds it to the thread (start-runner.ts).+// - Bound once, to one thread: `bind` takes the id out of the spares before+// it writes the record. A thread that has a record never takes a spare (a+// record hit resumes): the caller asks `known` in the thread's turn, before+// it takes one from the pool, and binds with no step in between.+// - A spare is made a thread's in that thread's turn (thread-lock.ts,+// `turn`), the one a start and a prune take, from before the record is+// looked for until the spare is claimed or discarded: nothing removes the+// thread's things under a bind, and the cold start after a failed claim+// takes the turn after it.+// - The record is written before anything of the person is mounted, so a+// container that holds a person's files always has a record saying whose.+// - The journal directory is among the mounts, so the API is minted before+// them: the runner opens its journal when it is claimed.+// - A spare that leaves is Removed, container and home, and its run directory+// goes with it; one whose record was written keeps the record and the run+// directory, and the thread's next start creates a container under the same+// id (start.ts, the resume).+// - A spare leaves by container, never by its own doing: it is stopped with+// no grace, then Removed, whether or not it was told to `exit` and whatever+// it did about it. That holds for one the pool evicts, one whose claim+// failed, one whose connection closed, and every spare when the host stops+// (`close`), the one being made included; after `close` none is made. One+// that could not be Removed is therefore not running.+// - The record `bind` writes says `unclaimed` until the claim was answered+// (`claimed`) or the spare was Removed. A container whose record says so is half-bound: it has the+// thread's files mounted and a runner that may or may not have taken the+// claim. It is never used: the thread's next start removes it and its home+// and creates anew (start.ts), a host restart stops it (sweep.ts).+// - Every Podman call here is made by containers.ts, mounts.ts or scripts.ts,+// each of which waits for the image lock (podman.ts lists how): no spare is+// created or started while provisioning holds it. None of what makes or+// binds a spare is `repeatable` there: a Create, the mount helper or the+// worktrees' exec that ran out of time behind the lock fails, and the spare+// is discarded.+// - Topping up does not compete with a delivery it can wait for: one spare is+// made at a time, none while a thread's start is in flight (`during`), and,+// while the pool still has a spare, none until SETTLE_MS after the last one+// ended, so that new threads coming one after the other take the spares+// there are with nothing made beside them. With no spare left there is+// nothing to protect: the next new thread starts cold, so the spare is made+// as soon as no start is in flight. A spare already being made when a+// delivery arrives is not held.+// - Topping up is not starved by deliveries: a spare that has waited DEFER_MS+// for its moment is made beside whatever is starting.+// - A spare is this host's by the run directory Create mounts into it, below+// this host's SP_RUN, like any container (containers.ts `inventory`). It is+// never adopted by a later host (C14): the host's start removes every+// container of its own that has no record, and the sweep removes one older+// than its age that has no record and no connected runner (sweep.ts).++import type net from 'node:net';+import path from 'node:path';+import { randomBytes } from 'node:crypto';+import type { RunnerSpec, SessionSpec } from '../../protocol.js';+import type { RunnerApi } from '../../protocol-api.js';+import { type RunRoot, socketFor } from '../../ipc.js';+import { log } from '../../log.js';+import type { Telemetry } from '../../telemetry/emitter.js';+import type { Dimensions } from '../../telemetry/envelope.js';+import { awaitRunner, dialSocket } from '../runner-sockets.js';+import type { Containers } from './containers.js';+import type { Records, SandboxRecord } from './records.js';+import type { ThreadLocks } from './thread-lock.js';+import type { SandboxWorkspace } from './workspace.js';++export interface SpareDeps {+ tm: Telemetry;+ records: Records;+ /** The threads' turns, shared with the starts and prune. */+ locks: ThreadLocks;+ containers: Pick<Containers, 'create' | 'up' | 'pid' | 'stop' | 'remove' | 'diagnose'>;+ /** Delete a run directory (sweep.ts); never rejects. */+ deleteRun(id: string): Promise<unknown>;+ runRoot(id: string): RunRoot;+ /** The model proxy's binding of a spare (model-access.ts): `spare` before it is made, rejecting when it was not bound; `closed` when it did not come up. */+ models: { spare(id: string): Promise<void>; closed(key: string, id: string): void };+ version: string;+ /** The session's journal, socket (below `run`) and token for this runner; undefined off the API. */+ mint(spec: SessionSpec, runnerId: string, run: RunRoot): Promise<RunnerApi | undefined>;+ workspace: Pick<SandboxWorkspace, 'repos' | 'dirs' | 'binds' | 'mount' | 'prepare'>;+ /** Connect to a runner's socket; undefined when nothing answers. */+ dial?: (socket: string) => Promise<net.Socket | undefined>;+ /** How long after a thread's start no spare is made while the pool has one; SETTLE_MS unless given. */+ settleMs?: number;+ /** How long a spare waits for its moment at most; DEFER_MS unless given. */+ deferMs?: number;+}++/** A spare that listens, not yet adopted. */+export interface Spare {+ id: string;+ run: RunRoot;+ sock: net.Socket;+ createMs: number;+ startMs: number;+}++/** A spare made one thread's: what the claim sends and the host keeps. */+export interface Bound {+ record: SandboxRecord;+ run: RunRoot;+ /** The session as the runner gets it: a new thread has no transcript. */+ session: SessionSpec;+ /** With its token, for the `claim` frame. */+ api?: RunnerApi;+ /** The record, the directories and the API's mint; the mounts (with the container's pid); the worktrees and root files. */+ readyMs: number;+ mountMs: number;+ addMs: number;+}++export type SandboxSpares = ReturnType<typeof sandboxSpares>;++/** Measured on 2 vCPU: a spare made beside a new thread's claim takes it from 0.6 s to 1.1 s; a claim ends within 1 s. */+export const SETTLE_MS = 2000;+/** Starts that keep coming for this long get a spare made beside them: five claims' worth of waiting, and less than a cold start's delay on the thread after the pool ran out. */+export const DEFER_MS = 10_000;++const fail = (why: string): never => {+ throw new Error(why);+};++export function sandboxSpares(d: SpareDeps) {+ const { tm, containers: c } = d;+ const dial = d.dial ?? dialSocket;+ /** The spares of this host that serve no thread: made here, not yet bound, not yet gone. */+ const mine = new Set<string>();+ const leaving = new Map<string, Promise<void>>();+ const settleMs = d.settleMs ?? SETTLE_MS;+ const deferMs = d.deferMs ?? DEFER_MS;+ let starts = 0;+ let lastStart = 0;+ const waiting: (() => void)[] = [];+ let queue: Promise<unknown> = Promise.resolve();+ /** The spare being made, if any; and whether the host is stopping. */+ let making: string | undefined;+ let closed = false;+ const open = () => {+ if (closed) throw new Error('the host is stopping');+ };++ /** A thread's start: no spare is made while one is in flight. */+ async function during<T>(fn: () => Promise<T>): Promise<T> {+ starts++;+ try {+ return await fn();+ } finally {+ lastStart = Date.now();+ if (!--starts) wake();+ }+ }+ /** Whoever waits for a moment to make a spare looks again: the last start ended, the pool changed, the host stops. */+ const wake = () => {+ for (const go of waiting.splice(0)) go();+ };+ /** Resolves when a spare may be made: no start in flight and, unless the pool is empty, settled; or DEFER_MS after it was asked. */+ const quiet = async () => {+ const latest = Date.now() + deferMs;+ for (;;) {+ const now = Date.now();+ if (closed || now >= latest) return;+ const settle = starts || !mine.size ? 0 : lastStart + settleMs - now;+ if (!starts && settle <= 0) return;+ let timer: NodeJS.Timeout | undefined;+ await new Promise<void>((r) => {+ waiting.push(r);+ timer = setTimeout(r, Math.min(latest - now, settle || latest - now));+ });+ clearTimeout(timer);+ }+ };++ /** Stop with no grace, Remove (container and home); the run directory too unless a record says the id is a thread's. Once per id at a time; never rejects. */+ function drop(id: string): Promise<void> {+ mine.delete(id);+ let p = leaving.get(id);+ if (!p) {+ p = (async () => {+ // Stopped first: what Podman then would not remove does not keep running; the sweep removes it later, or the thread's next start (start.ts).+ await c.stop(id, 0).catch((e) => log.warn(`spare ${id} not stopped: ${e?.message ?? e}`));+ if (await c.remove(id)) d.records.get(id)?.unclaimed && claimed(id); // nothing half-bound is left under the id+ if (!d.records.get(id)) await d.deleteRun(id);+ })().finally(() => leaving.delete(id));+ leaving.set(id, p);+ }+ return p;+ }++ /** The claim of the spare bound under `id` was answered, or the spare is gone: its record is a thread's like any other. Returns the record. */+ function claimed(id: string): SandboxRecord {+ const { unclaimed: _, ...record } = d.records.get(id) ?? fail(`${id} has no record`);+ d.records.write(record);+ return record;+ }++ async function one(): Promise<Spare> {+ await quiet();+ open();+ const id = randomBytes(8).toString('hex');+ const run = d.runRoot(id);+ mine.add(id);+ making = id;+ let bound = false;+ try {+ await d.models.spare(id);+ bound = true;+ const createMs = await c.create(id);+ open();+ // No session and no API: the runner parks, and knows nobody.+ const rs: RunnerSpec = { id, socket: socketFor(run, id), version: d.version };+ const t0 = Date.now();+ const up = await c.up(id, rs);+ try {+ open();+ const sock = await awaitRunner(rs, {+ tm, t0,+ dial: () => dial(rs.socket),+ late: async () => log.warn(`spare ${id} never listened:\n${(await c.diagnose(id)).slice(-4000)}`),+ });+ if (closed) sock.destroy();+ open();+ return { id, run, sock, createMs, startMs: up.startMs };+ } catch (e) {+ up.tokens.close();+ throw e;+ }+ } catch (e) {+ if (bound) d.models.closed('', id); // never adopted: no closing connection releases it+ await drop(id);+ throw e;+ } finally {+ making = undefined;+ }+ }++ /** Top the pool up by one: Create, bring up with no thread, wait for its runner. One at a time; a failure leaves nothing. */+ function launch(): Promise<Spare> {+ const p = queue.then(one);+ queue = p.catch(() => {});+ return p;+ }++ /**+ * Make the spare `id` the container of `spec`'s thread: the record under the spare's id, the directories, the mounts into the+ * running container, the worktrees. After this the runner can be claimed into `/workspace`. A rejection leaves the record (if+ * it was written); the caller discards the spare and starts the thread cold, which resumes under the same id.+ */+ async function bind(id: string, spec: SessionSpec, f: Dimensions): Promise<Bound> {+ if (!mine.delete(id)) throw new Error(`${id} is not a spare of this host`);+ wake(); // the pool has one fewer: a refill that waited for the settle may not have to+ const { sdkSessionId: _transcript, forkPath: _fork, ...session } = spec; // a new home has no transcript; the runner's fork is /workspace+ const now = new Date().toISOString();+ const record: SandboxRecord = { id, person: spec.owner.dir, key: spec.key, createdAt: now, usedAt: now, unclaimed: true };+ const t00 = Date.now();+ d.records.write(record);+ const run = d.runRoot(id);+ const names = d.workspace.repos(record);+ await d.workspace.dirs(record, names);+ const api = await d.mint(session, id, run);+ const t0 = Date.now();+ const readyMs = t0 - t00;+ await d.workspace.mount(id, await c.pid(id), record.person, d.workspace.binds(record, names, api && path.dirname(api.journal)));+ const mountMs = Date.now() - t0;+ const done = tm.start('fork.done', f);+ try {+ const p = await d.workspace.prepare(id, names);+ done.end({ outcome: 'completed', data: { repos: Object.keys(p.record.repos ?? {}).length } });+ return { record: p.record, run, session, api, readyMs, mountMs, addMs: p.addMs };+ } catch (e) {+ done.end({ outcome: 'failed', error_type: 'git_worktree', data: { fork_error_type: 'git_worktree' } });+ throw e;+ }+ }++ return {+ launch,+ bind,+ claimed,+ /** The host stops: every spare leaves, the one being made once its step in flight ended, and none is made after. Never rejects. */+ async close(): Promise<void> {+ closed = true;+ wake();+ await Promise.all([queue, ...[...mine].filter((id) => id !== making).map(drop), ...leaving.values()]);+ },+ during,+ /** `fn` in the thread's turn: a claim, from the look for its record to the spare claimed or discarded. */+ turn: <T>(spec: SessionSpec, fn: () => Promise<T>): Promise<T> => d.locks.run(spec.owner.dir, spec.key, fn),+ /** True when the thread has a record: it resumes, and never takes a spare. */+ known: (spec: SessionSpec) => !!d.records.find(spec.owner.dir, spec.key),+ /** A spare's connection closed (it exited, was evicted, the host told it to go): Remove. Nothing for a container that is a thread's. */+ gone: (id: string): Promise<void> => (mine.has(id) || leaving.has(id) ? drop(id) : Promise.resolve()),+ /** A spare that was taken and not claimed: Remove; its record, if written, stays. */+ discard: drop,+ /** True from before a spare's Create until it is a thread's or gone: the sweep leaves it alone (host.ts). */+ has: (id: string) => mine.has(id) || leaving.has(id),+ /** The ids of the spares that serve no thread. */+ ids: () => [...mine],+ };+}diff --git a/computer/src/host/sandbox/start.test.ts b/computer/src/host/sandbox/start.test.tsnew file mode 100644index 00000000..193130f2--- /dev/null+++ b/computer/src/host/sandbox/start.test.ts@@ -0,0 +1,298 @@+import type net from 'node:net';+import { mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { log as hostLog } from '../../log.js';+import type { RunnerSpec, SessionSpec } from '../../protocol.js';+import type { RunnerApi } from '../../protocol-api.js';+import { createTelemetry } from '../../telemetry/emitter.js';+import type { TelemetryEvent } from '../../telemetry/envelope.js';+import type { ContainerInfo } from './containers.js';+import { sandboxRecords } from './records.js';+import { type SandboxStartDeps, imageTag, sandboxStarts } from './start.js';+import { threadLocks } from './thread-lock.js';++const IMAGE = 'ghcr.io/diggerhq/computer-session:64a672bb773b059c82f67c9f52741a0540ca1d1c';+const owner = { dir: 'pat', gitName: 'Pat', gitEmail: '[email protected]' };+const spec: SessionSpec = { key: 'C1:1.1', kind: 'thread', owner, title: 't', mode: 'default' };+const sock = { destroyed: false } as net.Socket;++function rig(o: { have?: ContainerInfo[]; homes?: string[]; fail?: Partial<Record<'create' | 'up' | 'inventory' | 'mount' | 'prepare', Error>>; stale?: boolean;+ dial?: () => Promise<net.Socket | undefined>; definition?: boolean; clones?: string[]; api?: boolean; unread?: string; there?: boolean; stays?: boolean } = {}) {+ const log: string[] = [];+ const ups: RunnerSpec[] = [];+ const sent: TelemetryEvent[] = [];+ const tm = createTelemetry({ service: 'host', version: 'v', region: 'r', send: (b) => void sent.push(...b.events) });+ const dir = mkdtempSync(path.join(tmpdir(), 'records-'));+ if (o.unread) writeFileSync(path.join(dir, `${o.unread}.json`), '{"id":');+ const records = sandboxRecords(dir);+ const locks = threadLocks();+ const step = async <T>(name: string, v: T): Promise<T> => {+ log.push(name);+ const e = o.fail?.[name.split(' ')[0] as 'create'];+ if (e) throw e;+ return v;+ };+ const d: SandboxStartDeps = {+ tm, records, locks, image: IMAGE, abi: '2', version: 'v9',+ runRoot: (id) => `/run/sp/sandbox/${id}`,+ containers: {+ create: (id) => step(`create ${id}`, 11),+ recreate: (id) => step(`recreate ${id}`, 22),+ up: async (id, rs, record, mount) => {+ ups.push(rs);+ const up = await step(`up ${id} ${record?.key}`, { pid: 5, startMs: 33, tokens: { close: () => void log.push('tokens closed') } });+ await mount?.(5);+ return { ...up, mountMs: 4 };+ },+ stop: (id) => step(`stop ${id}`, undefined),+ remove: (id) => step(`remove ${id}`, !o.stays),+ inventory: () => step('inventory', { containers: o.have ?? [], volumes: (o.homes ?? []).map((id) => ({ id, createdAt: 0 })), foreign: [] }),+ stale: async () => !!o.stale,+ unitActive: async () => true,+ diagnose: async () => 'Active: inactive (dead)\n--- podman logs\nboom',+ },+ mint: async (s, id, run) => (log.push(`mint ${id} ${run} sdk=${s.sdkSessionId ?? '-'}`), o.api ? ({ journal: '/data/journals/s1/journal.jsonl' } as RunnerApi) : undefined),+ workspaces: () => !!o.definition,+ workspace: {+ repos: (r) => (r.repos ? Object.keys(r.repos) : (o.clones ?? [])),+ there: () => !!o.there,+ dirs: async (r, names) => void log.push(`dirs ${r.key} ${names.join(',')}`),+ binds: (r, names, journal) => [{ src: `ws:${r.key}`, dst: '/workspace' }, ...names.map((n) => ({ src: n, dst: `/clones/${n}` })), ...(journal ? [{ src: journal, dst: journal }] : [])],+ mount: (id, pid, person, b) => step(`mount ${id} ${pid} ${person} ${b.map((x) => x.dst).join(' ')}`, undefined),+ prepare: async (id, names) => {+ await step(`prepare ${id} ${names.join(',')}`, undefined);+ const record = { ...records.get(id)!, repos: Object.fromEntries(names.map((n) => [n, { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc' }])) };+ records.write(record);+ return { record, addMs: 7 };+ },+ },+ dial: o.dial ?? (async () => sock),+ };+ const events = async () => (await tm.flush(), sent);+ return { ...sandboxStarts(d), log, ups, records, locks, events, tm };+}+const container = (id: string, over: Partial<ContainerInfo> = {}): ContainerInfo => ({ id, state: 'exited', abi: '2', image: IMAGE, createdAt: 0, ...over });++afterEach(() => vi.useRealTimers());++describe('sandbox start', () => {+ it('a new thread: record, workspace, Create, up; no transcript and no host path go in', async () => {+ const t = rig();+ const s = await t.start({ ...spec, sdkSessionId: 'old', forkPath: '/data/people/pat/sessions/C1-1.1' }, {});+ const id = s.record.id;+ expect(id).toMatch(/^[0-9a-f]{16}$/);+ expect(t.records.find('pat', 'C1:1.1')).toMatchObject({ id, person: 'pat', key: 'C1:1.1' });+ expect(t.log).toEqual(['dirs C1:1.1 ', `mint ${id} /run/sp/sandbox/${id} sdk=-`, `create ${id}`, `up ${id} C1:1.1`, `mount ${id} 5 pat /workspace`]);+ expect(t.ups[0]).toMatchObject({ id, socket: `/run/sp/sandbox/${id}/runners/${id}.sock`, version: 'v9', session: { key: 'C1:1.1', forkPath: '/workspace' } });+ expect(t.ups[0].session).not.toHaveProperty('sdkSessionId');+ expect(s).toMatchObject({ sock, resumed: false, run: `/run/sp/sandbox/${id}` });+ expect(s.session.sdkSessionId).toBeUndefined();+ const ev = await t.events();+ expect(ev.find((e) => e.event_name === 'runner.launched')).toMatchObject({+ outcome: 'completed', data: { launch_mode: 'podman', image: '64a672bb773b', 'container.create_ms': 11, 'container.start_ms': 33, 'container.mount_ms': 4 },+ });+ expect(ev.some((e) => e.event_name === 'runner.ready')).toBe(true);+ expect(t.tm.dropped).toEqual({}); // every key is in the catalog+ });++ it("a thread with a record resumes under the record's id, with its transcript, on its container", async () => {+ const t = rig();+ const first = await t.start(spec, {});+ const id = first.record.id;+ const again = rig({ have: [container(id)], homes: [id] });+ again.records.write(first.record);+ const s = await again.start({ ...spec, sdkSessionId: 'sdk1' }, {});+ expect(s.record.id).toBe(id);+ expect(s.resumed).toBe(true);+ // The workspace directory is made again: the first start may have failed before it was.+ expect(again.log).toEqual(['dirs C1:1.1 ', 'inventory', `mint ${id} /run/sp/sandbox/${id} sdk=sdk1`, `up ${id} C1:1.1`, `mount ${id} 5 pat /workspace`]);+ expect(again.ups[0].session).toMatchObject({ sdkSessionId: 'sdk1', forkPath: '/workspace' });+ expect((await again.events()).find((e) => e.event_name === 'runner.launched')?.data).toMatchObject({ 'container.recreated': false });+ });++ it('a start waits for the thread\'s turn, and only then looks for its record: a thread pruned meanwhile starts as a new one and is prepared', async () => {+ const t = rig({ definition: true, clones: ['alpha'] });+ const old = { id: 'aaaaaaaaaaaaaaaa', person: 'pat', key: 'C1:1.1', createdAt: '', usedAt: '', repos: { alpha: { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc' } } };+ t.records.write(old);+ let pruned!: () => void;+ // What prune.ts does with the turn: everything of the thread goes, its record last.+ void t.locks.run('pat', 'C1:1.1', () => new Promise<void>((r) => (pruned = () => (t.records.delete(old.id), r()))));+ const starting = t.start(spec, {});+ await new Promise((r) => setTimeout(r, 20));+ expect(t.log).toEqual([]);+ expect(t.records.get(old.id)).toEqual(old); // not written by a start that has not begun+ pruned();+ const s = await starting;+ expect(s.record.id).not.toBe(old.id);+ expect(s.resumed).toBe(false);+ expect(t.log).toContain(`create ${s.record.id}`);+ expect(t.log).toContain(`prepare ${s.record.id} alpha`);+ });++ const resume = async (o: Parameters<typeof rig>[0], id = 'aaaaaaaaaaaaaaaa', sent: Partial<SessionSpec> = {}) => {+ const t = rig(o);+ t.records.write({ id, person: 'pat', key: 'C1:1.1', createdAt: 'then', usedAt: 'then' });+ const s = await t.start({ ...spec, ...sent }, {});+ return { t, s, id };+ };++ it('a thread with files but no record, while a record file did not load, is not started: nothing is made over what may be its', async () => {+ const t = rig({ unread: 'abababababababab', there: true });+ await expect(t.start(spec, {})).rejects.toThrow("this thread has files but no sandbox record, and the record abababababababab.json did not load; nothing was started. Repair that file in the host's state/sandboxes, or remove it for a new sandbox");+ expect(t.log).toEqual([]);+ expect(t.records.all()).toEqual([]);+ // A thread with no files is new whatever did not load, and so is every thread once all records load.+ expect((await rig({ unread: 'abababababababab' }).start(spec, {})).resumed).toBe(false);+ expect((await rig({ there: true }).start(spec, {})).resumed).toBe(false);+ });++ it('a record whose spare was never claimed: its container and home are removed and made again, never used, whatever state they are in', async () => {+ const id = 'aaaaaaaaaaaaaaaa';+ const record = { id, person: 'pat', key: 'C1:1.1', createdAt: 'then', usedAt: 'then', repos: {}, unclaimed: true as const };+ // The Remove after the failed claim did not go through: the container is there, of this ABI, not stale, its home too.+ const t = rig({ have: [container(id, { state: 'running' })], homes: [id] });+ t.records.write(record);+ const s = await t.start({ ...spec, sdkSessionId: 'sdk1' }, {});+ expect(t.log).toEqual(['dirs C1:1.1 ', `mint ${id} /run/sp/sandbox/${id} sdk=-`, `remove ${id}`, `create ${id}`, `up ${id} C1:1.1`, `mount ${id} 5 pat /workspace`]);+ expect(s.session.sdkSessionId).toBeUndefined(); // a new home has no transcript+ expect(s.record).not.toHaveProperty('unclaimed');+ expect(t.records.get(id)).not.toHaveProperty('unclaimed');+ expect((await t.events()).find((e) => e.event_name === 'runner.launched')).toMatchObject({ data: { 'container.recreated': true, 'container.create_ms': 11 } });+ expect(t.tm.dropped).toEqual({});++ const stuck = rig({ have: [container(id)], homes: [id], stays: true });+ stuck.records.write(record);+ await expect(stuck.start(spec, {})).rejects.toThrow(`the spare this thread took was not claimed and could not be removed (sp-runner-${id}); nothing was started`);+ expect(stuck.log.filter((l) => /^(create|up|recreate)/.test(l))).toEqual([]);+ expect(stuck.records.get(id)).toMatchObject({ unclaimed: true });+ });++ it('a resume keeps the transcript only when the home was there before this start', async () => {+ const id = 'aaaaaaaaaaaaaaaa';+ // A record alone: the first start's Create failed (and took the home with it), or the volume was removed.+ for (const o of [{ have: [] }, { have: [container(id)] }]) {+ const { t, s } = await resume(o, id, { sdkSessionId: 'sdk1', forkPath: '/data/people/pat/sessions/C1-1.1' });+ expect(t.log).toContain(`mint ${id} /run/sp/sandbox/${id} sdk=-`);+ expect(t.ups[0].session).not.toHaveProperty('sdkSessionId');+ expect(s.session.sdkSessionId).toBeUndefined();+ expect(t.ups[0].session?.forkPath).toBe('/workspace');+ }+ // The home is there and the container is not (an ABI change, a removed container): the transcript is in the home.+ const kept = await resume({ have: [], homes: [id] }, id, { sdkSessionId: 'sdk1' });+ expect(kept.t.ups[0].session).toMatchObject({ sdkSessionId: 'sdk1' });+ // The gateway sent none: none goes in.+ const none = await resume({ have: [container(id)], homes: [id] }, id);+ expect(none.t.ups[0].session).not.toHaveProperty('sdkSessionId');+ });++ it('a resume recreates the container when there is none, when its ABI differs, and when it is stale', async () => {+ for (const have of [[], [container('aaaaaaaaaaaaaaaa', { abi: '1' })], [container('aaaaaaaaaaaaaaaa', { state: 'running' })]]) {+ const { t, id } = await resume({ have, stale: have[0]?.state === 'running' });+ expect(t.log.filter((l) => !/^(mint|dirs|mount)/.test(l))).toEqual(['inventory', `recreate ${id}`, `up ${id} C1:1.1`]);+ expect((await t.events()).find((e) => e.event_name === 'runner.launched')?.data).toMatchObject({ 'container.recreated': true, 'container.create_ms': 22 });+ }+ });++ it('a resume stops a container that runs with nobody connected, then starts it', async () => {+ const { t, id } = await resume({ have: [container('aaaaaaaaaaaaaaaa', { state: 'running' })] });+ expect(t.log.filter((l) => !/^(mint|dirs|mount)/.test(l))).toEqual(['inventory', `stop ${id}`, `up ${id} C1:1.1`]);+ });++ it('a resume marks the record used and keeps what else it says', async () => {+ const { t, id } = await resume({ have: [container('aaaaaaaaaaaaaaaa')] });+ const r = t.records.get(id)!;+ expect(r.createdAt).toBe('then');+ expect(r.usedAt).not.toBe('then');+ });++ it('a failed Create removes what it left and fails the start; the record stays', async () => {+ const t = rig({ fail: { create: new Error('create timed out') } });+ await expect(t.start(spec, {})).rejects.toThrow('create timed out');+ const id = t.records.find('pat', 'C1:1.1')!.id;+ expect(t.log.slice(-2)).toEqual([`create ${id}`, `remove ${id}`]);+ expect((await t.events()).find((e) => e.event_name === 'runner.launched')).toMatchObject({ outcome: 'failed', error_type: 'launch' });+ });++ it('a failed inventory or up fails the start (up cleans up after itself)', async () => {+ await expect(resume({ fail: { inventory: new Error('inventory timed out') } })).rejects.toThrow('inventory timed out');+ const t = rig({ fail: { up: new Error('no pid') } });+ await expect(t.start(spec, {})).rejects.toThrow('no pid');+ expect(t.log.some((l) => l.startsWith('stop'))).toBe(false);+ });++ it('a runner that never listens: the one-line error, the diagnosis in the host log only, the container stopped', async () => {+ vi.useFakeTimers();+ const warned: string[] = [];+ const warn = vi.spyOn(hostLog, 'warn').mockImplementation((...a: unknown[]) => void warned.push(a.join(' ')));+ const t = rig({ dial: async () => undefined });+ const p = t.start(spec, {}).catch((e) => e);+ await vi.advanceTimersByTimeAsync(31_000);+ const e = await p;+ warn.mockRestore();+ expect(e.message).toBe('runner did not start within 30 s');+ expect(warned.join('\n')).toContain('Active: inactive (dead)\n--- podman logs\nboom');+ expect(t.log.slice(-2)).toEqual([`stop ${t.records.find('pat', 'C1:1.1')!.id}`, 'tokens closed']);+ });++ it('what it started can be abandoned by whoever takes it on: the container stops and its token socket closes', async () => {+ const t = rig();+ const s = await t.start(spec, {});+ await s.abandon();+ expect(t.log.slice(-2)).toEqual([`stop ${s.record.id}`, 'tokens closed']);+ });++ it('a new thread under a definition: its clones and journal mounted, its workspace prepared while the runner boots, the record given its repos', async () => {+ const t = rig({ definition: true, clones: ['alpha', 'beta'], api: true });+ const s = await t.start(spec, { trace_id: 'a'.repeat(32) });+ const id = s.record.id;+ expect(t.log.slice(0, 1)).toEqual(['dirs C1:1.1 alpha,beta']);+ expect(t.log.slice(-2)).toEqual([`mount ${id} 5 pat /workspace /clones/alpha /clones/beta /data/journals/s1`, `prepare ${id} alpha,beta`]);+ expect(Object.keys(s.record.repos ?? {})).toEqual(['alpha', 'beta']);+ expect(t.records.get(id)?.repos).toEqual(s.record.repos);+ const ev = await t.events();+ expect(ev.filter((e) => e.event_name === 'runner.launched')).toHaveLength(1);+ expect(ev.find((e) => e.event_name === 'runner.launched')).toMatchObject({ outcome: 'completed', data: { 'container.mount_ms': 4, 'container.add_ms': 7 } });+ expect(ev.find((e) => e.event_name === 'fork.done')).toMatchObject({ outcome: 'completed', data: { repos: 2 } });+ expect(t.tm.dropped).toEqual({});+ });++ it('a thread whose record has repos is not prepared again, and mounts what its record names', async () => {+ const t = rig({ definition: true, clones: ['alpha', 'beta'], have: [container('aaaaaaaaaaaaaaaa')] });+ t.records.write({ id: 'aaaaaaaaaaaaaaaa', person: 'pat', key: 'C1:1.1', createdAt: 'then', usedAt: 'then', repos: { beta: { branch: 'b', from: 'origin/main', base: 'abc' } } });+ await t.start(spec, {});+ expect(t.log.some((l) => l.startsWith('prepare'))).toBe(false);+ expect(t.log.at(-1)).toBe('mount aaaaaaaaaaaaaaaa 5 pat /workspace /clones/beta');+ expect((await t.events()).some((e) => e.event_name === 'fork.done')).toBe(false);+ });++ it('a record without repos is prepared at its next start: the one before failed', async () => {+ const t = rig({ definition: true, clones: ['alpha'], have: [container('aaaaaaaaaaaaaaaa')] });+ t.records.write({ id: 'aaaaaaaaaaaaaaaa', person: 'pat', key: 'C1:1.1', createdAt: 'then', usedAt: 'then' });+ const s = await t.start(spec, {});+ expect(t.log.at(-1)).toBe('prepare aaaaaaaaaaaaaaaa alpha');+ expect(s.record.repos).toHaveProperty('alpha');+ });++ it('a workspace that could not be prepared fails the start: the container stops, the record keeps no repos', async () => {+ const t = rig({ definition: true, clones: ['alpha'], fail: { prepare: new Error('tar: cannot unpack') } });+ await expect(t.start(spec, {})).rejects.toThrow('tar: cannot unpack');+ const id = t.records.find('pat', 'C1:1.1')!.id;+ expect(t.log.slice(-2)).toEqual([`stop ${id}`, 'tokens closed']);+ expect(t.records.get(id)?.repos).toBeUndefined();+ const ev = await t.events();+ expect(ev.find((e) => e.event_name === 'fork.done')).toMatchObject({ outcome: 'failed', error_type: 'git_worktree' });+ expect(ev.find((e) => e.event_name === 'runner.launched')).toMatchObject({ outcome: 'completed' });+ });++ it('mounts that fail fail the launch', async () => {+ const t = rig({ fail: { mount: new Error('sandbox-mount: refused') } });+ await expect(t.start(spec, {})).rejects.toThrow('sandbox-mount: refused');+ expect((await t.events()).find((e) => e.event_name === 'runner.launched')).toMatchObject({ outcome: 'failed', error_type: 'launch' });+ });++ it('shortens the image to its tag', () => {+ expect(imageTag(IMAGE)).toBe('64a672bb773b');+ });+});diff --git a/computer/src/host/sandbox/start.ts b/computer/src/host/sandbox/start.tsnew file mode 100644index 00000000..56c30b63--- /dev/null+++ b/computer/src/host/sandbox/start.ts@@ -0,0 +1,225 @@+// Starting a thread's runner in its container (work 103, "Sequences"): the+// new thread and the resume, one orchestration (cold-start.ts) for both.+// start-runner.ts adopts what this returns and sends the frames, as it does+// for every other runner.+//+// Invariants:+// - A thread has a record before it has a container, and the record decides:+// a hit resumes under the record's id, a miss is a new thread, which starts+// with no transcript and no fork path whatever the gateway sent.+// - A start has its thread's turn (thread-lock.ts) from before it looks for+// the record until it is connected or failed: whatever removes a thread's+// things (prune.ts) waits for it, and a start that waited for a prune finds+// no record and starts a new thread, cold, with its workspace prepared.+// - A thread without a record that has files, while some record's file did+// not load (records.ts `unread`), may be that record's: it is not started,+// and the error names the files. A new sandbox over it would prepare a+// workspace that has work in it and leave its home behind.+// - The runner's view of its workspace is `/workspace`, in the spec it boots+// from; the host path never goes in.+// - A start that fails leaves no container running and no token socket open;+// the record stays, so the next message resumes under the same id (and+// creates the container it does not find). That holds for whoever takes the+// started runner on, too: `Started.abandon` is theirs to call.+// - A transcript lives in the thread's home: `sdkSessionId` goes in only when+// the home volume was there before this start. A record alone (a first+// start whose Create failed, a volume removed) is a new home.+// - A record that says `unclaimed` (spares.ts) is of a spare bound to the+// thread whose claim failed, or was cut short by the host's end. Whatever+// Podman has under its id is never started: container and home are removed+// and created anew, with no transcript, and the record stops saying so once+// they are gone. When they cannot be removed the start fails.+// - The thread's workspace directory and its registries are made at every+// start: a first start may have failed before they were. The mounts+// (workspace.ts) are part of bringing the container up.+// - A thread whose record has no `repos` gets its workspace prepared while its+// runner boots; the runner is connected to, and so given credentials and+// its first message, only after that. A start whose preparation failed is+// abandoned and its record keeps no `repos`, so the next start prepares+// again.+// - `runner.launched` is one event per start with the container's timings,+// `container.add_ms` among them: it is emitted once the worktrees were+// added, with the time and the duration of the launch itself.+// - A start's error is one line. Why a runner never listened goes to the+// host's log, never into the error (it reaches the gateway's reply).+// - The runner's socket is in a directory the session can write: it is+// connected to only when it is a socket, and to the file that was checked+// (runner-sockets.ts `dialSocket`, checked-socket.ts).++import type net from 'node:net';+import path from 'node:path';+import { randomBytes } from 'node:crypto';+import type { RunnerSpec, SessionSpec } from '../../protocol.js';+import type { RunnerApi } from '../../protocol-api.js';+import { type RunRoot, socketFor } from '../../ipc.js';+import { log } from '../../log.js';+import type { Telemetry } from '../../telemetry/emitter.js';+import type { Dimensions } from '../../telemetry/envelope.js';+import { coldStart } from '../cold-start.js';+import { awaitRunner, dialSocket } from '../runner-sockets.js';+import type { Containers, Inventory } from './containers.js';+import { WORKSPACE } from './mounts.js';+import { containerName } from './podman-args.js';+import type { Records, SandboxRecord } from './records.js';+import type { ThreadLocks } from './thread-lock.js';+import type { SandboxWorkspace } from './workspace.js';++export { WORKSPACE };++export interface SandboxStartDeps {+ tm: Telemetry;+ records: Records;+ /** The threads' turns, shared with prune and the sweep. */+ locks: ThreadLocks;+ containers: Pick<Containers, 'create' | 'up' | 'stop' | 'remove' | 'recreate' | 'inventory' | 'stale' | 'unitActive' | 'diagnose'>;+ runRoot(id: string): RunRoot;+ /** SP_IMAGE and SP_IMAGE_ABI of the host's release. */+ image: string;+ abi: string;+ version: string;+ /** The session's journal, socket (below `run`) and token for this runner; undefined off the API. */+ mint(spec: SessionSpec, runnerId: string, run: RunRoot): Promise<RunnerApi | undefined>;+ /** The thread's files: directories, mounts, worktrees (workspace.ts). */+ workspace: Pick<SandboxWorkspace, 'repos' | 'there' | 'dirs' | 'binds' | 'mount' | 'prepare'>;+ /** True when a workspace definition is in effect (`workspacesEnabled`). */+ workspaces(): boolean;+ /** Connect to a runner's socket; undefined when nothing answers. */+ dial?: (socket: string) => Promise<net.Socket | undefined>;+}++export interface Started {+ record: SandboxRecord;+ run: RunRoot;+ sock: net.Socket;+ /** The session as the runner got it: without a transcript when the thread is new. */+ session: SessionSpec;+ /** With its token, for the `api` frame. */+ api?: RunnerApi;+ resumed: boolean;+ /** The runner is not taken on after all: stop its container and close its token socket. Never rejects. */+ abandon(): Promise<void>;+}++export type SandboxStarts = ReturnType<typeof sandboxStarts>;++/** The image's tag, shortened as telemetry carries it. */+export const imageTag = (image: string) => image.slice(image.lastIndexOf(':') + 1).slice(0, 12);++export function sandboxStarts(d: SandboxStartDeps) {+ const { tm, containers: c } = d;+ const dial = d.dial ?? dialSocket;++ /** The container for a thread that has a record: there, of this ABI and not left running by anything; made again otherwise. */+ async function ready(id: string, inventory: Inventory): Promise<{ recreated: boolean; ms?: number }> {+ const found = inventory.containers.find((x) => x.id === id);+ if (!found || found.abi !== d.abi || (await c.stale(found))) {+ log.info(`sandbox ${id}: ${!found ? 'no container' : found.abi !== d.abi ? `ABI ${found.abi}, now ${d.abi}` : 'stale'}; creating it again`);+ return { recreated: true, ms: await c.recreate(id) };+ }+ // Running with nobody connected (the host restarted): stopped, so that it starts with a fresh run directory and token socket.+ if (found.state !== 'created' && found.state !== 'exited') await c.stop(id);+ return { recreated: false };+ }++ /** Start the runner of `spec`'s thread and connect to it, in the thread's turn. `f`: the delivery's trace. */+ const start = (spec: SessionSpec, f: Dimensions): Promise<Started> => d.locks.run(spec.owner.dir, spec.key, () => startNow(spec, f));++ async function startNow(spec: SessionSpec, f: Dimensions): Promise<Started> {+ const now = new Date().toISOString();+ const found = d.records.find(spec.owner.dir, spec.key);+ const unread = found ? [] : d.records.unread();+ if (unread.length && d.workspace.there(spec.owner.dir, spec.key))+ throw new Error(`this thread has files but no sandbox record, and the record ${unread.map((id) => `${id}.json`).join(', ')} did not load; nothing was started. Repair that file in the host's state/sandboxes, or remove it for a new sandbox`);+ const { sdkSessionId, forkPath: _fork, ...fresh } = spec;+ let record: SandboxRecord = found ? { ...found, usedAt: now } : { id: randomBytes(8).toString('hex'), person: spec.owner.dir, key: spec.key, createdAt: now, usedAt: now };+ d.records.write(record);+ const { id } = record;+ const run = d.runRoot(id);+ let rs: RunnerSpec = { id, socket: socketFor(run, id), version: d.version };+ const data: Record<string, string | number | boolean> = { launch_mode: 'podman', image: imageTag(d.image) };+ const t0 = Date.now();+ let session: SessionSpec = fresh; // a new home has no transcript+ let api: RunnerApi | undefined;+ let tokens: { close(): void } | undefined;+ const abandon = async () => {+ await c.stop(id).catch((e) => log.warn(`sandbox ${id} not stopped after a failed start: ${e?.message ?? e}`));+ tokens?.close();+ };+ // What this start mounts; a thread without `repos` yet also gets a worktree of each (`prepare`).+ let names: string[] = [];+ const prepares = d.workspaces() && !record.repos;+ let launch: { at: number; ms: number } | undefined;+ const launched = (failed = false) => {+ if (!launch) return;+ tm.emit('runner.launched', { ...f, duration_ms: launch.ms, outcome: failed ? 'failed' : 'completed', ...(failed && { error_type: 'launch' as const }), data }, launch.at);+ launch = undefined;+ };+ const sock = await coldStart({+ up: async () => {+ const began = Date.now();+ try {+ names = d.workspace.repos(record);+ await d.workspace.dirs(record, names);+ const inventory = found && !found.unclaimed && (await c.inventory());+ // The transcript is in the home: resumed only into one that was there before this start.+ if (sdkSessionId && inventory && inventory.volumes.some((v) => v.id === id)) session = { ...fresh, sdkSessionId };+ api = await d.mint(session, id, run);+ rs = { ...rs, session: { ...session, forkPath: WORKSPACE }, api: api && { ...api, token: '' } };+ if (inventory) {+ const r = await ready(id, inventory);+ data['container.recreated'] = r.recreated;+ if (r.ms !== undefined) data['container.create_ms'] = r.ms;+ } else {+ if (record.unclaimed) {+ if (!(await c.remove(id))) throw new Error(`the spare this thread took was not claimed and could not be removed (${containerName(id)}); nothing was started`);+ const { unclaimed: _, ...claimed } = record;+ d.records.write((record = claimed));+ data['container.recreated'] = true;+ }+ data['container.create_ms'] = await c.create(id).catch(async (e) => {+ await c.remove(id); // whatever a failed Create left; the record stays+ throw e;+ });+ }+ const binds = d.workspace.binds(record, names, api && path.dirname(api.journal));+ const up = await c.up(id, rs, record, (pid) => d.workspace.mount(id, pid, record.person, binds));+ tokens = up.tokens;+ data['container.start_ms'] = up.startMs;+ if (up.mountMs !== undefined) data['container.mount_ms'] = up.mountMs;+ launch = { at: Date.now(), ms: Date.now() - began };+ if (!prepares) launched();+ } catch (e) {+ launch = { at: Date.now(), ms: Date.now() - began };+ launched(true);+ throw e;+ }+ },+ prepare: prepares+ ? async () => {+ const done = tm.start('fork.done', f);+ try {+ const p = await d.workspace.prepare(id, names);+ record = p.record;+ data['container.add_ms'] = p.addMs;+ done.end({ outcome: 'completed', data: { repos: Object.keys(p.record.repos ?? {}).length } });+ } catch (e) {+ done.end({ outcome: 'failed', error_type: 'git_worktree', data: { fork_error_type: 'git_worktree' } });+ throw e;+ } finally {+ launched();+ }+ }+ : undefined,+ ready: () =>+ awaitRunner(rs, {+ tm, f, t0,+ dial: () => dial(rs.socket),+ late: async () => log.warn(`sandbox ${id} never listened:\n${(await c.diagnose(id)).slice(-4000)}`),+ }),+ abandon,+ });+ return { record, run, sock, session, api, resumed: !!found, abandon };+ }++ return { start };+}diff --git a/computer/src/host/sandbox/sweep.test.ts b/computer/src/host/sandbox/sweep.test.tsnew file mode 100644index 00000000..030e7f06--- /dev/null+++ b/computer/src/host/sandbox/sweep.test.ts@@ -0,0 +1,220 @@+import { existsSync, mkdirSync, mkdtempSync, utimesSync } from 'node:fs';+import type net from 'node:net';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import type { ContainerInfo, Inventory } from './containers.js';+import { PodmanError } from './podman.js';+import type { SandboxRecord } from './records.js';+import { type SweepDeps, sandboxSweep } from './sweep.js';+import { threadLocks } from './thread-lock.js';++const A = 'aaaaaaaaaaaaaaaa';+const B = 'bbbbbbbbbbbbbbbb';+const C = 'cccccccccccccccc';+// An hour ahead of the clock: a directory this test makes has a change time the kernel set, and it must count as old.+const NOW = Date.now() + 3_600_000;+const OLD = NOW - 11 * 60_000;+const record = (id: string, usedAt = OLD): SandboxRecord => ({ id, person: 'p', key: `C1:${id}`, createdAt: '', usedAt: new Date(usedAt).toISOString() });+const box = (id: string, state = 'running', createdAt = OLD): ContainerInfo => ({ id, state, abi: '1', image: 'img', createdAt });++function rig(o: { inventory?: Partial<Inventory> | Error; records?: SandboxRecord[]; running?: string[]; sockets?: string[]; adopt?: (r: SandboxRecord) => Promise<unknown>; unread?: string[];+ answer?: (argv: string[]) => string | Error; remove?: boolean; over?: Partial<SweepDeps> } = {}) {+ const runDir = mkdtempSync(path.join(tmpdir(), 'sweep-'));+ const log: string[] = [];+ const events: { name: string; data: unknown }[] = [];+ const run = async (argv: string[]) => {+ log.push(argv.join(' '));+ const a = o.answer?.(argv) ?? '';+ if (a instanceof Error) throw a;+ return a;+ };+ const records = new Map((o.records ?? []).map((r) => [r.id, r]));+ const runRoot = (id: string) => path.join(runDir, id);+ const s = sandboxSweep({+ as: { settled: async () => {}, run, podman: (args) => run(['podman', ...args]) },+ tm: { emit: (name: string, f: { data: unknown }) => void events.push({ name, data: f.data }) } as never,+ records: { all: () => [...records.values()], get: (id) => records.get(id), unread: () => o.unread ?? [] },+ locks: threadLocks(),+ containers: {+ inventory: async () => {+ log.push('inventory');+ if (o.inventory instanceof Error) throw o.inventory;+ return { containers: [], volumes: [], foreign: [], ...o.inventory };+ },+ stop: async (id) => void log.push(`stop ${id}`),+ remove: async (id) => (log.push(`remove ${id}`), o.remove ?? true),+ },+ runDir, runRoot, dataDir: runDir,+ serveTokens: (_run, id, session) => (log.push(`tokens ${id} ${session()}`), { close: () => void log.push(`tokens closed ${id}`) }),+ dial: async (socket) => (log.push(`dial ${path.relative(runDir, socket)}`), (o.sockets ?? []).some((id) => socket === path.join(runRoot(id), 'runners', `${id}.sock`)) ? ({ destroy: () => {} } as net.Socket) : undefined),+ adopt: async (r) => (log.push(`adopt ${r.id} ${r.key}`), o.adopt?.(r)),+ running: (id) => (o.running ?? []).includes(id),+ now: () => NOW,+ ...o.over,+ });+ /** A run directory last touched at `at`. */+ const dir = (id: string, at = OLD) => {+ mkdirSync(runRoot(id));+ utimesSync(runRoot(id), at / 1000, at / 1000);+ return runRoot(id);+ };+ return { s, log, events, runRoot, dir, ran: (word: string) => log.filter((l) => l.includes(word)) };+}++describe('host restart', () => {+ it('takes back a running container as its record: token socket, checked dial, adopt; in that order', async () => {+ const t = rig({ inventory: { containers: [box(A)] }, records: [record(A)], sockets: [A] });+ expect([...(await t.s.reconcile())]).toEqual([A]);+ expect(t.log).toEqual(['inventory', `tokens ${A} C1:${A}`, `dial ${A}/runners/${A}.sock`, `adopt ${A} C1:${A}`]);+ });++ it('stops a running container whose record says its spare was never claimed: it is not taken back, whatever its runner would report', async () => {+ const t = rig({ inventory: { containers: [box(A)] }, records: [{ ...record(A), unclaimed: true }], sockets: [A] });+ expect((await t.s.reconcile()).size).toBe(0);+ expect(t.log).toEqual(['inventory', `stop ${A}`]);+ });++ it('stops a running container whose socket does not answer, or whose runner is not the record\'s; removes neither', async () => {+ const silent = rig({ inventory: { containers: [box(A)] }, records: [record(A)] });+ expect((await silent.s.reconcile()).size).toBe(0);+ expect(silent.log.slice(-2)).toEqual([`stop ${A}`, `tokens closed ${A}`]);+ const other = rig({ inventory: { containers: [box(A)] }, records: [record(A)], sockets: [A], adopt: () => Promise.reject(new Error('it reports another key')) });+ expect((await other.s.reconcile()).size).toBe(0);+ expect(other.log.slice(-3)).toEqual([`adopt ${A} C1:${A}`, `stop ${A}`, `tokens closed ${A}`]);+ expect(other.ran('remove')).toEqual([]);+ });++ it('leaves a stopped container for its next message, and removes every container without a record whatever its age', async () => {+ const t = rig({ inventory: { containers: [box(A, 'exited'), box(B, 'created'), box(C, 'running', NOW)] }, records: [record(A), record(B)] });+ t.dir(C, NOW);+ await t.s.reconcile();+ // C14: a spare of the host before this one is never taken back, and its run directory goes with it.+ expect(t.log).toEqual(['inventory', `remove ${C}`, expect.stringMatching(new RegExp(`^podman unshare find .*${C}/runners`))]);+ expect(existsSync(t.runRoot(C))).toBe(false);+ });++ it('does nothing when the inventory fails', async () => {+ const t = rig({ inventory: new Error('timed out'), records: [record(A)] });+ expect((await t.s.reconcile()).size).toBe(0);+ expect(t.log).toEqual(['inventory']);+ });+});++describe('sweep', () => {+ it('does nothing when the inventory fails', async () => {+ const t = rig({ inventory: new Error('timed out') });+ t.dir(A);+ expect(await t.s.sweep()).toBeUndefined();+ expect(t.log).toEqual(['inventory']);+ expect(existsSync(t.runRoot(A))).toBe(true);+ });++ it('an id whose record file did not load has a record: its container, its home and its run directory stay, at the start and at every sweep', async () => {+ const t = rig({ inventory: { containers: [box(A), box(B, 'exited')], volumes: [{ id: A, createdAt: OLD }, { id: B, createdAt: OLD }, { id: C, createdAt: OLD }] }, unread: [A, B, C] });+ for (const id of [A, B, C]) t.dir(id);+ expect((await t.s.reconcile()).size).toBe(0);+ expect(t.log).toEqual(['inventory', `stop ${A}`]); // running with nobody who could take it back: stopped, as any other+ expect(await t.s.sweep()).toMatchObject({ containers: 0, volumes: 0, run_dirs: 0 });+ expect(t.ran('remove')).toEqual([]);+ expect(t.ran('volume rm')).toEqual([]);+ for (const id of [A, B, C]) expect(existsSync(t.runRoot(id))).toBe(true);+ });++ it('removes an old container with no record and no runner; never one with a record, a runner, or younger than 10 minutes', async () => {+ const D = 'dddddddddddddddd';+ const t = rig({ inventory: { containers: [box(A), box(B), box(C), box(D, 'exited', NOW - 9 * 60_000)] }, records: [record(B)], running: [C] });+ expect(await t.s.sweep()).toMatchObject({ containers: 1 });+ expect(t.ran('remove')).toEqual([`remove ${A}`]);+ expect(t.events).toEqual([{ name: 'sandbox.swept', data: { containers: 1, volumes: 0, run_dirs: 0, units: 0 } }]);+ });++ it('removes a home only with no container of its id anywhere, no record, and a run directory of this host; without --force', async () => {+ const [D, E] = ['dddddddddddddddd', 'eeeeeeeeeeeeeeee'];+ const vol = (id: string, createdAt = OLD) => ({ id, createdAt });+ const t = rig({ inventory: { containers: [box(B, 'exited')], volumes: [vol(A), vol(B), vol(C), vol(D), vol(E), vol('ffffffffffffffff', NOW)], foreign: [C] }, records: [record(B), record(D)] });+ for (const id of [A, B, C, D, 'ffffffffffffffff']) t.dir(id); // none for E: nothing says it was this host's+ expect(await t.s.sweep()).toMatchObject({ volumes: 1, containers: 0 });+ expect(t.ran('volume rm')).toEqual([`podman volume rm sp-home-${A}`]);+ });++ it('a home labelled as this host\'s goes without its run directory (a reboot empties /run); one labelled as another host\'s never; one without the label only with the directory', async () => {+ const [D, E, F, G] = ['dddddddddddddddd', 'eeeeeeeeeeeeeeee', 'ffffffffffffffff', '0000000000000000'];+ const vol = (id: string, mine?: boolean, createdAt = OLD) => ({ id, createdAt, ...(mine !== undefined && { mine }) });+ const t = rig({ inventory: { containers: [box(D, 'exited')], volumes: [vol(A, true), vol(B, false), vol(C), vol(D, true), vol(E, true), vol(F, true, NOW), vol(G, true)], foreign: [G] }, records: [record(D), record(E)] });+ t.dir(B); // even with a directory here, the label says whose it is+ expect(await t.s.sweep()).toMatchObject({ volumes: 1, containers: 0 });+ expect(t.ran('volume rm')).toEqual([`podman volume rm sp-home-${A}`]);+ });++ it('deletes an old run directory with no container, home or runner: the session\'s part inside the user namespace, then the rest', async () => {+ const [D, E] = ['dddddddddddddddd', 'eeeeeeeeeeeeeeee'];+ const t = rig({ inventory: { containers: [box(B, 'exited')], volumes: [{ id: C, createdAt: NOW }] }, records: [record(B), record(E, NOW)], running: [D] });+ for (const id of [A, B, C, D, E]) t.dir(id);+ t.dir('ffffffffffffffff', NOW);+ mkdirSync(path.join(t.runRoot(A), '..', 'not-an-id'));+ expect(await t.s.sweep()).toMatchObject({ run_dirs: 1 });+ expect(existsSync(t.runRoot(A))).toBe(false);+ expect(t.ran('unshare')).toEqual([`podman unshare find ${t.runRoot(A)}/runners ${t.runRoot(A)}/secrets -mindepth 1 -delete`]);+ for (const id of [B, C, D, E, 'ffffffffffffffff', 'not-an-id']) expect(existsSync(t.runRoot(id))).toBe(true);+ });++ it('a run directory of a thread that is starting is left: the sweep waits for the thread\'s turn, then looks again', async () => {+ const locks = threadLocks();+ let rec = record(A);+ const t = rig({ over: { locks, records: { all: () => [rec], get: () => rec, unread: () => [] } } });+ t.dir(A);+ let end!: () => void;+ // A start: it has the turn, writes its record, and makes its container on this directory.+ void locks.run('p', `C1:${A}`, () => new Promise<void>((r) => (end = () => ((rec = record(A, NOW)), r()))));+ const pass = t.s.sweep();+ await new Promise((r) => setTimeout(r, 20));+ expect(t.ran('unshare')).toEqual([]);+ end();+ expect(await pass).toMatchObject({ run_dirs: 0 });+ expect(existsSync(t.runRoot(A))).toBe(true);+ // A thread nobody starts: its old run directory goes, in its turn.+ const idle = rig({ records: [record(B)] });+ idle.dir(B);+ expect(await idle.s.sweep()).toMatchObject({ run_dirs: 1 });+ });++ it('keeps a run directory whose content could not be removed, and one whose home could not be', async () => {+ const t = rig({ answer: (a) => (a[2] === 'find' ? new PodmanError('x', 1, 'find: cannot delete: Permission denied\n', false) : '') });+ t.dir(A);+ expect(await t.s.sweep()).toMatchObject({ run_dirs: 0 });+ expect(existsSync(t.runRoot(A))).toBe(true);+ const home = rig({ inventory: { volumes: [{ id: A, createdAt: OLD }] }, answer: (a) => (a[1] === 'volume' ? new PodmanError('in use', 2, 'volume is being used', false) : '') });+ home.dir(A);+ expect(await home.s.sweep()).toMatchObject({ volumes: 0, run_dirs: 0 });+ expect(existsSync(home.runRoot(A))).toBe(true);+ });++ it('a container that Remove left a part of keeps its run directory for the next pass', async () => {+ const t = rig({ inventory: { containers: [box(A)], volumes: [{ id: A, createdAt: OLD }] }, remove: false });+ t.dir(A);+ expect(await t.s.sweep()).toEqual({ containers: 0, volumes: 0, run_dirs: 0, units: 0 });+ expect(existsSync(t.runRoot(A))).toBe(true);+ expect(t.events).toEqual([]);+ });++ it('resets the failed units of its own sandboxes only', async () => {+ const t = rig({+ records: [record(A)],+ inventory: { containers: [box(A, 'exited')] },+ answer: (a) => (a.includes('list-units') ? `sp-runner-${A}.service loaded failed failed x\nsp-runner-${B}.service loaded failed failed x\nsp-runner-${C}.service loaded failed failed x\n` : ''),+ });+ t.dir(B); // deleted in this very pass, and its unit is still this host's+ expect(await t.s.sweep()).toMatchObject({ units: 2, run_dirs: 1 });+ expect(t.ran('reset-failed')).toEqual([`/usr/bin/systemctl --user reset-failed sp-runner-${A}.service sp-runner-${B}.service`]);+ });++ it('health: containers by state and Podman\'s total, as of the last sweep', async () => {+ const df = JSON.stringify([{ Type: 'Images', RawSize: 3000 }, { Type: 'Containers', RawSize: 200 }, { Type: 'Local Volumes', RawSize: 1 }]);+ const t = rig({ inventory: { containers: [box(A), box(B, 'exited'), box(C, 'stopping')] }, records: [record(A), record(B), record(C)], answer: (a) => (a[1] === 'system' ? df : '') });+ expect(t.s.health()).toBeUndefined();+ await t.s.sweep();+ expect(t.s.health()).toMatchObject({ containers_running: 1, containers_exited: 1, containers_created: 0, containers_other: 1, podman_bytes: 3201 });+ expect(t.s.health()?.data_used_pct).toBeGreaterThanOrEqual(0);+ });+});diff --git a/computer/src/host/sandbox/sweep.ts b/computer/src/host/sandbox/sweep.tsnew file mode 100644index 00000000..43232ab8--- /dev/null+++ b/computer/src/host/sandbox/sweep.ts@@ -0,0 +1,262 @@+// What a `podman` host does about containers it did not start in this life+// (work 103, "Sequences"): at its start it takes the running ones back+// (Host restart), and at every housekeeping pass it removes what belongs to+// no thread (Sweep) and counts what there is (Health).+//+// Invariants:+// - Both begin with an Inventory and do nothing at all when it fails: the next+// pass tries again. The Inventory lists only this host's containers+// (containers.ts), so neither ever touches another host's.+// - A running container is taken back only as its record's thread: its token+// socket is served first, its runner's socket is dialed checked (rule 4),+// and the first report within 5 s must name the record's key+// (start-runner.ts `adopt`). Anything else is stopped; nothing is removed+// for it, and the next message resumes the thread.+// - A container without a record is removed at the start whatever its age+// (C14: no spare outlives its host). The sweep removes only what is older+// than `ageMs`, has no record and no connected runner.+// - A home volume is removed only when Podman has no container for its id at+// all, this host's or another's, there is no record of it, and it is this+// host's: by its label (containers.ts `mine`), whether or not the run+// directory is still there (a reboot empties `/run`, and the home of a+// pruned or never-recorded id would stay for ever); one labelled as another+// host's never goes. A home without the label (made before homes had one)+// is this host's only while this host's run directory for the id exists.+// It is removed without `--force`, which would take a container using it+// along.+// - A run directory goes only when its id has no container and no volume, no+// runner, and nothing touched it (or its record) for `ageMs`: a start makes+// the directory before the container. The directory of an id that has a+// record goes in its thread's turn (thread-lock.ts), asked about again+// there: never under a start, which mounts it. Nothing else the sweep+// removes can be a starting thread's: a start writes its record first, and+// what has a record is not removed here.+// - An id whose record file is there but did not load (records.ts `unread`)+// has a record, for all of the above: nothing of it is removed, at the+// start or by a sweep. Running, it is stopped: nobody can say whose it is.+// - Records are never deleted here (prune.ts does, last).++import type net from 'node:net';+import path from 'node:path';+import { lstatSync, readdirSync, rmSync, statfsSync } from 'node:fs';+import { type RunRoot, socketFor } from '../../ipc.js';+import { log } from '../../log.js';+import type { Telemetry } from '../../telemetry/emitter.js';+import type { Containers, Inventory } from './containers.js';+import { TIMEOUTS } from './containers.js';+import type { AsRunner } from './podman.js';+import { emptyRunArgs, volumeRmArgs } from './podman-args.js';+import type { Records, SandboxRecord } from './records.js';+import type { ThreadLocks } from './thread-lock.js';++/** "Only objects older than 10 minutes." */+export const SWEEP_AGE_MS = 10 * 60_000;+const SYSTEMCTL = '/usr/bin/systemctl';+const ID = /^[0-9a-f]{16}$/;++export interface SweepDeps {+ as: AsRunner;+ tm: Telemetry;+ records: Pick<Records, 'all' | 'get' | 'unread'>;+ /** The threads' turns, shared with the starts. */+ locks: ThreadLocks;+ containers: Pick<Containers, 'inventory' | 'stop' | 'remove'>;+ /** `$SP_RUN/sandbox`, and a runner's run root in it. */+ runDir: string;+ runRoot(id: string): RunRoot;+ /** The host's SP_DATA, for its use in percent. */+ dataDir: string;+ /** `tokens.serveRunner`. */+ serveTokens(run: RunRoot, id: string, session: () => string | undefined): { close(): void };+ /** The checked dial of a runner's socket (runner-sockets.ts `dialSocket`); undefined when nothing answers. */+ dial(socket: string): Promise<net.Socket | undefined>;+ /** Take a runner found running on as its record's (start-runner.ts `adopt`, verified); rejects when it is not, having told it to go. */+ adopt(record: SandboxRecord, run: RunRoot, sock: net.Socket): Promise<unknown>;+ /** True while a runner with this id is connected: a thread's, or a spare. */+ running(id: string): boolean;+ /** How old an object must be for the sweep (SP_SWEEP_AGE_MS; 10 minutes). */+ ageMs?: number;+ now?: () => number;+}++/** What one pass removed, by kind (`sandbox.swept`). */+export interface Swept { containers: number; volumes: number; run_dirs: number; units: number }++/** For `host.sample`: containers by Podman's state, `/data` used in percent, `podman system df`'s total in bytes. */+export interface SandboxHealth {+ containers_running: number;+ containers_exited: number;+ containers_created: number;+ containers_other: number;+ data_used_pct?: number;+ podman_bytes?: number;+}++export type SandboxSweep = ReturnType<typeof sandboxSweep>;++const msg = (e: unknown) => (e as Error)?.message ?? String(e);++export function sandboxSweep(d: SweepDeps) {+ const { as, containers: c } = d;+ const now = d.now ?? Date.now;+ const age = d.ageMs ?? SWEEP_AGE_MS;+ let health: SandboxHealth | undefined;+ /** True when the id has a record, loaded or not. */+ const known = (id: string) => !!d.records.get(id) || d.records.unread().includes(id);++ /** Delete a run directory: what the session wrote goes inside Podman's user namespace, the rest is the host's. Never rejects; true when it is gone. */+ async function deleteRun(id: string): Promise<boolean> {+ const run = d.runRoot(id);+ try {+ await as.podman(emptyRunArgs(run), { timeoutMs: TIMEOUTS.remove }).catch((e) => {+ const lines = String(e?.stderr ?? '').trim().split('\n').filter(Boolean);+ if (!lines.length || !lines.every((l) => /No such file or directory/.test(l))) throw e; // a directory no start ever filled+ });+ rmSync(run, { recursive: true, force: true });+ return true;+ } catch (e) {+ log.warn(`sandbox ${id}: run directory not deleted: ${msg(e)}`);+ return false;+ }+ }++ /** Host restart: take back every running container that is its record's, stop the others, remove what has no record. The ids taken back. */+ async function reconcile(): Promise<Set<string>> {+ const adopted = new Set<string>();+ let inventory: Inventory;+ try {+ inventory = await c.inventory();+ } catch (e) {+ log.warn(`sandbox: no inventory at start (${msg(e)}); the sweep tries again`);+ return adopted;+ }+ await Promise.all(inventory.containers.map(async ({ id, state }) => {+ const record = d.records.get(id);+ if (!record && known(id)) {+ log.warn(`sandbox ${id}: its record did not load; kept${state === 'running' ? ', stopped' : ''}`);+ if (state === 'running') await c.stop(id).catch((x) => log.warn(`sandbox ${id} not stopped: ${msg(x)}`));+ return;+ }+ // C14: a spare of the host before this one (or a start that never got its record); its run directory serves nobody either.+ if (!record) return void ((await c.remove(id)) && (await deleteRun(id)), log.info(`sandbox ${id}: a container without a record, removed`));+ if (state !== 'running') return; // the next message resumes it (start.ts)+ // A spare whose claim was not answered when the host before this one ended (spares.ts): never taken back; the next start makes it anew.+ if (record.unclaimed) return void (await c.stop(id).catch((x) => log.warn(`sandbox ${id} not stopped: ${msg(x)}`)));+ const run = d.runRoot(id);+ const t0 = now();+ let tokens: { close(): void } | undefined;+ let sock: net.Socket | undefined;+ try {+ tokens = d.serveTokens(run, id, () => record.key);+ sock = await d.dial(socketFor(run, id));+ if (!sock) throw new Error('nothing answers on its socket');+ await d.adopt(record, run, sock);+ adopted.add(id);+ log.info(`sandbox ${id}: running, taken back for ${record.key} in ${now() - t0} ms`);+ } catch (e) {+ log.warn(`sandbox ${id}: running but not taken back (${msg(e)}); stopping it`);+ sock?.destroy();+ await c.stop(id).catch((x) => log.warn(`sandbox ${id} not stopped: ${msg(x)}`));+ tokens?.close();+ }+ }));+ return adopted;+ }++ /** Failed units of this host's sandboxes (`mine`: the ids with a run directory when the pass began, and every record's), reset so that their names can start again. */+ async function resetFailed(mine: Set<string>): Promise<number> {+ const out = await as.run([SYSTEMCTL, '--user', 'list-units', '--state=failed', '--plain', '--no-legend', 'sp-runner-*.service'], { timeoutMs: TIMEOUTS.unit });+ const units = out.split('\n').map((l) => l.trim().split(/\s+/)[0]).filter((u) => {+ const id = /^sp-runner-([0-9a-f]{16})\.service$/.exec(u)?.[1];+ return !!id && (known(id) || mine.has(id));+ });+ if (units.length) await as.run([SYSTEMCTL, '--user', 'reset-failed', ...units], { timeoutMs: TIMEOUTS.unit });+ return units.length;+ }++ /** The ids that have a run directory. */+ function runDirs(): string[] {+ try {+ return readdirSync(d.runDir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() && ID.test(e.name) ? [e.name] : []));+ } catch {+ return []; // no sandbox ever started+ }+ }++ const exists = (p: string) => !!lstatSync(p, { throwIfNoEntry: false });++ async function measure(inventory: Inventory) {+ const n = (f: (s: string) => boolean) => inventory.containers.filter((x) => f(x.state)).length;+ const named = ['running', 'exited', 'created'];+ const h: SandboxHealth = {+ containers_running: n((s) => s === 'running'), containers_exited: n((s) => s === 'exited'), containers_created: n((s) => s === 'created'),+ containers_other: n((s) => !named.includes(s)),+ };+ try {+ const s = statfsSync(d.dataDir);+ if (s.blocks > 0) h.data_used_pct = Math.round(((s.blocks - s.bavail) / s.blocks) * 100);+ } catch {+ // no figure+ }+ try {+ const rows = JSON.parse(await as.podman(['system', 'df', '--format', 'json'], { timeoutMs: TIMEOUTS.inventory, repeatable: true })) as { RawSize?: number }[];+ h.podman_bytes = rows.reduce((sum, r) => sum + (Number(r?.RawSize) || 0), 0);+ } catch (e) {+ log.warn(`sandbox: podman system df: ${msg(e)}`);+ }+ health = h;+ }++ /** One pass. Undefined when the Inventory failed: nothing was looked at. Never rejects. */+ async function sweep(): Promise<Swept | undefined> {+ let inventory: Inventory;+ try {+ inventory = await c.inventory();+ } catch (e) {+ log.warn(`sandbox: no inventory (${msg(e)}); nothing swept this pass`);+ return undefined;+ }+ const swept: Swept = { containers: 0, volumes: 0, run_dirs: 0, units: 0 };+ try {+ const old = (at: number) => now() - at >= age;+ const idle = (id: string) => !known(id) && !d.running(id);+ const has = new Set([...inventory.containers.map((x) => x.id), ...inventory.foreign]);+ const homes = new Set(inventory.volumes.map((v) => v.id));+ for (const x of inventory.containers) {+ if (!idle(x.id) || !old(x.createdAt)) continue;+ log.info(`sandbox ${x.id}: a container without a record, removed`);+ // Remove takes the home too; what stays of either is the next pass's.+ if (await c.remove(x.id)) (swept.containers++, has.delete(x.id), homes.delete(x.id));+ }+ for (const v of inventory.volumes) {+ if (has.has(v.id) || !homes.has(v.id) || !idle(v.id) || !old(v.createdAt) || !(v.mine ?? exists(d.runRoot(v.id)))) continue;+ await as.podman(volumeRmArgs(v.id), { timeoutMs: TIMEOUTS.remove }).then(+ () => (swept.volumes++, homes.delete(v.id), log.info(`sandbox ${v.id}: a home without a container or a record, removed`)),+ (e) => log.warn(`sandbox ${v.id}: home not removed: ${msg(e)}`),+ );+ }+ const dirs = runDirs();+ for (const id of dirs) {+ if (has.has(id) || homes.has(id) || d.running(id) || d.records.unread().includes(id)) continue;+ const unused = () => {+ const st = lstatSync(path.join(d.runDir, id), { throwIfNoEntry: false });+ const used = Date.parse(d.records.get(id)?.usedAt ?? '') || 0;+ return !!st && old(Math.max(st.mtimeMs, st.ctimeMs, used));+ };+ if (!unused()) continue;+ // A thread's directory goes in the thread's turn: a start that had it wrote the record, and this looks again.+ const r = d.records.get(id);+ const gone = r ? await d.locks.run(r.person, r.key, async () => !d.running(id) && unused() && deleteRun(id)) : await deleteRun(id);+ if (gone) swept.run_dirs++;+ }+ swept.units = await resetFailed(new Set(dirs)).catch((e) => (log.warn(`sandbox: failed units not reset: ${msg(e)}`), 0));+ await measure(inventory);+ } catch (e) {+ log.warn(`sandbox: sweep: ${msg(e)}`);+ }+ if (Object.values(swept).some(Boolean)) d.tm.emit('sandbox.swept', { data: { ...swept } });+ return swept;+ }++ return { reconcile, sweep, deleteRun, health: () => health };+}diff --git a/computer/src/host/sandbox/tar.test.ts b/computer/src/host/sandbox/tar.test.tsnew file mode 100644index 00000000..a6036275--- /dev/null+++ b/computer/src/host/sandbox/tar.test.ts@@ -0,0 +1,28 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, readFileSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import { tarOf } from './tar.js';++describe('tarOf', () => {+ it('is a stream tar unpacks: the files, their text and mode', () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'tar-'));+ const big = 'x'.repeat(1300) + 'é\n';+ execFileSync('tar', ['-x', '-f', '-', '-C', dir], { input: tarOf([{ name: '.fork.json', text: '{"a":1}\n' }, { name: 'docs/AGENTS.md', text: big }, { name: 'empty', text: '' }], 1_700_000_000_000) });+ expect(readFileSync(path.join(dir, '.fork.json'), 'utf8')).toBe('{"a":1}\n');+ expect(readFileSync(path.join(dir, 'docs', 'AGENTS.md'), 'utf8')).toBe(big);+ expect(readFileSync(path.join(dir, 'empty'), 'utf8')).toBe('');+ expect(statSync(path.join(dir, '.fork.json')).mtimeMs).toBe(1_700_000_000_000);+ expect(execFileSync('tar', ['-t', '-v', '-f', '-'], { input: tarOf([{ name: 'a', text: 'b' }]), encoding: 'utf8' })).toMatch(/^-rw-r--r-- /);+ });++ it('is blocks of 512 bytes, ended by two empty ones', () => {+ expect(tarOf([]).length).toBe(1024);+ expect(tarOf([{ name: 'a', text: 'b' }]).length).toBe(512 + 512 + 1024);+ });++ it('refuses a name that would land outside', () => {+ for (const name of ['', '/etc/passwd', '../x', 'a/../b', 'a//b', './a', 'n'.repeat(101)]) expect(() => tarOf([{ name, text: '' }])).toThrow('not a name');+ });+});diff --git a/computer/src/host/sandbox/tar.ts b/computer/src/host/sandbox/tar.tsnew file mode 100644index 00000000..e60c108a--- /dev/null+++ b/computer/src/host/sandbox/tar.ts@@ -0,0 +1,51 @@+// A tar stream of a few small text files (work 103): how the host gives a+// thread's workspace its root files (.fork.json, AGENTS.md) without writing+// there itself. bin/ws-add.sh unpacks it inside the thread's container, as+// the session's user.+//+// Invariants:+// - Plain ustar: regular files, mode 0644, no owner names; a name is a+// relative path of at most 100 bytes with no `..` and no leading `/`.+// - Pure: the same files give the same bytes but for the time given.++const BLOCK = 512;++export interface TarFile {+ /** Relative to where it is unpacked. */+ name: string;+ text: string;+}++function header(name: string, size: number, mtime: number): Buffer {+ const h = Buffer.alloc(BLOCK);+ const field = (at: number, len: number, value: string) => void h.write(value, at, len, 'utf8');+ const octal = (at: number, len: number, n: number) => field(at, len, n.toString(8).padStart(len - 1, '0') + '\0');+ field(0, 100, name);+ octal(100, 8, 0o644);+ octal(108, 8, 0);+ octal(116, 8, 0);+ octal(124, 12, size);+ octal(136, 12, mtime);+ h.fill(' ', 148, 156); // the checksum counts its own field as spaces+ h.write('0', 156); // a regular file+ field(257, 6, 'ustar\0');+ field(263, 2, '00');+ let sum = 0;+ for (const b of h) sum += b;+ field(148, 8, sum.toString(8).padStart(6, '0') + '\0 ');+ return h;+}++/** The files as one tar stream. `now`: their modification time, Unix milliseconds. */+export function tarOf(files: TarFile[], now = Date.now()): Buffer {+ const parts: Buffer[] = [];+ for (const f of files) {+ const segments = f.name.split('/');+ if (!f.name || f.name.startsWith('/') || segments.some((p) => !p || p === '.' || p === '..') || Buffer.byteLength(f.name) > 100)+ throw new Error(`not a name for a tar entry: ${f.name}`);+ const body = Buffer.from(f.text, 'utf8');+ parts.push(header(f.name, body.length, Math.floor(now / 1000)), body, Buffer.alloc((BLOCK - (body.length % BLOCK)) % BLOCK));+ }+ parts.push(Buffer.alloc(2 * BLOCK));+ return Buffer.concat(parts);+}diff --git a/computer/src/host/sandbox/thread-lock.test.ts b/computer/src/host/sandbox/thread-lock.test.tsnew file mode 100644index 00000000..b181d0f3--- /dev/null+++ b/computer/src/host/sandbox/thread-lock.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';+import { threadLocks } from './thread-lock.js';++const gate = () => {+ let open!: () => void;+ const wait = new Promise<void>((r) => (open = r));+ return { wait, open };+};+const tick = () => new Promise((r) => setImmediate(r));++describe('a thread\'s turn', () => {+ it('one at a time per thread, in the order asked; other threads are not held', async () => {+ const l = threadLocks();+ const log: string[] = [];+ const g = gate();+ const a = l.run('pat', 'C1:1.1', async () => (log.push('a begins'), await g.wait, log.push('a ends')));+ const b = l.run('pat', 'C1:1.1', async () => void log.push('b'));+ const c = l.run('pat', 'C1:2.2', async () => void log.push('c, another thread'));+ const d = l.run('quinn', 'C1:1.1', async () => void log.push('d, another person'));+ await Promise.all([c, d]);+ await tick();+ expect(log).toEqual(['a begins', 'c, another thread', 'd, another person']);+ expect(l.busy('pat', 'C1:1.1')).toBe(true);+ g.open();+ await Promise.all([a, b]);+ expect(log.slice(3)).toEqual(['a ends', 'b']);+ await tick();+ expect(l.busy('pat', 'C1:1.1')).toBe(false);+ });++ it('a turn that rejects ends: its error is its caller\'s, and the next turn runs', async () => {+ const l = threadLocks();+ const a = l.run('pat', 'k', async () => {+ throw new Error('boom');+ });+ const b = l.run('pat', 'k', async () => 'next');+ await expect(a).rejects.toThrow('boom');+ expect(await b).toBe('next');+ });+});diff --git a/computer/src/host/sandbox/thread-lock.ts b/computer/src/host/sandbox/thread-lock.tsnew file mode 100644index 00000000..13a3c440--- /dev/null+++ b/computer/src/host/sandbox/thread-lock.ts@@ -0,0 +1,36 @@+// One thing at a time per thread (work 103, "Sequences"): a start (new,+// resume, claim) and whatever removes a thread's container, home, workspace or+// run directory (prune.ts, artifacts.ts, the sweep's run directories) take the+// thread's turn here, so neither ever works on what the other is half through.+//+// Invariants:+// - A thread is its person and its key, never its sandbox id: a start that+// waited for a prune looks its record up only once it has the turn, and+// finds none (a new thread) or the one a kept thread still has.+// - Turns are given in the order they were asked for. A turn ends when its+// function settles, whatever it settles with; the next one starts then.+// - Nothing here times out: every holder bounds its own steps (podman.ts).+// - In memory only: one host process owns its threads (containers.ts).++export interface ThreadLocks {+ /** Run `fn` once every turn asked for before it, for this thread, has ended. */+ run<T>(person: string, key: string, fn: () => Promise<T>): Promise<T>;+ /** True while a turn of this thread runs or waits. */+ busy(person: string, key: string): boolean;+}++export function threadLocks(): ThreadLocks {+ /** The end of the last turn asked for, by thread. */+ const tails = new Map<string, Promise<void>>();+ const name = (person: string, key: string) => `${person}\n${key}`;+ return {+ run(person, key, fn) {+ const k = name(person, key);+ const turn = (tails.get(k) ?? Promise.resolve()).then(fn);+ const tail = turn.then(() => undefined, () => undefined).then(() => void (tails.get(k) === tail && tails.delete(k)));+ tails.set(k, tail);+ return turn;+ },+ busy: (person, key) => tails.has(name(person, key)),+ };+}diff --git a/computer/src/host/sandbox/use.test.ts b/computer/src/host/sandbox/use.test.tsnew file mode 100644index 00000000..7f5e2f06--- /dev/null+++ b/computer/src/host/sandbox/use.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';+import { Unavailable, UPDATING } from '../unavailable.js';+import type { SandboxRecord } from './records.js';+import { sandboxUses } from './use.js';++const ID = '00aa11bb22cc33dd';+const record = { id: ID, person: 'pat', key: 'C1:1.0', usedAt: '2026-11-13T00:00:00.000Z' } as SandboxRecord;++function rig(o: { held?: boolean; record?: SandboxRecord | undefined; active?: boolean } = {}) {+ const log: string[] = [];+ const uses = sandboxUses({+ as: { settled: async (ms) => {+ log.push(`settled ${ms}`);+ if (o.held) throw new Unavailable(UPDATING);+ } },+ records: { get: () => ('record' in o ? o.record : record) },+ workspace: (r) => `/data/people/${r.person}/sessions/k`,+ unitActive: async () => (log.push('active?'), o.active ?? true),+ });+ return { uses, log };+}++describe('entering a sandbox (work 103, C13)', () => {+ it('waits for the image lock, 10 s at most, then says where the thread is now', async () => {+ const t = rig({ active: false });+ const use = await t.uses.enter(ID);+ expect(use.place).toEqual({ id: ID, person: 'pat', workspace: '/data/people/pat/sessions/k', running: false });+ expect(t.log).toEqual(['settled 10000', 'active?']);+ });++ it('is refused while provisioning holds the storage, and asks nothing of Podman or the unit', async () => {+ const t = rig({ held: true });+ await expect(t.uses.enter(ID)).rejects.toThrow(/The computer is updating, try again/);+ expect(t.log).toEqual(['settled 10000']);+ });++ it('a thread is in use from the moment it is entered until it is left, and nobody may claim it then or for what was read before', async () => {+ const t = rig();+ const t0 = Date.now();+ const use = await t.uses.enter(ID);+ expect(t.uses.claim(ID, t0)).toBeUndefined();+ use.leave();+ use.leave();+ // Used since `t0`: what was found out about the thread before may be old.+ expect(t.uses.claim(ID, t0)).toBeUndefined();+ const free = t.uses.claim(ID, Date.now() + 1);+ expect(free).toBeTypeOf('function');+ // Claimed: nothing enters, and nobody else claims.+ expect(t.uses.claim(ID, Date.now() + 1)).toBeUndefined();+ const e = await t.uses.enter(ID).catch((x) => x);+ expect([e.name, e.retryable]).toEqual(['Unavailable', true]);+ expect(e.message).toMatch(/being cleaned up/);+ free?.();+ (await t.uses.enter(ID)).leave();+ });++ it('one that waits for the image lock is in use already, and one that was refused is not', async () => {+ const t = rig({ held: true });+ const entering = t.uses.enter(ID);+ expect(t.uses.claim(ID, 0)).toBeUndefined();+ await expect(entering).rejects.toThrow(/updating/);+ expect(t.uses.claim(ID, Date.now() + 1)).toBeTypeOf('function');+ });++ it('a thread whose record is gone has nothing to enter', async () => {+ const t = rig({ record: undefined });+ const e = await t.uses.enter(ID).catch((x) => x);+ expect(e).toBeInstanceOf(Unavailable);+ expect(e.retryable).toBe(false);+ });+});diff --git a/computer/src/host/sandbox/use.ts b/computer/src/host/sandbox/use.tsnew file mode 100644index 00000000..e8c0dfe4--- /dev/null+++ b/computer/src/host/sandbox/use.ts@@ -0,0 +1,96 @@+// Using a thread's sandbox from outside a turn of the agent (work 103, C13):+// what a `/files` script and a terminal do before they start anything in a+// container. `enter` answers where the thread is at this moment, and whoever+// entered says when it has left.+//+// Invariants:+// - Nothing is started for a person while provisioning holds Podman's+// storage: `enter` waits for the image lock, WAIT_MS at most (less than the+// relay waits for the host's answer, 15 s), and is refused with Unavailable+// past it. So such a call never hangs for the minutes an image takes.+// - Where the thread is (its container running or not, its workspace) is read+// when it is entered, from the thread's record and its unit: never taken+// from what an earlier call was told. A thread whose record is gone has+// nothing to enter.+// - A script never runs over a workspace that is being removed, and nothing+// is removed under a script or a terminal: a thread is in use from the+// moment it is entered (before any wait) until it is left, whoever removes+// a stopped thread's files claims it first (prune.ts, artifacts.ts), and+// neither happens between the other's check and its act, both being one+// step of this process. A claim is refused while the thread is in use, and+// when it was used since the claimer looked at its files (`since`): what+// git said before an upload is old. While claimed, nothing enters.+// - A use does not take the thread's turn (thread-lock.ts): a download of an+// hour would hold every message to the thread behind it. A start and a+// `/files` helper may work on one workspace at once, as a session and its+// own `/files` scripts do.+// - In memory only, like the turns: a host that restarts has no script and+// no terminal of its own left to protect.++import { Unavailable } from '../unavailable.js';+import type { AsRunner } from './podman.js';+import type { Records, SandboxRecord } from './records.js';+import type { SandboxPlace } from './scripts.js';++/** How long a person's call waits for the image lock. */+export const WAIT_MS = 10_000;++export interface Use {+ place: SandboxPlace;+ /** The script or the terminal is over. Once; more calls do nothing. */+ leave(): void;+}++export interface UsesDeps {+ as: Pick<AsRunner, 'settled'>;+ records: Pick<Records, 'get'>;+ /** The record's workspace on the host (mounts.ts). */+ workspace(r: SandboxRecord): string;+ /** `containers.unitActive`. */+ unitActive(id: string): Promise<boolean>;+ waitMs?: number;+}++export type SandboxUses = ReturnType<typeof sandboxUses>;++export function sandboxUses(d: UsesDeps) {+ /** Uses not yet left, and when the last one was, by sandbox id. */+ const open = new Map<string, number>();+ const last = new Map<string, number>();+ const claimed = new Set<string>();++ async function enter(id: string): Promise<Use> {+ if (claimed.has(id)) throw new Unavailable("The session's files are being cleaned up, try again in a minute.");+ open.set(id, (open.get(id) ?? 0) + 1);+ let left = false;+ const leave = () => {+ if (left) return;+ left = true;+ const n = (open.get(id) ?? 1) - 1;+ if (n > 0) open.set(id, n);+ else open.delete(id);+ last.set(id, Date.now());+ };+ try {+ await d.as.settled(d.waitMs ?? WAIT_MS);+ const r = d.records.get(id);+ if (!r) throw new Unavailable('The session has no files on this computer any more.', false);+ return { place: { id, person: r.person, workspace: d.workspace(r), running: await d.unitActive(id) }, leave };+ } catch (e) {+ leave();+ throw e;+ }+ }++ /**+ * For whoever removes files of a stopped thread: the thread, until the function returned is called. Undefined when a+ * script or a terminal is in it, was in it at or after `since` (ms), or somebody else has it.+ */+ function claim(id: string, since: number): (() => void) | undefined {+ if (open.has(id) || claimed.has(id) || (last.get(id) ?? -1) >= since) return undefined;+ claimed.add(id);+ return () => void claimed.delete(id);+ }++ return { enter, claim };+}diff --git a/computer/src/host/sandbox/workspace.test.ts b/computer/src/host/sandbox/workspace.test.tsnew file mode 100644index 00000000..14a39101--- /dev/null+++ b/computer/src/host/sandbox/workspace.test.ts@@ -0,0 +1,186 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { beforeEach, describe, expect, it } from 'vitest';+import type { ScriptRunner } from '../../workspaces/script-runner.js';+import type { AsRunner } from './podman.js';+import type { SandboxRecord } from './records.js';++// HOST_DATA is read when protocol.ts loads, so SP_DATA must be set first.+const data = mkdtempSync(path.join(os.tmpdir(), 'sp-wsp-'));+process.env.SP_DATA = data;+const definition = path.join(data, 'def', 'acme.json');+process.env.SP_DEFINITION = definition;+const { useScripts } = await import('../../workspaces/clones.js');+const { mounts } = await import('./mounts.js');+const { sandboxRecords } = await import('./records.js');+const { NO_DEFINITION, sandboxWorkspaces } = await import('./workspace.js');++mkdirSync(path.dirname(definition), { recursive: true });+writeFileSync(path.join(data, 'def', 'AGENTS.md'), 'house rules\n');+writeFileSync(definition, JSON.stringify({+ name: 'acme',+ repos: [+ { name: 'alpha', remote: 'https://github.com/acme/alpha' },+ { name: 'beta', remote: 'https://github.com/acme/beta', branch: 'trunk' },+ { name: 'lazy', remote: 'https://github.com/acme/lazy', clone: 'lazy', description: 'on demand' },+ ],+ rootFiles: { 'AGENTS.md': 'AGENTS.md' },+}));++const ID = '00aa11bb22cc33dd';+const ws = path.join(data, 'people', 'pat', 'ws');+const clone = (name: string) => mkdirSync(path.join(ws, name, '.git'), { recursive: true });+/** The names of the regular files in a tar stream. */+const tarNames = (tar: Buffer) => {+ const names: string[] = [];+ for (let at = 0; at + 512 <= tar.length && tar[at]; ) {+ names.push(tar.subarray(at, at + 100).toString().replace(/\0.*$/, ''));+ at += 512 + Math.ceil(Number.parseInt(tar.subarray(at + 124, at + 135).toString(), 8) / 512) * 512;+ }+ return names;+};+const tarText = (tar: Buffer, name: string) => {+ const at = tar.indexOf(Buffer.from(name.padEnd(100, '\0')));+ return tar.subarray(at + 512, at + 512 + Number.parseInt(tar.subarray(at + 124, at + 135).toString(), 8)).toString();+};++function rig(answer: (args: string[]) => string | Error = (args) => args.slice(4).map((a) => `${a.split('=')[0]}\tok\tsp/C1-1-1\t${a.split('=')[1] ?? 'main'}\tabc123\t\n`).join('')) {+ const log: string[] = [];+ const runs: { args: string[]; stdin?: Buffer; timeoutMs: number }[] = [];+ const as: AsRunner = { settled: async () => {}, run: async (argv) => (log.push(argv.join(' ').replaceAll(data, '')), ''), podman: async (args) => (log.push(`podman ${args.slice(0, 7).join(' ').replaceAll(data, '')}`), '') };+ const records = sandboxRecords(mkdtempSync(path.join(data, 'records-')));+ const record: SandboxRecord = { id: ID, person: 'pat', key: 'C1:1.1', createdAt: '2026-11-12T00:00:00.000Z', usedAt: '2026-11-12T00:00:00.000Z' };+ records.write(record);+ const scripts = (): ScriptRunner => ({+ clones: '/clones', workspace: () => '/workspace',+ async run(script, args, o) {+ runs.push({ args, stdin: o.stdin as Buffer | undefined, timeoutMs: o.timeoutMs });+ log.push(`${script} ${args.slice(3).join(' ')}${o.stdin ? ' <tar' : ''}`);+ const a = o.stdin ? '' : answer(args);+ if (a instanceof Error) throw a;+ return a;+ },+ });+ const w = sandboxWorkspaces({ as, records, mounts: mounts({ as, root: '/opt/r1', dataDir: data }), scripts, pid: async () => 4242 });+ return { w, log, runs, records, record };+}++beforeEach(() => {+ rmSync(ws, { recursive: true, force: true });+ clone('alpha');+ clone('beta');+ writeFileSync(path.join(ws, '.workspace-prepared'), 'now\n'); // nothing is cloned in the background+ useScripts(() => ({+ clones: ws, workspace: () => '',+ run: async (_s, args) => (clone(args[1]), `${args[1]}\tok\n`),+ }));+});++describe('a sandboxed thread\'s workspace (work 103, "Sequences")', () => {+ it('a start mounts the definition\'s cloned repositories, then the record\'s once it has any', () => {+ const t = rig();+ expect(t.w.repos(t.record)).toEqual(['alpha', 'beta']); // lazy is not cloned+ expect(t.w.repos({ ...t.record, repos: {} })).toEqual([]);+ clone('lazy');+ expect(t.w.repos({ ...t.record, repos: { lazy: { branch: 'b', from: 'origin/main', base: 'x' }, gone: { branch: 'b', from: 'origin/main', base: 'x' } } })).toEqual(['lazy']);+ });++ it('dirs: the workspace and a registry per repository, made as the runners\' user in one command', async () => {+ const t = rig();+ await t.w.dirs(t.record, ['alpha', 'beta']);+ expect(t.log).toEqual(['/bin/mkdir -p -- /people/pat/sessions/C1-1-1 /people/pat/ws /people/pat/wt/C1-1-1/alpha /people/pat/wt/C1-1-1/beta']);+ });++ it('prepare: one ws-add.sh for all repositories, then the record\'s copy and the root files by tar, then `repos` in the record', async () => {+ const t = rig();+ const { record, addMs } = await t.w.prepare(ID, ['alpha', 'beta']);+ expect(t.log).toEqual(['ws-add.sh 1 alpha beta=trunk', 'ws-add.sh 0 <tar']);+ expect(t.runs[0].args.slice(0, 3)).toEqual(['/clones', '/workspace', 'sp/C1-1-1']);+ expect(t.runs[0].timeoutMs).toBe(60_000);+ expect(record.repos).toEqual({+ alpha: { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc123' },+ beta: { branch: 'sp/C1-1-1', from: 'origin/trunk', base: 'abc123' },+ });+ expect(t.records.get(ID)).toEqual(record);+ expect(addMs).toBeGreaterThanOrEqual(0);+ const tar = t.runs[1].stdin!;+ expect(tarNames(tar)).toEqual(['.fork.json', 'AGENTS.md']);+ expect(JSON.parse(tarText(tar, '.fork.json'))).toEqual({ key: 'C1:1.1', owner: 'pat', createdAt: t.record.createdAt, ms: addMs, repos: record.repos });+ const agents = tarText(tar, 'AGENTS.md');+ expect(agents).toContain('house rules');+ expect(agents).toContain('lazy'); // the index of what is not checked out+ // Fetched a moment ago: the next thread's run does not fetch again.+ const next = rig();+ await next.w.prepare(ID, ['alpha', 'beta']);+ expect(next.log[0]).toBe('ws-add.sh 0 alpha beta=trunk');+ });++ it('prepare: a repository that could not be added is left out; a run that failed whole leaves all out, and the thread still starts', async () => {+ const one = rig(() => 'alpha\tok\tsp/C1-1-1\tmain\tabc\tcould not resolve host\nbeta\tfailed\tno branch trunk\n');+ expect((await one.w.prepare(ID, ['alpha', 'beta'])).record.repos).toEqual({ alpha: { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc', fetchError: 'could not resolve host' } });+ const none = rig(() => new Error('ws-add.sh: timed out'));+ expect((await none.w.prepare(ID, ['alpha'])).record.repos).toEqual({});+ expect(tarNames(none.runs[1].stdin!)).toEqual(['.fork.json', 'AGENTS.md']);+ });++ it('prepare: no `repos` in the record when the root files could not be written, so the next start prepares again', async () => {+ const t = rig();+ const scripts = t.runs;+ const w = sandboxWorkspaces({+ as: { settled: async () => {}, run: async () => '', podman: async () => '' }, records: t.records, mounts: mounts({ as: { settled: async () => {}, run: async () => '', podman: async () => '' }, root: '/opt/r1', dataDir: data }), pid: async () => 1,+ scripts: () => ({ clones: '/clones', workspace: () => '/workspace', run: async (_s, args, o) => {+ scripts.push({ args, timeoutMs: o.timeoutMs });+ if (o.stdin) throw new Error('ws-add.sh: tar: write error');+ return 'alpha\tok\tb\tmain\tabc\t\n';+ } }),+ });+ await expect(w.prepare(ID, ['alpha'])).rejects.toThrow('write error');+ expect(t.records.get(ID)?.repos).toBeUndefined();+ });++ it('checkout: resolved against the definition, cloned by a helper, its two mounts added, its worktree added, the record and its copy updated', async () => {+ const t = rig();+ await t.w.prepare(ID, ['alpha']);+ t.log.length = 0;+ const out = await t.w.checkout(ID, ['acme/lazy', 'nope', '../alpha', 'lazy']);+ expect(out).toEqual(expect.arrayContaining([+ { name: 'lazy', dir: 'lazy', branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc123' },+ { name: 'nope', dir: 'nope', branch: 'sp/C1-1-1', from: '', base: '', error: 'no repository nope in this workspace; the list is in AGENTS.md' },+ expect.objectContaining({ name: '../alpha', error: expect.stringContaining('no repository') }),+ ]));+ expect(out.length).toBe(3);+ expect(t.log).toEqual([+ '/bin/mkdir -p -- /people/pat/sessions/C1-1-1 /people/pat/ws /people/pat/wt/C1-1-1/lazy',+ `podman unshare python3 -I /opt/r1/bin/sandbox-mount.py 4242 ${ID} pat`,+ 'ws-add.sh 0 lazy',+ 'ws-add.sh 0 <tar',+ ]);+ expect(Object.keys(t.records.get(ID)!.repos!)).toEqual(['alpha', 'lazy']);+ const tar = t.runs.at(-1)!.stdin!;+ expect(tarNames(tar)).toEqual(['.fork.json']); // AGENTS.md is the session's by now+ expect(Object.keys(JSON.parse(tarText(tar, '.fork.json')).repos)).toEqual(['alpha', 'lazy']);+ });++ it('checkout: a repository whose worktree could not be added says why, and the record does not gain it', async () => {+ const t = rig((args) => (args.includes('alpha') ? 'alpha\tok\tb\tmain\tabc\t\n' : 'lazy\tfailed\tdisk full\n'));+ await t.w.prepare(ID, ['alpha']);+ expect(await t.w.checkout(ID, ['lazy'])).toEqual([{ name: 'lazy', dir: 'lazy', branch: 'sp/C1-1-1', from: '', base: '', error: 'disk full' }]);+ expect(Object.keys(t.records.get(ID)!.repos!)).toEqual(['alpha']);+ });++ it('checkout without a definition says so; touch marks the thread used', async () => {+ const t = rig();+ const before = t.records.get(ID)!.usedAt;+ t.w.touch(ID);+ expect(Date.parse(t.records.get(ID)!.usedAt)).toBeGreaterThan(Date.parse(before));+ t.w.touch('ffffffffffffffff'); // no record: nothing+ delete process.env.SP_DEFINITION;+ try {+ await expect(t.w.checkout(ID, ['alpha'])).rejects.toThrow(NO_DEFINITION);+ expect(t.w.repos(t.record)).toEqual([]);+ } finally {+ process.env.SP_DEFINITION = definition;+ }+ });+});diff --git a/computer/src/host/sandbox/workspace.ts b/computer/src/host/sandbox/workspace.tsnew file mode 100644index 00000000..0a813083--- /dev/null+++ b/computer/src/host/sandbox/workspace.ts@@ -0,0 +1,246 @@+// A thread's workspace when the thread runs in a container (work 103,+// "Sequences"): which repositories it gets, the directories its mounts need,+// its worktrees and root files (`prepare`), and repositories added later+// (`checkout`). The sandbox record is the fork record: it says which+// repositories the thread has, and `.fork.json` in the workspace is a copy the+// session reads, never read back.+//+// Invariants:+// - The host runs no git and writes no file in a workspace, a clone or a+// registry: worktrees are added by bin/ws-add.sh inside the thread's+// container, as the session's user, and root files reach the workspace as a+// tar stream on that script's stdin. The host only makes the empty+// directories the mounts need, as the runners' user, before anything is+// mounted.+// - A repository's name comes from the definition or the record, never from a+// session: `checkout` resolves what the session asked for against the+// definition before it names a path.+// - A record has `repos` only once the workspace was prepared whole (worktrees+// added, root files unpacked): a start that finds none prepares it again,+// and ws-add.sh leaves what is already there as it is.+// - One clone, one worktree operation at a time (clones.ts `serial`), all of+// a thread's clones held for the one run that adds its worktrees.+// - A repository that cannot be added is left out with a warning, not fatal.++import { lstatSync, readFileSync } from 'node:fs';+import { log } from '../../log.js';+import type { CheckoutResult, Person } from '../../protocol.js';+import {+ cloneRepo, errText, fetchedAt, forkFetchFresh, freshness, isClone, prepareInBackground, safeKey, serial, workspacePrepared,+} from '../../workspaces/clones.js';+import { type Definition, isLazy, loadDefinition, workspacesEnabled } from '../../workspaces/definition.js';+import { findRepo, type ForkInfo } from '../../workspaces/fork.js';+import { FORK_FILE } from '../../workspaces/idle.js';+import { repoIndex } from '../../workspaces/repo-index.js';+import { rows, type ScriptRunner } from '../../workspaces/script-runner.js';+import { CLONES, type Mounts, WORKSPACE } from './mounts.js';+import type { AsRunner } from './podman.js';+import type { Bind } from './podman-args.js';+import type { Records, SandboxRecord } from './records.js';+import { type TarFile, tarOf } from './tar.js';++/** ws-add.sh in a session, in all (the spec's "Exec `ws-add.sh`"); each of its fetches has 5 s inside the script. */+export const ADD_TIMEOUT_MS = 60_000;+const MKDIR_TIMEOUT_MS = 10_000;+export const NO_DEFINITION = 'this host has no workspace definition; there is nothing to check out';++type Repos = NonNullable<SandboxRecord['repos']>;++export interface WorkspaceDeps {+ as: AsRunner;+ records: Records;+ mounts: Mounts;+ /** `sandboxScripts.sessionScripts`: the scripts in a thread's running container. */+ scripts(id: string): ScriptRunner;+ /** `containers.pid`: the running container's first process. */+ pid(id: string): Promise<number>;+}++export type SandboxWorkspace = ReturnType<typeof sandboxWorkspaces>;++/** `fn` with every one of these clones' worktree locks held, taken in one order whoever asks. */+const holding = <T>(clones: string[], fn: () => Promise<T>): Promise<T> =>+ [...new Set(clones)].sort().reduceRight<() => Promise<T>>((inner, c) => () => serial(c, inner), fn)();++/** AGENTS.md and the other root files of the definition, as text, with the repository index when some repository is not checked out. */+function rootFiles(def: Definition, checkedOut: string[]): TarFile[] {+ const files = new Map<string, string>();+ for (const [target, source] of Object.entries(def.rootFiles)) {+ try {+ files.set(target, readFileSync(source, 'utf8'));+ } catch (e) {+ log.warn(`workspaces: root file ${target}: ${errText(e)}`);+ }+ }+ const index = repoIndex(def.repos, new Set(checkedOut));+ if (index) files.set('AGENTS.md', `${files.get('AGENTS.md') ?? ''}\n${index}`);+ return [...files].map(([name, text]) => ({ name, text }));+}++export function sandboxWorkspaces(d: WorkspaceDeps) {+ const { mounts: m } = d;+ const branchOf = (r: SandboxRecord) => `sp/${safeKey(r.key)}`;+ const need = (id: string) => {+ const r = d.records.get(id);+ if (!r) throw new Error(`no sandbox record ${id}`);+ return r;+ };+ const cloned = (person: string, name: string) => {+ try {+ return isClone(m.clone(person, name));+ } catch {+ return false; // not a name for a path+ }+ };++ /** The repositories a start mounts: the record's once it has any, else the definition's; only those whose clone is there. */+ function repos(r: SandboxRecord): string[] {+ const names = r.repos ? Object.keys(r.repos) : workspacesEnabled() ? loadDefinition().repos.filter((x) => !x.unpublished).map((x) => x.name) : [];+ return names.filter((name) => cloned(r.person, name));+ }++ /** True when the thread has a workspace on this host, whatever its record says. */+ const there = (person: string, key: string) => {+ try {+ return !!lstatSync(m.workspace({ person, key }), { throwIfNoEntry: false });+ } catch {+ return true; // not to be looked at: not known to be absent+ }+ };++ /**+ * The thread's workspace, the person's clones (which every helper container mounts, also one that only reads the+ * workspace of a thread with no repository) and the thread's registry for each of these repositories, made as the+ * runners' user. Safe to repeat.+ */+ async function dirs(r: SandboxRecord, names: string[]): Promise<void> {+ await d.as.run(['/bin/mkdir', '-p', '--', m.workspace(r), m.clones(r.person), ...names.map((name) => m.registry(r, name))], { timeoutMs: MKDIR_TIMEOUT_MS });+ }++ /** What a start mounts, in order (mounts.ts). */+ const binds = (r: SandboxRecord, names: string[], journalDir?: string): Bind[] => m.bindsFor(r, names, journalDir);+ const mount = (id: string, pid: number, person: string, b: Bind[]) => m.applyMounts(id, pid, person, b);++ /** One run of ws-add.sh in the thread's container for all of `names`: what was added, and why the rest was not. */+ async function add(r: SandboxRecord, id: string, names: string[], def: Definition): Promise<{ added: Repos; failed: Map<string, string> }> {+ const added: Repos = {};+ const failed = new Map<string, string>();+ if (!names.length) return { added, failed };+ const clones = new Map(names.map((name) => [name, m.clone(r.person, name)] as const));+ await holding([...clones.values()], async () => {+ // One flag for the run: fetched unless every clone's refs are fresh (fetch-schedule.ts).+ const fetch = [...clones.values()].some((c) => !freshness.fresh(c, forkFetchFresh()));+ const started = Date.now();+ // The branch forks start from, when the definition names it; the script finds origin/HEAD otherwise.+ const args = names.map((name) => {+ const b = def.repos.find((x) => x.name === name)?.branch;+ return b ? `${name}=${b}` : name;+ });+ const out = rows(await d.scripts(id).run('ws-add.sh', [CLONES, WORKSPACE, branchOf(r), fetch ? '1' : '0', ...args], { timeoutMs: ADD_TIMEOUT_MS }));+ for (const name of names) {+ const [status, ...f] = out.get(name) ?? [];+ if (status !== 'ok') {+ failed.set(name, status === 'failed' ? f[0] || 'failed' : `no result for ${name}`);+ continue;+ }+ const [branch, base, head, fetchError] = f;+ added[name] = { branch, from: `origin/${base}`, base: head, ...(fetchError && { fetchError }) };+ if (fetch && !fetchError) {+ fetchedAt.set(clones.get(name)!, new Date().toISOString());+ freshness.fetchedFrom(clones.get(name)!, started);+ }+ }+ });+ return { added, failed };+ }++ /** The session's copy of the record, in the shape a fork's record has always had. */+ const forkFile = (r: SandboxRecord, all: Repos, ms: number): TarFile => {+ const info: ForkInfo = { key: r.key, owner: r.person, createdAt: r.createdAt, ms, repos: all };+ return { name: FORK_FILE, text: JSON.stringify(info, null, 2) + '\n' };+ };+ /** Files into the workspace's root: unpacked in the thread's container, as the session's user. */+ const unpack = (id: string, r: SandboxRecord, files: TarFile[]) =>+ d.scripts(id).run('ws-add.sh', [CLONES, WORKSPACE, branchOf(r), '0'], { stdin: tarOf(files), timeoutMs: ADD_TIMEOUT_MS });++ /**+ * Make the workspace of a thread whose record has no `repos` yet, in its running container: a worktree of each of+ * `names` (those `repos` gave this start, mounted already), then `.fork.json` and the root files. Resolves with the+ * record, now with `repos`, and the time the worktrees took. Rejects when the root files could not be written.+ */+ async function prepare(id: string, names: string[]): Promise<{ record: SandboxRecord; addMs: number }> {+ return serial(`sandbox:${id}`, async () => {+ const r = need(id);+ const def = loadDefinition();+ const person = { dir: r.person } as Person;+ // Nothing here waits on a clone (work 056): eager repositories still missing are cloned in the background.+ if (!workspacePrepared(person) || def.repos.some((x) => !x.unpublished && !isLazy(x) && !cloned(r.person, x.name))) prepareInBackground(person);+ const t0 = Date.now();+ const { added, failed } = await add(r, id, names, def).catch((e) => ({ added: {} as Repos, failed: new Map(names.map((name) => [name, errText(e)])) }));+ const addMs = Date.now() - t0;+ for (const [name, why] of failed) log.warn(`workspaces: ${name} left out of ${r.key}: ${why}`);+ await unpack(id, r, [forkFile(r, added, addMs), ...rootFiles(def, Object.keys(added))]);+ const record = { ...need(id), repos: added };+ d.records.write(record);+ log.info(`workspaces: ${Object.keys(added).length} repos in the container of ${r.key} (${r.person}) in ${addMs} ms`);+ for (const [name, x] of Object.entries(added)) if (x.fetchError) log.warn(`workspaces: ${name} from cached ${x.from} (${x.base.slice(0, 8)}); fetch failed: ${x.fetchError}`);+ return { record, addMs };+ });+ }++ /**+ * Check repositories out into a running thread (the session's `checkout_repo`): clone each if missing, in a helper+ * container, then mount it and its registry and add its worktree. `wanted` holds definition names or `owner/name`.+ * Each repository succeeds or fails on its own; the record gains the ones checked out.+ */+ async function checkout(id: string, wanted: string[]): Promise<CheckoutResult[]> {+ if (!workspacesEnabled()) throw new Error(NO_DEFINITION);+ const r = need(id);+ const def = loadDefinition();+ const branch = branchOf(r);+ const results = new Map<string, CheckoutResult>();+ const fail = (name: string, error: string) => void results.set(name, { name, dir: name, branch, from: '', base: '', error });+ const names: string[] = [];+ await Promise.all(+ [...new Set(wanted.map((w) => w.trim()).filter(Boolean))].map(async (want) => {+ const repo = findRepo(def.repos, want);+ if (!repo) return fail(want, `no repository ${want} in this workspace; the list is in AGENTS.md`);+ if (repo.unpublished) return fail(repo.name, `${repo.name} is not published yet`);+ try {+ const t0 = Date.now();+ if (await cloneRepo(m.clone(r.person, repo.name), repo)) log.info(`workspaces: ${repo.name} cloned on demand for ${r.key} in ${Date.now() - t0} ms`);+ if (!names.includes(repo.name)) names.push(repo.name);+ } catch (e) {+ fail(repo.name, errText(e));+ }+ }),+ );+ if (names.length)+ await serial(`sandbox:${id}`, async () => {+ try {+ await dirs(r, names);+ await mount(id, await d.pid(id), r.person, m.repoBinds(r, names));+ const { added, failed } = await add(r, id, names, def);+ for (const [name, why] of failed) fail(name, why);+ if (!Object.keys(added).length) return;+ // The record first read may be older than a checkout that ran meanwhile.+ const now = need(id);+ const all = { ...now.repos, ...added };+ await unpack(id, now, [forkFile(now, all, 0)]);+ d.records.write({ ...need(id), repos: all });+ for (const [name, x] of Object.entries(added)) results.set(name, { name, dir: name, ...x });+ } catch (e) {+ for (const name of names) if (!results.has(name)) fail(name, errText(e));+ }+ });+ return [...results.values()];+ }++ /** Mark the thread as used now (a delivery): what pruning counts from. */+ function touch(id: string) {+ const r = d.records.get(id);+ if (r) d.records.write({ ...r, usedAt: new Date().toISOString() });+ }++ return { repos, there, dirs, binds, mount, prepare, checkout, touch };+}diff --git a/computer/src/host/spare-frames.test.ts b/computer/src/host/spare-frames.test.tsnew file mode 100644index 00000000..58ddfc8d--- /dev/null+++ b/computer/src/host/spare-frames.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';+import type { RunnerToHost } from '../protocol.js';+import { NO_THREAD, refusal, spareMay } from './spare-frames.js';++describe('a runner that serves no thread', () => {+ it('is heard on its state, its telemetry and its replies only', () => {+ const heard: RunnerToHost['t'][] = ['spare', 'telemetry', 'reply'];+ const all: RunnerToHost['t'][] = ['report', 'spare', 'token', 'spawn', 'read', 'post', 'preview', 'unpreview', 'secret-request', 'checkout', 'telemetry', 'out-of-credits', 'model-denied', 'reply'];+ expect(all.filter((t) => spareMay({ t } as RunnerToHost))).toEqual(heard);+ });++ it('gets each request answered with an error under the request\'s id', () => {+ const answer = (t: string) => refusal({ t, id: 'q' } as RunnerToHost);+ expect(answer('token')).toEqual({ t: 'token', id: 'q', error: NO_THREAD });+ expect(['spawn', 'read', 'post', 'secret-request', 'preview', 'unpreview', 'checkout'].map((t) => answer(t)?.t)).toEqual(['spawned', 'thread', 'posted', 'secret-asked', 'previewed', 'previewed', 'checked-out']);+ expect(refusal({ t: 'out-of-credits' })).toBeUndefined();+ expect(refusal({ t: 'model-denied', model: 'a', fallbackTo: 'b' })).toBeUndefined();+ });+});diff --git a/computer/src/host/spare-frames.ts b/computer/src/host/spare-frames.tsnew file mode 100644index 00000000..33ba4ecb--- /dev/null+++ b/computer/src/host/spare-frames.ts@@ -0,0 +1,32 @@+// What a runner in a container that serves no thread may say (work 103, step+// 10): a spare, from its start until it is bound (sandbox/spares.ts `bind`).+//+// Invariant: on a `podman` host no frame of a runner is handled for the+// session ''. A runner with no record has no thread to ask anything for: its+// state (`spare`), its telemetry and its replies to the host's calls are read;+// a request gets its answer with an error, at once, and nothing else is read.+// From the moment it is bound its key is its record's (start-runner.ts), so+// what it asks for between the bind and the claim's answer is that thread's.++import type { HostToRunner, RunnerToHost } from '../protocol.js';++export const NO_THREAD = 'this runner serves no thread';++/** The answer's `t` for each request a runner makes. */+const ANSWERS = {+ token: 'token',+ spawn: 'spawned',+ read: 'thread',+ post: 'posted',+ 'secret-request': 'secret-asked',+ preview: 'previewed',+ unpreview: 'previewed',+ checkout: 'checked-out',+} as const;++/** True for what a runner with no thread is heard on. A `report` is not among them: start-runner.ts stops the runner that sends one. */+export const spareMay = (m: RunnerToHost) => m.t === 'spare' || m.t === 'telemetry' || m.t === 'reply';++/** The refusal of a request from a runner with no thread; undefined for a frame that has no answer (it is dropped). */+export const refusal = (m: RunnerToHost): HostToRunner | undefined =>+ m.t in ANSWERS && 'id' in m ? ({ t: ANSWERS[m.t as keyof typeof ANSWERS], id: m.id, error: NO_THREAD } satisfies HostToRunner) : undefined;diff --git a/computer/src/host/start-runner-spares.test.ts b/computer/src/host/start-runner-spares.test.tsnew file mode 100644index 00000000..27e361af--- /dev/null+++ b/computer/src/host/start-runner-spares.test.ts@@ -0,0 +1,246 @@+// Step 10 of work 103: how a new thread on a `podman` host takes a spare+// container, and what happens when it cannot (start-runner.ts).+import net from 'node:net';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { lines, send } from '../ipc.js';+import type { HostToRunner, RunnerToHost, SessionSpec } from '../protocol.js';+import { createTelemetry } from '../telemetry/emitter.js';+import type { TelemetryEvent } from '../telemetry/envelope.js';+import type { Bound, SandboxSpares } from './sandbox/spares.js';+import type { SandboxStarts, Started } from './sandbox/start.js';+import { type Runner, type StartDeps, runnerStarts } from './start-runner.js';++vi.mock('../workspaces/index.js', async (orig) => ({ ...(await orig<typeof import('../workspaces/index.js')>()), workspacesEnabled: () => true, workspacePrepared: () => true }));++const owner = { dir: 'pat', gitName: 'Pat', gitEmail: '[email protected]' };+const spec: SessionSpec = { key: 'C1:1.1', kind: 'thread', owner, title: 't', mode: 'default', sdkSessionId: 'old' };+const ID = 'aaaaaaaaaaaaaaaa';+const record = { id: ID, person: 'pat', key: 'C1:1.1', createdAt: '', usedAt: '', repos: {} };+const creds = { slackBotToken: 'x', slackBotUserId: 'U', anthropicApiKey: 'k' };+const open: (net.Socket | net.Server)[] = [];+afterEach(() => {+ for (const s of open.splice(0)) 'destroy' in s ? s.destroy() : s.close();+});++/** A connected pair: the host's end, and what the runner's end was sent; `answer` is the runner's reply to a call. */+async function pair(answer: (m: HostToRunner & { id?: string }) => RunnerToHost | RunnerToHost[] | undefined) {+ const file = path.join(mkdtempSync(path.join(tmpdir(), 'sp-')), 'r.sock');+ const got: HostToRunner[] = [];+ let runner!: net.Socket;+ const server = net.createServer((s) => {+ open.push((runner = s));+ lines(s, (m: HostToRunner) => {+ got.push(m);+ for (const a of [answer(m) ?? []].flat()) send(s, a);+ if (m.t === 'exit') s.end();+ });+ });+ await new Promise<void>((r) => server.listen(file, r));+ const sock = net.createConnection(file);+ await new Promise((r) => sock.once('connect', r));+ open.push(sock, server);+ await vi.waitFor(() => expect(runner).toBeDefined());+ return { sock, got, say: (m: RunnerToHost) => send(runner, m) };+}++async function rig(o: { known?: boolean; bind?: () => Promise<Bound>; answer?: Parameters<typeof pair>[0]; noSpares?: boolean; unbound?: boolean } = {}) {+ const log: string[] = [];+ /** What the model proxy was asked for a claim, and after which step. */+ const proxy: string[] = [];+ const sent: TelemetryEvent[] = [];+ const tm = createTelemetry({ service: 'host', version: 'v', region: 'r', send: (b) => void sent.push(...b.events) });+ const spare = await pair(o.answer ?? ((m) => (m.t === 'claim' ? { t: 'reply', id: m.id!, ok: true } : undefined)));+ const cold = await pair(() => undefined);+ const pool = new Set<Runner>();+ const spares = {+ launch: async () => ({ id: ID, run: `/run/sp/sandbox/${ID}`, sock: spare.sock, createMs: 1, startMs: 2 }),+ known: () => !!o.known,+ bind: async (id, s) => {+ log.push(`bind ${id} ${s.key}`);+ if (o.bind) return o.bind();+ const { sdkSessionId: _s, ...session } = s;+ return { record, run: `/run/sp/sandbox/${ID}`, session, api: undefined, readyMs: 2, mountMs: 3, addMs: 4 };+ },+ discard: async (id) => void log.push(`removed ${id}`),+ gone: async (id) => void log.push(`gone ${id}`),+ during: (fn) => fn(),+ claimed: (id) => (log.push(`claimed ${id}`), record),+ turn: (_s, fn) => fn(),+ } as Partial<SandboxSpares> as SandboxSpares;+ const started: Started = { record, run: `/run/sp/sandbox/${ID}`, sock: cold.sock, session: spec, resumed: true, abandon: async () => void log.push('abandoned') };+ const sandbox: SandboxStarts = { start: async () => (log.push('cold start'), started) };+ const d = {+ tm, sandbox, spares, image: 'ghcr.io/x/y:64a672bb773b059c', launch: { mode: 'podman' }, run: '/run/sp',+ pool: {+ enabled: true,+ add: (r: Runner) => pool.add(r),+ changed: () => {},+ take: (kind: string | undefined) => {+ log.push(`take of kind ${kind}`);+ const r = [...pool][0];+ return r ? (pool.delete(r), r) : 'none';+ },+ },+ serveTokens: (run: string, id: string) => (log.push(`tokens ${run} ${id}`), { close: () => void log.push('tokens closed') }),+ creds: () => undefined,+ models: {+ up: true, canSpare: () => !o.noSpares, kind: (key: string) => `kind-of-${key}`, forRunner: () => undefined,+ claim: async (id: string, key: string, harness: string) => {+ proxy.push(`claim ${id} ${key} ${harness} after ${log.at(-1)}`);+ if (o.unbound) throw new Error('the model proxy did not bind it');+ },+ },+ register: (r: Runner) => void log.push(`registered ${r.key}`), closed: () => {}, exit: (s: net.Socket) => (send(s, { t: 'exit' }), log.push('exit sent'), s.end()),+ message: (r: Runner, m: RunnerToHost) => (m.t === 'reply' ? r.calls.get(m.id)?.(m) : m.t === 'report' ? void (r.report = m.report) : void log.push(`${m.t} handled for '${r.key}'`)),+ stopSandbox: async (id: string) => void log.push(`stopped ${id}`),+ toGateway: (m: { t: string }) => void log.push(`gateway ${m.t}`), fillPool: () => void log.push('fill'),+ } as unknown as StartDeps;+ const starts = runnerStarts(d);+ await starts.launchSpare();+ const events = async () => (await tm.flush(), sent);+ return { log, proxy, starts, pool, spare, cold, events, tm };+}++describe('a new thread on a podman host with a spare', () => {+ it('the spare is adopted under its own run root, as nobody\'s', async () => {+ const t = await rig();+ expect(t.log).toEqual([`tokens /run/sp/sandbox/${ID} ${ID}`]);+ expect([...t.pool][0]).toMatchObject({ id: ID, key: '' });+ expect([...t.pool][0].sandbox).toBeUndefined();+ expect((await t.events()).find((e) => e.event_name === 'pool.spare_started')).toMatchObject({ data: { launch_mode: 'podman', image: '64a672bb773b', 'container.create_ms': 1, 'container.start_ms': 2 } });+ expect(t.tm.dropped).toEqual({});+ });++ it('takes it: bound first, at the model proxy next, then credentials and claim into /workspace with no transcript; the pool is filled after', async () => {+ const t = await rig();+ t.log.length = 0;+ const r = await t.starts.startRunner(spec, {}, creds);+ expect(r).toMatchObject({ id: ID, key: 'C1:1.1', sandbox: { record }, cold: { resumed: false, prewarmed: true } });+ expect(t.log).toEqual(['take of kind kind-of-C1:1.1', `bind ${ID} C1:1.1`, `claimed ${ID}`, 'registered C1:1.1', 'fill']);+ const claim = t.spare.got.find((m) => m.t === 'claim') as Extract<HostToRunner, { t: 'claim' }>;+ expect(t.spare.got.map((m) => m.t)).toEqual(['credentials', 'claim']);+ expect(t.proxy).toEqual([`claim ${ID} C1:1.1 claude after bind ${ID} C1:1.1`]); // the session's route is the spare's before it is claimed+ expect(claim.session).toMatchObject({ key: 'C1:1.1', forkPath: '/workspace' });+ expect(claim.session).not.toHaveProperty('sdkSessionId');+ expect((await t.events()).find((e) => e.event_name === 'runner.claimed')).toMatchObject({ data: { launch_mode: 'podman', image: '64a672bb773b', 'container.mount_ms': 3, 'container.add_ms': 4 } });+ expect(t.tm.dropped).toEqual({});+ });++ it.each([+ ['could not be bound', { bind: () => Promise.reject(new Error('mount refused')) }, 'bind'],+ ['the model proxy did not bind to the session', { unbound: true }, 'refused'],+ ['refused the claim', { answer: (m: HostToRunner & { id?: string }) => (m.t === 'claim' ? ({ t: 'reply', id: m.id!, ok: false, error: 'no' } as RunnerToHost) : undefined) }, 'refused'],+ ])('a spare that %s is told to exit and removed, and the delivery starts cold', async (_n, o, reason) => {+ const t = await rig(o);+ t.log.length = 0;+ const r = await t.starts.startRunner(spec, {}, creds);+ expect(r).toMatchObject({ id: ID, key: 'C1:1.1', sock: t.cold.sock });+ expect(t.log).toEqual(['take of kind kind-of-C1:1.1', `bind ${ID} C1:1.1`, 'exit sent', `removed ${ID}`, 'tokens closed', 'cold start', `tokens /run/sp/sandbox/${ID} ${ID}`, 'registered C1:1.1', 'fill']);+ await new Promise((x) => setTimeout(x, 20));+ expect(t.spare.got.at(-1)).toEqual({ t: 'exit' });+ expect((await t.events()).find((e) => e.event_name === 'pool.spare_missed')).toMatchObject({ data: { reason } });+ expect(t.tm.dropped).toEqual({});+ });++ it('a thread that has a record resumes: the pool is not asked', async () => {+ const t = await rig({ known: true });+ t.log.length = 0;+ await t.starts.startRunner(spec, {}, creds);+ expect(t.log).toEqual(['cold start', `tokens /run/sp/sandbox/${ID} ${ID}`, 'registered C1:1.1', 'fill']);+ expect(t.pool.size).toBe(1);+ });++ it('with no model route to park a spare on (model-access.ts `canSpare`), a thread starts cold', async () => {+ const t = await rig({ noSpares: true });+ t.log.length = 0;+ await t.starts.startRunner(spec, {}, creds);+ expect(t.log[0]).toBe('cold start');+ });++ it('a spare the pool evicts is not asked to go, which it could ignore: its socket is destroyed and it is removed by container', async () => {+ const t = await rig();+ t.log.length = 0;+ const [r] = [...t.pool];+ t.starts.evict(r);+ expect(r.sock.destroyed).toBe(true);+ expect(t.log).toEqual([`gone ${ID}`]);+ await new Promise((x) => setTimeout(x, 20));+ expect(t.spare.got).toEqual([]);+ });++ it('a spare that reports a session while it is nobody\'s is stopped', async () => {+ const t = await rig();+ t.log.length = 0;+ t.spare.sock.emit('data', Buffer.from(`${JSON.stringify({ t: 'report', report: { key: 'C9:9.9', status: 'idle' } })}\n`));+ await new Promise((r) => setTimeout(r, 20));+ expect(t.log[0]).toBe(`stopped ${ID}`); // not asked to go, which it could ignore+ expect(t.spare.sock.destroyed).toBe(true);+ expect([...t.pool][0]?.report).toBeUndefined();+ });++ it('a claimed spare that reports another thread than its record\'s is stopped', async () => {+ const t = await rig();+ const r = await t.starts.startRunner(spec, {}, creds);+ t.log.length = 0;+ r.sock.emit('data', Buffer.from(`${JSON.stringify({ t: 'report', report: { key: 'C9:9.9', status: 'idle' } })}\n`));+ await new Promise((x) => setTimeout(x, 20));+ expect(t.log[0]).toBe(`stopped ${ID}`);+ expect(r.sock.destroyed).toBe(true);+ });++ // A frame handled for the session '' would be asked of the gateway, the token broker and the previews under no thread's name.+ const asks: RunnerToHost[] = [+ { t: 'token', id: 'q1' },+ { t: 'preview', id: 'q2', req: { port: 3000 } },+ { t: 'unpreview', id: 'q3', req: { name: 'x' } },+ { t: 'spawn', id: 'q4', req: {} as never },+ { t: 'read', id: 'q5', req: {} as never },+ { t: 'post', id: 'q6', req: {} as never },+ { t: 'secret-request', id: 'q7', req: {} as never },+ { t: 'checkout', id: 'q8', repos: ['a'] },+ { t: 'out-of-credits' },+ { t: 'model-denied', model: 'm', fallbackTo: 'n' },+ ];+ const refusals = ['token', 'previewed', 'previewed', 'spawned', 'thread', 'posted', 'secret-asked', 'checked-out'].map((t, i) => ({ t, id: `q${i + 1}`, error: 'this runner serves no thread' }));++ it('what a parked spare asks for is refused, never handled: it serves no thread', async () => {+ const t = await rig();+ t.log.length = 0;+ for (const m of asks) t.spare.say(m);+ await vi.waitFor(() => expect(t.spare.got.filter((m) => m.t !== 'credentials')).toEqual(refusals));+ expect(t.log).toEqual([]);+ });++ it('while it is being bound it is still nobody\'s: a token it asks for then is refused, and never asked for the session \'\'', async () => {+ let bound!: (b: Bound) => void;+ const t = await rig({ bind: () => new Promise<Bound>((r) => (bound = r)) });+ t.log.length = 0;+ const starting = t.starts.startRunner(spec, {}, creds);+ await vi.waitFor(() => expect(t.log).toContain(`bind ${ID} C1:1.1`));+ for (const m of asks) t.spare.say(m);+ await vi.waitFor(() => expect(t.spare.got).toEqual(refusals));+ bound({ record, run: `/run/sp/sandbox/${ID}`, session: spec, api: undefined, readyMs: 2, mountMs: 3, addMs: 4 });+ await starting;+ expect(t.log.filter((l) => l.includes('handled'))).toEqual([]);+ });++ it('once bound, before the claim is answered, what it asks for is its record\'s thread\'s', async () => {+ const t = await rig({ answer: (m) => (m.t === 'claim' ? [{ t: 'token', id: 'q1' }, { t: 'preview', id: 'q2', req: { port: 3000 } }, { t: 'reply', id: m.id!, ok: true }] : undefined) });+ t.log.length = 0;+ const r = await t.starts.startRunner(spec, {}, creds);+ expect(r.key).toBe('C1:1.1');+ expect(t.log).toEqual(['take of kind kind-of-C1:1.1', `bind ${ID} C1:1.1`, "token handled for 'C1:1.1'", "preview handled for 'C1:1.1'", `claimed ${ID}`, 'registered C1:1.1', 'fill']);+ });++ it('a spare whose claim failed after it was bound is never registered, and is not a spare again', async () => {+ const t = await rig({ answer: (m) => (m.t === 'claim' ? [{ t: 'token', id: 'q1' }, { t: 'reply', id: m.id!, ok: false, error: 'no' }] : undefined) });+ t.log.length = 0;+ const r = await t.starts.startRunner(spec, {}, creds);+ expect(r.sock).toBe(t.cold.sock);+ expect(t.log.filter((l) => l.includes('handled'))).toEqual(["token handled for 'C1:1.1'"]);+ expect(t.pool.size).toBe(0);+ });+});diff --git a/computer/src/host/start-runner.test.ts b/computer/src/host/start-runner.test.tsnew file mode 100644index 00000000..2f86f082--- /dev/null+++ b/computer/src/host/start-runner.test.ts@@ -0,0 +1,100 @@+import net from 'node:net';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';+import { send } from '../ipc.js';+import type { SessionSpec } from '../protocol.js';+import { createTelemetry } from '../telemetry/emitter.js';+import type { SandboxStarts, Started } from './sandbox/start.js';+import { type StartDeps, runnerStarts } from './start-runner.js';++const owner = { dir: 'pat', gitName: 'Pat', gitEmail: '[email protected]' };+const spec: SessionSpec = { key: 'C1:1.1', kind: 'thread', owner, title: 't', mode: 'default' };+const record = { id: 'aaaaaaaaaaaaaaaa', person: 'pat', key: 'C1:1.1', createdAt: '', usedAt: '' };++/** A host whose sandbox start hands back `sock`; `log` says what was done with it. */+function rig(sock: net.Socket) {+ const log: string[] = [];+ const started: Started = { record, run: '/run/sp/sandbox/a', sock, session: spec, resumed: false, abandon: async () => void log.push('abandoned') };+ const sandbox: SandboxStarts = { start: async () => started };+ const d = {+ tm: createTelemetry({ service: 'host', version: 'v', region: 'r', send: () => {} }),+ sandbox,+ serveTokens: () => ({ close: () => void log.push('tokens closed') }),+ creds: () => undefined, models: { up: true, forRunner: () => undefined },+ register: () => void log.push('registered'), closed: () => void log.push('closed'), message: (_r: unknown, m: { t: string }) => void log.push(`message ${m.t}`), exit: () => void log.push('exit sent'),+ stopSandbox: async (id: string) => void log.push(`stopped ${id}`),+ } as unknown as StartDeps;+ return { log, start: () => runnerStarts(d).startRunner(spec, {}),+ /** Host restart: the runner found in the record's container (sandbox/sweep.ts). */+ takeBack: (s: net.Socket) => runnerStarts({ ...d, exit: (x: net.Socket) => (log.push('exit sent'), x.destroy()) } as StartDeps).adopt(record.id, s, { verify: true, sandbox: { record: { ...record, repos: {} }, run: '/run/sp/sandbox/a' } }) };+}++/** A connected pair: the host's end, and the runner's to write its first message on. */+async function pair(): Promise<{ host: net.Socket; runner: net.Socket; close(): void }> {+ const file = path.join(mkdtempSync(path.join(tmpdir(), 'adopt-')), 's');+ const server = net.createServer();+ await new Promise<void>((ok) => server.listen(file, ok));+ const runner = new Promise<net.Socket>((ok) => server.once('connection', ok));+ const host = net.connect(file);+ return { host, runner: await runner, close: () => (host.destroy(), server.close()) };+}++describe('a sandboxed start that is not taken on', () => {+ it('a runner that exited while it started: its container is stopped and its token socket closed', async () => {+ const sock = new net.Socket();+ sock.destroy();+ const t = rig(sock);+ await expect(t.start()).rejects.toThrow('runner exited while it started');+ expect(t.log).toEqual(['abandoned']);+ });++ it('a runner that is there is taken on, and nothing of it is stopped', async () => {+ const sock = new net.Socket();+ const t = rig(sock);+ const r = await t.start();+ expect(r).toMatchObject({ id: record.id, key: 'C1:1.1', sandbox: { record } });+ expect(t.log).toEqual(['registered']);+ sock.destroy();+ });++ it('a runner that reports another thread once it was taken on is not asked to go: its socket is destroyed and its container stopped', async () => {+ const p = await pair();+ const t = rig(p.host);+ await t.start();+ send(p.runner, { t: 'report', report: { key: 'C1:1.1', status: 'idle', forkPath: '/workspace' } });+ send(p.runner, { t: 'report', report: { key: 'C1:9.9', status: 'idle', forkPath: '/workspace' } });+ send(p.runner, { t: 'token', id: 'x' }); // what it sends after is never read+ await new Promise((r) => p.host.once('close', r));+ await new Promise((r) => setImmediate(r));+ expect(p.host.destroyed).toBe(true);+ expect(t.log).toEqual(['registered', 'message report', `stopped ${record.id}`, 'tokens closed', 'closed']);+ p.close();+ });+});++describe('a container found running after a host restart', () => {+ const report = (key: string) => ({ t: 'report', report: { key, status: 'idle', forkPath: '/workspace' } });++ it('is taken back when its first report names its record\'s thread', async () => {+ const p = await pair();+ const t = rig(p.host);+ send(p.runner, report('C1:1.1'));+ expect(await t.takeBack(p.host)).toMatchObject({ id: record.id, key: 'C1:1.1' });+ expect(t.log).toEqual(['registered', 'message report']);+ p.close();+ });++ it('is not taken back when it reports another thread, or says it is a spare: it is told to go', async () => {+ for (const first of [report('C1:9.9'), { t: 'spare', spare: { state: 'parked' } }]) {+ const p = await pair();+ const t = rig(p.host);+ send(p.runner, first);+ await expect(t.takeBack(p.host)).rejects.toThrow(/it reports C1:9.9, not its record's C1:1.1|it says it is a spare/); // at once, not at the adoption timeout+ await new Promise((r) => p.host.once('close', r));+ expect(t.log).toEqual([`stopped ${record.id}`, 'tokens closed']);+ p.close();+ }+ });+});diff --git a/computer/src/host/start-runner.ts b/computer/src/host/start-runner.tsindex 66f91b69..ea8118e8 100644--- a/computer/src/host/start-runner.ts+++ b/computer/src/host/start-runner.ts@@ -1,7 +1,8 @@// Starting runners and taking them on (work 045, 069; split out of host/main.ts// for work 103): `adopt` makes a connected runner the host's (its session's, or// a spare), `startRunner` gets a session its runner (a claimed spare, else a-// cold start in its fork), `launchSpare` starts one for the pool.+// cold start in its fork; on a `podman` host its thread's container,+// sandbox/start.ts), `launchSpare` starts one for the pool.// host/main.ts keeps the registry (`runners`), what a runner's messages mean,// and delivery; it passes those in as `StartDeps`.//@@ -12,6 +13,31 @@// always starts cold, to resume.// - The API token of a cold-started runner goes over its socket, never in// argv or the environment.+// - A sandboxed runner serves the thread of its record (work 103): the key is+// the record's, and a report naming another stops the runner, before or+// after it was taken on. It is not asked to go, which it could ignore: its+// socket is destroyed, so nothing it sends is read again, and its container+// is stopped.+// - A sandboxed runner that started and was not adopted (it exited meanwhile,+// or adoption refused it) leaves no container running and no token socket.+// - On a `podman` host a spare is a container (step 10, sandbox/spares.ts). It+// is made its thread's (record, mounts, worktrees) before `claim` is sent,+// and from then on it is held to that record like any sandboxed runner. One+// that reports a session while it is nobody's is stopped, as any container's+// runner is: its socket destroyed, its container stopped. The claim is made+// in the thread's turn (sandbox/thread-lock.ts), as a start is.+// - On a `podman` host a runner's key is '' exactly while it has no record:+// the two are set together when a spare is bound, before `claim` is sent.+// Until then nothing it asks for is handled (spare-frames.ts); after, it is+// asked for the record's thread, whether or not the claim was answered yet.+// - A spare in a container that leaves is never only asked to: one the pool+// evicts has its socket destroyed and is stopped and Removed by container.+// - A spare taken and not claimed, for whatever reason, is told to exit and+// Removed, and the delivery starts cold under the record's id: a failed+// claim loses no delivery.+// - On a `podman` host the pool is topped up once the start that took a spare+// has ended, not beside it, unless starts kept coming for 10 s+// (sandbox/spares.ts `quiet`).import type net from 'node:net';import { randomBytes } from 'node:crypto';@@ -39,7 +65,11 @@ import { coldStart, forkFor } from './cold-start.js';import { type HostModelAccess, PROXY_DOWN } from './model-access.js';import type { Pool } from './pool.js';import { callRunner as call } from './runner-call.js';-import { launchRunner } from './runner-sockets.js';+import { awaitRunner, launchProcess, launchRunner } from './runner-sockets.js';+import { refusal, spareMay } from './spare-frames.js';+import type { SandboxRecord } from './sandbox/records.js';+import type { Bound, SandboxSpares } from './sandbox/spares.js';+import { type SandboxStarts, WORKSPACE, imageTag } from './sandbox/start.js';import type { ColdStart, Forwarded } from './trace.js';export interface Runner {@@ -64,8 +94,12 @@ export interface Runner {/** The last trace forwarded (also in `<key>.trace.json`), for `turn.abandoned`. */forwarded?: Forwarded;calls: Map<string, (r: { ok: boolean; error?: string }) => void>;+ /** Work 103: the thread's record and run root, for a runner in a container. */+ sandbox?: Sandboxed;}+export interface Sandboxed { record: SandboxRecord; run: RunRoot }+/** What host/main.ts owns and a start needs. Everything is asked for when used, so main.ts may wire it before its parts exist. */export interface StartDeps {tm: Telemetry;@@ -81,8 +115,15 @@ export interface StartDeps {models: Pick<HostModelAccess, 'up' | 'canSpare' | 'kind' | 'spare' | 'claim' | 'closed' | 'forRunner'>;/** Work 084: the session's journal, socket and token for this runner; undefined off the API. */mint(spec: SessionSpec, runnerId: string): Promise<RunnerApi | undefined>;- /** The runner's own token socket, naming the session it serves now (tokens.ts). */- serveTokens(id: string, session: () => string | undefined): { close(): void };+ /** The runner's own token socket below its run root, naming the session it serves now (tokens.ts). */+ serveTokens(run: RunRoot, id: string, session: () => string | undefined): { close(): void };+ /** Work 103: on a `podman` host, how a thread's runner starts; every session then starts through it. */+ sandbox?: SandboxStarts;+ /** Step 10: its spares, and the image they are made from (for telemetry). */+ spares?: SandboxSpares;+ image?: string;+ /** Work 103: stop a runner's container with no grace (sandbox/containers.ts `stop`). */+ stopSandbox?(id: string): Promise<void>;fillPool(): void;/** Run a fork so its workspace events join the delivery's trace. */inFork<T>(f: Dimensions, fn: () => Promise<T>): Promise<T>;@@ -108,9 +149,11 @@ export function runnerStarts(d: StartDeps) {/** Take a connected runner on (adoption.ts): register it as its session's, or as a spare, follow its messages, send it `credentials`.* `key`: the session it was launched for; a verified runner names it in its first report, and one with no session is a spare.* `first`: the delivery's credentials, sent instead of the welcome ones, since the runner starts its harness with the first it gets. */- function adopt(id: string, sock: net.Socket, o: { key?: string; verify?: boolean; first?: HostCredentials; harness?: HarnessName } = {}): Promise<Runner> {- const r: Runner = { id, key: o.key ?? '', sock, lastDelivery: Date.now(), connectedAt: Date.now(), calls: new Map(), harness: o.harness };- const tokens = d.serveTokens(id, () => r.key); // its own token socket names the session it serves now (work 080)+ function adopt(id: string, sock: net.Socket, o: { key?: string; verify?: boolean; first?: HostCredentials; harness?: HarnessName; sandbox?: Sandboxed; run?: RunRoot } = {}): Promise<Runner> {+ const r: Runner = { id, key: o.sandbox?.record.key ?? o.key ?? '', sock, lastDelivery: Date.now(), connectedAt: Date.now(), calls: new Map(), harness: o.harness, sandbox: o.sandbox };+ // Its own token socket names the session it serves now (work 080). A container's is open since before its start (the same one: idempotent).+ // `run`: the run root of a spare in a container, which has no record yet.+ const tokens = d.serveTokens(o.sandbox?.run ?? o.run ?? d.run, id, () => r.key);sock.once('close', () => tokens.close()); // gone with the runnerreturn new Promise((resolve, reject) => {const take = (m?: First) => {@@ -126,19 +169,137 @@ export function runnerStarts(d: StartDeps) {if (c) send(sock, { t: 'credentials', credentials: c } satisfies HostToRunner);resolve(r);};- const stop = (why: string) => {+ /** Set when a sandboxed runner was stopped: what it had already sent is not read either. */+ let refused = false;+ const stopped = (why: string) => {log.warn(`runner ${id}: ${why}; stopping it`);- d.exit(sock);+ if (!d.sandbox) return d.exit(sock);+ refused = true;+ sock.destroy();+ void d.stopSandbox?.(id).catch((e) => log.warn(`sandbox ${id} not stopped: ${e?.message ?? e}`));+ };+ const stop = (why: string) => {+ stopped(why);reject(new Error(why));};- const a = adoption({ verify: !!o.verify, complete: forkComplete, take, stop, gone: () => reject(new Error('runner gone')) });- lines(sock, (m: RunnerToHost) => a.message(m) && void d.message(r, m));+ // A container's fork record is its sandbox record: complete once it has `repos`.+ const complete = o.sandbox ? () => !workspacesEnabled() || !!o.sandbox!.record.repos : forkComplete;+ const a = adoption({ verify: !!o.verify, complete, take, stop, gone: () => reject(new Error('runner gone')) });+ lines(sock, (m: RunnerToHost) => {+ if (refused) return;+ // Which thread a container serves is the record's word, never the runner's; a spare's container has none until it is bound.+ if (r.sandbox && m.t === 'report' && m.report.key !== r.sandbox.record.key) return stop(`it reports ${m.report.key}, not its record's ${r.sandbox.record.key}`);+ if (d.sandbox && !r.sandbox && m.t === 'report') return stop(`it reports ${m.report.key} and has no record`);+ // With no record it serves no thread: nothing it asks for is handled, for the session '' or any other (spare-frames.ts).+ if (d.sandbox && !r.sandbox && !spareMay(m)) {+ const no = refusal(m);+ return no && send(sock, no);+ }+ // Found running after a restart, a record's container serves its thread or nothing: never taken on as a spare.+ if (o.sandbox && o.verify && m.t === 'spare' && a.state === 'pending') return stop(`it says it is a spare, not ${o.sandbox.record.key}'s runner`);+ return a.message(m) && void d.message(r, m);+ });sock.once('close', () => a.closed());});}+ /**+ * Step 10: a new thread takes a spare container when today's pool rule lets it. Undefined when it took none, or took one and+ * could not make it the thread's: that spare is gone by then (exit, Remove) and the caller starts cold, under the record's id+ * when the record was written.+ */+ async function claimSandboxed(spares: SandboxSpares, spec: SessionSpec, f: Dimensions, first?: HostCredentials): Promise<Runner | undefined> {+ const codex = spec.harness === 'codex';+ if (!d.pool.enabled || spares.known(spec) || !workspacesEnabled() || !workspacePrepared(spec.owner)) return;+ if (!d.models.canSpare()) return;+ const t0 = Date.now();+ const data: Record<string, string | number | boolean> = { launch_mode: 'podman', ...(d.image && { image: imageTag(d.image) }) };+ let taken: Runner | undefined;+ let bound: Bound | undefined;+ const got = await claimSpare<Runner>({+ take: () => {+ const t = d.pool.take(d.models.kind(spec.key, 'claude'), codex); // of its route's spare kind (C6); Codex any+ if (typeof t !== 'string') taken = t;+ return t;+ },+ fork: async (r) => {+ const b = (bound = await spares.bind(r.id, spec, f));+ // From here on it is the record's thread's: its reports are held to the record, and what it asks for is asked for that thread.+ r.sandbox = { record: b.record, run: b.run };+ r.key = b.record.key;+ data['container.mount_ms'] = b.mountMs;+ data['container.add_ms'] = b.addMs;+ return WORKSPACE;+ },+ claim: async (r, forkPath) => {+ // As a claim outside a container: bound to the session at the model proxy first (C6), then Claude's credentials before the claim, Codex's after.+ await d.models.claim(r.id, spec.key, spec.harness ?? 'claude');+ const c = first ?? d.models.forRunner(spec.key, d.creds(), spec.harness ?? 'claude');+ if (c && !codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);+ const t1 = Date.now();+ await call(r, { t: 'claim', session: { ...bound!.session, forkPath }, api: bound!.api }, 5000);+ data['container.claim_ms'] = Date.now() - t1;+ if (c && codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);+ },+ discard: (r) => d.exit(r.sock),+ }).catch((e) => {+ log.warn(`spare ${taken?.id} not made ${spec.key}'s: ${e?.message ?? e}`);+ return { missed: 'bind' as const };+ });+ if ('runner' in got) {+ const r = got.runner;+ r.sandbox = { record: spares.claimed(r.id), run: bound!.run }; // the record no longer says `unclaimed`+ r.harness = spec.harness;+ r.lastDelivery = Date.now();+ d.register(r);+ if (r.report) d.toGateway({ t: 'session', report: r.report });+ r.cold = { resumed: false, prewarmed: true };+ tm.emit('runner.claimed', { ...f, duration_ms: Date.now() - t0, data });+ log.info(`spare ${r.id} claimed for ${spec.key} in ${Date.now() - t0} ms (record and directories ${bound?.readyMs} ms, mounts ${data['container.mount_ms']} ms, worktrees ${data['container.add_ms']} ms, claim ${data['container.claim_ms']} ms)`);+ return r;+ }+ tm.emit('pool.spare_missed', { ...f, data: { reason: got.missed } });+ if (!taken) return;+ // A spare leaves: `exit` went with the discard; Remove, and its connection closed (its token socket with it) before the+ // cold start opens the same paths again under the same id.+ await spares.discard(taken.id);+ const { sock } = taken;+ await new Promise<void>((done) => {+ if (sock.closed) return done();+ sock.once('close', () => done()); // after adopt's own listeners, which close its token socket+ sock.destroy();+ });+ }++ /** Work 103: the thread's runner in its container; a new thread and a resume alike. A new thread may take a spare (step 10). */+ async function startSandboxed(sandbox: SandboxStarts, spec: SessionSpec, f: Dimensions, first?: HostCredentials): Promise<Runner> {+ const { spares } = d;+ // In the thread's turn, which the cold start below takes after it.+ const claimed = spares && (await spares.turn(spec, () => claimSandboxed(spares, spec, f, first)));+ if (claimed) return claimed;+ const s = await sandbox.start(spec, f);+ try {+ if (s.sock.destroyed) throw new Error('runner exited while it started');+ const r = await adopt(s.record.id, s.sock, { first, harness: spec.harness, sandbox: { record: s.record, run: s.run } });+ if (s.api) send(s.sock, { t: 'api', api: s.api } satisfies HostToRunner); // the token stays out of boot.env+ r.cold = { resumed: !!s.session.sdkSessionId };+ return r;+ } catch (e) {+ // Not taken on: nothing of the start stays (its container may still run, its token socket is open).+ s.sock.destroy();+ await s.abandon();+ throw e;+ }+ }+async function startRunner(spec: SessionSpec, f: Dimensions, first?: HostCredentials): Promise<Runner> {if (!d.models.up) throw new Error(PROXY_DOWN);+ if (d.sandbox) {+ const sandbox = d.sandbox;+ const go = () => startSandboxed(sandbox, spec, f, first);+ // No spare is made beside a start; the pool is topped up once this one settled.+ return d.spares ? d.spares.during(go).finally(() => d.fillPool()) : go();+ }let existing = spec.forkPath && existsSync(spec.forkPath) && forkComplete(spec.forkPath) ? spec.forkPath : undefined;// A new session in a prepared workspace may take a spare (work 069); a resumed one starts cold, to resume.// Claude takes one of its route's spare kind (C6); Codex (work 082) any.@@ -176,15 +337,30 @@ export function runnerStarts(d: StartDeps) {existing ??= got.forkPath;}// A workspace fork's directory is known before forking: the runner boots in it while the worktrees are added.- const dir = existing ?? (workspacesEnabled() ? forkDir(spec.owner, spec.key) : undefined);- if (dir && !existing) await mkdirAsRunner(dir);+ // Elsewhere (a laptop) the fork says where it is, so it comes first.+ const fork = () => d.inFork(f, () => forkFor(tm, spec, f));+ const dir = existing ?? (workspacesEnabled() ? forkDir(spec.owner, spec.key) : await fork());+ const forking = !existing && workspacesEnabled();+ if (forking) await mkdirAsRunner(dir);const id = newRunnerId();const runnerApi = await d.mint(spec, id); // work 084: the session's journal, socket and token; undefined off the API- const { ready: sock } = await coldStart({- dir,- fork: existing ? undefined : () => d.inFork(f, () => forkFor(tm, spec, f)),- start: (cwd) => launchRunner({ id, session: { ...spec, forkPath: cwd }, socket: socketFor(d.run, id), api: runnerApi && { ...runnerApi, token: '' }, version: d.version }, { ...d.launch, f }),- abandon: d.exit,+ const rs = { id, session: { ...spec, forkPath: dir }, socket: socketFor(d.run, id), api: runnerApi && { ...runnerApi, token: '' }, version: d.version };+ let t0 = Date.now();+ let ready: Promise<net.Socket> | undefined;+ const sock = await coldStart({+ up: async () => void (t0 = await launchProcess(rs, { ...d.launch, f })),+ prepare: forking+ ? async () => {+ const at = await fork();+ if (at !== dir) throw new Error(`fork landed in ${at}, not in ${dir} where the runner was started`);+ }+ : undefined,+ ready: () => (ready = awaitRunner(rs, { tm, f, t0 })),+ // The fork failed: the runner goes once it is up (it only listens until then).+ abandon: async () => {+ const up = await ready?.catch(() => undefined);+ if (up) d.exit(up);+ },});if (sock.destroyed) throw new Error('runner exited while its fork was made');const r = await adopt(id, sock, { key: spec.key, first, harness: spec.harness });@@ -195,6 +371,14 @@ export function runnerStarts(d: StartDeps) {/** Start a spare for the pool, bound to `models.claude` first: a runner with no session, which parks a Claude Code once it has credentials. */async function launchSpare() {+ if (d.spares) {+ // A container with no thread (sandbox/spares.ts): adopted as a spare under its own run root.+ // It is taken on at once (not verified), so this does not reject; when it goes, its close Removes it (`closed`).+ const s = await d.spares.launch();+ await adopt(s.id, s.sock, { run: s.run });+ tm.emit('pool.spare_started', { data: { launch_mode: d.launch.mode, ...(d.image && { image: imageTag(d.image) }), 'container.create_ms': s.createMs, 'container.start_ms': s.startMs } });+ return;+ }const id = newRunnerId();await d.models.spare(id);await launchRunner({ id, socket: socketFor(d.run, id), version: d.version }, d.launch).then((sock) => adopt(id, sock))@@ -202,5 +386,12 @@ export function runnerStarts(d: StartDeps) {tm.emit('pool.spare_started', { data: { launch_mode: d.launch.mode } });}- return { adopt, startRunner, launchSpare };+ /** The pool lets a spare go (pool.ts). A container's is not asked, which it could ignore: its socket is destroyed and it is Removed (sandbox/spares.ts). */+ function evict(r: Runner) {+ if (!d.spares) return d.exit(r.sock);+ r.sock.destroy();+ void d.spares.gone(r.id);+ }++ return { adopt, startRunner, launchSpare, evict };}diff --git a/computer/src/host/terminal-pty.py b/computer/src/host/terminal-pty.pyindex 2d6465fd..7cf05ea3 100644--- a/computer/src/host/terminal-pty.py+++ b/computer/src/host/terminal-pty.py@@ -5,15 +5,21 @@# (or, with tty false, three pipes) and speaks frames on stdin/stdout:## frame = type (1 byte) | length (u32 big-endian) | payload-# in: S start {cols, rows, command, tty, term, env, cwd} D data R resize {cols, rows}-# E eof (tty: ^D; pipes: close stdin) H hang up (stdin closing counts as H)+# in: S start {cols, rows, command, tty, term, env, cwd, inherit} D data R resize {cols, rows}+# E eof (tty: ^D; pipes: close stdin) H hang up (stdin closing and SIGHUP count as H)# out: O output X standard error (tty false) Z exit {exitCode, signal}, last## Invariants: the child's environment is exactly `env` from the start frame# (no secrets: the host builds it from a fixed list, and BASH_ENV/ENV are never-# set); the child leads its own session and process group; a hang-up sends-# SIGHUP to the group (again every 0.5 s) and SIGKILL 5 s later; every byte of output is framed-# before `Z`; this process exits right after `Z`.+# set). With `inherit` (work 103: the helper runs inside a session's+# container, by `podman exec`) it is this process's own environment, which is+# the container's and holds no credential, with `env` over it and without+# BASH_ENV and ENV. There a SIGHUP is how the host hangs up a helper whose+# `podman exec` client is gone (`pkill -HUP -f`; extra arguments, the+# terminal's unit name, are only there for it to match). The child leads its+# own session and process group; a hang-up sends SIGHUP to the group (again+# every 0.5 s) and SIGKILL 5 s later; every byte of output is framed before+# `Z`; this process exits right after `Z`.import fcntlimport json@@ -66,7 +72,8 @@ def winsize(fd, cols, rows):def start(spec):- env = {k: str(v) for k, v in (spec.get('env') or {}).items()}+ env = {k: v for k, v in os.environ.items() if k not in ('BASH_ENV', 'ENV')} if spec.get('inherit') else {}+ env.update({k: str(v) for k, v in (spec.get('env') or {}).items()})env['TERM'] = spec.get('term') or 'xterm-256color'shell = env.get('SHELL') or '/bin/bash'argv = ['/bin/bash', '-lc', spec['command']] if spec.get('command') else [shell, '-l']@@ -125,6 +132,10 @@ def main():exited_at = Nonestdin_open = Trueopen_out = {}+ # A SIGHUP wakes the loop through a pipe; it is a hang-up.+ hup_r, hup_w = os.pipe()+ os.set_blocking(hup_w, False)+ signal.signal(signal.SIGHUP, lambda *_: os.write(hup_w, b'h'))def hang_up():nonlocal hup_at@@ -139,13 +150,16 @@ def main():passwhile True:- watch = [fd for fd in open_out if fd is not None]+ watch = [fd for fd in open_out if fd is not None] + [hup_r]if stdin_open:watch.append(in_fd)timeout = 0.1 if (hup_at is not None or exited_at is not None or status is None and pid is not None) else Noneready, _, _ = select.select(watch, [], [], timeout)for fd in ready:- if fd == in_fd:+ if fd == hup_r:+ os.read(hup_r, CHUNK)+ hang_up()+ elif fd == in_fd:try:chunk = os.read(in_fd, CHUNK)except BlockingIOError:diff --git a/computer/src/host/terminal.test.ts b/computer/src/host/terminal.test.tsindex e55de8b5..c7399dac 100644--- a/computer/src/host/terminal.test.ts+++ b/computer/src/host/terminal.test.ts@@ -1,8 +1,10 @@+import { spawn } from 'node:child_process';import { mkdtempSync, rmSync } from 'node:fs';import net from 'node:net';import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { Unavailable, UPDATING } from './unavailable.js';import { createTerminals, frame, frames, type Terminals, TERMINALS_PER_SESSION } from './terminal.js';let dir: string;@@ -128,3 +130,47 @@ describe('terminals (real PTY)', () => {expect(terms.count('cs_b')).toBe(0);}, 20_000);});++describe('terminals in containers (work 103, C13)', () => {+ it('on a podman host, an open that names no sandbox starts nothing', async () => {+ const podman = createTerminals({ dir: path.join(dir, 'p'), launch: 'podman' });+ podman.prewarm(); // no helper ahead either: it would be a process outside every container+ const r = await podman.open({ sessionId: 'cs_a', cwd: dir, cols: 80, rows: 24, tty: true }, onExit);+ expect('error' in r && [r.error.code, r.error.status]).toEqual(['unavailable', 503]);+ expect(podman.count('cs_a')).toBe(0);+ await podman.closeAll();+ });++ it('enters the sandbox first: refused with the words of the refusal, or as not running, and nothing starts; no use is left', async () => {+ const log: string[] = [];+ let answer: () => Promise<{ running: boolean; leave(): void }> = async () => ({ running: false, leave: () => void log.push('left') });+ const podman = createTerminals({ dir: path.join(dir, 'p'), launch: 'podman', inside: { enter: (id) => (log.push(`enter ${id}`), answer()), hangUp() {} } });+ const open = () => podman.open({ sessionId: 'cs_a', sandbox: '00aa11bb22cc33dd', cwd: '/workspace', cols: 80, rows: 24, tty: true }, onExit);+ const stopped = await open();+ expect('error' in stopped && [stopped.error.code, stopped.error.reason]).toEqual(['conflict', 'session_not_running']);+ answer = () => Promise.reject(new Unavailable(UPDATING));+ const updating = await open();+ expect('error' in updating && updating.error).toEqual({ code: 'unavailable', message: 'The computer is updating, try again in a few minutes.', status: 503, retryable: true });+ answer = () => Promise.reject(new Error('systemctl: /run/user/1500'));+ const other = await open();+ expect('error' in other && [other.error.code, other.error.message]).toEqual(['unavailable', 'The terminal could not start.']);+ expect(log).toEqual(['enter 00aa11bb22cc33dd', 'left', 'enter 00aa11bb22cc33dd', 'enter 00aa11bb22cc33dd']);+ expect(podman.count('cs_a')).toBe(0);+ await podman.closeAll();+ });++ it('the helper, as podman exec runs it: its own environment with TERM over it, never BASH_ENV, and SIGHUP hangs up', async () => {+ const helper = path.resolve(import.meta.dirname, 'terminal-pty.py');+ const p = spawn('python3', [helper, 'sp-term-test'], { stdio: ['pipe', 'pipe', 'inherit'], env: { PATH: env.PATH, HOME: '/home/agent', BASH_ENV: '/nonexistent', SP_INSIDE: 'yes' } });+ let out = '';+ let exit: { exitCode: number | null; signal: string | null } | undefined;+ p.stdout.on('data', frames((k, payload) => (k === 'O' ? (out += payload.toString()) : k === 'Z' && (exit = JSON.parse(payload.toString())))));+ p.stdin.write(frame('S', JSON.stringify({ cols: 80, rows: 24, tty: true, cwd: dir, env: { TERM: 'vt100' }, term: 'vt100', inherit: true,+ command: 'echo "$SP_INSIDE $HOME $TERM ${BASH_ENV:-unset}"; sleep 60' })));+ await until(() => out.includes('vt100'));+ expect(out).toContain('yes /home/agent vt100 unset');+ p.kill('SIGHUP');+ await until(() => !!exit);+ expect(exit).toEqual({ exitCode: null, signal: 'SIGHUP' });+ });+});diff --git a/computer/src/host/terminal.ts b/computer/src/host/terminal.tsindex b8355a61..01e62f5c 100644--- a/computer/src/host/terminal.ts+++ b/computer/src/host/terminal.ts@@ -17,6 +17,19 @@// - `onExit` runs once, after every socket has been ended.// - One helper is kept started ahead (`prewarm`), so an open costs a frame,// not a process start.+// - On a host whose sessions run in containers (launch `podman`, work 103+// C13) the helper runs inside the session's container (`podman exec`, as+// the session's user, in `/workspace`), its shell gets the container's own+// environment plus TERM, and nothing is started ahead: a helper cannot+// start before its container is known. An open that names no sandbox is+// refused there; no shell ever starts outside a container. Stopping the+// unit ends only the `podman exec` client, so a helper that outlives it is+// hung up inside the container (terminal-pty.py takes SIGHUP as a hang-up).+// - There a terminal enters its sandbox before anything starts (`inside`,+// sandbox/use.ts) and leaves it when its helper has exited: an open while+// the computer pulls an image is refused within seconds with words for the+// person, and one whose container is not running then is refused+// (`session_not_running`), whatever its caller knew a moment before.import { type ChildProcess, execFile, spawn } from 'node:child_process';import { randomBytes } from 'node:crypto';@@ -28,6 +41,9 @@ import { apiError } from '../api/writer.js';import { mintId } from '../session-ids.js';import { log } from '../log.js';import type { RunnerUser } from './runner-user.js';+import { PODMAN } from './sandbox/podman.js';+import { terminalArgs } from './sandbox/podman-args.js';+import { unavailable } from './unavailable.js';export const TERMINALS_PER_SESSION = 8;const PENDING_MAX = 1 << 20;@@ -42,6 +58,8 @@ export interface TerminalOpen {command?: string;tty: boolean;term?: string;+ /** The session's sandbox id, on a `podman` host: the terminal opens inside its container, which the caller knows to be running. */+ sandbox?: string;}export type TerminalExit = (terminalId: string, exitCode: number | null, signal: string | null) => void;@@ -61,7 +79,7 @@ export interface Terminals {export interface TerminalsOptions {dir: string;- launch: 'systemd' | 'detached';+ launch: 'systemd' | 'detached' | 'podman';user?: RunnerUser;/** The systemd-run prefix runners use (`SP_SYSTEMD_RUN`, else runner-limits.ts). */systemdRun?: string;@@ -70,11 +88,23 @@ export interface TerminalsOptions {/** gid that may connect to the sockets (sp-wire). */group?: number;python?: string;+ /** On a `podman` host (sandbox/host.ts `terminal`); without it no terminal opens there. */+ inside?: {+ /** Before a terminal starts in this sandbox: waits as long as a person may be kept waiting, rejects with Unavailable; `leave` once the terminal is over. */+ enter(sandbox: string): Promise<{ running: boolean; leave(): void }>;+ /** Hang up the helper `unit` inside the sandbox's container. */+ hangUp(sandbox: string, unit: string): void;+ };}+/** A terminal is a shell in the session's container: none while it is stopped, and opening one never starts it (work 103, C13). */+export const sessionNotRunning = () => apiError('conflict', 'The session is not running, so it has no terminal. Resume the session first.', 409, { reason: 'session_not_running' });+interface Helper {proc: ChildProcess;unit: string | undefined;+ /** The sandbox it runs in, on a `podman` host. */+ sandbox?: string;exited: Promise<void>;}@@ -143,15 +173,16 @@ export function createTerminals(o: TerminalsOptions): Terminals {};};- function startHelper(): Helper {+ function startHelper(inside?: { sandbox: string; cwd: string; term?: string }): Helper {const python = o.python ?? 'python3';let unit: string | undefined;let cmd: string;let args: string[];- if (o.launch === 'systemd') {+ if (o.launch !== 'detached') {unit = `sp-term-${randomBytes(6).toString('hex')}`;const prefix = [...(o.user?.sudo ?? []), ...(o.systemdRun ?? 'systemd-run --user').trim().split(/\s+/)];- [cmd, ...args] = [...prefix, `--unit=${unit}`, '--collect', '--quiet', '--pipe', '--', python, HELPER];+ const helper = inside ? [PODMAN, ...terminalArgs(inside.sandbox, inside.cwd, inside.term || 'xterm-256color', [python, HELPER, unit])] : [python, HELPER];+ [cmd, ...args] = [...prefix, `--unit=${unit}`, '--collect', '--quiet', '--pipe', '--', ...helper];} else {[cmd, args] = [python, [HELPER]];}@@ -159,10 +190,11 @@ export function createTerminals(o: TerminalsOptions): Terminals {proc.stderr?.on('data', (d: Buffer) => log.warn('terminal helper:', d.toString('utf8').trim().slice(0, 300)));proc.stdin?.on('error', () => {});const exited = new Promise<void>((r) => proc.once('exit', () => r()));- return { proc, unit, exited };+ return { proc, unit, sandbox: inside?.sandbox, exited };}- const takeHelper = () => {+ const takeHelper = (inside?: { sandbox: string; cwd: string; term?: string }) => {+ if (inside) return startHelper(inside);const h = warm && warm.proc.exitCode === null && !warm.proc.killed ? warm : startHelper();warm = undefined;return h;@@ -218,6 +250,8 @@ export function createTerminals(o: TerminalsOptions): Terminals {if (t.helper.unit) {const [cmd, ...pre] = [...(o.user?.sudo ?? []), 'systemctl', '--user', 'stop', t.helper.unit];execFile(cmd, pre, { env: { ...process.env, ...o.user?.env } }, () => {});+ // The unit held the `podman exec` client only: the helper itself is in the container.+ if (t.helper.sandbox) o.inside?.hangUp(t.helper.sandbox, t.helper.unit);}t.helper.proc.kill('SIGKILL');}, STOP_AFTER_MS);@@ -242,11 +276,30 @@ export function createTerminals(o: TerminalsOptions): Terminals {const self: Terminals = {async open(req, onExit) {- if (self.count(req.sessionId) >= TERMINALS_PER_SESSION) {- return { error: apiError('too_many_terminals', '8 terminals are already open in this session.', 409, { retryable: false }) };+ const full = () => self.count(req.sessionId) >= TERMINALS_PER_SESSION && { error: apiError('too_many_terminals', '8 terminals are already open in this session.', 409, { retryable: false }) };+ const many = full();+ if (many) return many;+ if (o.launch === 'podman' && !(req.sandbox && o.inside)) {+ log.warn(`terminal for ${req.sessionId} refused: no sandbox named on a podman host`);+ return { error: apiError('unavailable', 'The terminal could not start.', 503, { retryable: false }) };+ }+ const inside = o.launch === 'podman' && req.sandbox ? { sandbox: req.sandbox, cwd: req.cwd, term: req.term } : undefined;+ let use: { running: boolean; leave(): void } | undefined;+ if (inside) {+ try {+ use = await o.inside?.enter(inside.sandbox);+ } catch (e) {+ const told = unavailable(e);+ if (!told) log.warn(`terminal for ${req.sessionId}: cannot enter its sandbox: ${(e as Error)?.message ?? e}`);+ return { error: told ?? apiError('unavailable', 'The terminal could not start.', 503, { retryable: true }) };+ }+ // Others may have opened while this one waited; and the container is asked about now, not when the call came in.+ const refused = full() || (!use?.running && { error: sessionNotRunning() });+ if (refused) return use?.leave(), refused;}const id = mintId('tm');- const helper = takeHelper();+ const helper = takeHelper(inside);+ if (use) void helper.exited.then(use.leave);const t: Term = {id, sessionId: req.sessionId, helper, servers: [], onExit, done: false,out: { pending: [], pendingBytes: 0, ended: false },@@ -275,7 +328,9 @@ export function createTerminals(o: TerminalsOptions): Terminals {);helper.proc.once('exit', (code) => finish(t, exit?.exitCode ?? (exit ? null : code), exit?.signal ?? null));helper.proc.stdin?.write(- frame('S', JSON.stringify({ cols: req.cols, rows: req.rows, command: req.command ?? null, tty: req.tty, term: req.term, env: shellEnv(req.term), cwd: req.cwd })),+ // In a container the shell's environment is the container's own (`inherit`), plus TERM.+ frame('S', JSON.stringify({ cols: req.cols, rows: req.rows, command: req.command ?? null, tty: req.tty, term: req.term, cwd: req.cwd,+ ...(inside ? { env: { TERM: req.term || 'xterm-256color' }, inherit: true } : { env: shellEnv(req.term) }) })),);self.prewarm();return { terminalId: id, socket, stderrSocket };@@ -310,6 +365,7 @@ export function createTerminals(o: TerminalsOptions): Terminals {await Promise.all(all.map((t) => t.helper.exited));},prewarm() {+ if (o.launch === 'podman') return;if (!warm || warm.proc.exitCode !== null) warm = startHelper();},};diff --git a/computer/src/host/tokens.test.ts b/computer/src/host/tokens.test.tsindex 2455bf56..909342ef 100644--- a/computer/src/host/tokens.test.ts+++ b/computer/src/host/tokens.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdtempSync, statSync } from 'node:fs';+import { existsSync, mkdtempSync, readlinkSync, statSync } from 'node:fs';import net from 'node:net';import { tmpdir } from 'node:os';import path from 'node:path';@@ -86,6 +86,8 @@ describe('token relay', () => {const sock = path.join(dir, 'r1.sock');expect(sock).toBe(tokenSocketFor(root, 'r1'));await vi.waitFor(() => expect(existsSync(sock)).toBe(true));+ // Work 103: in a run root that is not the host's, the name the helpers know leads to the runner's own socket.+ expect(readlinkSync(path.join(root, 'token.sock'))).toBe('tokens/r1.sock');serving.close();await vi.waitFor(() => expect(existsSync(sock)).toBe(false));});@@ -125,4 +127,36 @@ describe('token relay', () => {server.close();}});++ it("the helpers' socket gives GitHub tokens for the definition's repositories and nothing else", async () => {+ const asked: Extract<HostToGateway, { t: 'token' }>[] = [];+ const tm = createTelemetry({ service: 'host', version: 'v', region: 'r', send: () => {} });+ const relay = tokenRelay((m) => {+ asked.push(m);+ queueMicrotask(() => relay.answer({ id: m.id, result: { token: 'ghs_h', expiresAt: new Date(Date.now() + 3600_000).toISOString() } }));+ return true;+ }, tm);+ const dir = mkdtempSync(path.join(tmpdir(), 'tokens-'));+ const socket = path.join(dir, 'token.sock');+ const server = relay.serveHelper(socket, () => ['Acme/Widgets']);+ await new Promise((r) => server.once('listening', r));+ const ask = (req: unknown) =>+ new Promise<{ token?: string; error?: string }>((resolve, reject) => {+ const c = net.connect(socket, () => c.write(JSON.stringify(req) + '\n'));+ let got = '';+ c.on('data', (d) => (got += d)).on('end', () => resolve(JSON.parse(got))).on('error', reject);+ });+ try {+ expect(await ask({ repos: ['acme/widgets.git'] })).toMatchObject({ token: 'ghs_h' });+ expect(asked).toEqual([expect.objectContaining({ repos: ['acme/widgets.git'], sessionKey: undefined })]);+ expect(await ask({ repos: ['acme/widgets', 'acme/other'] })).toEqual({ error: 'not a repository of this workspace' });+ expect(await ask({})).toEqual({ error: 'not a repository of this workspace' });+ expect(await ask({ repos: 'acme/widgets' })).toEqual({ error: 'not a repository of this workspace' });+ expect(await ask({ kind: 'opencomputer' })).toEqual({ error: 'this socket gives GitHub tokens only' });+ expect(await ask({ kind: 'automation-repo', repos: ['acme/widgets'] })).toEqual({ error: 'this socket gives GitHub tokens only' });+ expect(asked.length).toBe(1);+ } finally {+ server.close();+ }+ });});diff --git a/computer/src/host/tokens.ts b/computer/src/host/tokens.tsindex 4e9c2cf4..a198bcad 100644--- a/computer/src/host/tokens.ts+++ b/computer/src/host/tokens.ts@@ -8,15 +8,18 @@// The session a token is for is the host's word, never the asker's (work 080):// each runner has its own token socket in a directory only the host writes, and// the host names the session it serves. The shared socket names none.+// The helper containers' socket (work 103) serves no session either, and only+// GitHub tokens for repositories of the workspace definition: a helper runs+// git on clones a session can write.//// Invariants: a request fails fast when the gateway is not connected and// times out after 15 s; a failed request is not cached. Tokens are never logged.import net from 'node:net';import { randomUUID } from 'node:crypto';-import { chmodSync, mkdirSync, rmSync } from 'node:fs';+import { chmodSync, mkdirSync, renameSync, rmSync, symlinkSync } from 'node:fs';import path from 'node:path';-import type { GitHubToken, HostToGateway, TokenKind } from '../protocol.js';+import { type GitHubToken, HOST_RUN, HOST_TOKEN_SOCKET, type HostToGateway, RUNNER_TOKEN_DIR, type TokenKind } from '../protocol.js';import { type RunRoot, lines, tokenSocketFor } from '../ipc.js';import type { Telemetry } from '../telemetry/emitter.js';@@ -33,8 +36,15 @@ export interface TokenRelay {/*** A runner's own token socket below its run root (`tokenSocketFor`); `session` is the host's word for who asks.* Idempotent per id; the caller closes it when the runner is gone. The directory is the caller's to make (`freshTokenDir`).+ * In a sandbox's run root (work 103) it also makes `token.sock` a relative link to it, so the helpers find it under the+ * name they know; at HOST_RUN that name is the host's shared token socket and stays.*/serveRunner(run: RunRoot, id: string, session: () => string | undefined): { close(): void };+ /**+ * The helper containers' token socket: GitHub tokens only, for no session, and only for repositories among+ * `allowed()` (`owner/name` of each repository in the workspace definition). A request naming none is refused.+ */+ serveHelper(socket: string, allowed: () => string[]): net.Server;}/**@@ -105,24 +115,41 @@ export function tokenRelay(ask: (m: Extract<HostToGateway, { t: 'token' }>) => bconst open = served.get(socket);if (open) return open;const server = relay.serve(socket, session);+ if (path.resolve(run) !== path.resolve(HOST_RUN)) {+ const link = path.join(run, HOST_TOKEN_SOCKET);+ rmSync(`${link}.tmp`, { force: true });+ symlinkSync(path.join(RUNNER_TOKEN_DIR, `${id}.sock`), `${link}.tmp`);+ renameSync(`${link}.tmp`, link);+ }const handle = { close: () => void (served.get(socket) === handle && (served.delete(socket), server.close())) };served.set(socket, handle);return handle;},- serve(socket, session) {- rmSync(socket, { force: true });- const server = net.createServer((sock) => {- sock.on('error', () => {});- lines(sock, async (req: { repos?: string[]; kind?: TokenKind }) => {- const kind = req.kind === 'opencomputer' || req.kind === 'automation-repo' ? req.kind : 'github';- const res = await request(session?.() || undefined, req.repos, kind).catch((e) => ({ error: String(e?.message ?? e) }));- sock.end(JSON.stringify(res) + '\n');- });- });- // 0660: runners reach it through the group of SP_RUN (setgid), also when they run as another user (work 077).- server.listen(socket, () => chmodSync(socket, 0o660));- return server;- },+ serve: (socket, session) =>+ listen(socket, (req) => request(session?.() || undefined, req.repos, req.kind === 'opencomputer' || req.kind === 'automation-repo' ? req.kind : 'github')),+ serveHelper: (socket, allowed) =>+ listen(socket, async (req) => {+ if (req.kind !== undefined && req.kind !== 'github') throw new Error('this socket gives GitHub tokens only');+ const slug = (r: string) => r.replace(/\.git$/, '').toLowerCase();+ const granted = new Set(allowed().map(slug));+ const repos = Array.isArray(req.repos) ? req.repos.filter((r): r is string => typeof r === 'string') : [];+ if (!repos.length || !repos.every((r) => granted.has(slug(r)))) throw new Error('not a repository of this workspace');+ return request(undefined, repos, 'github');+ }),};+ /** One JSON line in, one out: `answer`'s token, or its error's message. */+ function listen(socket: string, answer: (req: { repos?: string[]; kind?: TokenKind }) => Promise<GitHubToken>) {+ rmSync(socket, { force: true });+ const server = net.createServer((sock) => {+ sock.on('error', () => {});+ lines(sock, async (req: { repos?: string[]; kind?: TokenKind }) => {+ const res = await Promise.resolve().then(() => answer(req ?? {})).catch((e) => ({ error: String(e?.message ?? e) }));+ sock.end(JSON.stringify(res) + '\n');+ });+ });+ // 0660: runners reach it through the group of SP_RUN (setgid), also when they run as another user (work 077).+ server.listen(socket, () => chmodSync(socket, 0o660));+ return server;+ }return relay;}diff --git a/computer/src/host/unavailable.test.ts b/computer/src/host/unavailable.test.tsnew file mode 100644index 00000000..98491277--- /dev/null+++ b/computer/src/host/unavailable.test.ts@@ -0,0 +1,10 @@+import { describe, expect, it } from 'vitest';+import { Unavailable, unavailable } from './unavailable.js';++describe('Unavailable', () => {+ it('is told as unavailable 503 with its own words; nothing else is', () => {+ expect(unavailable(new Unavailable('The computer is updating, try again.'))).toEqual({ code: 'unavailable', message: 'The computer is updating, try again.', status: 503, retryable: true });+ expect(unavailable(new Unavailable('Gone.', false))).toMatchObject({ retryable: false });+ expect(unavailable(new Error('podman exec: /data/x'))).toBeUndefined();+ });+});diff --git a/computer/src/host/unavailable.ts b/computer/src/host/unavailable.tsnew file mode 100644index 00000000..223816f4--- /dev/null+++ b/computer/src/host/unavailable.ts@@ -0,0 +1,26 @@+// A failure of the host that the person who asked is told as it is (work 103):+// the computer cannot serve this call now, and why. Anything else a `/files`+// call or a terminal open throws reaches the client as `internal`, with no+// words of the host's.+//+// Invariants:+// - The message is written for the person: it never carries a path, a+// command or an id.+// - `retryable` is true when the same call may succeed a little later.++import type { ApiError } from '../protocol.js';+import { apiError } from '../api/writer.js';++export class Unavailable extends Error {+ constructor(message: string, readonly retryable = true) {+ super(message);+ this.name = 'Unavailable';+ }+}++/** What an image pull or warm-up in progress makes of a call that cannot wait for it (sandbox/image-lock.ts). */+export const UPDATING = 'The computer is updating, try again in a few minutes.';++/** `e` as the API says it: `unavailable` 503 for an Unavailable, undefined for anything else. */+export const unavailable = (e: unknown): ApiError | undefined =>+ e instanceof Unavailable ? apiError('unavailable', e.message, 503, { retryable: e.retryable }) : undefined;diff --git a/computer/src/host/wire-link.test.ts b/computer/src/host/wire-link.test.tsindex b96efcfe..a3826a8c 100644--- a/computer/src/host/wire-link.test.ts+++ b/computer/src/host/wire-link.test.ts@@ -1,4 +1,4 @@-import { execFileSync } from 'node:child_process';+import { execFileSync, spawn } from 'node:child_process';import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';import net from 'node:net';import os from 'node:os';@@ -6,6 +6,7 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { lines } from '../ipc.js';import { createTerminals } from './terminal.js';+import { Unavailable } from './unavailable.js';import { serveWireLink, type WireLink, type WireLinkHooks } from './wire-link.js';import { createWorkspaceFiles } from './workspace-files.js';@@ -18,7 +19,10 @@ const counts: [string, number][] = [];const hooks: WireLinkHooks = {where: (sid) => (sid === 'cs_a' ? { socket: '/x/api.sock', token: 't', writer: 'host', epoch: 1 } : undefined),resume: async () => ({ status: 'starting' }),- workspace: (sid) => (sid === 'cs_a' ? { forkPath: fork, owner: 'usr_owner' } : undefined),+ workspace: (sid) =>+ sid === 'cs_a' ? { forkPath: fork, owner: 'usr_owner' }+ : sid === 'cs_stopped' ? { forkPath: fork, owner: 'usr_owner', sandbox: { id: '0123456789abcdef', person: 'U1', workspace: fork, running: false } }+ : undefined,record: async (sid, type, data) => {recorded.push([sid, type, data]);return 42;@@ -126,6 +130,19 @@ describe('wire link', () => {expect(counts.at(-1)).toEqual(['cs_a', 0]);});+ it("refuses a terminal in a session whose container is stopped, and starts nothing (C13)", async () => {+ const r = await relay();+ r.send({ t: 'hello', version: 'test' });+ await r.next((m) => m.t === 'welcome');+ r.send({ t: 'terminal.open', id: 't1', sessionId: 'cs_stopped', member: 'usr_owner', cols: 80, rows: 24, tty: true });+ const { error } = await r.next((m) => m.id === 't1');+ expect(error).toMatchObject({ code: 'conflict', status: 409, reason: 'session_not_running' });+ expect(error.message).toMatch(/[Rr]esume the session first/);+ expect(recorded).toEqual([]);+ expect(counts).toEqual([]);+ r.sock.destroy();+ });+it('lets only the relay peer that opened a terminal resize, eof or close it', async () => {const [a, b] = [await relay(), await relay()];for (const r of [a, b]) {@@ -147,6 +164,52 @@ describe('wire link', () => {b.sock.destroy();});+ it('tells the relay what the host has words for (the computer is updating), as the call\'s result or its files.done', async () => {+ // The first script of this place starts; every later one is refused as behind the image lock.+ let n = 0;+ const dir = path.join(root, 'wire2');+ const other = await serveWireLink(hooks, {+ dir,+ terminals: createTerminals({ dir: path.join(dir, 'terminals'), launch: 'detached' }),+ files: createWorkspaceFiles({+ dir: path.join(root, 'files-scratch2'),+ place: (ws) => ({+ root: ws.forkPath,+ spawn: async (argv) => {+ if (n++) throw new Unavailable('The computer is updating, try again in a few minutes.');+ return spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] });+ },+ }),+ }),+ });+ const sock = net.connect(other.socket);+ const got: Frame[] = [];+ lines(sock, (m) => got.push(m));+ const next = async (pred: (m: Frame) => boolean) => {+ for (const end = Date.now() + 8000; Date.now() < end; await new Promise((r) => setTimeout(r, 10))) {+ const i = got.findIndex(pred);+ if (i >= 0) return got.splice(i, 1)[0];+ }+ throw new Error(`no frame; have ${JSON.stringify(got)}`);+ };+ const send = (m: object) => sock.write(`${JSON.stringify(m)}\n`);+ send({ t: 'hello', version: 'test' });+ await next((m) => m.t === 'welcome');+ const updating = { code: 'unavailable', status: 503, retryable: true, message: 'The computer is updating, try again in a few minutes.' };+ // A download: its size was read (the first script), its bytes are refused.+ send({ t: 'files.get', id: 'g', sessionId: 'cs_a', member: 'usr_owner', path: 'hello.txt', file: true });+ const first = await next((m) => m.id === 'g' && m.t === 'result');+ const s = await connect(first.result.socket);+ s.resume();+ expect((await next((m) => m.id === 'g' && m.t === 'files.done')).error).toEqual(updating);+ send({ t: 'files.list', id: 'l', sessionId: 'cs_a', member: 'usr_owner', path: '' });+ expect((await next((m) => m.id === 'l')).error).toEqual(updating);+ send({ t: 'files.put', id: 'p', sessionId: 'cs_a', member: 'usr_owner', path: 'notes', format: 'tar' });+ expect((await next((m) => m.id === 'p')).error).toEqual(updating);+ sock.destroy();+ await other.close();+ });+it('streams a file out and an upload in, with files.done', async () => {const r = await relay();r.send({ t: 'hello', version: 'test' });diff --git a/computer/src/host/wire-link.ts b/computer/src/host/wire-link.tsindex 96a4e580..17534be8 100644--- a/computer/src/host/wire-link.ts+++ b/computer/src/host/wire-link.ts@@ -29,19 +29,26 @@ import { lines, send } from '../ipc.js';import { log } from '../log.js';import { HOST_RUN } from '../protocol.js';import { oneShotSocket } from './one-shot-socket.js';-import type { Terminals } from './terminal.js';+import { sessionNotRunning, type Terminals } from './terminal.js';+import { unavailable } from './unavailable.js';+import { WORKSPACE } from './sandbox/mounts.js';+import type { SandboxPlace } from './sandbox/scripts.js';import type { WorkspaceFiles } from './workspace-files.js';export const WIRE_DIR = path.join(HOST_RUN, 'wire');-type Workspace = { forkPath: string; owner: string };+/** `sandbox`: the session runs in a container (work 103); its terminal and its files are reached there. */+type Workspace = { forkPath: string; owner: string; sandbox?: SandboxPlace };export interface WireLinkHooks {/** The session's writer, if this host runs the session. */where(sessionId: string): WhereResult | undefined | Promise<WhereResult | undefined>;/** Start the session's runner if it is suspended (attach with resume=1). */resume(sessionId: string, actor: ApiActor): Promise<{ status: ApiSessionStatus } | { error: ApiError }>;- /** The session's fork and owner (`usr_…`); undefined: not a session this host runs, or no fork yet. */+ /**+ * The session's fork and owner (`usr_…`), asked before a terminal or `/files` acts in it; undefined: not a session+ * this host runs, or no fork yet.+ */workspace(sessionId: string): Workspace | undefined | Promise<Workspace | undefined>;/** Record an event in the session's log through its writer; resolves with its seq. */record?(sessionId: string, type: 'terminal.opened' | 'terminal.closed' | 'files.pushed', data: unknown, actor: ApiActor): Promise<number | undefined>;@@ -109,8 +116,10 @@ export async function serveWireLink(hooks: WireLinkHooks, o: { dir?: string; groconst ws = await hooks.workspace(m.sessionId);if (!ws) return { error: sessionNotFound() };if (m.member !== ws.owner && !admins.includes(m.member) && !access.get(m.sessionId)?.admins?.includes(m.member)) return { error: apiError('forbidden', "Only the session's owner or an admin can open a terminal.", 403, { reason: 'terminal_owner_only' }) };+ // A terminal is a shell in the session's container: none while it is stopped, and opening one never starts it (C13).+ if (ws.sandbox && !ws.sandbox.running) return { error: sessionNotRunning() };const r = await o.terminals.open(- { sessionId: m.sessionId, cwd: ws.forkPath, cols: m.cols, rows: m.rows, command: m.command, tty: m.tty, term: m.term },+ { sessionId: m.sessionId, sandbox: ws.sandbox?.id, cwd: ws.sandbox ? WORKSPACE : ws.forkPath, cols: m.cols, rows: m.rows, command: m.command, tty: m.tty, term: m.term },(terminalId, exitCode, signal) => {const t = terms.get(terminalId);terms.delete(terminalId);@@ -138,7 +147,7 @@ export async function serveWireLink(hooks: WireLinkHooks, o: { dir?: string; grocase 'files.list': {const ws = await hooks.workspace(m.sessionId);if (!ws) return { error: sessionNotFound() };- const r = await o.files.list({ sessionId: m.sessionId, forkPath: ws.forkPath }, m);+ const r = await o.files.list({ sessionId: m.sessionId, forkPath: ws.forkPath, sandbox: ws.sandbox }, m);return 'error' in r ? { error: r.error } : { result: r };}case 'files.get':@@ -158,7 +167,7 @@ export async function serveWireLink(hooks: WireLinkHooks, o: { dir?: string; groconst fail = (error: ApiError) => send(peer, { t: 'result', id: m.id, error } satisfies HostToWire);const ws = await hooks.workspace(m.sessionId);if (!ws) return fail(sessionNotFound());- const where = { sessionId: m.sessionId, forkPath: ws.forkPath };+ const where = { sessionId: m.sessionId, forkPath: ws.forkPath, sandbox: ws.sandbox };let out: (() => { stream: Readable; done: Promise<void> }) | undefined;let extra: Record<string, unknown> = {};if (m.t === 'files.get') {@@ -186,15 +195,21 @@ export async function serveWireLink(hooks: WireLinkHooks, o: { dir?: string; gro() => true,() => false,);- const ended = await r.done.then(- () => true,- (e) => (log.warn('wire: files.get', e?.message ?? e), false),+ const cut = () => apiError('internal', 'The transfer failed.', 500, { retryable: true });+ // What the host has words for (the computer is updating, the session stopped) is said; anything else is a transfer that failed.+ const failed = await r.done.then(+ () => (ok ? undefined : cut()),+ (e) => (log.warn('wire: files.get', e?.message ?? e), unavailable(e) ?? cut()),);- return done(ok && ended ? { result: {} } : { error: apiError('internal', 'The transfer failed.', 500, { retryable: true }) });+ return done(failed ? { error: failed } : { result: {} });}if (m.t !== 'files.put') return;const actor = memberActor(m.member);- const r = await o.files.upload(where, m.path, m.format, actor, conn);+ // The relay has its socket and waits for `files.done`: a failure from here on is said there.+ const r = await o.files.upload(where, m.path, m.format, actor, conn).catch((e) => {+ log.warn('wire: files.put', e?.message ?? e);+ return { error: unavailable(e) ?? apiError('internal', 'The transfer failed.', 500, { retryable: true }) };+ });conn.destroy();if ('error' in r) return done({ error: r.error });const u = r.upload;@@ -226,7 +241,8 @@ export async function serveWireLink(hooks: WireLinkHooks, o: { dir?: string; groif (r && id !== undefined) send(peer, { t: 'result', id, ...r } satisfies HostToWire);} catch (e) {log.warn(`wire: ${m.t} failed`, e);- if (id !== undefined) send(peer, { t: 'result', id, error: apiError('internal', 'The host failed this call.', 500, { retryable: true }) } satisfies HostToWire);+ // What the host has words for (the computer is updating) is said; anything else is the host's own failure.+ if (id !== undefined) send(peer, { t: 'result', id, error: unavailable(e) ?? apiError('internal', 'The host failed this call.', 500, { retryable: true }) } satisfies HostToWire);}});});diff --git a/computer/src/host/workspace-files.test.ts b/computer/src/host/workspace-files.test.tsindex f55e579a..308bb592 100644--- a/computer/src/host/workspace-files.test.ts+++ b/computer/src/host/workspace-files.test.ts@@ -1,11 +1,12 @@-import { execFileSync } from 'node:child_process';+import { execFileSync, spawn } from 'node:child_process';import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import os from 'node:os';import path from 'node:path';import { Readable } from 'node:stream';import zlib from 'node:zlib';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { contentType, createWorkspaceFiles, type Workspace, type WorkspaceFiles } from './workspace-files.js';+import { Unavailable } from './unavailable.js';+import { contentType, createWorkspaceFiles, parseListing, type Workspace, type WorkspaceFiles } from './workspace-files.js';let root: string;let ws: Workspace;@@ -127,6 +128,16 @@ describe('upload', () => {expect(list.entries.find((e) => e.path === 'repo')).toMatchObject({ pushedAt: null });});+ it('takes an archive whose unpacking ends before its last bytes are written', async () => {+ // tar stops at the end-of-archive mark and exits; what follows (padding) is then written to nobody.+ const padded = Buffer.concat([tarOf(srcDir('v1')), Buffer.alloc(8 * 2 ** 20)]);+ for (let i = 0; i < 5; i++) {+ const r = await files.upload(ws, 'padded', 'tar', actor, Readable.from([padded.subarray(0, 4096), padded.subarray(4096)]));+ if ('error' in r) throw new Error(r.error.message);+ expect(readFileSync(path.join(ws.forkPath, 'padded/lib/x.txt'), 'utf8')).toBe('v1');+ }+ });+it('never overwrites what was not uploaded', async () => {const r = await files.upload(ws, 'repo', 'tar', actor, body(tarOf(srcDir('x'))));expect('error' in r && r.error.code).toBe('path_exists');@@ -142,3 +153,289 @@ describe('upload', () => {expect(readdirSync(ws.forkPath).filter((n) => n.startsWith('.opc-'))).toEqual([]);});});++describe('an upload that is cut (work 103, C13)', () => {+ const opc = () => readdirSync(ws.forkPath).filter((n) => n.startsWith('.opc-'));+ const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));++ /** A place whose `mkdir` takes `ms`: a machine under load, where the script has not made its directory when its upload fails. */+ function slowMkdir(ms: number) {+ const bin = path.join(root, 'slow-bin');+ mkdirSync(bin);+ writeFileSync(path.join(bin, 'mkdir'), `#!/bin/sh\nsleep ${ms / 1000}\nexec /bin/mkdir "$@"\n`, { mode: 0o755 });+ return createWorkspaceFiles({+ dir: path.join(root, 'scratch-slow'),+ place: (w) => ({+ root: w.forkPath,+ spawn: (argv) => spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, PATH: `${bin}:${process.env.PATH}` } }),+ }),+ });+ }++ it('leaves no directory when the body fails before the script made its own', async () => {+ const f = slowMkdir(300);+ const r = await f.upload(ws, 'junk', 'tar', actor, body(Buffer.from('nope'.repeat(300))));+ expect('error' in r && r.error.code).toBe('invalid_archive');+ await settle(600);+ expect(opc()).toEqual([]);+ });++ it('leaves none when the body stops halfway, and the next upload removes what an earlier one could not', async () => {+ const big = path.join(root, 'big');+ mkdirSync(big);+ writeFileSync(path.join(big, 'a.bin'), Buffer.alloc(300_000, 7));+ const tar = tarOf(big);+ const cut = new Readable({ read() {} });+ cut.push(tar.subarray(0, 100_000));+ const up = files.upload(ws, 'half', 'tar', actor, cut);+ await settle(200);+ cut.destroy(new Error('the request ended'));+ expect(await up).toMatchObject({ error: { code: 'invalid_archive' } });+ expect(opc()).toEqual([]);+ // What a script that was killed outright left (the container stopped, the machine went down).+ mkdirSync(path.join(ws.forkPath, '.opc-upload-half-0000'));+ mkdirSync(path.join(ws.forkPath, '.opc-replaced-half-0000'));+ expect(await files.upload(ws, 'half', 'tar', actor, body(tar))).toMatchObject({ upload: { path: 'half', bytes: 300_000 } });+ expect(opc()).toEqual([]);+ });+});++describe('a script that is ended before it is done (work 103, "Timeouts and failures")', () => {+ /**+ * A place as a `podman` host's is: the script under timeout(1), under a stand-in for sudo that does with signals what+ * sudo does (SIGTERM goes on to the command, SIGKILL ends sudo alone). `slow` are commands that never finish there.+ * `alive()`: something of the script still runs (timeout(1) leads its process group).+ */+ function underSudo(slow: string[], o: { scriptWaitMs?: number } = {}) {+ const bin = path.join(root, 'stuck-bin');+ mkdirSync(bin);+ for (const name of slow) writeFileSync(path.join(bin, name), '#!/bin/sh\nexec sleep 30\n', { mode: 0o755 });+ const pidFile = path.join(root, 'pid');+ const sudo = path.join(root, 'sudo');+ writeFileSync(sudo, `#!/bin/sh\n"$@" <&0 &\npid=$!\ntrap 'kill -TERM "$pid" 2>/dev/null' TERM\necho "$pid" > ${pidFile}\nwhile :; do wait "$pid"; rc=$?; kill -0 "$pid" 2>/dev/null || exit "$rc"; done\n`, { mode: 0o755 });+ const f = createWorkspaceFiles({+ dir: path.join(root, 'scratch-sudo'),+ ...o,+ place: (w) => ({+ root: w.forkPath,+ spawn: (argv) => spawn(sudo, ['/usr/bin/timeout', '--kill-after=2', '60', ...argv], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, PATH: `${bin}:${process.env.PATH}` } }),+ }),+ });+ const group = () => -Number(readFileSync(pidFile, 'utf8'));+ const alive = () => {+ try {+ return process.kill(group(), 0);+ } catch {+ return false;+ }+ };+ const gone = async () => {+ for (const end = Date.now() + 1500; alive() && Date.now() < end; ) await new Promise((r) => setTimeout(r, 20));+ if (!alive()) return true;+ process.kill(group(), 'SIGKILL');+ return false;+ };+ return { f, gone, alive };+ }++ it('one that runs over its time is ended with all it started', async () => {+ const t = underSudo(['find'], { scriptWaitMs: 200 });+ await expect(t.f.list(ws, { path: 'repo' })).rejects.toThrow('ran over 200 ms');+ expect(await t.gone()).toBe(true);+ });++ it('a download whose reader goes away is ended', async () => {+ const t = underSudo(['cat']);+ const file = await t.f.file(ws, 'repo/README.md');+ if ('error' in file) throw new Error(file.error.code);+ const r = file.read();+ await new Promise((res) => setTimeout(res, 100));+ expect(t.alive()).toBe(true);+ r.stream.destroy();+ await expect(r.done).rejects.toThrow();+ expect(await t.gone()).toBe(true);+ });++ it('a download read to its end is not', async () => {+ const t = underSudo([]);+ const file = await t.f.file(ws, 'repo/README.md');+ if ('error' in file) throw new Error(file.error.code);+ const r = file.read();+ expect((await collect(r.stream)).toString()).toBe('# hi\n');+ await r.done;+ });++ it('an upload whose body stops is ended, and leaves no directory', async () => {+ const t = underSudo(['tar']);+ const cut = new Readable({ read() {} });+ cut.push(Buffer.alloc(512));+ const up = t.f.upload(ws, 'half', 'tar', actor, cut);+ await new Promise((res) => setTimeout(res, 200));+ expect(readdirSync(ws.forkPath).filter((n) => n.startsWith('.opc-'))).toHaveLength(1);+ cut.destroy(new Error('the request ended'));+ expect(await up).toMatchObject({ error: { code: 'invalid_archive' } });+ expect(await t.gone()).toBe(true);+ expect(readdirSync(ws.forkPath).filter((n) => n.startsWith('.opc-'))).toEqual([]);+ });+});++describe('where the scripts run (work 103, C13)', () => {+ /** A place whose root is the fork under another name: what a container's /workspace is to the host's path. */+ function elsewhere() {+ const started: { script: string; args: string[]; write?: boolean; stdin?: boolean }[] = [];+ const inside = path.join(root, 'inside');+ symlinkSync(ws.forkPath, inside);+ const f = createWorkspaceFiles({+ dir: path.join(root, 'scratch2'),+ place: () => ({+ root: inside,+ spawn(argv, mode) {+ started.push({ script: argv[2], args: argv.slice(3), ...mode });+ return spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] });+ },+ }),+ });+ return { f, started, nowhere: { sessionId: 'cs_t', forkPath: '/nonexistent/on/this/host' } };+ }++ it('reaches every file through the place, never through the host path, and nothing chosen by the caller is script text', async () => {+ const { f, started, nowhere } = elsewhere();+ const l = await f.list(nowhere, { path: 'repo', depth: 2 });+ expect('entries' in l && l.entries.map((e) => e.path)).toEqual(['repo/.git', 'repo/README.md', 'repo/bin.dat', 'repo/src', 'repo/src/a.ts']);+ const one = await f.file(nowhere, 'repo/README.md');+ if ('error' in one) throw new Error(one.error.code);+ expect((await collect(one.read().stream)).toString()).toBe('# hi\n');+ const a = await f.archive(nowhere, 'repo/src');+ expect(a).toMatchObject({ files: 2, bytes: 20 });+ const up = await f.upload(nowhere, 'pushed', 'tar', actor, body(tarOf(path.join(ws.forkPath, 'repo/src'))));+ expect(up).toMatchObject({ upload: { path: 'pushed', files: 2 } });+ expect(readFileSync(path.join(ws.forkPath, 'pushed/a.ts'), 'utf8')).toContain('export const a');+ for (const s of started) {+ expect(s.args[0]).toBe('sh');+ expect(s.args[1]).toBe(path.join(root, 'inside'));+ for (const word of ['repo', 'README', 'pushed']) expect(s.script.includes(word), word).toBe(false);+ }+ // Only an upload's scripts may change the workspace, and only its unpacking reads standard input.+ const writers = started.filter((s) => s.write);+ expect(writers.map((s) => s.args[2].replace(/-[0-9a-f]{12}$/, ''))).toEqual(['.opc-upload-pushed', '.opc-upload-pushed']);+ expect(started.filter((s) => s.stdin)).toHaveLength(1);+ expect(started.filter((s) => !s.write).length).toBeGreaterThanOrEqual(5);+ });++ it('holds a symlink to the place it is resolved in: outside is invalid_path for every read', async () => {+ const { f, nowhere } = elsewhere();+ symlinkSync('/etc/hostname', path.join(ws.forkPath, 'repo/leak'));+ symlinkSync('README.md', path.join(ws.forkPath, 'repo/alias'));+ for (const p of ['escape', 'repo/leak', 'escape/hostname']) {+ expect(await f.file(nowhere, p), p).toMatchObject({ error: { code: 'invalid_path' } });+ expect(await f.archive(nowhere, p), p).toMatchObject({ error: { code: 'invalid_path' } });+ }+ expect(await f.file(nowhere, 'repo/alias')).toMatchObject({ size: 5 });+ expect(await f.file(nowhere, 'repo/src')).toMatchObject({ error: { code: 'path_not_found' } });+ expect(await f.file(nowhere, 'repo/nope')).toMatchObject({ error: { code: 'path_not_found' } });+ expect(await f.canUpload(nowhere, '../x')).toMatchObject({ error: { code: 'invalid_path' } });+ expect(await f.canUpload(nowhere, '.hidden')).toMatchObject({ error: { code: 'invalid_path' } });+ });++ it('fails, and reads nothing on the host, when a workspace has no place', async () => {+ const f = createWorkspaceFiles({ dir: path.join(root, 'scratch3'), place: () => { throw new Error('session cs_t has no sandbox'); } });+ await expect(f.list(ws, { path: '' })).rejects.toThrow('no sandbox');+ await expect(f.file(ws, 'repo/README.md')).rejects.toThrow('no sandbox');+ await expect(f.canUpload(ws, 'x')).rejects.toThrow('no sandbox');+ });++ it('a place that starts its scripts later, or cannot now: the caller gets the place\'s own refusal, and a download ends with it', async () => {+ let refuse = false;+ const f = createWorkspaceFiles({+ dir: path.join(root, 'scratch4'),+ place: () => ({+ root: ws.forkPath,+ spawn: async (argv) => {+ await new Promise((r) => setTimeout(r, 20));+ if (refuse) throw new Unavailable('The computer is updating, try again.');+ return spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] });+ },+ }),+ });+ const file = await f.file(ws, 'repo/README.md');+ if ('error' in file) throw new Error(file.error.code);+ expect((await collect(file.read().stream)).toString()).toBe('# hi\n');+ refuse = true;+ await expect(f.list(ws, { path: '' })).rejects.toBeInstanceOf(Unavailable);+ const r = file.read();+ expect((await collect(r.stream)).length).toBe(0);+ await expect(r.done).rejects.toThrow('The computer is updating');+ await expect(f.upload(ws, 'x', 'tar', actor, body(tarOf(path.join(ws.forkPath, 'repo/src'))))).rejects.toBeInstanceOf(Unavailable);+ });++ describe('a session that stops under a script (work 103, C13)', () => {+ /** A place whose scripts numbered in `lose` are killed as a stopped container kills them, after printing `said`. */+ function stopping(lose: number[], said = '') {+ const started: { write?: boolean }[] = [];+ const lost = new Set<unknown>();+ const f = createWorkspaceFiles({+ dir: path.join(root, 'scratch5'),+ place: () => ({+ root: ws.forkPath,+ spawn(argv, mode) {+ started.push({ write: mode.write });+ if (!lose.includes(started.length)) return spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] });+ const p = spawn('/bin/sh', ['-c', 'printf %s "$1"; kill -9 $$', 'sh', said], { stdio: ['pipe', 'pipe', 'pipe'] });+ lost.add(p);+ return p;+ },+ lost: async (p) => lost.has(p),+ }),+ });+ return { f, started };+ }++ it('a script that only reads is run once more, where the session is then', async () => {+ const t = stopping([1, 3]);+ const l = await t.f.list(ws, { path: 'repo/src' });+ expect('entries' in l && l.entries.map((e) => e.path)).toEqual(['repo/src/a.ts']);+ const file = await t.f.file(ws, 'repo/README.md');+ expect(file).toMatchObject({ size: 5 });+ expect(t.started).toHaveLength(4);+ // Twice in a row: said, not tried for ever.+ await expect(stopping([1, 2]).f.list(ws, { path: '' })).rejects.toThrow(/The session stopped/);+ });++ it('a download that had sent nothing starts again; one that had sent bytes fails, and says why', async () => {+ const t = stopping([2]);+ const file = await t.f.file(ws, 'repo/README.md');+ if ('error' in file) throw new Error(file.error.code);+ const r = file.read();+ expect((await collect(r.stream)).toString()).toBe('# hi\n');+ await r.done;+ expect(t.started).toHaveLength(3);+ const cut = stopping([2], 'half');+ const again = await cut.f.file(ws, 'repo/README.md');+ if ('error' in again) throw new Error(again.error.code);+ const c = again.read();+ expect((await collect(c.stream)).toString()).toBe('half');+ await expect(c.done).rejects.toBeInstanceOf(Unavailable);+ expect(cut.started).toHaveLength(2);+ });++ it('a script that writes is never run twice: the upload fails with words, and nothing is in place', async () => {+ // 1 is the name's check, 2 the unpacking, which the stop kills.+ const t = stopping([2]);+ const up = await t.f.upload(ws, 'pushed', 'tar', actor, body(tarOf(path.join(ws.forkPath, 'repo/src'))));+ expect(up).toMatchObject({ error: { code: 'unavailable', status: 503, retryable: true, message: expect.stringMatching(/The session stopped while its files were being changed/) } });+ expect(existsSync(path.join(ws.forkPath, 'pushed'))).toBe(false);+ expect(t.started.filter((s) => s.write).length).toBe(2); // the unpacking, and the removal of what it left+ // The move into place, killed: said too, not taken for a name that changed.+ const moved = stopping([3]);+ const m = await moved.f.upload(ws, 'pushed2', 'tar', actor, body(tarOf(path.join(ws.forkPath, 'repo/src'))));+ expect(m).toMatchObject({ error: { code: 'unavailable' } });+ });+ });++ it('orders a listing by path components, whatever order find printed it in', () => {+ const rec = (y: string, p: string) => `${y}\t3\t1700000000.5000000000\t${p}\0`;+ const out = Buffer.from(rec('f', 'b') + rec('f', 'a/z') + rec('d', 'a') + rec('f', 'a.txt') + rec('l', 'a/b c\nd') + rec('f', 'B'));+ expect(parseListing(out).map((e) => `${e.type}:${e.rel}`)).toEqual(['file:B', 'dir:a', 'symlink:a/b c\nd', 'file:a/z', 'file:a.txt', 'file:b']);+ expect(parseListing(out)[0].modifiedAt).toBe('2023-11-14T22:13:20.500Z');+ });+});diff --git a/computer/src/host/workspace-files.ts b/computer/src/host/workspace-files.tsindex e65489c0..e4918505 100644--- a/computer/src/host/workspace-files.ts+++ b/computer/src/host/workspace-files.ts@@ -4,39 +4,87 @@// this decides what is allowed and does the filesystem work.//// Invariants:-// - Every path resolves inside the session's fork (symlinks included); one-// that leaves it is `invalid_path`, one that does not exist `path_not_found`.-// - Writes run as the runner user (`user.sudo`, as runners are launched), so-// an upload belongs to the agent and the host never writes into a fork as-// itself. Reads of content (`cat`, `tar -c`) run as that user too; listing-// and stat run in the host, which is in the agent's group.+// - The host never opens, lists or stats a workspace file itself (work 103,+// C13): every operation is one `sh -c` script (GNU coreutils, findutils and+// tar) started by the workspace's Place, as the runners' user where the+// session's files are. On a host whose sessions run in containers that is+// inside the session's container, or a helper container with the+// workspace bound when the session is stopped (sandbox/scripts.ts+// `filesPlace`); there a workspace without a sandbox has no Place and the+// call fails.+// - A script that ended because the session stopped under it (the Place says+// so, `lost`) is run once more, where the session is then, only when it+// changes nothing and none of its output was passed on: a listing, a stat,+// a download that had sent no byte. A script that writes, and a download+// cut part way, fail as Unavailable, with words that say the session+// stopped (work 103, C13).+// - Every path resolves inside the workspace (symlinks included); one that+// leaves it is `invalid_path` (the script's exit 45), one that does not+// exist `path_not_found` (44). The check and the read are the same script+// in the same process, so nothing on the host acts on a path checked+// earlier. Paths and names reach a script as arguments, never as its text.// - An upload is checked as it streams (tar-check.ts), unpacked into a hidden// directory beside its target, and renamed into place only when complete;-// a failure removes it and changes nothing. A name that exists and was not-// uploaded is `path_exists`; uploads in one session are serialized.+// a failure removes it and changes nothing. The script that unpacks removes+// its own directory when it does not finish, and the next upload of the+// session removes what a killed one left: the host's own removal is not+// relied on, since the script may outlive the process the host started. A+// name that exists and was not uploaded is `path_exists`; uploads in one+// session are serialized.+// - A script is ended before it is done (its time is up, it printed too+// much, its upload failed, the reader of its download went away) with+// SIGTERM, never SIGKILL: the place decides what that ends (on a `podman`+// host timeout(1) under sudo, and the limit inside the container or of the+// helper, sandbox/scripts.ts `filesPlace`).// - Which top-level names were uploaded, when and by whom, is kept in// `<stateDir>/<sessionId>.json` (0600, the host's); losing it fails safe// (a re-push of that name is refused until it is removed).-import { spawn } from 'node:child_process';+import { type ChildProcess, spawn } from 'node:child_process';import { randomBytes } from 'node:crypto';import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';-import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';import path from 'node:path';-import type { Readable, Writable } from 'node:stream';+import { PassThrough, type Readable, Writable } from 'node:stream';import { pipeline } from 'node:stream/promises';import zlib from 'node:zlib';import type { ApiActor, ApiError } from '../protocol.js';import { apiError } from '../api/writer.js';import type { RunnerUser } from './runner-user.js';+import { Unavailable, unavailable } from './unavailable.js';+import type { SandboxPlace } from './sandbox/scripts.js';import { TarCheck, TarError, UPLOAD_MAX_BYTES, UPLOAD_MAX_FILES } from './tar-check.js';+import { ARCHIVE, CAN_UPLOAD, CAT, COUNT, LIST, MOVE_IN, NOT_FOUND, OUTSIDE, REMOVE, STAT, UNPACK } from './workspace-scripts.js';export const FILE_MAX_BYTES = 100 * 1024 ** 2;const LIST_WALK_MAX = 200_000;+/** How long a script that answers with a few lines may take (a helper container starts in well under a second). */+const SCRIPT_WAIT_MS = 30_000;+/** Seconds a script that carries a file, an archive or an upload may take. */+const STREAM_WAIT_S = 3600;+const OUTPUT_MAX = 64 * 2 ** 20;+/** How long a script that was told to end has before its process is killed: past timeout(1)'s own 2 s (sandbox/podman.ts). */+const LAST_RESORT_MS = 5_000;+export interface Workspace {sessionId: string;+ /** The workspace on the host. */forkPath: string;+ /** Where it is when the session runs in a container (work 103). */+ sandbox?: SandboxPlace;+}++/** Where a workspace's files are reached: `root` is the workspace as a process started by `spawn` sees it. */+export interface Place {+ root: string;+ /**+ * `argv`: `/bin/sh` and what it is given. `write`: the script changes the workspace; `stdin`: it reads its standard+ * input; `seconds`: how long it may run, for a Place that can end it where it runs. stdio is always three pipes.+ * A Place that cannot start anything now rejects with Unavailable (unavailable.ts), which the caller is told.+ */+ spawn(argv: string[], o: { write?: boolean; stdin?: boolean; seconds?: number }): ChildProcess | Promise<ChildProcess>;+ /** A script this Place started has ended, and not by itself: the session it ran in stopped under it. */+ lost?(p: ChildProcess): Promise<boolean>;}export interface ListEntry {@@ -78,8 +126,16 @@ export interface WorkspaceFilesOptions {/** Where upload records live; should survive a reboot (HOST_DATA/state/uploads). Default `<dir>/state`. */stateDir?: string;user?: RunnerUser;+ /** How long a script that answers with a few lines may take (30 s); tests pass less. */+ scriptWaitMs?: number;+ /** Where a workspace's scripts run. Default: on this machine, as `user`, at the workspace's own path. */+ place?(ws: Workspace): Place;}+const STOPPED_WRITE = 'The session stopped while its files were being changed. Try again.';+const STOPPED_READ = 'The session stopped while its files were being read. Try again.';+const STOPPED_DOWNLOAD = 'The session stopped during the download. Try again.';+const notFound = (): Fail => ({ error: apiError('path_not_found', 'Nothing at path.', 404) });const badPath = (): Fail => ({ error: apiError('invalid_path', 'path must be relative and stay inside the workspace.', 400) });@@ -97,34 +153,146 @@ export function contentType(name: string, head: Buffer): string {return head.includes(0) ? 'application/octet-stream' : 'text/plain; charset=utf-8';}+/** A top-level name an upload may take (the relay checks the same, src/wire/files.ts): it becomes part of file names in the workspace. */+const UPLOAD_NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;++interface Listed {+ rel: string;+ type: ListEntry['type'];+ bytes: number;+ modifiedAt: string;+}++/** What LIST printed (`type\tsize\tmtime\tpath\0` per entry), in path order: a directory before its contents, names by code unit. */+export function parseListing(out: Buffer): Listed[] {+ const rows: { parts: string[]; e: Listed }[] = [];+ for (const rec of out.toString('utf8').split('\0')) {+ const m = /^(.)\t(\d+)\t([\d.]+)\t([\s\S]+)$/.exec(rec);+ if (!m) continue;+ const type = m[1] === 'l' ? 'symlink' : m[1] === 'd' ? 'dir' : 'file';+ rows.push({ parts: m[4].split('/'), e: { rel: m[4], type, bytes: Number(m[2]), modifiedAt: new Date(Math.floor(Number(m[3]) * 1000)).toISOString() } });+ }+ rows.sort((a, b) => {+ for (let i = 0; i < a.parts.length && i < b.parts.length; i++) if (a.parts[i] !== b.parts[i]) return a.parts[i] < b.parts[i] ? -1 : 1;+ return a.parts.length - b.parts.length;+ });+ return rows.map((r) => r.e);+}+export function createWorkspaceFiles(o: WorkspaceFilesOptions): WorkspaceFiles {const stateDir = o.stateDir ?? path.join(o.dir, 'state');mkdirSync(stateDir, { recursive: true, mode: 0o700 });const chains = new Map<string, Promise<unknown>>();+ const waitMs = o.scriptWaitMs ?? SCRIPT_WAIT_MS;- const asUser = (argv: string[], stdio: ('pipe' | 'ignore')[] = ['ignore', 'pipe', 'pipe']) => {- const [cmd, ...args] = [...(o.user?.sudo ?? []), ...argv];- return spawn(cmd, args, { stdio: stdio as ['pipe', 'pipe', 'pipe'], env: { ...process.env, ...o.user?.env } });- };- const runAsUser = (argv: string[]) =>- new Promise<void>((resolve, reject) => {- const p = asUser(argv);+ const onHost = (ws: Workspace): Place => ({+ root: ws.forkPath,+ spawn(argv) {+ const [cmd, ...args] = [...(o.user?.sudo ?? []), ...argv];+ return spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, ...o.user?.env } });+ },+ });+ const placeOf = o.place ?? onHost;++ /**+ * End a script before its time: SIGTERM, which sudo passes on and timeout(1) turns into the end of the command and+ * all it started (sandbox/podman.ts), and which a script that cleans up after itself acts on. SIGKILL would stop at+ * sudo, or at the shell, and leave the rest running. `LAST_RESORT_MS` later the child itself is killed, so that+ * whoever waits for its exit never waits for good.+ */+ function end(p: ChildProcess) {+ if (p.exitCode !== null || p.signalCode !== null) return;+ p.kill('SIGTERM');+ const last = setTimeout(() => p.kill('SIGKILL'), LAST_RESORT_MS);+ last.unref();+ p.once('exit', () => clearTimeout(last));+ }++ const places = new WeakMap<ChildProcess, Place>();+ /** `p` failed because the session stopped under it. */+ const lost = async (p: ChildProcess) => (await places.get(p)?.lost?.(p)) ?? false;++ /** Start `script` with the workspace's root as `$1` and `args` after it. */+ async function start(ws: Workspace, script: string, args: string[], mode: { write?: boolean; stdin?: boolean; seconds?: number } = {}): Promise<ChildProcess> {+ const place = placeOf(ws);+ const p = await place.spawn(['/bin/sh', '-c', script, 'sh', place.root, ...args], { seconds: STREAM_WAIT_S, ...mode });+ places.set(p, place);+ p.stdin?.on('error', () => {});+ if (!mode.stdin) p.stdin?.end();+ return p;+ }++ /** Run `script` to its end: its exit code and what it printed. Rejects when it cannot start, runs too long or prints too much. */+ async function run(ws: Workspace, script: string, args: string[], mode: { write?: boolean } = {}, again = true): Promise<{ code: number | null; out: Buffer; err: string }> {+ const p = await start(ws, script, args, { ...mode, seconds: waitMs / 1000 });+ const r = await once(p);+ if (r.code === 0 || !(await lost(p))) return r;+ // What a script that writes had done when the session stopped is not known: it is not done twice.+ if (mode.write) throw new Unavailable(STOPPED_WRITE);+ if (again) return run(ws, script, args, mode, false);+ throw new Unavailable(STOPPED_READ);+ }+ function once(p: ChildProcess): Promise<{ code: number | null; out: Buffer; err: string }> {+ return new Promise((resolve, reject) => {+ const out: Buffer[] = [];+ let bytes = 0;let err = '';- p.stderr?.on('data', (d: Buffer) => (err += d.toString('utf8')).slice(0, 2000));- p.stdout?.resume();- p.once('error', reject);- p.once('exit', (code) => (code === 0 ? resolve() : reject(new Error(err.trim() || `${argv[0]} exited ${code}`))));- });- const streamed = (argv: string[]): Streamed => {- const p = asUser(argv);- let err = '';- p.stderr?.on('data', (d: Buffer) => (err = (err + d.toString('utf8')).slice(-2000)));- const done = new Promise<void>((resolve, reject) => {- p.once('error', reject);- p.once('exit', (code) => (code === 0 ? resolve() : reject(new Error(err.trim() || `${argv[0]} exited ${code}`))));+ const timer = setTimeout(() => (end(p), reject(new Error(`workspace script ran over ${waitMs} ms`))), waitMs);+ p.stdout?.on('data', (d: Buffer) => {+ out.push(d);+ if ((bytes += d.length) > OUTPUT_MAX) end(p), reject(new Error('workspace script printed too much'));+ });+ p.stderr?.on('data', (d: Buffer) => (err = (err + d.toString('utf8')).slice(-2000)));+ p.once('error', (e) => (clearTimeout(timer), reject(e)));+ p.once('close', (code) => (clearTimeout(timer), resolve({ code, out: Buffer.concat(out), err })));});- done.catch(() => {});- return { stream: p.stdout as Readable, done };+ }++ /** `invalid_path` and `path_not_found` from a script's exit code; any other failure is the host's, and thrown. */+ function failed(r: { code: number | null; err: string }): Fail | undefined {+ if (r.code === 0) return undefined;+ if (r.code === NOT_FOUND) return notFound();+ if (r.code === OUTSIDE) return badPath();+ throw new Error(`workspace script exited ${r.code}: ${r.err.trim().split('\n').pop() ?? ''}`);+ }+ const refusedPath = (rel: string) => rel.startsWith('/') || rel.split('/').includes('..') || rel.includes('\0');++ /** A script whose output is the answer's body. The stream is there at once; the script starts when its place lets it, and `done` says how it went. */+ const streamed = (ws: Workspace, script: string, args: string[]): Streamed => {+ const stream = new PassThrough();+ const attempt = async (again: boolean): Promise<void> => {+ const p = await start(ws, script, args);+ let err = '';+ p.stderr?.on('data', (d: Buffer) => (err = (err + d.toString('utf8')).slice(-2000)));+ const exited = new Promise<number | null>((resolve, reject) => {+ p.once('error', reject);+ p.once('exit', resolve);+ });+ // Whoever read it went away before its end (the request was cut): nobody is left to end the script by closing it.+ const gone = () => stream.readableEnded || end(p);+ if (stream.destroyed) end(p);+ else stream.once('close', gone);+ // The body ends when the script is known to have ended well: one the session stopped under may start again.+ const out = p.stdout as Readable;+ let sent = 0;+ out.on('data', (d: Buffer) => (sent += d.length));+ const drained = new Promise<void>((resolve) => {+ for (const e of ['end', 'close', 'error']) out.once(e, () => resolve());+ stream.once('close', () => resolve());+ });+ out.pipe(stream, { end: false });+ const code = await exited;+ if (code === 0) return void (out.readableEnded ? stream.end() : out.once('end', () => stream.end()));+ if (!stream.destroyed) await drained;+ if (!(await lost(p))) throw new Error(err.trim() || `workspace script exited ${code}`);+ if (sent > 0 || !again || stream.destroyed) throw new Unavailable(STOPPED_DOWNLOAD);+ stream.off('close', gone);+ return attempt(false);+ };+ const done = attempt(true);+ // A script that never started has nothing to say: the body ends, and `done` tells why.+ done.catch(() => stream.end());+ return { stream, done };};const statePath = (sessionId: string) => path.join(stateDir, `${sessionId}.json`);@@ -141,43 +309,6 @@ export function createWorkspaceFiles(o: WorkspaceFilesOptions): WorkspaceFiles {renameSync(tmp, statePath(sessionId));};- /** The real path of `rel` in the fork, if it exists and stays inside. */- async function resolveIn(ws: Workspace, rel: string): Promise<{ abs: string } | Fail> {- if (rel.startsWith('/') || rel.split('/').includes('..') || rel.includes('\0')) return badPath();- let root: string;- let abs: string;- try {- root = await realpath(ws.forkPath);- abs = await realpath(path.join(root, rel));- } catch {- return notFound();- }- if (abs !== root && !abs.startsWith(root + path.sep)) return badPath();- return { abs };- }-- async function count(abs: string, limitFiles: number, limitBytes: number) {- let files = 0;- let bytes = 0;- const visit = async (p: string): Promise<void> => {- const st = await lstat(p);- if (!st.isDirectory()) {- files += 1;- if (st.isFile()) bytes += st.size;- return;- }- files += 1;- if (files > limitFiles || bytes > limitBytes) return;- for (const name of await readdir(p)) {- if (name === '.git') continue;- await visit(path.join(p, name));- if (files > limitFiles || bytes > limitBytes) return;- }- };- await visit(abs);- return { files, bytes };- }-function serialized<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {const prev = chains.get(sessionId) ?? Promise.resolve();const next = prev.then(fn, fn);@@ -201,92 +332,64 @@ export function createWorkspaceFiles(o: WorkspaceFilesOptions): WorkspaceFiles {return { error: apiError('invalid_cursor', 'cursor is not from this listing.', 400) };}}- const r = await resolveIn(ws, q.path);- if ('error' in r) return r;- if (!(await stat(r.abs)).isDirectory()) return notFound();+ if (refusedPath(q.path)) return badPath();+ const r = await run(ws, LIST, [q.path, String(depth), String(LIST_WALK_MAX + 1)]);+ const fail = failed(r);+ if (fail) return fail;const pushed = q.path === '' ? readState(ws.sessionId) : {};- const entries: ListEntry[] = [];- let seen = 0;- let more = false;- const walk = async (dir: string, rel: string, level: number): Promise<boolean> => {- let names: string[];- try {- names = (await readdir(dir)).sort();- } catch {- return true;- }- for (const name of names) {- const childRel = rel ? `${rel}/${name}` : name;- const p = path.join(dir, name);- const st = await lstat(p).catch(() => undefined);- if (!st) continue;- if (seen++ >= offset) {- if (entries.length === limit) {- more = true;- return false;- }- const type = st.isSymbolicLink() ? 'symlink' : st.isDirectory() ? 'dir' : 'file';- const pr = level === 1 && type === 'dir' ? pushed[name] : undefined;- entries.push({- path: q.path ? `${q.path}/${childRel}` : childRel,- type,- bytes: type === 'file' ? st.size : null,- modifiedAt: st.mtime.toISOString(),- pushedAt: pr?.pushedAt ?? null,- pushedBy: pr?.pushedBy ?? null,- });- }- if (seen > LIST_WALK_MAX) return false;- if (st.isDirectory() && name !== '.git' && level < depth && !(await walk(p, childRel, level + 1))) return false;- }- return true;- };- await walk(r.abs, '', 1);- const nextCursor = more ? Buffer.from(JSON.stringify({ p: q.path, d: depth, o: offset + entries.length })).toString('base64url') : null;+ const page = parseListing(r.out).slice(offset, offset + limit + 1);+ const entries = page.slice(0, limit).map((e): ListEntry => {+ const pr = e.type === 'dir' && !e.rel.includes('/') ? pushed[e.rel] : undefined;+ return { path: q.path ? `${q.path}/${e.rel}` : e.rel, type: e.type, bytes: e.type === 'file' ? e.bytes : null, modifiedAt: e.modifiedAt,+ pushedAt: pr?.pushedAt ?? null, pushedBy: pr?.pushedBy ?? null };+ });+ const nextCursor = page.length > limit ? Buffer.from(JSON.stringify({ p: q.path, d: depth, o: offset + entries.length })).toString('base64url') : null;return { path: q.path, entries, nextCursor };},async file(ws, rel) {- const r = await resolveIn(ws, rel);- if ('error' in r) return r;- const st = await stat(r.abs);- if (!st.isFile()) return notFound();- if (st.size > FILE_MAX_BYTES) return { error: apiError('too_large', 'The file is over 100 MiB. Download it as an archive.', 413, { bytes: st.size }) };- const head = Buffer.alloc(Math.min(8192, st.size));- try {- const fh = await open(r.abs, 'r');- await fh.read(head, 0, head.length, 0).finally(() => fh.close());- } catch {- head.fill(0); // unreadable here: still served as the user, typed as bytes- }+ if (refusedPath(rel)) return badPath();+ const r = await run(ws, STAT, [rel]);+ const fail = failed(r);+ if (fail) return fail;+ const [stat, head64 = ''] = r.out.toString('latin1').split('\n');+ const [size, mtime, ino] = stat.split(' ');+ const bytes = Number(size);+ if (!Number.isSafeInteger(bytes)) throw new Error(`workspace stat printed ${stat.slice(0, 80)}`);+ if (bytes > FILE_MAX_BYTES) return { error: apiError('too_large', 'The file is over 100 MiB. Download it as an archive.', 413, { bytes }) };return {- size: st.size,- etag: `"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}-${st.ino.toString(36)}"`,- contentType: contentType(r.abs, head),- read: () => streamed(['cat', '--', r.abs]),+ size: bytes,+ etag: `"${bytes.toString(36)}-${Math.floor(Number(mtime) * 1000).toString(36)}-${Number(ino).toString(36)}"`,+ contentType: contentType(rel, Buffer.from(head64, 'base64')), // empty when it could not be read: typed as text, served as the user+ read: () => streamed(ws, CAT, [rel]),};},async archive(ws, rel) {- const r = await resolveIn(ws, rel);- if ('error' in r) return r;- const n = await count(r.abs, UPLOAD_MAX_FILES, UPLOAD_MAX_BYTES);- if (n.files > UPLOAD_MAX_FILES || n.bytes > UPLOAD_MAX_BYTES) {- return { error: apiError('too_large', 'Over 1 GiB or 100,000 files.', 413, { bytes: n.bytes, files: n.files }) };+ if (refusedPath(rel)) return badPath();+ const r = await run(ws, COUNT, [rel, String(UPLOAD_MAX_FILES + 1)]);+ const fail = failed(r);+ if (fail) return fail;+ let files = 0;+ let bytes = 0;+ for (const line of r.out.toString('latin1').split('\n')) {+ const m = /^(.) (\d+)$/.exec(line);+ if (!m) continue;+ files += 1;+ if (m[1] === 'f') bytes += Number(m[2]);+ }+ if (!files) throw new Error('workspace count printed nothing');+ if (files > UPLOAD_MAX_FILES || bytes > UPLOAD_MAX_BYTES) {+ return { error: apiError('too_large', 'Over 1 GiB or 100,000 files.', 413, { bytes, files }) };}- const isDir = (await stat(r.abs)).isDirectory();- const [cwd, member] = isDir ? [r.abs, '.'] : [path.dirname(r.abs), path.basename(r.abs)];- const argv = ['tar', '-c', '--exclude=.git', '--owner=0', '--group=0', '--numeric-owner', '--mode=u+rw,go-w,a+rX', '-C', cwd, '-f', '-', '--', member];- return { ...n, read: () => streamed(argv) };+ return { files, bytes, read: () => streamed(ws, ARCHIVE, [rel]) };},async canUpload(ws, name) {- const target = path.join(ws.forkPath, name);- const exists = await lstat(target).then(- () => true,- () => false,- );- if (exists && !readState(ws.sessionId)[name]) {+ if (!UPLOAD_NAME.test(name)) return badPath();+ const r = await run(ws, CAN_UPLOAD, [name]);+ if (r.code !== 0) throw new Error(`workspace script exited ${r.code}: ${r.err.trim()}`);+ if (r.out.toString('latin1').trim() === 'exists' && !readState(ws.sessionId)[name]) {return { error: apiError('path_exists', `${name} exists in the workspace and was not uploaded.`, 409) };}return undefined;@@ -300,43 +403,54 @@ export function createWorkspaceFiles(o: WorkspaceFilesOptions): WorkspaceFiles {return taken;}const tag = randomBytes(6).toString('hex');- const tmp = path.join(ws.forkPath, `.opc-upload-${name}-${tag}`);- const trash = path.join(ws.forkPath, `.opc-replaced-${name}-${tag}`);- const target = path.join(ws.forkPath, name);+ const tmp = `.opc-upload-${name}-${tag}`;+ const trash = `.opc-replaced-${name}-${tag}`;+ const remove = () => run(ws, REMOVE, [tmp], { write: true }).catch(() => {});const check = new TarCheck();- const tar = asUser(['sh', '-c', 'mkdir -- "$1" && exec tar -x --no-same-owner --no-same-permissions -C "$1" -f -', 'sh', tmp], ['pipe', 'ignore', 'pipe']);+ const tar = await start(ws, UNPACK, [tmp], { write: true, stdin: true });+ tar.stdout?.resume();let tarErr = '';tar.stderr?.on('data', (d: Buffer) => (tarErr = (tarErr + d.toString('utf8')).slice(-1000)));const exited = new Promise<number | null>((resolve) => {tar.once('exit', resolve);tar.once('error', () => resolve(-1));});- tar.stdin?.on('error', () => {});+ // tar stops reading at the end-of-archive mark and may exit before the body's last bytes (padding) are written:+ // its closed input is then no failure of the body, so the rest is checked and written to nobody. A tar that+ // failed ends the transfer at once.const sink = tar.stdin as Writable;+ let closed = false;+ sink.once('close', () => (closed = true));+ const toTar = new Writable({+ write: (chunk, _enc, cb) => (closed ? cb() : void sink.write(chunk, () => cb())),+ final: (cb) => (closed ? cb() : void sink.end(() => cb())),+ destroy: (err, cb) => (sink.destroy(), cb(err)),+ });+ tar.once('exit', (code) => code !== 0 && toTar.destroy(new Error('tar failed')));const z = format === 'tar+gzip' ? zlib.createGunzip() : format === 'tar+zstd' ? zlib.createZstdDecompress() : undefined;let failure: ApiError | undefined;try {- await (z ? pipeline(body, z, check, sink) : pipeline(body, check, sink));+ await (z ? pipeline(body, z, check, toTar) : pipeline(body, check, toTar));} catch (e) {failure = e instanceof TarError ? e.error : apiError('invalid_archive', `The body could not be read as ${format}.`, 400);- tar.kill('SIGKILL');+ end(tar);}const code = await exited;+ if (code !== 0 && (await lost(tar))) failure = unavailable(new Unavailable(STOPPED_WRITE));// tar quitting first breaks the pipe: its own message says why, the pipe's does not.- if (code !== 0 && tarErr.trim() && failure?.code === 'invalid_archive' && failure.message.startsWith('The body could not be read')) failure = undefined;+ else if (code !== 0 && tarErr.trim() && failure?.code === 'invalid_archive' && failure.message.startsWith('The body could not be read')) failure = undefined;if (!failure && code !== 0) failure = apiError('invalid_archive', `The archive could not be unpacked: ${tarErr.trim().split('\n').pop() ?? ''}`, 400);if (failure) {- await runAsUser(['rm', '-rf', '--', tmp]).catch(() => {});+ await remove();return { error: failure };}const state = readState(ws.sessionId);const prev = state[name] ?? null;- try {- // -T: never move into a directory that appeared meanwhile; a name the agent created since the check fails here.- await runAsUser(['sh', '-c', 'set -e; if [ -n "$4" ]; then mv -T -- "$2" "$3"; fi; mv -T -- "$1" "$2"; rm -rf -- "$3"', 'sh', tmp, target, trash, prev ? '1' : '']);- } catch {- await runAsUser(['rm', '-rf', '--', tmp]).catch(() => {});- return { error: apiError('path_exists', `${name} changed in the workspace during the upload.`, 409) };+ let stopped: ApiError | undefined;+ const moved = await run(ws, MOVE_IN, [tmp, name, trash, prev ? '1' : ''], { write: true }).catch((e) => void (stopped = unavailable(e)));+ if (moved?.code !== 0) {+ await remove();+ return { error: stopped ?? apiError('path_exists', `${name} changed in the workspace during the upload.`, 409) };}state[name] = { pushedAt: new Date().toISOString(), pushedBy: actor };writeState(ws.sessionId, state);diff --git a/computer/src/host/workspace-scripts.ts b/computer/src/host/workspace-scripts.tsnew file mode 100644index 00000000..42faf235--- /dev/null+++ b/computer/src/host/workspace-scripts.ts@@ -0,0 +1,90 @@+// The shell scripts behind the `/files` routes (workspace-files.ts): each is+// the whole of one operation, run by `/bin/sh -c <script> sh <root> <args…>`+// where the workspace's files are (work 103, C13). They need GNU coreutils,+// findutils and tar, which every computer and the session image have.+//+// Invariants:+// - `$1` is the workspace's root as the script's process sees it; what the+// caller chose (a path, a name, a number) is `$2` and up. Nothing is ever+// put into a script's text.+// - A script that takes a path resolves it first, symlinks included, and+// acts on the resolved path only: exit 44 when it does not exist (or is not+// the kind the operation reads), 45 when it leaves the workspace. Any other+// non-zero exit is a fault.+// - `.git` is never descended into, archived or counted.++export const NOT_FOUND = 44;+export const OUTSIDE = 45;++/** `$abs`: the real path of `$2` under the real `$root`. */+const RESOLVE = `+root=$(realpath -e -- "$1" 2>/dev/null) || exit ${NOT_FOUND}+abs=$(realpath -e -- "$root/$2" 2>/dev/null) || exit ${NOT_FOUND}+case "$abs" in "$root"|"$root"/*) ;; *) exit ${OUTSIDE};; esac+`;++/**+ * `<path> <depth> <most>`: the entries of a directory down to `depth`, at most `most`, each+ * `type\tbytes\tmtime\tpath\0` (find's %y %s %T@ %P). A `.git` is listed and not entered; a directory that cannot+ * be read is listed and skipped.+ */+export const LIST = `${RESOLVE}+[ -d "$abs" ] || exit ${NOT_FOUND}+cd "$abs" || exit ${NOT_FOUND}+find . -mindepth 1 -maxdepth "$3" -printf '%y\\t%s\\t%T@\\t%P\\0' -name .git -prune 2>/dev/null | head -z -n "$4"+`;++/** `<path>`: a regular file's `size mtime inode` on one line, then its first 8192 bytes in base64 (nothing when it cannot be read). */+export const STAT = `${RESOLVE}+[ -f "$abs" ] || exit ${NOT_FOUND}+stat -c '%s %.3Y %i' -- "$abs" || exit 1+head -c 8192 -- "$abs" 2>/dev/null | base64 -w0+exit 0+`;++/** `<path>`: a regular file's bytes. */+export const CAT = `${RESOLVE}+[ -f "$abs" ] || exit ${NOT_FOUND}+exec cat -- "$abs"+`;++/** `<path> <most>`: `type bytes` for a directory and each entry under it, at most `most` lines; for anything else, one line for itself. */+export const COUNT = `${RESOLVE}+if [ -d "$abs" ]; then+ { echo 'd 0'; find "$abs" -mindepth 1 -name .git -prune -o -printf '%y %s\\n' 2>/dev/null; } | head -n "$3"+else+ stat -c 'f %s' -- "$abs"+fi+`;++/** `<path>`: a tar of a directory's contents, or of one file under its own name; owned by root, no mode a group or other can write. */+export const ARCHIVE = `${RESOLVE}+if [ -d "$abs" ]; then cd "$abs" || exit ${NOT_FOUND}; m=.; else cd "\${abs%/*}/" || exit ${NOT_FOUND}; m=\${abs##*/}; fi+exec tar -c --exclude=.git --owner=0 --group=0 --numeric-owner --mode=u+rw,go-w,a+rX -f - -- "$m"+`;++/** `<name>`: `exists` when the workspace has that name (a dangling link too), else `free`. */+export const CAN_UPLOAD = `if [ -e "$1/$2" ] || [ -L "$1/$2" ]; then echo exists; else echo free; fi`;++/**+ * `<tmp>`: unpack the tar on standard input into a new directory `tmp` of the workspace, and remove that directory+ * unless all of it was unpacked: when tar fails, when the input stops, and when the script is told to end (it waits for+ * `mkdir` or tar first, so no directory appears after it is gone). What an earlier upload left because it was killed+ * outright goes first: uploads of one session are one at a time, so every such name is a leftover.+ */+export const UNPACK = `trap 'exit 143' TERM HUP INT+rm -rf -- "$1"/.opc-upload-* "$1"/.opc-replaced-*+mkdir -- "$1/$2" || exit 1+ok=+trap '[ -n "$ok" ] || rm -rf -- "$1/$2"' EXIT+tar -x --no-same-owner --no-same-permissions -C "$1/$2" -f - && ok=1+`;++/**+ * `<tmp> <name> <trash> <replace>`: `tmp` becomes `name`; with `replace`, what was there goes first. `-T`: never+ * into a directory that appeared meanwhile, so a name the agent created since the check fails here.+ */+export const MOVE_IN = `set -e; if [ -n "$5" ]; then mv -T -- "$1/$3" "$1/$4"; fi; mv -T -- "$1/$2" "$1/$3"; rm -rf -- "$1/$4"`;++/** `<name>`: remove it and everything in it. */+export const REMOVE = `rm -rf -- "$1/$2"`;diff --git a/computer/src/ipc.ts b/computer/src/ipc.tsindex 7d0880b4..52c1c635 100644--- a/computer/src/ipc.ts+++ b/computer/src/ipc.ts@@ -38,6 +38,8 @@ export function send(sock: Socket | undefined, m: object) {/** The directory a runner sees as SP_RUN: HOST_RUN itself, or its own under HOST_RUN/sandbox (work 103). */export type RunRoot = string;export const runnersDir = (run: RunRoot) => path.join(run, 'runners');+/** The run root of the runner `id` in a container (work 103): its own directory, mounted at the same path inside. */+export const sandboxRunFor = (hostRun: string, id: string): RunRoot => path.join(hostRun, 'sandbox', id);/*** <run>/runners/<name>.sock, a `.pid` file next to it. The name is thediff --git a/computer/src/protocol.ts b/computer/src/protocol.tsindex cd0885b2..335c1c12 100644--- a/computer/src/protocol.ts+++ b/computer/src/protocol.ts@@ -470,7 +470,8 @@ export type HostToRunner =| { t: 'claim'; id: string; session: SessionSpec & { forkPath: string }; api?: RunnerApi }/** The session's owner changed (their name or email became known): commits from now on carry it. */| { t: 'owner'; owner: Person }- | HostToRunnerV4;+ /** Work 103: the previews a thread's container had before it stopped; once per start of the container, after `secrets` and before the first `deliver`. */+ | { t: 'preview-ports'; ports: { port: number; name: string }[] } | HostToRunnerV4;/** A repository checked out into a running session's fork (`checkout_repo`), cloned first if needed. */export interface CheckoutResult {diff --git a/computer/src/runner-env.ts b/computer/src/runner-env.tsindex 26abdd8a..afd0cd03 100644--- a/computer/src/runner-env.ts+++ b/computer/src/runner-env.ts@@ -20,6 +20,8 @@ export const RUNNER_ENV = ['SP_COMMITTER_NAME', 'SP_COMMITTER_EMAIL', 'SP_REAL_GH', 'SP_REAL_OPENCOMPUTER', 'SP_FAKE_SLACK', 'SP_SLACK_API_URL', 'MODEL', 'FOLD_AT', 'WORKDIR','PERMISSION_MODE', 'DISABLE_AUTOUPDATER', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM', 'SP_REGION', 'SP_SUBSTRATE','SP_PROMPT_CACHE_TTL', 'SP_CONTEXT_WINDOW', 'SP_COMPACT_AT', 'SP_PROMPT_GUARD', 'SP_CODEX_BIN', 'SP_CODEX_PEER_CHECK',+ // Set by a container's Create (work 103); empty elsewhere, and then the runner serves no preview socket.+ 'SP_PREVIEW_SOCKET',// Unset on a computer's host, but inherited each would run a session's code in, or route the traffic of,// another session's runner. The host's own value when it has one (a laptop's proxy).'NODE_OPTIONS', 'NODE_PATH', 'NODE_EXTRA_CA_CERTS', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'BASH_ENV',diff --git a/computer/src/runner/main.ts b/computer/src/runner/main.tsindex 280eaac2..e34b1c9c 100644--- a/computer/src/runner/main.ts+++ b/computer/src/runner/main.ts@@ -74,6 +74,7 @@ import { TIERS, tierOf } from '../tiers.js';import { codexRoot } from '../codex-home.js';import { meteredClient } from './surface-meter.js';import { serveFiles } from './send-file-socket.js';+import { servedPreviews } from './preview-socket.js';import { Waiters } from './waiters.js';import { TurnEvents } from './turn-events.js';import { sampleLoopLag } from './loop-lag.js';@@ -216,6 +217,10 @@ const report = (status: SessionReport['status'] = s!.isBusy ? 'busy' : 'idle'):});const sendSpare = () => spare && out({ t: 'spare', spare: { id: spec.id!, ready: spare.ready, version: spec.version, kind: spare.kind } });+const previews = servedPreviews(env.SP_PREVIEW_SOCKET, {+ preview: (req) => askGateway<PreviewToolResult>((id) => ({ t: 'preview', id, req })),+ unpreview: (name) => askGateway<unknown>((id) => ({ t: 'unpreview', id, req: { name } })).then(() => {}),+});const hooks: SessionHooks = {busy: (busy) => {out({ t: 'report', report: report() });@@ -226,10 +231,7 @@ const hooks: SessionHooks = {output: () => clearFeedback(),spawn,threads: { read: readThread, post: postThread, attach: (linked) => fetchAttachments(linkedFiles([linked]), botToken, ss!.key) },- previews: {- preview: (req) => askGateway<PreviewToolResult>((id) => ({ t: 'preview', id, req })),- unpreview: (name) => askGateway<unknown>((id) => ({ t: 'unpreview', id, req: { name } })).then(() => {}),- },+ previews,...(workspacesEnabled() && { checkout }),restart: () => {restarting = true;@@ -505,6 +507,7 @@ async function onHost(m: HostToRunner) {return gateway.answer(m.id, m);case 'secrets':return secrets.apply(m.secrets);+ case 'preview-ports': return previews.restore(m.ports); // after a resume: its previews answer again without a new `preview` (work 103)case 'secret-asked':return secretAsks.answer(m.id, m);case 'checked-out':diff --git a/computer/src/runner/preview-socket.test.ts b/computer/src/runner/preview-socket.test.tsnew file mode 100644index 00000000..68d18db5--- /dev/null+++ b/computer/src/runner/preview-socket.test.ts@@ -0,0 +1,140 @@+import { mkdirSync, mkdtempSync, rmSync, statSync } from 'node:fs';+import http from 'node:http';+import net from 'node:net';+import os from 'node:os';+import path from 'node:path';+import { once } from 'node:events';+import { afterEach, describe, expect, it } from 'vitest';+import { previewSocketFor } from '../ipc.js';+import { gatedPreviews, portOf, previewSocket, servedPreviews } from './preview-socket.js';++const closers: (() => void)[] = [];+afterEach(() => { for (const c of closers.splice(0)) c(); });++/** A run root with a preview socket for runner `r1`, as a container's runner and the host both see it. */+async function gate() {+ const run = mkdtempSync(path.join(os.tmpdir(), 'sp-prev-'));+ mkdirSync(path.join(run, 'runners'));+ const g = previewSocket(previewSocketFor(run, 'r1'));+ await once(g.server, 'listening');+ closers.push(() => (g.server.close(), rmSync(run, { recursive: true, force: true })));+ return { run, g, file: previewSocketFor(run, 'r1') };+}++async function app(body = 'hello from inside') {+ const s = http.createServer((req, res) => res.end(`${body} ${req.headers.host} ${req.url}`));+ s.listen(0, '127.0.0.1');+ await once(s, 'listening');+ closers.push(() => (s.closeAllConnections(), s.close()));+ return (s.address() as net.AddressInfo).port;+}++/** Everything the socket answers to `line`, until it ends. */+function raw(file: string, line: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const c = net.connect(file, () => c.write(line));+ let got = '';+ c.on('data', (d) => (got += d)).on('end', () => resolve(got)).on('error', reject);+ });+}++/** One HTTP request through the socket, as the host's dialer makes it: the line, then the request. */+const get = async (file: string, port: number, urlPath = '/') => {+ const got = await raw(file, `${port}\nGET ${urlPath} HTTP/1.1\r\nHost: demo.example\r\nConnection: close\r\n\r\n`);+ return { ok: got.startsWith('ok\nHTTP/1.1 200 OK\r\n'), body: got.split('\r\n\r\n')[1] ?? '' };+};++describe('portOf', () => {+ it('takes a decimal port and nothing else', () => {+ expect(portOf('5173')).toBe(5173);+ expect(portOf('65535')).toBe(65535);+ for (const bad of ['', '0', '65536', '080', '5173 ', '-1', '1e3', '0x50', '51a']) expect(portOf(bad), bad).toBeUndefined();+ });+});++describe('the preview socket', () => {+ it('is 0660 and carries bytes both ways to a previewed port', async () => {+ const { g, file } = await gate();+ expect(statSync(file).mode & 0o777).toBe(0o660);+ const port = await app();+ g.allow(port);+ const r = await get(file, port, '/a?b=1');+ expect(r.ok).toBe(true);+ expect(r.body).toContain('hello from inside demo.example /a?b=1');+ });++ it('ends without a reply for a port the runner did not preview, and for what is not a port line', async () => {+ const { g, file } = await gate();+ const port = await app();+ expect(await raw(file, `${port}\n`)).toBe('');+ for (const line of ['GET / HTTP/1.1\r\n', '1234567', '\n', '65536\n', '22 \n']) expect(await raw(file, line), line).toBe('');+ g.allow(port);+ expect((await get(file, port)).ok).toBe(true);+ g.revoke(port);+ expect(await raw(file, `${port}\n`)).toBe('');+ });++ it('answers closed when nothing listens on a previewed port', async () => {+ const { g, file } = await gate();+ const port = await app();+ closers.splice(1)[0](); // the app goes, the gate stays+ await new Promise((r) => setTimeout(r, 20));+ g.allow(port);+ expect(await raw(file, `${port}\n`)).toBe('closed\n');+ });+});++describe('gatedPreviews', () => {+ const fakeGate = () => {+ const ports = new Set<number>();+ return { ports, allow: (p: number) => void ports.add(p), revoke: (p: number) => void ports.delete(p), allowed: (p: number) => ports.has(p) };+ };++ it('opens the port before the request goes out and keeps it until its name is unpreviewed', async () => {+ const g = fakeGate();+ let during: boolean | undefined;+ const hooks = gatedPreviews({+ preview: async (req) => ((during = g.ports.has(req.port)), { url: 'https://demo.x', name: 'demo', port: req.port, listening: true }),+ unpreview: async () => {},+ }, g);+ await hooks.preview({ port: 5173 });+ expect(during).toBe(true);+ expect([...g.ports]).toEqual([5173]);+ await hooks.unpreview('other');+ expect([...g.ports]).toEqual([5173]);+ await hooks.unpreview('demo');+ expect([...g.ports]).toEqual([]);+ });++ it('restore: the ports and names the host gives back after a resume are as if `preview` had just succeeded', async () => {+ const g = fakeGate();+ const unpreviewed: string[] = [];+ const hooks = gatedPreviews({ preview: async (req) => ({ url: 'https://x', name: 'x', port: req.port, listening: true }), unpreview: async (name) => void unpreviewed.push(name) }, g);+ hooks.restore([{ port: 5173, name: 'demo' }, { port: 8080, name: 'api' }]);+ expect([...g.ports]).toEqual([5173, 8080]);+ await hooks.unpreview('demo');+ expect(unpreviewed).toEqual(['demo']);+ expect([...g.ports]).toEqual([8080]);+ // Without a socket (a runner outside a container) there is nothing to restore.+ expect(() => servedPreviews(undefined, { preview: async () => ({}) as never, unpreview: async () => {} }).restore([{ port: 1, name: 'n' }])).not.toThrow();+ });++ it('closes a port whose request failed, unless it was open before', async () => {+ const g = fakeGate();+ let fail = true;+ const hooks = gatedPreviews({+ preview: async (req) => {+ if (fail) throw new Error('demo is taken');+ return { url: 'https://demo.x', name: 'demo', port: req.port, listening: true };+ },+ unpreview: async () => {},+ }, g);+ await expect(hooks.preview({ port: 3000 })).rejects.toThrow('demo is taken');+ expect([...g.ports]).toEqual([]);+ fail = false;+ await hooks.preview({ port: 3000 });+ fail = true;+ await expect(hooks.preview({ port: 3000, name: 'taken' })).rejects.toThrow();+ expect([...g.ports]).toEqual([3000]);+ });+});diff --git a/computer/src/runner/preview-socket.ts b/computer/src/runner/preview-socket.tsnew file mode 100644index 00000000..7cf7f45f--- /dev/null+++ b/computer/src/runner/preview-socket.ts@@ -0,0 +1,136 @@+// The runner's preview socket (work 103, C9): how the host reaches a server+// this session previews when the session runs in a container, whose loopback+// the host cannot dial. The host connects to SP_PREVIEW_SOCKET and writes one+// line, the port in decimal and `\n` (6 bytes at most). For a port this+// runner asked a preview of, the runner connects to 127.0.0.1:<port> and+// answers `ok\n`, then carries bytes both ways until either side ends; when+// nothing listens there it answers `closed\n` and ends.+//+// Invariants:+// - A port is reachable only between this runner's `preview` request for it+// and an `unpreview` of its name (or the request's failure): for any other+// port, and for anything that is not a port line, the connection ends+// without a reply. So the socket is no way into the session's other+// listeners, whoever connects to it.+// - The set of ports is this process's memory: a runner that starts again+// serves none until the host tells it the ports its thread had+// (`preview-ports`, once per start of its container; `restore`), or its+// session calls `preview` again.+// - Without SP_PREVIEW_SOCKET (a runner outside a container) nothing listens+// and the hooks pass through unchanged.++import net from 'node:net';+import { chmodSync, rmSync } from 'node:fs';+import { log } from '../log.js';+import type { PreviewHooks } from './preview.js';++/** `65535\n`. */+const LINE_MAX = 6;+/** How long a connection has to send its line. */+const LINE_WAIT_MS = 5000;++export interface PreviewGate {+ allow(port: number): void;+ revoke(port: number): void;+ allowed(port: number): boolean;+ server: net.Server;+}++/** The port a line names, or undefined: digits only, 1 to 65535. */+export function portOf(line: string): number | undefined {+ if (!/^[1-9]\d{0,4}$/.test(line)) return undefined;+ const n = Number(line);+ return n <= 65535 ? n : undefined;+}++/** Listen on `socketPath` (0660: the host is in the socket's group). `connect`: tests pass their own. */+export function previewSocket(socketPath: string, connect: (port: number) => net.Socket = (port) => net.connect({ host: '127.0.0.1', port, noDelay: true })): PreviewGate {+ const ports = new Set<number>();+ const server = net.createServer((c) => {+ c.on('error', () => {});+ let head = Buffer.alloc(0);+ const timer = setTimeout(() => c.destroy(), LINE_WAIT_MS);+ const onData = (d: Buffer) => {+ head = Buffer.concat([head, d]);+ const nl = head.indexOf(0x0a);+ if (nl < 0 && head.length < LINE_MAX) return;+ clearTimeout(timer);+ c.off('data', onData);+ c.pause();+ const port = nl >= 0 && nl < LINE_MAX ? portOf(head.subarray(0, nl).toString('latin1')) : undefined;+ if (port === undefined || !ports.has(port)) return void c.end();+ const rest = head.subarray(nl + 1);+ const up = connect(port);+ let connected = false;+ up.once('connect', () => {+ connected = true;+ c.write('ok\n');+ if (rest.length) up.write(rest);+ up.on('error', () => c.destroy());+ c.on('error', () => up.destroy());+ c.on('close', () => up.destroy());+ up.on('close', () => c.destroy());+ up.pipe(c).pipe(up);+ });+ up.once('error', () => {+ if (!connected) c.end('closed\n');+ });+ };+ c.on('data', onData);+ c.on('close', () => clearTimeout(timer));+ });+ server.on('error', (e) => log.error(`preview socket ${socketPath}: ${e.message}`));+ rmSync(socketPath, { force: true });+ server.listen(socketPath, () => chmodSync(socketPath, 0o660));+ server.unref();+ return { allow: (p) => void ports.add(p), revoke: (p) => void ports.delete(p), allowed: (p) => ports.has(p), server };+}++/** Preview hooks that can be given their previews back (the host's `preview-ports`, after a resume: the gate and the names are in memory only). */+export interface RestoredPreviews extends PreviewHooks {+ /** Allow each port and remember each name, as if `preview` had just succeeded for it. */+ restore(ports: { port: number; name: string }[]): void;+}++/**+ * `hooks`, opening a port on the gate when its preview is asked for (the host probes it before it answers) and+ * closing it when the request fails or its name is unpreviewed.+ */+export function gatedPreviews(hooks: PreviewHooks, gate: Pick<PreviewGate, 'allow' | 'revoke' | 'allowed'>): RestoredPreviews {+ const names = new Map<string, number>();+ const named = (name: string, port: number) => {+ for (const [n, p] of names) if (p === port) names.delete(n); // a port has one name+ names.set(name, port);+ };+ return {+ restore(ports) {+ for (const { port, name } of ports) {+ if (!Number.isInteger(port) || typeof name !== 'string') continue;+ gate.allow(port);+ named(name, port);+ }+ },+ async preview(req) {+ const had = gate.allowed(req.port);+ gate.allow(req.port);+ try {+ const r = await hooks.preview(req);+ named(r.name, req.port);+ return r;+ } catch (e) {+ if (!had) gate.revoke(req.port);+ throw e;+ }+ },+ async unpreview(name) {+ await hooks.unpreview(name);+ const port = names.get(name);+ names.delete(name);+ if (port !== undefined) gate.revoke(port);+ },+ };+}++/** The hooks a runner uses: gated behind a preview socket at `socketPath`, or `hooks` itself without one. */+export const servedPreviews = (socketPath: string | undefined, hooks: PreviewHooks): RestoredPreviews =>+ socketPath ? gatedPreviews(hooks, previewSocket(socketPath)) : { ...hooks, restore: () => {} };diff --git a/computer/src/telemetry/catalog.ts b/computer/src/telemetry/catalog.tsindex eb19babf..13140e6e 100644--- a/computer/src/telemetry/catalog.ts+++ b/computer/src/telemetry/catalog.ts@@ -77,17 +77,23 @@ export const CATALOG = {// `fetch_skipped`: the clone's refs were fresh (workspaces/fetch-schedule.ts), no fetch on the fork's path.'fork.repo': host('repo', 'fetch_ms', 'worktree_ms', 'lock_wait_ms', 'fetch_error_type', 'fetch_skipped'),'fork.done': host('repos', 'fork_error_type'),- 'runner.launched': host('launch_mode', 'attempt'),+ 'runner.launched': host('launch_mode', 'attempt', 'image', 'container.create_ms', 'container.start_ms', 'container.recreated', 'container.mount_ms', 'container.add_ms'),+ // One script in a helper container (work 103): `script` is a workspace script's file name, or `files` for a `/files` script on a stopped thread.+ 'sandbox.helper': host('script'),+ // What one sweep of a `podman` host removed, by kind (work 103); emitted only when it removed something.+ 'sandbox.swept': host('containers', 'volumes', 'run_dirs', 'units'),'runner.ready': host('polls'),'deliver.forwarded': host('credentials_sent', 'secrets_count'),'runner.exited': host('busy', 'exit_reason', 'last_status'),// The warm pool (work 069, host/pool.ts): spare runners, their Claude Code parked before any session.- 'pool.spare_started': host('launch_mode'),+ // A spare that is a container (work 103) says its image and what Create and Start took.+ 'pool.spare_started': host('launch_mode', 'image', 'container.create_ms', 'container.start_ms'),// `reason`: version (an older release), surplus (the pool was made smaller).'pool.spare_evicted': host('reason'),// A spare that exited before it was ever ready (its Claude Code did not start).'pool.spare_failed': host(),- // A delivery that could have taken a spare and started cold. `reason`: none, kind (none of the session's spare kind), refused, timeout, gone (the spare exited first).+ // A delivery that could have taken a spare and started cold. `reason`: none, kind (none of the session's spare kind), refused, timeout, gone (the spare exited first),+ // bind (a spare container could not be made the thread's: its record, mounts or worktrees).'pool.spare_missed': host('reason'),// The model proxy's events (work 097, computer/modelproxy/README.md), relayed by the host from its control socket;// the envelope's `provider` dimension is the event's profile. A Responses request adds `first_output_ms` (headers@@ -107,7 +113,8 @@ export const CATALOG = {// The runner stepped a subscription session's model down after the seat refused it.'model.downgraded': runner('from', 'to'),// A spare became this session's runner; `duration_ms` is the claim's round trip.- 'runner.claimed': host(),+ // A spare container (work 103) adds what making it the thread's took: the mounts and the worktrees.+ 'runner.claimed': host('launch_mode', 'image', 'container.mount_ms', 'container.add_ms', 'container.claim_ms'),'turn.abandoned': host('exit_reason'),'token.minted': host('cache_hit', 'repos', 'kind'),// `trigger`: 'periodic' (the housekeeping pass) or 'pushed' (a push to the branch forks start from).@@ -127,6 +134,13 @@ export const CATALOG = {'since_gateway_message_s','telemetry_spooled_bytes','telemetry_dropped',+ // A `podman` host (work 103), as of its last sweep: its containers by Podman's state, the use of its data volume, `podman system df`'s total.+ 'containers_running',+ 'containers_exited',+ 'containers_created',+ 'containers_other',+ 'data_used_pct',+ 'podman_bytes','model_proxy_down_s',),// ---------------------------------------------------------------- host: the computer API (work 084 instrumentation)diff --git a/computer/src/workspaces/clones.test.ts b/computer/src/workspaces/clones.test.tsnew file mode 100644index 00000000..0146d8ba--- /dev/null+++ b/computer/src/workspaces/clones.test.ts@@ -0,0 +1,24 @@+import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { expect, test } from 'vitest';+import { isClone } from './clones.js';++test('isClone: a directory with a .git directory, and nothing else', () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'clones-'));+ mkdirSync(path.join(dir, 'repo', '.git'), { recursive: true });+ mkdirSync(path.join(dir, 'real'));+ mkdirSync(path.join(dir, 'worktree'));+ writeFileSync(path.join(dir, 'worktree', '.git'), 'gitdir: elsewhere\n');+ writeFileSync(path.join(dir, '.workspace-prepared'), '');+ mkdirSync(path.join(dir, 'linked'));+ symlinkSync(path.join(dir, 'repo', '.git'), path.join(dir, 'linked', '.git'));+ expect(isClone(path.join(dir, 'repo'))).toBe(true);+ expect(isClone(path.join(dir, 'real'))).toBe(false);+ expect(isClone(path.join(dir, 'worktree'))).toBe(false);+ expect(isClone(path.join(dir, 'missing'))).toBe(false);+ // A marker file among the clones is not one, and does not stop a housekeeping pass (ENOTDIR).+ expect(isClone(path.join(dir, '.workspace-prepared'))).toBe(false);+ // A link a session left in place of .git is not followed.+ expect(isClone(path.join(dir, 'linked'))).toBe(false);+});diff --git a/computer/src/workspaces/clones.ts b/computer/src/workspaces/clones.tsindex f7ebe108..895c07b2 100644--- a/computer/src/workspaces/clones.ts+++ b/computer/src/workspaces/clones.ts@@ -12,7 +12,7 @@// the background, one preparation per person at a time.import { execFile } from 'node:child_process';-import { existsSync } from 'node:fs';+import { existsSync, lstatSync } from 'node:fs';import path from 'node:path';import { promisify } from 'node:util';import { log } from '../log.js';@@ -21,7 +21,7 @@ import { type Definition, isLazy, loadDefinition, type RepoDef } from './definitimport { command, copyFile, mkdir, writeFile } from './as-runner.js';import { Freshness, keyedQueue } from './fetch-schedule.js';import { syncKnowledgeHooks } from './knowledge-hooks.js';-import { hostScripts, row } from './script-runner.js';+import { hostScripts, row, type ScriptRunner } from './script-runner.js';const exec = promisify(execFile);@@ -64,14 +64,24 @@ export async function git(cwd: string, args: string[], timeout = 0) {const c = command('git', args, { GIT_TERMINAL_PROMPT: '0' });return (await exec(c.cmd, c.args, { cwd, timeout, env: c.env, maxBuffer: 20 << 20 })).stdout.trim();}+let scripts: (clonesDir: string) => ScriptRunner = hostScripts;+/** Who runs the scripts for a clones directory: the host itself unless told otherwise (a `podman` host: a helper container, host/sandbox/scripts.ts). */+export const useScripts = (f: (clonesDir: string) => ScriptRunner) => void (scripts = f);/** The scripts (script-runner.ts) for the clones directory this clone is in, and its name there. */-export const scriptsFor = (clone: string) => ({ s: hostScripts(path.dirname(clone)), repo: path.basename(clone) });+export const scriptsFor = (clone: string) => ({ s: scripts(path.dirname(clone)), repo: path.basename(clone) });export function errText(e: any): string {if (e?.killed) return 'timed out';const lines = String(e?.stderr || e?.message || e).trim().split('\n').filter(Boolean);return lines.find((l) => /^(fatal|error):/.test(l)) ?? lines.pop() ?? 'failed';}-export const isClone = (dir: string) => existsSync(path.join(dir, '.git'));+/** A clone has a `.git` directory. Never followed: a session can write in a clone. */+export const isClone = (dir: string) => {+ try {+ return lstatSync(path.join(dir, '.git'), { throwIfNoEntry: false })?.isDirectory() ?? false;+ } catch {+ return false; // `dir` is a file (ENOTDIR), or cannot be looked into+ }+};export const fetchErrorType = (e: unknown) => ((e as { killed?: boolean })?.killed ? 'timeout' : 'git_fetch');/** Timings the host agent reports as telemetry (work 054); calls never affect the work. */diff --git a/computer/src/workspaces/fork.ts b/computer/src/workspaces/fork.tsindex c25cab84..5f13d046 100644--- a/computer/src/workspaces/fork.ts+++ b/computer/src/workspaces/fork.ts@@ -179,7 +179,8 @@ export async function checkoutRepos(forkPath: string, wanted: string[]): Promisereturn results;}-function findRepo(repos: RepoDef[], want: string): RepoDef | undefined {+/** The definition's repository for a name or `owner/name`, as a session wrote it. */+export function findRepo(repos: RepoDef[], want: string): RepoDef | undefined {const w = want.replace(/\.git$/, '').toLowerCase();return repos.find((r) => r.name.toLowerCase() === w) ?? repos.find((r) => repoSlug(r.remote).toLowerCase() === w);}diff --git a/computer/src/workspaces/housekeep.ts b/computer/src/workspaces/housekeep.tsindex b6a2989e..e2df8d5c 100644--- a/computer/src/workspaces/housekeep.ts+++ b/computer/src/workspaces/housekeep.ts@@ -78,6 +78,16 @@ async function syncRepo(person: Person, repo: RepoDef, trigger: FetchTrigger): P}}+/** What a pass does about a person's forks: the rows of those it kept from pruning. */+export type ForkKeeper = (person: Person, active: Set<string>) => Promise<RepoStatus[]>;+let keepForks: ForkKeeper = async (person, active) => {+ const kept = await pruneForks(person);+ await pruneIdleArtifacts(path.join(personRoot(person), 'sessions'), active);+ return kept;+};+/** A `podman` host keeps forks its own way (host/sandbox/artifacts.ts): nothing here may run git or remove files in one. */+export const useForkKeeper = (f: ForkKeeper) => void (keepForks = f);+/*** One housekeeping pass for a person: root files, clone new repositories, fetch and* fast-forward the rest, report repositories removed from the definition, prune idle forks@@ -93,8 +103,7 @@ export async function housekeep(person: Person, active: Set<string> = new Set())for (const name of (await readdir(ws)).sort()) {if (!defined.has(name) && isClone(path.join(ws, name))) repos.push({ name, problem: 'removed from the definition; clone kept' });}- repos.push(...(await pruneForks(person)));- await pruneIdleArtifacts(path.join(personRoot(person), 'sessions'), active);+ repos.push(...(await keepForks(person, active)));const status = { person: person.dir, repos };lastStatus.set(person.dir, status);return status;diff --git a/computer/src/workspaces/idle.test.ts b/computer/src/workspaces/idle.test.tsindex cdbf6614..b3e2088f 100644--- a/computer/src/workspaces/idle.test.ts+++ b/computer/src/workspaces/idle.test.ts@@ -1,12 +1,12 @@// pruneArtifacts and pruneFork against real git in a temp dir: names with a// tab or a newline, which the scripts' line protocol cannot carry.import { execFileSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { existsSync, lutimesSync, mkdirSync, mkdtempSync, renameSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { beforeAll, describe, expect, it } from 'vitest';import { configureAsRunner } from './as-runner.js';-import { pruneArtifacts } from './idle.js';+import { allWorktrees, artifactQuestion, lastUsed, pruneArtifacts, stillInside, worktrees } from './idle.js';import { pruneFork } from './prune.js';const tmp = mkdtempSync(path.join(tmpdir(), 'ws-idle-'));@@ -69,6 +69,72 @@ describe('pruneArtifacts', () => {});});+describe('links a session left in a fork (work 103 step 7 review)', () => {+ /** Another person's fork: a worktree `alpha` with an ignored node_modules. */+ const victim = () => {+ const other = path.join(tmp, 'other', `v${++forks}`);+ repo(path.join(other, 'alpha'), 'node_modules/\n', ['node_modules']);+ return other;+ };++ it('a .wt that links to another directory: nothing there is listed, asked about or removed', async () => {+ const fork = newFork();+ const other = victim();+ repo(path.join(fork, 'mine'), 'node_modules/\n', ['node_modules']);+ symlinkSync(other, path.join(fork, '.wt'));+ expect(await allWorktrees(fork)).toEqual([path.join(fork, 'mine')]);+ expect((await artifactQuestion(fork)).names).toEqual(['mine']);+ expect(await pruneArtifacts(fork)).toEqual([path.join(fork, 'mine', 'node_modules')]);+ expect(existsSync(path.join(other, 'alpha', 'node_modules'))).toBe(true);+ });++ it('a fork that is itself a link: nothing is listed or removed, and its target\'s use is not its own', async () => {+ const other = victim();+ const fork = path.join(tmp, 'sessions', `link${++forks}`);+ symlinkSync(other, fork);+ expect(await worktrees(fork)).toEqual([]);+ expect(await allWorktrees(fork)).toEqual([]);+ expect(await pruneArtifacts(fork)).toEqual([]);+ expect(existsSync(path.join(other, 'alpha', 'node_modules'))).toBe(true);+ expect(await pruneFork(fork)).toBeUndefined(); // only the link goes+ expect(existsSync(path.join(other, 'alpha', 'node_modules'))).toBe(true);+ const again = path.join(tmp, 'sessions', `link${++forks}`);+ symlinkSync(other, again);+ const old = new Date(Date.now() - 96 * 3600e3);+ lutimesSync(again, old, old);+ expect(await lastUsed(again)).toBe(old.getTime()); // the link's own time+ });++ it('a worktree or a directory in it that is a link is not walked into', async () => {+ const fork = newFork();+ const other = victim();+ repo(path.join(fork, 'mine'), 'node_modules/\n', []);+ symlinkSync(path.join(other, 'alpha'), path.join(fork, 'linked'));+ symlinkSync(path.join(other, 'alpha'), path.join(fork, 'mine', 'pkg'));+ symlinkSync(path.join(other, 'alpha', 'node_modules'), path.join(fork, 'mine', 'node_modules'));+ expect(await allWorktrees(fork)).toEqual([path.join(fork, 'mine')]);+ expect((await artifactQuestion(fork)).asked).toEqual([]);+ expect(await pruneArtifacts(fork)).toEqual([]);+ });++ it('stillInside: a directory found and then replaced by a link, or below one, is dropped before removal', async () => {+ const fork = newFork();+ const other = victim();+ repo(path.join(fork, 'mine'), 'node_modules/\n', ['node_modules', 'pkg/node_modules']);+ repo(path.join(fork, '.wt', 'beta'), 'node_modules/\n', ['node_modules']);+ const q = await artifactQuestion(fork);+ expect(await stillInside(fork, q.asked)).toEqual(q.asked);+ // Between the listing and the removal: .wt becomes a link, and so does a directory above an artifact.+ renameSync(path.join(fork, '.wt'), path.join(fork, 'was-wt'));+ symlinkSync(path.join(other), path.join(fork, '.wt'));+ mkdirSync(path.join(other, 'beta', 'node_modules'), { recursive: true });+ renameSync(path.join(fork, 'mine', 'pkg'), path.join(fork, 'mine', 'was-pkg'));+ symlinkSync(path.join(other, 'alpha'), path.join(fork, 'mine', 'pkg'));+ expect(await stillInside(fork, q.asked)).toEqual([path.join(fork, 'mine', 'node_modules')]);+ expect(await stillInside(path.join(fork, '.wt'), [path.join(fork, '.wt', 'beta', 'node_modules')])).toEqual([]);+ });+});+describe('pruneFork', () => {it('says why a fork is kept when a worktree has a tab in its name', async () => {const fork = newFork();diff --git a/computer/src/workspaces/idle.ts b/computer/src/workspaces/idle.tsindex 9b916eb9..ee84e330 100644--- a/computer/src/workspaces/idle.ts+++ b/computer/src/workspaces/idle.ts@@ -2,10 +2,30 @@// directories of idle ones (work 071): a Node worktree's node_modules is about// 1 GiB, the bulk of a fork on disk, and an install or build brings each back.// prune.ts prunes whole forks.+//+// Invariants (a session wrote everything in a fork, and can leave a link+// anywhere in it, to another person's tree for one):+// - What is looked for in a fork (worktrees, artifact directories) is found+// with readdir and lstat alone, and a directory is listed only after lstat+// said it is a directory and not a link, at every hop from the fork down:+// the fork itself, its `.wt`, each worktree, each directory below one (the+// last two by the type readdir gives, which is the entry's own). A link is+// never listed, walked into or timed through.+// - That look and the listing after it are two calls: a live session can swap+// a directory for a link in between. So nothing is removed on the walk's+// word alone: just before removal `stillInside` resolves every directory+// again and drops one whose real path is no longer the same path below the+// fork. What is left is the time between that check and the removal itself,+// and only for a session that runs then: pruneIdleArtifacts skips the forks+// with a runner when the pass began, the sandbox asks again right before it+// removes (host/sandbox/artifacts.ts). On the host path the removal runs as+// the runners' user, which a session there already is.+// host/sandbox/artifacts.ts does the same pruning for a thread that runs in a+// container, with these same lists and the same check.import { execFile } from 'node:child_process';-import { existsSync } from 'node:fs';-import { readdir, stat } from 'node:fs/promises';+import { lstatSync } from 'node:fs';+import { lstat, readdir, realpath } from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';import { log } from '../log.js';@@ -17,7 +37,7 @@ const exec = promisify(execFile);export const FORK_FILE = '.fork.json';/** A fork idle this long loses its ignored build and dependency directories (work 071). */-const artifactsIdle = () => Number(process.env.SP_ARTIFACTS_IDLE_HOURS || 24) * 3600e3;+export const artifactsIdle = () => Number(process.env.SP_ARTIFACTS_IDLE_HOURS || 24) * 3600e3;/** How deep below a worktree's root to look (packages/<name>/node_modules is 2). */const ARTIFACT_DEPTH = 3;/**@@ -27,7 +47,8 @@ const ARTIFACT_DEPTH = 3;const ARTIFACTS = new Set(['node_modules', '.next', '.nuxt', '.svelte-kit', '.turbo', '.parcel-cache', '.wrangler','.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', '.gradle']);const isArtifact = (dir: string, name: string) =>- ARTIFACTS.has(name) || (name === 'target' && existsSync(path.join(dir, 'Cargo.toml')));+ ARTIFACTS.has(name) || (name === 'target' && there(path.join(dir, 'Cargo.toml')));+const there = (p: string) => !!lstatSync(p, { throwIfNoEntry: false });/** A person's clones directory, from one of their forks: <root>/sessions/<key> and <root>/ws (clones.ts). */export const clonesOf = (fork: string) => path.join(path.dirname(path.dirname(path.resolve(fork))), 'ws');@@ -39,21 +60,29 @@ const git = async (cwd: string, args: string[]) => {return (await exec(c.cmd, c.args, { cwd, env: c.env })).stdout.trim();};-const mtime = async (p: string) => (await stat(p).catch(() => undefined))?.mtimeMs ?? 0;+/** The entry's own time: a link's, not its target's. */+const mtime = async (p: string) => (await lstat(p).catch(() => undefined))?.mtimeMs ?? 0;+/** True for a directory that is not a link. The last name only: the caller has looked at the ones above. */+export const realDir = async (p: string) => (await lstat(p).catch(() => undefined))?.isDirectory() ?? false;++/** The worktrees directly in `fork`, which is a fork or its `.wt`; none when it is a link or no directory. */export async function worktrees(fork: string) {+ if (!(await realDir(fork))) return [];const entries = await readdir(fork, { withFileTypes: true }).catch(() => []);- return entries.filter((d) => d.isDirectory() && existsSync(path.join(fork, d.name, '.git'))).map((d) => path.join(fork, d.name));+ return entries.filter((d) => d.isDirectory() && there(path.join(fork, d.name, '.git'))).map((d) => path.join(fork, d.name));}/** A fork's worktrees, and those agents add under its `.wt/` (git worktree add .wt/<name>). */-async function allWorktrees(fork: string) {+export async function allWorktrees(fork: string) {+ if (!(await realDir(fork))) return []; // `.wt` below a link is somewhere elsereturn [...(await worktrees(fork)), ...(await worktrees(path.join(fork, '.wt')))];}/** Latest use: the fork record (touchFork) and each worktree's index and HEAD log (git activity). */export async function lastUsed(fork: string) {- const times = [await mtime(fork), await mtime(path.join(fork, FORK_FILE))];+ const times = [await mtime(fork)];+ if (await realDir(fork)) times.push(await mtime(path.join(fork, FORK_FILE)));for (const wt of await allWorktrees(fork)) {for (const f of ['index', 'logs/HEAD']) {const p = await git(wt, ['rev-parse', '--git-path', f]).catch(() => '');@@ -63,10 +92,23 @@ export async function lastUsed(fork: string) {return Math.max(...times);}+/**+ * Of `dirs`, found below `fork` by the walk, those still where they were found: the fork is a directory and no+ * link, and the real path of each is the same path below the fork's, so no name from the fork down is a link now.+ * Asked just before removal (the header says what that leaves).+ */+export async function stillInside(fork: string, dirs: string[]): Promise<string[]> {+ const root = (await realDir(fork)) ? await realpath(fork).catch(() => undefined) : undefined;+ if (!root) return [];+ const real = await Promise.all(dirs.map((dir) => realpath(dir).catch(() => undefined)));+ return dirs.filter((dir, i) => real[i] === path.join(root, path.relative(fork, dir)));+}+/** The artifact directories under `dir` (not below one another, not in .git), at most `depth` levels down. */async function findArtifacts(dir: string, depth = ARTIFACT_DEPTH): Promise<string[]> {const found: string[] = [];for (const d of await readdir(dir, { withFileTypes: true }).catch(() => [])) {+ // isDirectory is the entry's own type: false for a link to a directory, so `p` is walked into only as a real one.if (!d.isDirectory() || d.name === '.git') continue;const p = path.join(dir, d.name);if (isArtifact(dir, d.name)) found.push(p);@@ -75,40 +117,62 @@ async function findArtifacts(dir: string, depth = ARTIFACT_DEPTH): Promise<strinreturn found;}-/**- * Remove the git-ignored build and dependency directories of a fork's- * worktrees: the bulk of a fork on disk and regenerable. Tracked or unignored- * ones are kept. Returns the directories removed.- */-export async function pruneArtifacts(forkPath: string): Promise<string[]> {- const wts: string[] = [];- /** The directories asked about, in the order of the lines on stdin. */+/** What ws-inspect.sh `--only=ignored` is asked about a fork: its worktrees by name, and one line of stdin per artifact directory. */+export interface ArtifactQuestion {+ /** The worktrees with artifact directories, relative to the fork: the script's arguments. */+ names: string[];+ /** The directories asked about, in the order of the lines. */+ asked: string[];+ /** `<worktree, from 1>\t<path in it>` per directory. */+ lines: string;+}++/** The artifact directories of a fork's worktrees, as the question for ws-inspect.sh. */+export async function artifactQuestion(forkPath: string): Promise<ArtifactQuestion> {+ const names: string[] = [];const asked: string[] = [];let lines = '';for (const wt of await allWorktrees(forkPath)) {// A path with a tab or a newline does not fit a line of the script's input: not asked about, so kept.const dirs = (await findArtifacts(wt)).filter((dir) => !/[\t\n]/.test(path.relative(wt, dir)));if (!dirs.length) continue;- wts.push(wt);+ names.push(path.relative(forkPath, wt));for (const dir of dirs) {asked.push(dir);- lines += `${wts.length}\t${path.relative(wt, dir)}\n`;+ lines += `${names.length}\t${path.relative(wt, dir)}\n`;}}- if (!asked.length) return [];- // ws-inspect.sh says which git ignores; tracked files are never ignored. It answers a worktree by its- // position and a directory by its line, both from 1: a name with a tab would not survive being printed.- const s = hostScripts(clonesOf(forkPath));- const names = wts.map((wt) => path.relative(forkPath, wt));- const out = await s.run('ws-inspect.sh', ['--only=ignored', s.clones, s.workspace(forkPath), ...names], { stdin: lines, timeoutMs: 0 });- const removed: string[] = [];- for (const n of wts.keys()) {+ return { names, asked, lines };+}++/**+ * The directories git ignores, from the script's answer: tracked files are never ignored. It answers a worktree by+ * its position and a directory by its line, both from 1: a name with a tab would not survive being printed.+ */+export function ignoredArtifacts(q: ArtifactQuestion, out: string): string[] {+ const ignored: string[] = [];+ for (const n of q.names.keys())for (const line of row(out, String(n + 1)).slice(4)) {- const dir = asked[Number(line) - 1];- if (!dir) continue;- await rm(dir);- removed.push(dir);+ const dir = q.asked[Number(line) - 1];+ if (dir) ignored.push(dir);}+ return ignored;+}++/**+ * Remove the git-ignored build and dependency directories of a fork's+ * worktrees: the bulk of a fork on disk and regenerable. Tracked or unignored+ * ones are kept. Returns the directories removed.+ */+export async function pruneArtifacts(forkPath: string): Promise<string[]> {+ const q = await artifactQuestion(forkPath);+ if (!q.asked.length) return [];+ const s = hostScripts(clonesOf(forkPath));+ const out = await s.run('ws-inspect.sh', ['--only=ignored', s.clones, s.workspace(forkPath), ...q.names], { stdin: q.lines, timeoutMs: 0 });+ const removed: string[] = [];+ for (const dir of await stillInside(forkPath, ignoredArtifacts(q, out))) {+ await rm(dir);+ removed.push(dir);}return removed;}diff --git a/computer/src/workspaces/index.ts b/computer/src/workspaces/index.tsindex 3bf3f44e..ed1d557d 100644--- a/computer/src/workspaces/index.ts+++ b/computer/src/workspaces/index.ts@@ -29,9 +29,9 @@export * from './definition.js';export { configureAsRunner, mkdir as mkdirAsRunner } from './as-runner.js';export {- ensureWorkspace, type FetchTrigger, forkDir, observeWorkspaces, personRoot, prepareInBackground, safeKey, workspaceDir, type WorkspaceObserver,- workspacePrepared,+ ensureWorkspace, type FetchTrigger, forkDir, observeWorkspaces, personRoot, prepareInBackground, safeKey, useScripts, workspaceDir,+ type WorkspaceObserver, workspacePrepared,} from './clones.js';export { checkoutRepos, type ForkInfo, forkInfo, forkSession, touchFork } from './fork.js';-export { fetchRepo, housekeep, markPushed, oldestFetchAgeS, startHousekeeping } from './housekeep.js';+export { fetchRepo, type ForkKeeper, housekeep, markPushed, oldestFetchAgeS, startHousekeeping, useForkKeeper } from './housekeep.js';export { pruneFork } from './prune.js';diff --git a/computer/src/workspaces/prune.ts b/computer/src/workspaces/prune.tsindex 7f131d54..65271958 100644--- a/computer/src/workspaces/prune.ts+++ b/computer/src/workspaces/prune.ts@@ -13,13 +13,15 @@ import { rm } from './as-runner.js';import { errText, git, personRoot, retention, scriptsFor, serial } from './clones.js';import { removeCodexHome } from './codex-homes.js';import { forkInfo } from './fork.js';-import { clonesOf, lastUsed, worktrees } from './idle.js';+import { clonesOf, lastUsed, realDir, worktrees } from './idle.js';import { hostScripts, row } from './script-runner.js';type RepoStatus = WorkspaceStatus['repos'][number];/** Remove a fork unless a worktree has uncommitted changes or commits on no remote. Returns why it was kept. */export async function pruneFork(forkPath: string): Promise<string | undefined> {+ // A link where a fork should be: only the link goes, and nothing is read or run through it (not its target's key either).+ if (!(await realDir(forkPath))) return void (await rm(forkPath));const wts = await worktrees(forkPath);// ws-inspect.sh reads without refreshing the index, whose new mtime would make the fork look used (lastUsed).const s = hostScripts(clonesOf(forkPath));diff --git a/computer/src/workspaces/script-runner.test.ts b/computer/src/workspaces/script-runner.test.tsindex 3741fe71..2937b9db 100644--- a/computer/src/workspaces/script-runner.test.ts+++ b/computer/src/workspaces/script-runner.test.ts@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';import path from 'node:path';import { beforeAll, describe, expect, it } from 'vitest';import { configureAsRunner } from './as-runner.js';+import { tarOf } from '../host/sandbox/tar.js';import { hostScripts, row, rows, ScriptError } from './script-runner.js';const tmp = mkdtempSync(path.join(tmpdir(), 'ws-scripts-'));@@ -139,6 +140,36 @@ describe('workspace scripts', () => {expect(await run('ws-add.sh', [clones, workspace, 'sp/k1', '0', 'alpha=main'])).toBe(line);});+ it('ws-add.sh unpacks a tar from its stdin into the workspace root, after the worktrees and with no repository at all', async () => {+ const tar = tarOf([{ name: '.fork.json', text: '{"a":1}\n' }, { name: 'docs/AGENTS.md', text: 'hello\n' }]);+ const ws = path.join(tmp, 'sessions', 'k3');+ mkdirSync(ws);+ writeFileSync(path.join(ws, '.fork.json'), 'old');+ expect(await s.run('ws-add.sh', [clones, ws, 'sp/k3', '0'], { stdin: tar, timeoutMs: 20_000 })).toBe('');+ expect(readFileSync(path.join(ws, '.fork.json'), 'utf8')).toBe('{"a":1}\n');+ expect(readFileSync(path.join(ws, 'docs', 'AGENTS.md'), 'utf8')).toBe('hello\n');+ const out = await s.run('ws-add.sh', [clones, ws, 'sp/k3', '0', 'alpha=main'], { stdin: tarOf([{ name: 'alpha/planted.txt', text: 'last' }]), timeoutMs: 20_000 });+ expect(row(out, 'alpha')[0]).toBe('sp/k3');+ expect(readFileSync(path.join(ws, 'alpha', 'planted.txt'), 'utf8')).toBe('last'); // unpacked after the worktree was there+ });++ it('ws-add.sh works several repositories at once and answers in the order asked', async () => {+ const ws = path.join(tmp, 'sessions', 'k4');+ mkdirSync(ws);+ const out = await run('ws-add.sh', [clones, ws, 'sp/k4', '0', 'beta', 'nope', 'alpha=main']);+ expect(out.split('\n').filter(Boolean).map((l) => l.split('\t').slice(0, 2).join(' '))).toEqual(['beta ok', 'nope failed', 'alpha ok']);+ });++ it('a clone keeps what only a registry elsewhere reaches: gc never prunes, and .git/worktrees is there', async () => {+ const clone = path.join(clones, 'alpha');+ expect(git(clone, 'config', '--local', 'gc.pruneExpire')).toBe('never');+ expect(git(clone, 'config', '--local', 'gc.worktreePruneExpire')).toBe('never');+ git(clone, 'config', '--local', '--unset', 'gc.pruneExpire');+ await run('ws-sync.sh', ['--only=fetch', clones, 'alpha']);+ expect(git(clone, 'config', '--local', 'gc.pruneExpire')).toBe('never');+ expect(existsSync(path.join(clone, '.git', 'worktrees'))).toBe(true);+ });+it('ws-add.sh reports each repository on its own: not a worktree, no such clone, a failed fetch', async () => {mkdirSync(path.join(workspace, 'beta'));writeFileSync(path.join(workspace, 'beta', 'mine.txt'), 'x');@@ -178,6 +209,19 @@ describe('workspace scripts', () => {);});+ it('ws-inspect.sh runs nothing a session configured: no fsmonitor, no hooks', async () => {+ const clone = path.join(clones, 'alpha');+ const planted = path.join(tmp, 'ran-by-inspect');+ git(clone, 'config', '--local', 'core.fsmonitor', `touch ${planted}; false`);+ try {+ await run('ws-inspect.sh', ['--only=state', clones, workspace, 'alpha']);+ await run('ws-inspect.sh', ['--only=ignored', clones, workspace, 'alpha'], '1\tnode_modules\n');+ expect(existsSync(planted)).toBe(false);+ } finally {+ git(clone, 'config', '--local', '--unset', 'core.fsmonitor');+ }+ });+it('ws-forget.sh deletes the branch, and has nothing to do the second time', async () => {const clone = path.join(clones, 'alpha');git(clone, 'worktree', 'remove', '--force', path.join(workspace, 'alpha'));diff --git a/computer/src/workspaces/script-runner.ts b/computer/src/workspaces/script-runner.tsindex 160ebb13..49a04e6c 100644--- a/computer/src/workspaces/script-runner.ts+++ b/computer/src/workspaces/script-runner.ts@@ -2,7 +2,8 @@// hold the git sequences; clones.ts, fork.ts, housekeep.ts, prune.ts and// idle.ts keep the locks, the scheduling, the telemetry and the parsing, and// reach git only through a ScriptRunner. `hostScripts` runs a script on the-// host as the runners' user (as-runner.ts), with host paths.+// host as the runners' user (as-runner.ts), with host paths; on a `podman`+// host the two runners of host/sandbox/scripts.ts run it in a container.//// Invariants:// - A script prints one line per repository, tab-separated: the repository,@@ -33,7 +34,7 @@ export class ScriptError extends Error {export interface ScriptRunner {/** Run bin/<script> with these arguments; resolves with stdout, rejects with ScriptError { code, stderr } on a non-zero exit or the timeout (0: none). */- run(script: string, args: string[], o: { stdin?: string; timeoutMs: number }): Promise<string>;+ run(script: string, args: string[], o: { stdin?: string | Buffer; timeoutMs: number }): Promise<string>;/** How this runner names the clones directory and a workspace: host paths, or /clones and /workspace. */clones: string;workspace(hostForkPath: string): string;