barebox 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,45 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
 
7
+ ## [0.8.0] - 2026-11-02
8
+
9
+ ### Added
10
+
11
+ - `sbx run` asks in its own terminal. When stdin and stderr are terminals, a held request prints a plain-language question (what the agent wants to do, why, the URL, a masked body preview) and waits for `y`; anything else denies. A second terminal can still answer; the first answer wins.
12
+ - `sbx run --name <n>` names the sandbox: the agent name and a runtime dir that persists after the run. `sbx pending|approve|deny|diff|commit|rollback --name <n>` address it instead of `SBX_RUNTIME` (giving both is a usage error).
13
+ - `~/.local/bin` is on the agent's inside `PATH` when it exists, after the system dirs, so tools installed there (Claude Code's native `claude`) run by bare name. The dir was already visible through the read-only `$HOME` bind; nothing new is exposed.
14
+
15
+ ### Changed
16
+
17
+ - The proxy builds one MITM TLS context per host (cached, at most 256, oldest evicted) instead of one per tunnel. Over HTTPS at 40 agents this cut about 37 MB; the budget is now about 205-245 MB in the full HTTPS worst case, quiet to busy machine.
18
+ - Calls to a model endpoint are no longer card-scanned. A card number in the conversation held a Claude Code call and killed the agent, while its larger calls passed unscanned. Every other request keeps the floor, in every mode.
19
+
20
+ ### Fixed
21
+
22
+ - `sbx approve` and `sbx deny` no longer overwrite an earlier answer: the first answer to a hold wins, and a later one prints `<id> already answered` and exits 1. The terminal prompt prints `answered elsewhere` when it loses.
23
+ - The sandbox bridge no longer prints socat connection errors (`E write(…): Broken pipe`, `Connection reset by peer`) on the agent's stderr when a connection closes early, such as a denied hold.
24
+ - `#!/bin/sh` scripts and Node's `exec` failed inside the sandbox on merged-`/usr` hosts (`/bin`, `/sbin` and `/lib` did not exist; only `/lib64` was recreated). The sandbox now mirrors the host's top-level `/bin`, `/sbin`, `/lib` and `/lib64`. This shipped in 0.7.0 and earlier.
25
+
26
+ ## [0.7.0] - 2026-11-01
27
+
28
+ ### Added
29
+
30
+ - The agent's `node` is the host's: the Node install that runs barebox (`process.execPath`, or `launch({ nodeExec })`) is bound read-only and its `bin` dir put first on the inside `PATH` when it lives outside `/usr`, `$HOME` and the project (nvm, fnm, asdf, a CI toolcache). An exec in a `bin/` dir binds the dir above it, where npm and global CLIs live; any other layout binds only its own dir. It is never bound when that dir is `/`, `$HOME` or above it (then it is not on `PATH` either, and `sbx run` says so on stderr).
31
+
32
+ ### Changed
33
+
34
+ - A secret's placeholder in the URL path or query is refused `403 denied: secret.url` in every mode, before the gate. Keys are swapped in headers only; before, the placeholder was sent as is and the API answered 401 with no hint why.
35
+ - A runtime or project under the bound Node install is safe: the runtime is masked like one under `$HOME` (its `asks/`, `answers/` and `socks/` are not visible), a project there keeps its overlay writable, and `launch()` throws when the runtime IS the Node install dir (or `/etc`, `/usr`).
36
+
37
+ ### Fixed
38
+
39
+ - Node's built-in `fetch` to an `http://` URL failed inside the sandbox (`UND_ERR_SOCKET`), local models such as Ollama included: with `NODE_USE_ENV_PROXY=1` Node tunnels plain http with `CONNECT`, and the proxy treated every tunnel as TLS. The first byte inside a tunnel now decides; plain HTTP is checked like any request (a placeholder there gets `403 denied: secret.scheme`). A certificate is minted only for a TLS tunnel; a plain one mints nothing. The same holds when the first bytes (a TLS ClientHello, or a plain request) arrive in the same write as the `CONNECT` line: the hello was dropped and the handshake never answered.
40
+ - `node` (and npm-installed CLIs) from nvm, fnm or a toolcache were `not found` inside the sandbox (exit 127).
41
+
42
+ ### Security
43
+
44
+ - A locked drawer or `maskDirs` folder under `/etc` or `/usr` (or the bound Node install) is now hidden like one under `$HOME`; before, only paths under `$HOME` and the project were masked, so such a folder stayed readable.
45
+
7
46
  ## [0.6.0] - 2026-11-01
8
47
 
9
48
  ### Added
package/README.md CHANGED
@@ -72,8 +72,8 @@ The agent works in your house:
72
72
  - **Walls** are [bubblewrap](https://github.com/containers/bubblewrap), unprivileged: separate net/pid/ipc/uts namespaces, read-only binds, tmpfs over locked paths.
73
73
  - **Identity** is the socket, not a header the agent could fake. One socket per agent, all into one proxy.
74
74
  - **HTTPS inspection** uses a local CA that exists only inside the sandbox; the proxy reads method, URL, headers and body, then forwards.
75
- - **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment paths (`/checkout`, `/payment`, `/orders`, `/purchase`; a list of payment domains is not built) → rwxmap labels for known APIs → every other request by its letter and the mode (`ask`, `auto`, `trust`; see `barebox.context.md`). The card and payment floor asks in every mode, `trust` included; card numbers are checked in bodies of 64 KB or less.
76
- - **Approvals** come from a second terminal (`sbx pending`, `sbx approve <id>`, `sbx deny <id>`). Timeout means deny, with a clear `403` reason. One held request per agent at a time: later ones wait in line (16 at most, then `429 hold queue full`), and the deadline counts from arrival.
75
+ - **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment paths (`/checkout`, `/payment`, `/orders`, `/purchase`; a list of payment domains is not built) → rwxmap labels for known APIs → every other request by its letter and the mode (`ask`, `auto`, `trust`; see `barebox.context.md`). The card and payment floor asks in every mode, `trust` included (calls to a model endpoint are not card-scanned); card numbers are checked in bodies of 64 KB or less.
76
+ - **Approvals** are asked in the terminal where you ran `sbx run`, in plain words (`agent wants to SEND data to httpbin.org … Allow? [y/N]`); `y` allows, anything else denies. Name the sandbox (`sbx run --name docs-bot -- <cmd>`) and a second terminal can answer too (`sbx pending --name docs-bot`, `sbx approve <id> --name docs-bot`, `sbx deny <id> --name docs-bot`); the first answer wins. Timeout means deny, with a clear `403` reason. One held request per agent at a time: later ones wait in line (16 at most, then `429 hold queue full`), and the deadline counts from arrival.
77
77
 
78
78
  ## Keys the agent never holds
79
79
 
@@ -88,7 +88,7 @@ Put the key in `~/.config/barebox/config.json`, bound to its hosts:
88
88
  }
89
89
  ```
90
90
 
91
- Inside the sandbox `$STRIPE_API_KEY` is a random placeholder, new each run. The agent sends it as it would the key (`curl -H "Authorization: Bearer $STRIPE_API_KEY"`, `curl -u "$STRIPE_API_KEY:"`). The proxy swaps the real value into the request headers only after the request is allowed, and only for `api.stripe.com`. A denied request never leaves. The same placeholder sent to any other host is refused: `403 denied: secret.host`. A real value is swapped only into a request that goes upstream over TLS: a placeholder to a bound host over plain `http://` is refused `403 denied: secret.scheme`. The rest of your environment stays out too, except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...) and the names in `env.pass`; `env.pass` refuses names like `*_TOKEN` and `*_KEY` (use `secrets`). Headers only. Details: `barebox.context.md`.
91
+ Inside the sandbox `$STRIPE_API_KEY` is a random placeholder, new each run. The agent sends it as it would the key (`curl -H "Authorization: Bearer $STRIPE_API_KEY"`, `curl -u "$STRIPE_API_KEY:"`). The proxy swaps the real value into the request headers only after the request is allowed, and only for `api.stripe.com`. A denied request never leaves. The same placeholder sent to any other host is refused: `403 denied: secret.host`. A real value is swapped only into a request that goes upstream over TLS: a placeholder to a bound host over plain `http://` is refused `403 denied: secret.scheme`. The rest of your environment stays out too, except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...) and the names in `env.pass`; `env.pass` refuses names like `*_TOKEN` and `*_KEY` (use `secrets`; a harmless match such as `XKB_KEYMAP` goes in `env.set`). Keys are swapped in headers only: a placeholder in the URL is refused `403 denied: secret.url`. Details: `barebox.context.md`.
92
92
 
93
93
  ## Numbers
94
94
 
@@ -97,13 +97,13 @@ Measured, not estimated. Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22.
97
97
  | | barebox (measured) | [srt](https://github.com/anthropic-experimental/sandbox-runtime) 0.0.81 (measured) |
98
98
  |---|---|---|
99
99
  | Memory per sandbox | **7.8 MB** mean, 8.0 MB max | ~100 MB (each sandbox runs its own proxy) |
100
- | Proxy | one shared: **about 85-120 MB** in normal use; **about 100 / 113-120 / 127-133 / 145-175 MB** at 10 / 20 / 30 / 40 agents in the full worst case (each agent with 1 parked + 16 waiting + a filled body slot). The low end is a quiet machine, the high end a busy one | one per sandbox |
100
+ | Proxy | one shared: **about 95-160 MB** in normal use over HTTPS (10 to 40 agents, keep-alive tunnels open, no holds; plain HTTP alone is about 85-120 MB); **about 117 / 133-151 / 177-207 / 207-241 MB** at 10 / 20 / 30 / 40 agents in the full HTTPS worst case (each agent with 1 parked + 16 waiting + a filled body slot, every request in its own TLS tunnel). The low end is a quiet machine, the high end a busy one. HTTPS costs more because each live TLS session holds about 50 KB of OpenSSL state | one per sandbox |
101
101
  | Start + exit | **10 ms** (M0 POC; unmeasured on the rewrite, TODO re-measure) | 1.87-2.05 s |
102
- | 10 agents | ~180 MB worst case (proxy + 10 x 8 MB) | ~1 GB |
103
- | 20 agents | ~275-280 MB worst case | ~2 GB |
104
- | 40 agents | ~465-495 MB worst case | not measured |
102
+ | 10 agents | ~195-200 MB worst case (proxy + 10 x 8 MB) | ~1 GB |
103
+ | 20 agents | ~295-310 MB worst case | ~2 GB |
104
+ | 40 agents | ~525-560 MB worst case | not measured |
105
105
 
106
- barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents. Budget: shared proxy about 145-175 MB in the full worst case at 40 agents, each extra sandbox 10 MB or less. 40 agents per proxy is the maximum and it is enforced: `addAgent` refuses the 41st with an error telling you to run another proxy. Above 40, run more proxies. Machine load moves the number. A long audit file does not: 205 MB of audit measured the same as 3 MB. Bypass attempts (`--noproxy`, unset proxy env, direct IP, host localhost) all fail closed, and a red-team script breaks each wall on purpose to prove the checks can fail. Setup, dead ends and why: [findings](docs/logs/findings.md).
106
+ barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents. Budget: shared proxy about 205-245 MB in the full HTTPS worst case at 40 agents, each extra sandbox 10 MB or less. 40 agents per proxy is the maximum and it is enforced: `addAgent` refuses the 41st with an error telling you to run another proxy. Above 40, run more proxies. Machine load moves the number. A long audit file does not: 205 MB of audit measured the same as 3 MB. Bypass attempts (`--noproxy`, unset proxy env, direct IP, host localhost) all fail closed, and a red-team script breaks each wall on purpose to prove the checks can fail. Setup, dead ends and why: [findings](docs/logs/findings.md).
107
107
 
108
108
  ## Roadmap
109
109
 
@@ -126,7 +126,7 @@ M0–M2 are the go/no-go. Later: macOS (`sandbox-exec` + APFS clones), Windows v
126
126
  npm install barebox
127
127
  ```
128
128
 
129
- Requires Node.js >= 22.21. Two production dependencies, [bareguard](https://npmjs.com/package/bareguard) (the gate) and [rwxmap](https://npmjs.com/package/rwxmap) (the labels), pinned exactly. Needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollback` (Ubuntu 24.04 ships 0.9.0: build from source or use a newer distro); plain runs work with older bwrap. CI builds bubblewrap 0.12.0 from a checksum-pinned source tarball, copies its Node into `/usr/bin` (the sandbox binds `/usr` only, so a Node installed elsewhere, such as under nvm, is not found inside), and fails if any test is skipped. The API is in [`barebox.context.md`](barebox.context.md) and `primitives.json` (both ship in the package); the `sbx` CLI comes with it.
129
+ Requires Node.js >= 22.21. Two production dependencies, [bareguard](https://npmjs.com/package/bareguard) (the gate) and [rwxmap](https://npmjs.com/package/rwxmap) (the labels), pinned exactly. Needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollback` (Ubuntu 24.04 ships 0.9.0: build from source or use a newer distro); plain runs work with older bwrap. CI builds bubblewrap 0.12.0 from a checksum-pinned source tarball (`scripts/ci-runner-deps.sh`) and fails if any test is skipped. The host's Node runs inside the sandbox: one under `$HOME` (a default nvm) or `/usr` is already visible, and one outside both (a CI toolcache, a Node with `HOME` set elsewhere) is bound read-only, with its `bin` dir first on the inside `PATH`. A runtime or project under that bound install stays hidden or writable as it would elsewhere. The API is in [`barebox.context.md`](barebox.context.md) and `primitives.json` (both ship in the package); the `sbx` CLI comes with it.
130
130
 
131
131
  ## Try the POCs
132
132
 
@@ -56,9 +56,25 @@ await proxy.close();
56
56
  ## Holds (human approval)
57
57
 
58
58
  When a request needs a decision (see "Modes and the gate" below), it parks.
59
- Decide from a second terminal through the file checkpoint (`<runtime>/asks` + `<runtime>/answers`):
59
+ `sbx run` with a terminal (stdin and stderr are TTYs, no `--json`) asks in place:
60
+ the sandbox name, what it wants to do and why, the URL, a masked body
61
+ preview, then `Allow? [y/N] (h3)`. `y` or `yes` allows; anything else, Enter
62
+ included, denies with `denied at the terminal`. A line typed before a question
63
+ appears answers nothing. Name the sandbox with `sbx run --name docs-bot`: the
64
+ name is the agent name and picks the runtime dir
65
+ (`$XDG_RUNTIME_DIR/barebox/<name>`, else `<tmpdir>/sbx-<uid>/<name>`, kept
66
+ after the run), and every other command takes `--name docs-bot` instead of
67
+ `SBX_RUNTIME` (giving both is a usage error).
68
+
69
+ A second terminal can answer at the same time through the file checkpoint
70
+ (`<runtime>/asks` + `<runtime>/answers`); the first answer wins and the
71
+ prompt says `answered elsewhere`:
60
72
 
61
73
  ```bash
74
+ npx sbx pending --name docs-bot
75
+ npx sbx approve h1 --name docs-bot
76
+ npx sbx deny h2 "reason here" --name docs-bot
77
+ # or, for a runtime made by the library: SBX_RUNTIME=/tmp/sbx npx sbx pending
62
78
  SBX_RUNTIME=/tmp/sbx npx sbx pending
63
79
  SBX_RUNTIME=/tmp/sbx npx sbx approve h1
64
80
  SBX_RUNTIME=/tmp/sbx npx sbx deny h2 "reason here"
@@ -93,14 +109,15 @@ const { exit, asks, audit, diff, runtime } = await run({
93
109
  ```
94
110
 
95
111
  ```bash
96
- sbx run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]
112
+ sbx run [--name <n>] [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]
97
113
  ```
98
114
 
99
- `sbx run` uses the current directory as the project and `SBX_RUNTIME` as the
100
- runtime (a short temp dir otherwise, printed on stderr). It prints an `ask`
101
- line when a request parks and a `decided` line when it ends, then `done`;
102
- with `--json` stdout carries only JSON lines. Its exit code mirrors the
103
- agent's.
115
+ `sbx run` uses the current directory as the project and `--name`'s runtime or
116
+ `SBX_RUNTIME` as the runtime (a short temp dir otherwise, printed on stderr). With a
117
+ terminal it asks each held request in place (see above); without one, or with `--json`, it
118
+ prints an `ask` line when a request parks. Either way a `decided` line follows when it ends,
119
+ then `done`; with `--json` stdout carries only JSON lines and nothing is ever prompted.
120
+ Its exit code mirrors the agent's.
104
121
 
105
122
  `sbx run` reads one optional config file,
106
123
  `${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`, with keys `mode`,
@@ -130,8 +147,9 @@ mode letters, the labels and the floor decide. The floor is two bareguard flags,
130
147
  `cardLike` (a body of 64 KB or less holding a card number: 13-19 digits,
131
148
  optional single space or dash, first digit 2-6, Luhn-valid) and `paymentPath`
132
149
  (`/checkout`, `/payment`, `/orders`, `/purchase`); both ask in every mode,
133
- `trust` included. Nothing is denied because of a card. Bodies over 64 KB
134
- stream through unscanned. The body never enters the gate's action.
150
+ `trust` included. Nothing is denied because of a card. One exception: a call
151
+ to a model endpoint (see "Labels and model endpoints") is never card-scanned,
152
+ in any mode. Bodies over 64 KB stream through unscanned. The body never enters the gate's action.
135
153
 
136
154
  barebox's hold queue is each gate's `humanChannel`: the ask files, `onAsk`
137
155
  and `sbx approve|deny` work as above, and the ask carries the gate's `rule`
@@ -158,7 +176,7 @@ private/loopback check, never link-local (cloud metadata).
158
176
  ## Keys the agent never holds
159
177
 
160
178
  The sandbox does not get your environment. The agent sees only barebox's own
161
- variables (`HOME`, `PATH`, the proxy and CA variables, `NODE_USE_ENV_PROXY=1`), a short default list
179
+ variables (`HOME`, `PATH`, the proxy and CA variables, `NODE_USE_ENV_PROXY=1`, so Node's `fetch` reaches `http://` and `https://` URLs, local models included, through the proxy), a short default list
162
180
  (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`, `TZ`, `USER`, `LOGNAME`,
163
181
  `SHELL`, `EDITOR`, `PAGER`), the host variables you name in `env.pass`, the
164
182
  values in `env.set`, and one placeholder per secret. Nothing else reaches it,
@@ -195,7 +213,9 @@ values in `env.set`, and one placeholder per secret. Nothing else reaches it,
195
213
  - A real value is swapped only into a request that goes upstream over TLS. A
196
214
  placeholder to a bound host over plain http is refused in every mode, before
197
215
  the gate: `403 denied: secret.scheme`. Nothing goes upstream.
198
- - Headers only. A key in a body, URL or query string is not swapped.
216
+ - Headers only. A key in a body is not swapped. A placeholder in the URL (path
217
+ or query string) is refused in every mode, before the gate: `403 denied:
218
+ secret.url`. Nothing goes upstream.
199
219
  - Audit: one `annotate` line per hit, `verdict: "secret"`,
200
220
  `meta: { agent, rid, name, host, swapped }`, joined to the gate line by
201
221
  `rid`. The value is never written to the audit, an ask file or an error body.
@@ -225,6 +245,9 @@ hands the real value to the agent.
225
245
 
226
246
  `<runtime>/gate.jsonl` (`runtimePaths(runtime).audit`; `run()` returns it as
227
247
  `audit`) is the only log, one JSON object per line, all in bareguard's shape.
248
+ It is never rotated. `sbx run` without `SBX_RUNTIME` or `--name` gets a fresh runtime, so a
249
+ fresh log, each run; with a reused `SBX_RUNTIME` or `--name` (its runtime dir is kept) the file keeps growing: delete
250
+ it between runs (no proxy running) to start a new one.
228
251
  - Decisions: bareguard's gate lines carry the action (`method`, `url`, `tool`,
229
252
  `agent`, `rid`) and an `aid`.
230
253
  - Response status: a `phase:"record"` line with the same `aid` and
@@ -275,8 +298,10 @@ Model endpoints are `r` (free in every mode): `api.anthropic.com`
275
298
  `POST /v1/messages` and `/v1/messages/count_tokens`; `api.openai.com`
276
299
  `POST /v1/chat/completions`, `/v1/responses` and `/v1/embeddings`; and on each
277
300
  `localLlm` host:port `POST /api/chat`, `/api/generate`, `/api/embed`,
278
- `/v1/chat/completions` and `/v1/completions` (http only). Any other path on
279
- those hosts is a normal `POST`.
301
+ `/v1/chat/completions` and `/v1/completions` (over http or https). Any other path on
302
+ those hosts is a normal `POST`. Model calls skip the card floor (the
303
+ `paymentPath` mark still applies): a model call carries the whole conversation,
304
+ and a card number in it must not kill the agent.
280
305
 
281
306
  Label folders are hidden inside the sandbox like the config file, so the agent
282
307
  cannot rewrite a letter. `run()` and `createProxy()` take `labels:
@@ -291,11 +316,13 @@ project: the agent sees the real files, every write lands on the upper.
291
316
  Review and press it down from the same runtime:
292
317
 
293
318
  ```bash
294
- SBX_RUNTIME=/tmp/sbx npx sbx diff [--agent <name>] # A/M/D, conflicts flagged
295
- SBX_RUNTIME=/tmp/sbx npx sbx commit [--skip-conflicts] # refuses on conflicts by default
296
- SBX_RUNTIME=/tmp/sbx npx sbx rollback # throw the paper away
319
+ npx sbx diff --name docs-bot # A/M/D, conflicts flagged
320
+ npx sbx commit --name docs-bot [--skip-conflicts] # refuses on conflicts by default
321
+ npx sbx rollback --name docs-bot # throw the paper away
297
322
  ```
298
323
 
324
+ (Without `--name`: `SBX_RUNTIME=/tmp/sbx npx sbx diff [--agent <name>]`, same for the others.)
325
+
299
326
  A path the project changed after the run started is a conflict: commit
300
327
  refuses all of it unless `--skip-conflicts`. `node_modules` is invisible to
301
328
  the layer (extend with `SBX_OVERLAY_IGNORE=a,b`). Commit strips setuid/setgid
@@ -314,12 +341,12 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
314
341
  `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
315
342
  verification. Only `ca.pem` enters the sandbox, never the key.
316
343
  - Certificates live in `<runtime>/certs` (`runtime` is required). There is no `certDir` option and no control socket: decisions flow through `<runtime>/asks` + `<runtime>/answers` or `hold.onAsk`. Each minted certificate gets a random 128-bit serial (no shared `ca.srl`), and at most 4 mints run at once.
317
- - Memory and limits: one proxy serves at most 40 agents, enforced. `addAgent` throws `createProxy: agent limit reached (40 agents per proxy); run another proxy for more`; the TCP door's `tcp` agent does not count, and `removeAgent` frees a place. For more than 40 agents run more proxies. Measured worst case (every agent with 1 parked + 16 waiting + a filled 64 KB body slot): proxy about 100 / 113-120 / 127-133 / 143-172 MB at 10 / 20 / 30 / 40 agents, quiet to busy machine (the budget at 40 agents is the range 145-175 MB; needs bareguard 0.30.0), plus about 8 MB per sandbox (limit 10). Normal use is about 85-120 MB. Audit file size does not move these numbers. barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents.
344
+ - Memory and limits: one proxy serves at most 40 agents, enforced. `addAgent` throws `createProxy: agent limit reached (40 agents per proxy); run another proxy for more`; the TCP door's `tcp` agent does not count, and `removeAgent` frees a place. For more than 40 agents run more proxies. Measured worst case (every agent with 1 parked + 16 waiting + a filled 64 KB body slot): proxy about 117 / 133-151 / 177-207 / 207-241 MB at 10 / 20 / 30 / 40 agents with every request in its own HTTPS tunnel, quiet to busy machine (the budget at 40 agents is the range 205-245 MB; needs bareguard 0.30.0), plus about 8 MB per sandbox (limit 10). Normal use is about 95-160 MB over HTTPS with keep-alive tunnels open (about 85-120 MB for plain HTTP). Audit file size does not move these numbers. barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents.
318
345
  - The TCP door is one agent: every connection through `createProxy`'s TCP `port` counts as the agent `tcp` and shares one hold line. Use `addAgent` sockets (`sbx run` does) for separate lines per agent. `removeAgent(name)` ends that agent's open connections; its held requests end as deny / client gone. `run()` calls it when the sandbox exits, so a request still held then ends as client gone, not `proxy closing`.
319
346
  - The upstream wall answers `403` for loopback, link-local (incl. `169.254.169.254`), the host's own addresses, private LAN ranges and unresolvable names. An IPv4 embedded in IPv6 is checked in every spelling: mapped, compat, uncompressed, NAT64 `64:ff9b::/96` (local-use `/48` denied outright) and 6to4 `2002::/16`; NAT64 and 6to4 of public sites stay reachable. Every DNS answer is checked and the dial is pinned to the checked IP; test-only options live under `unsafeTestOnly` (`allowLoopback`, `resolveUpstream`) and production never sets them.
320
347
  - `createProxy` throws synchronously on an unopenable `logFile` (a directory, a missing parent, no permission) and releases the runtime. The runtime root, `asks/`, `answers/`, `held/` and `socks/` are owner-only (`0700`) whatever the umask. An existing runtime dir you own is tightened to `0700`; one you don't own (such as `/tmp`) is refused with an error naming the dir and its owner and suggesting a subdir like `/tmp/sbx`. The audit file (`logFile`, `gate.jsonl`) is set to `0600` every time a proxy starts. No request header and no body content is written to it: a body is logged as its length and SHA-256 only. The ask payload's `bodyPreview` (the first 4 KB, card numbers masked except the last 4) lives in the ask file only; other secrets inside a body still show there until bareguard redaction lands. Your `redact` hook shapes the `meta` of barebox's own annotate lines.
321
348
  - One proxy per runtime: `createProxy` throws "in use by pid N" (`run()` rejects, `sbx run` exits 1) while a live proxy owns the runtime. The claim is held by the proxy process and the kernel frees it when the process dies, so a crashed proxy never blocks the runtime. Use another `SBX_RUNTIME`, or leave it unset for a fresh one.
322
- - `launch()` starts the agent in the project dir, in a new session (no controlling terminal). Locked drawers are 21 credential stores (see `LOCKED_PATHS` in `src/launcher.js`); the agent's own model credentials in `~/.claude` stay readable (a known gap: its sign-in tokens refresh themselves, so `secrets` does not cover them). The host environment does not reach the inside: callers that relied on an inherited variable list it in `env.pass` (or pass `launch({ env })` / `extraEnv`). `launch()` finds `bwrap` on your `PATH` but starts it with a fixed `PATH`.
349
+ - `launch()` starts the agent in the project dir, in a new session (no controlling terminal). Locked drawers are 21 credential stores (see `LOCKED_PATHS` in `src/launcher.js`); the agent's own model credentials in `~/.claude` stay readable (a known gap: its sign-in tokens refresh themselves, so `secrets` does not cover them). The host environment does not reach the inside: callers that relied on an inherited variable list it in `env.pass` (or pass `launch({ env })` / `extraEnv`). `launch()` finds `bwrap` on your `PATH` but starts it with a fixed `PATH`. The sandbox sees `/usr`, `/etc`, `$HOME` and the project read-only, with the host's `/bin`, `/sbin`, `/lib` and `/lib64` mirrored (symlinks into `/usr` on merged-/usr hosts, so `#!/bin/sh` and Node's `exec` work); the Node you run barebox with is visible too: a Node outside those (nvm, a CI toolcache) has its install bound read-only and its dir first on the inside `PATH`, so `node` and global CLIs run inside. `$HOME/.local/bin`, when it exists, is last on the inside `PATH` (after the system dirs; already visible through the `$HOME` bind), so tools installed there run by bare name. A node in a `bin/` dir binds the dir above it; any other layout binds only the node's own dir. It is never bound when that dir is `/`, `$HOME` or above it; then its dir is not on `PATH` either and `sbx run` prints `barebox: not exposing Node at <dir> ...` on stderr (the sandbox uses `/usr/bin/node` if present). `launch({ nodeExec })` overrides `process.execPath`. Locked drawers and `maskDirs` folders are hidden wherever they sit under any of these (`/etc` and the Node install included). So is the runtime tree: a runtime under any of them gets an empty mask, and a runtime that IS `/etc`, `/usr` or the Node install dir throws. A project under the Node install keeps its overlay (the install is bound before it).
323
350
  - `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
324
351
  - Any listening unix socket under `$HOME` (IDE IPC, rootless-container sockets) is reachable from inside the sandbox: a read-only bind does not block `connect(2)`; the locked-paths list is the lever.
325
352
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Lightweight local sandbox for AI agents: every write undoable, nothing leaves the machine without passing the doorman.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/primitives.json CHANGED
@@ -34,7 +34,7 @@
34
34
  "when": "Reach for this to HARNESS-ONLY start one sandboxed agent run: it creates the sandbox the agent lives in. It does not decide anything; combine with the proxy for the front door and the gate (M3) for policy. Pass overlay:true for a writable tracing-paper run (M4). The agent starts in the project dir.",
35
35
  "import": "import { launch } from 'barebox'",
36
36
  "signature": "launch(opts: object) => ChildProcess",
37
- "fails": "Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on a non-integer `proxyPort`, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, when `runtime` IS `HOME` or the project dir (its sockets could not be hidden from the agent), or with overlay on when the runtime sits inside the project or uncommitted changes linger. The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.",
37
+ "fails": "Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on a non-integer `proxyPort`, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, when `runtime` IS `HOME`, the project dir, `/etc`, `/usr` or the bound Node install dir (its sockets could not be hidden from the agent), or with overlay on when the runtime sits inside the project or uncommitted changes linger. The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.",
38
38
  "example": "import { launch } from \"barebox\";\nconst child = launch({ runtime: \"/tmp/sbx\", agent: \"fx\", proj: \"/tmp/proj\", command: [\"bash\", \"-c\", \"echo hi\"] });\nawait new Promise((r) => child.on(\"close\", r)); // child.exitCode === 0"
39
39
  },
40
40
  {
package/src/cli.js CHANGED
@@ -9,7 +9,11 @@
9
9
  // Settings (mode, holdTimeoutSec, heldBodyMaxMB, localLlm) come from the one config file, see config.js;
10
10
  // a flag beats the file. A bad file is a usage-class error (exit 2).
11
11
  //
12
- // sbx run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]
12
+ // With a terminal (stdin and stderr TTYs, no --json) `sbx run` asks each hold in place (prompt.js);
13
+ // `--name <n>` names the sandbox (agent name + runtime dir, runtime.js namedRuntime) and every
14
+ // command takes `--name` instead of SBX_RUNTIME (both together: exit 2).
15
+ //
16
+ // sbx run [--mode ask|auto|trust] [--name <n>] [--json] [--overlay] -- <cmd> [...]
13
17
  // Runs one sandboxed agent start-to-finish in this process (project = cwd).
14
18
  // The runtime is SBX_RUNTIME when set, else a short temp dir (printed to
15
19
  // stderr so a second terminal can approve from it). With --json, stdout
@@ -33,12 +37,12 @@ import { parseArgs } from 'node:util';
33
37
  import { resolveConfig } from './config.js';
34
38
  import { loadLabels } from './labels.js';
35
39
  import { MODES } from './policy.js';
36
- import { writeFileAtomic } from './holds.js';
37
40
  import { run as sandboxRun } from './run.js';
41
+ import { createTerminalPrompt } from './prompt.js';
38
42
  import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
39
- import { assertAgentName, createRuntime, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
43
+ import { assertAgentName, createRuntime, namedRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
40
44
 
41
- const USAGE = 'usage: sbx [--help] | pending | approve <id> | deny <id> [reason] | diff [--agent <name>] | commit [--agent <name>] [--skip-conflicts] | rollback [--agent <name>] | run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]';
45
+ const USAGE = 'usage: sbx [--help] | run [--mode ask|auto|trust] [--name <n>] [--json] [--overlay] -- <cmd> [...] | pending|diff|rollback [--name <n>] | approve <id> [--name <n>] | deny <id> [reason] [--name <n>] | commit [--name <n>] [--skip-conflicts] (--name replaces SBX_RUNTIME; --agent stays for diff/commit/rollback)';
42
46
 
43
47
  /** Hold ids the CLI accepts: `h<n>` only. Anything else is a usage error, never a path. */
44
48
  const HOLD_ID_RE = /^h\d+$/;
@@ -60,8 +64,27 @@ function usage() {
60
64
  err(USAGE);
61
65
  process.exit(2);
62
66
  }
63
- /** `SBX_RUNTIME` or a usage error. @returns {string} */
64
- function needRuntime() {
67
+ /**
68
+ * The runtime a command addresses: `--name` (via `namedRuntime`) or
69
+ * `SBX_RUNTIME`, never both, never neither. Only `sbx run` creates the dirs.
70
+ *
71
+ * @param {string|undefined} name the `--name` value
72
+ * @param {boolean} [create] make the named dirs (run only)
73
+ * @returns {string} runtime dir
74
+ */
75
+ function needRuntime(name, create = false) {
76
+ if (name !== undefined) {
77
+ if (process.env.SBX_RUNTIME) {
78
+ err('give --name or SBX_RUNTIME, not both');
79
+ process.exit(2);
80
+ }
81
+ try {
82
+ return namedRuntime(name, process.env, { create });
83
+ } catch (e) {
84
+ err(e instanceof Error ? e.message : String(e));
85
+ process.exit(2);
86
+ }
87
+ }
65
88
  const runtime = process.env.SBX_RUNTIME;
66
89
  if (!runtime) usage();
67
90
  return runtime;
@@ -73,13 +96,13 @@ function needRuntime() {
73
96
  * @returns {{ runtime: string, agent: string, skipConflicts: boolean }}
74
97
  */
75
98
  function overlayArgs(rest, { skipConflicts = false } = {}) {
76
- const runtime = needRuntime();
77
- /** @type {{ agent?: string, 'skip-conflicts'?: boolean }} */
99
+ /** @type {{ name?: string, agent?: string, 'skip-conflicts'?: boolean }} */
78
100
  let flagValues;
79
101
  try {
80
102
  ({ values: flagValues } = parseArgs({
81
103
  args: rest,
82
104
  options: {
105
+ name: { type: 'string' },
83
106
  agent: { type: 'string' },
84
107
  'skip-conflicts': { type: 'boolean' },
85
108
  },
@@ -89,7 +112,8 @@ function overlayArgs(rest, { skipConflicts = false } = {}) {
89
112
  } catch {
90
113
  usage();
91
114
  }
92
- const agent = flagValues.agent ?? 'agent';
115
+ const runtime = needRuntime(flagValues.name);
116
+ const agent = flagValues.agent ?? flagValues.name ?? 'agent';
93
117
  const skip = flagValues['skip-conflicts'] ?? false;
94
118
  if (skip && !skipConflicts) usage();
95
119
  try {
@@ -105,15 +129,16 @@ function overlayArgs(rest, { skipConflicts = false } = {}) {
105
129
  * @returns {{ runtime: string, positionals: string[] }}
106
130
  */
107
131
  function decideArgs(rest) {
108
- const runtime = needRuntime();
109
132
  /** @type {string[]} */
110
133
  let positionals;
134
+ /** @type {{ name?: string }} */
135
+ let values;
111
136
  try {
112
- ({ positionals } = parseArgs({ args: rest, options: {}, strict: true, allowPositionals: true }));
137
+ ({ positionals, values } = parseArgs({ args: rest, options: { name: { type: 'string' } }, strict: true, allowPositionals: true }));
113
138
  } catch {
114
139
  usage();
115
140
  }
116
- return { runtime, positionals };
141
+ return { runtime: needRuntime(values.name), positionals };
117
142
  }
118
143
  /** Overlay failure on stderr, exit 1 (`process.exit` is already `never`). @param {unknown} e @returns {never} */
119
144
  function fail(e) {
@@ -134,6 +159,24 @@ if (!cmd || cmd === '--help' || cmd === '-h') {
134
159
  if (!Object.hasOwn(COMMANDS, /** @type {string} */ (cmd))) usage();
135
160
  await COMMANDS[/** @type {keyof typeof COMMANDS} */ (cmd)](args);
136
161
 
162
+ /**
163
+ * Library errors speak of runtimes and agents; for a named sandbox say what
164
+ * the user can do with the name.
165
+ *
166
+ * @param {string|undefined} name the `--name` value
167
+ * @param {string} msg the error message
168
+ * @returns {string} message in terms of the sandbox
169
+ */
170
+ function named(name, msg) {
171
+ if (name === undefined) return msg;
172
+ const pid = /is in use by pid (\d+)/.exec(msg);
173
+ if (pid) return `sandbox ${name} is already running (pid ${pid[1]}): pick another --name, or wait for it to end`;
174
+ if (msg.includes('uncommitted overlay changes')) {
175
+ return `sandbox ${name} has uncommitted changes: review with 'sbx diff --name ${name}', then 'sbx commit --name ${name}' or 'sbx rollback --name ${name}'`;
176
+ }
177
+ return msg;
178
+ }
179
+
137
180
  /**
138
181
  * One sandboxed run in this process. Reports every parked ask from the
139
182
  * queue's events (same process, so nothing is polled and no ask is missed),
@@ -147,12 +190,13 @@ async function run(args) {
147
190
  if (sep < 0) usage();
148
191
  const flags = args.slice(0, sep);
149
192
  const command = args.slice(sep + 1);
150
- /** @type {{ mode?: string, json?: boolean, overlay?: boolean }} */
193
+ /** @type {{ name?: string, mode?: string, json?: boolean, overlay?: boolean }} */
151
194
  let values;
152
195
  try {
153
196
  ({ values } = parseArgs({
154
197
  args: flags,
155
198
  options: {
199
+ name: { type: 'string' },
156
200
  mode: { type: 'string' },
157
201
  json: { type: 'boolean' },
158
202
  overlay: { type: 'boolean' },
@@ -185,14 +229,30 @@ async function run(args) {
185
229
  if (!command.length) usage();
186
230
  const json = values.json ?? false;
187
231
  const overlay = values.overlay ?? false;
188
- const runtime = process.env.SBX_RUNTIME || createRuntime();
232
+ const name = values.name;
233
+ if (name !== undefined) {
234
+ try { assertAgentName(name); } catch (e) { err(e instanceof Error ? e.message : String(e)); process.exit(2); }
235
+ }
236
+ const runtime = name !== undefined ? needRuntime(name, true) : (process.env.SBX_RUNTIME || createRuntime());
237
+ const node = hostNode(process.execPath, process.env.HOME || '/root', process.cwd());
238
+ if (node.refused) err(`barebox: not exposing Node at ${node.dir} (${node.refused}); the sandbox uses /usr/bin/node if present`);
189
239
  // Agent-controlled bytes, sanitized before they reach a terminal or a JSON consumer.
190
240
  const clean = (o, keys) => {
191
241
  const c = { ...o };
192
242
  for (const k of keys) if (c[k] != null) c[k] = safe(c[k]);
193
243
  return c;
194
244
  };
245
+ // A person at this terminal (stdin and stderr are TTYs, not --json) answers
246
+ // holds here; the file channel stays on, so `sbx approve` still works too.
247
+ const prompt = !json && process.stdin.isTTY && process.stderr.isTTY
248
+ ? createTerminalPrompt({
249
+ input: process.stdin,
250
+ output: process.stderr,
251
+ answer: (id, decision, reason) => writeAnswer(runtimePaths(runtime), id, decision, reason),
252
+ })
253
+ : null;
195
254
  const emitAsk = (h) => {
255
+ if (prompt?.ask(h)) return;
196
256
  const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
197
257
  if (json) out(JSON.stringify({ ev: 'ask', ...c }));
198
258
  else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}`);
@@ -202,7 +262,9 @@ async function run(args) {
202
262
  if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
203
263
  else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
204
264
  };
205
- err(`runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
265
+ err(name !== undefined
266
+ ? `sandbox ${name} (answer from another terminal: sbx approve --name ${name} <id>)`
267
+ : `runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
206
268
  /** @type {{ exit: number, diff: { path: string }[] } | null} */
207
269
  let result = null;
208
270
  try {
@@ -211,27 +273,33 @@ async function run(args) {
211
273
  .map((s) => s.trim()).filter(Boolean);
212
274
  result = await sandboxRun({
213
275
  runtime, proj: process.cwd(), command, mode, timeoutMs,
276
+ ...(name !== undefined ? { agent: name } : {}),
214
277
  allowLocal: cfg.localLlm, labels, secrets: cfg.secrets, env: cfg.env,
215
278
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
216
279
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
217
280
  overlay,
218
281
  ...(extraIgnore.length ? { overlayIgnore: ['node_modules', ...extraIgnore] } : {}),
219
- onEvent: (e) => { if (e.type === 'ask') emitAsk(e.ask); else emitDecided(e); },
282
+ onEvent: (e) => {
283
+ if (e.type === 'ask') emitAsk(e.ask);
284
+ else { prompt?.decided(e); emitDecided(e); }
285
+ },
220
286
  // With --json stdout is a pure event stream: agent output goes to
221
287
  // stderr so a parser never trips over it.
222
288
  ...(json ? { stdout: process.stderr, stderr: process.stderr } : {}),
223
289
  });
224
290
  } catch (e) {
225
- err(`run failed: ${e instanceof Error ? e.message : String(e)}`);
291
+ prompt?.close();
292
+ err(`run failed: ${named(name, e instanceof Error ? e.message : String(e))}`);
226
293
  process.exitCode = 1;
227
294
  return;
228
295
  }
296
+ prompt?.close();
229
297
  if (json) out(JSON.stringify({ ev: 'done', exit: result.exit }));
230
298
  else out(`done exit ${result.exit}`);
231
299
  if (overlay) {
232
300
  const n = result.diff.length;
233
301
  err(n
234
- ? `overlay: ${n} change(s) — review with: SBX_RUNTIME=${runtime} sbx diff`
302
+ ? `overlay: ${n} change(s) — review with: ${name !== undefined ? `sbx diff --name ${name}` : `SBX_RUNTIME=${runtime} sbx diff`}`
235
303
  : 'overlay: no changes');
236
304
  }
237
305
  process.exitCode = result.exit;
@@ -371,16 +439,49 @@ async function answerTarget(rest) {
371
439
  return { id, reason: ids.join(' ') || 'denied by user', paths };
372
440
  }
373
441
 
442
+ /**
443
+ * The one writer of answer files (`sbx approve`, `sbx deny`, the terminal prompt).
444
+ * The first answer wins: the file is created exclusively (hard link of a 0600
445
+ * tmp file), so a second answer for the same id writes nothing.
446
+ *
447
+ * @param {ReturnType<typeof runtimePaths>} paths runtime paths
448
+ * @param {string} id hold id
449
+ * @param {'allow'|'deny'} decision the answer
450
+ * @param {string} [reason] deny reason
451
+ * @returns {boolean} true when written, false when the hold was already answered
452
+ */
453
+ function writeAnswer(paths, id, decision, reason) {
454
+ const final = paths.answerFile(id);
455
+ fs.mkdirSync(path.dirname(final), { recursive: true });
456
+ const tmp = `${final}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
457
+ fs.writeFileSync(tmp, JSON.stringify(decision === 'allow' ? { decision } : { decision, reason }), { mode: 0o600 });
458
+ try {
459
+ fs.linkSync(tmp, final);
460
+ return true;
461
+ } catch (e) {
462
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'EEXIST') return false;
463
+ throw e;
464
+ } finally {
465
+ fs.unlinkSync(tmp);
466
+ }
467
+ }
468
+
469
+ /** @param {string} id hold id @returns {never} */
470
+ function alreadyAnswered(id) {
471
+ err(`${id} already answered`);
472
+ process.exit(1);
473
+ }
474
+
374
475
  /** @param {string[]} rest @returns {Promise<void>} */
375
476
  async function approve(rest) {
376
477
  const { id, paths } = await answerTarget(rest);
377
- writeFileAtomic(paths.answerFile(id), JSON.stringify({ decision: 'allow' }));
478
+ if (!writeAnswer(paths, id, 'allow')) alreadyAnswered(id);
378
479
  out(`approved ${id}`);
379
480
  }
380
481
 
381
482
  /** @param {string[]} rest @returns {Promise<void>} */
382
483
  async function deny(rest) {
383
484
  const { id, reason, paths } = await answerTarget(rest);
384
- writeFileAtomic(paths.answerFile(id), JSON.stringify({ decision: 'deny', reason }));
485
+ if (!writeAnswer(paths, id, 'deny', reason)) alreadyAnswered(id);
385
486
  out(`denied ${id}`);
386
487
  }