barebox 0.7.0 → 0.9.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,40 @@ 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.9.0] - 2026-11-03
8
+
9
+ ### Added
10
+
11
+ - `sbx run --hold <seconds|never>` sets how long a held request waits, per run, overriding the `holdTimeoutSec` config key.
12
+ - Terminal colors in the `sbx run` question and answers, only when stderr is a terminal and `NO_COLOR` is unset: yellow header with the agent name in bold, bold labels, cyan URL, dim data and hold id, green for allowed, red for denied or timed out. `--json` and piped output stay plain.
13
+ - The hold id shows in the question as `(hold hN)`.
14
+ - `sbx approve` and `sbx deny` on a hold that already ended print `<id> already decided` and exit 1; when the answer is written but the proxy has not read it yet, they print `<id>: answer written, the proxy has not read it yet`.
15
+ - `--name` for a sandbox that never ran exits 1 with `no sandbox named <n>` and creates nothing.
16
+ - Demo A (`examples/demo-a`): a scripted flight-booking run in ask, auto and trust modes, and a live driver (`--driver muse`) where you answer the holds. The README carries the measured numbers and a captioned demo.
17
+
18
+ ### Changed
19
+
20
+ - `sbx run` waits for your answer by default (was 120 s); `--hold <seconds|never>` sets a deadline per run, and the `holdTimeoutSec` config key sets one for all runs. The library's `createHolds`/`createProxy` default stays 120 s. Unattended runs need `--hold <seconds>`.
21
+
22
+ ## [0.8.0] - 2026-11-02
23
+
24
+ ### Added
25
+
26
+ - `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.
27
+ - `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).
28
+ - `~/.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.
29
+
30
+ ### Changed
31
+
32
+ - 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.
33
+ - 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.
34
+
35
+ ### Fixed
36
+
37
+ - `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.
38
+ - 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.
39
+ - `#!/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.
40
+
7
41
  ## [0.7.0] - 2026-11-01
8
42
 
9
43
  ### Added
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  ```
10
10
 
11
11
  > An agent runs on your machine with your real tools, every write is undoable, and nothing leaves the machine without passing a doorman. You're asked only when something irreversible is about to happen.
12
- > No root, no daemon, no image. One shared proxy, many thin sandboxes: ~8 MB each, 10 ms to start (M0 POC figure — unmeasured on the rewritten code, TODO re-measure).
12
+ > No root, no daemon, no image. One shared proxy, many thin sandboxes: ~8 MB each, about 0.7 s from `sbx run` to exit with the proxy included.
13
13
 
14
14
  <p align="center">
15
15
  <img src="https://img.shields.io/github/package-json/v/hamr0/barebox?label=version&color=2a4f8c" alt="version (auto from package.json)">
@@ -21,7 +21,7 @@
21
21
 
22
22
  Agents need real access to be useful — shell, files, network. Today you pick one of two bad options:
23
23
 
24
- - **Approve everything.** About forty prompts per task. People stop reading them, or switch prompts off.
24
+ - **Approve everything.** A prompt for nearly every command and edit. People stop reading them, or switch prompts off.
25
25
  - **Heavy isolation.** Docker or a VM: images, a daemon, root, and the agent can't use your installed toolchain. Most people skip it.
26
26
 
27
27
  Neither matches where the risk is. Reads are mostly harmless. File writes can be fixed. Only a few actions can't be undone: paying, sending, publishing, pushing. barebox asks about those and nothing else.
@@ -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 the built-in model endpoints, Anthropic and OpenAI, and to a `localLlm` server are not card-scanned; a model API you label `r` yourself still is); 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. A hold waits until you answer by default; `sbx run --hold 120 -- <cmd>` (or the `holdTimeoutSec` config key) sets a deadline, and a 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 any deadline counts from arrival. Unattended runs (cron, CI, no terminal) have nobody to answer, so pass `--hold <seconds>` or the first held request waits forever.
77
77
 
78
78
  ## Keys the agent never holds
79
79
 
@@ -97,13 +97,23 @@ 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 |
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 |
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
+ | Start + exit | **0.70 s** median for `sbx run -- true`, proxy start to teardown (0.80 s with `--overlay`; 11 runs, quiet machine). The sandbox alone (bwrap) is 6 ms; Node's own start is 0.16 s of it | 1.87-2.05 s |
102
+ | One real agent | Claude Code peaks at **248 MB** inside vs 249 MB bare: barebox does not change the agent. barebox itself adds **about 91 MB** for the first agent (the `sbx` process with its proxy 83 MB, plus 8 MB of walls), then about 11 MB per further agent | not measured |
103
+ | 10 agents | ~195-200 MB worst case (proxy + 10 x 8 MB) | ~1 GB |
104
+ | 20 agents | ~295-310 MB worst case | ~2 GB |
105
+ | 40 agents | ~525-560 MB worst case | not measured |
105
106
 
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).
107
+ **What the demos show** (scripts in `examples/`, run by hand, every cell asserted):
108
+
109
+ ![Demo A: a real agent books a trip inside barebox. Reads and model calls go out free, a payment waits for a yes and only then gets the real key, a no never leaves the machine](assets/demo-a.gif)
110
+
111
+ The full 92-second take, captioned: [assets/demo-a.webm](assets/demo-a.webm).
112
+
113
+ - **Demo A, a real agent books a trip.** Meta's muse model (via Baseten) planned and booked a trip inside barebox in a recorded, unedited live run: 31 requests, **23 went out with no question** (3 searches, weather, exchange rate, and 18 model calls, one of them to a second model) and **8 stopped for a person** (payments, a hotel order, a car, a calendar entry, a chat message, a `DELETE`, an email). The real Stripe-style key reached the server once, after a yes; the agent only ever held a placeholder. Log, timing and captions: `docs/logs/m7-muse-runs/`.
114
+ - **Demo B, a prompt-injected agent.** In every mode (`ask`, `auto`, `trust`) all three exfiltration attempts fail: `~/.ssh` reads empty, the POST to the attacker's host is refused, a direct socket has no route. The good edits are committed and the injected agent's edits rolled back.
115
+
116
+ 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
117
 
108
118
  ## Roadmap
109
119
 
@@ -56,15 +56,31 @@ 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] (hold 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"
65
81
  ```
66
82
 
67
- Held requests wait (default 120 s, `never` supported), counting from arrival:
83
+ Held requests wait, counting from arrival, until a deadline: the library's default is 120 s (`createHolds`/`createProxy`; `'never'` supported), while `sbx run` waits until answered by default (`holdTimeoutSec` `"never"`; `--hold <seconds|never>` or the config key sets a deadline):
68
84
  time spent in line and reading the body counts too, and a request past its
69
85
  deadline is denied `hold timeout` whether waiting, sending, or parked. Each
70
86
  agent holds at most one request being read or parked; later ones wait in
@@ -72,6 +88,9 @@ line, unread, in order — at most 16, the next gets `429 hold queue full`.
72
88
  Approve forwards, deny and timeout answer 403 with the reason. A held body is spooled to `<runtime>/held/<id>` (never kept in memory, deleted when the hold ends); one over `hold.maxBody` (default 50 MB) is denied `403 body too large to hold`. These commands
73
89
  need the proxy to be alive: with no live proxy on the runtime `sbx pending`,
74
90
  `approve` and `deny` exit 1 and say so, because nothing would read the answer.
91
+ `approve` and `deny` wait briefly to learn what the proxy did: an answer for a hold that already ended exits 1 with `<id> already decided`; if the proxy has not read it yet they print `answer written, the proxy has not read it yet` and still report `approved` / `denied`. `--name` for a sandbox that never ran exits 1 with `no sandbox named <n>` and creates nothing. The terminal question is colored only when stderr is a TTY and `NO_COLOR` is unset.
92
+
93
+ Unattended runs (cron, CI, no TTY, `--json`): nobody answers on the terminal, and `sbx run` waits forever by default, so a held request would hang the run. Pass `--hold <seconds>` (or set `holdTimeoutSec`) so a hold times out as a deny.
75
94
 
76
95
  ## One call: `run()` and `sbx run`
77
96
 
@@ -93,18 +112,19 @@ const { exit, asks, audit, diff, runtime } = await run({
93
112
  ```
94
113
 
95
114
  ```bash
96
- sbx run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]
115
+ sbx run [--name <n>] [--mode ask|auto|trust] [--hold <seconds|never>] [--json] [--overlay] -- <cmd> [...]
97
116
  ```
98
117
 
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.
118
+ `sbx run` uses the current directory as the project and `--name`'s runtime or
119
+ `SBX_RUNTIME` as the runtime (a short temp dir otherwise, printed on stderr). With a
120
+ terminal it asks each held request in place (see above); without one, or with `--json`, it
121
+ prints an `ask` line when a request parks. Either way a `decided` line follows when it ends,
122
+ then `done`; with `--json` stdout carries only JSON lines and nothing is ever prompted.
123
+ Its exit code mirrors the agent's.
104
124
 
105
125
  `sbx run` reads one optional config file,
106
126
  `${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`, with keys `mode`,
107
- `holdTimeoutSec` (positive integer or `"never"`), `heldBodyMaxMB`
127
+ `holdTimeoutSec` (positive integer or `"never"`; default `"never"`, overridden per run by `--hold`), `heldBodyMaxMB`
108
128
  (positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
109
129
  unknown key, bad value or bad JSON exits 2 naming the file and key. The file
110
130
  is hidden inside the sandbox wherever it resolves. The library does not read it.
@@ -130,8 +150,9 @@ mode letters, the labels and the floor decide. The floor is two bareguard flags,
130
150
  `cardLike` (a body of 64 KB or less holding a card number: 13-19 digits,
131
151
  optional single space or dash, first digit 2-6, Luhn-valid) and `paymentPath`
132
152
  (`/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.
153
+ `trust` included. Nothing is denied because of a card. One exception: a call
154
+ to a model endpoint (see "Labels and model endpoints") is never card-scanned,
155
+ in any mode. Bodies over 64 KB stream through unscanned. The body never enters the gate's action.
135
156
 
136
157
  barebox's hold queue is each gate's `humanChannel`: the ask files, `onAsk`
137
158
  and `sbx approve|deny` work as above, and the ask carries the gate's `rule`
@@ -227,8 +248,8 @@ hands the real value to the agent.
227
248
 
228
249
  `<runtime>/gate.jsonl` (`runtimePaths(runtime).audit`; `run()` returns it as
229
250
  `audit`) is the only log, one JSON object per line, all in bareguard's shape.
230
- It is never rotated. `sbx run` without `SBX_RUNTIME` gets a fresh runtime, so a
231
- fresh log, each run; with a reused `SBX_RUNTIME` the file keeps growing: delete
251
+ It is never rotated. `sbx run` without `SBX_RUNTIME` or `--name` gets a fresh runtime, so a
252
+ fresh log, each run; with a reused `SBX_RUNTIME` or `--name` (its runtime dir is kept) the file keeps growing: delete
232
253
  it between runs (no proxy running) to start a new one.
233
254
  - Decisions: bareguard's gate lines carry the action (`method`, `url`, `tool`,
234
255
  `agent`, `rid`) and an `aid`.
@@ -281,7 +302,9 @@ Model endpoints are `r` (free in every mode): `api.anthropic.com`
281
302
  `POST /v1/chat/completions`, `/v1/responses` and `/v1/embeddings`; and on each
282
303
  `localLlm` host:port `POST /api/chat`, `/api/generate`, `/api/embed`,
283
304
  `/v1/chat/completions` and `/v1/completions` (over http or https). Any other path on
284
- those hosts is a normal `POST`.
305
+ those hosts is a normal `POST`. Model calls skip the card floor (the
306
+ `paymentPath` mark still applies): a model call carries the whole conversation,
307
+ and a card number in it must not kill the agent.
285
308
 
286
309
  Label folders are hidden inside the sandbox like the config file, so the agent
287
310
  cannot rewrite a letter. `run()` and `createProxy()` take `labels:
@@ -296,11 +319,13 @@ project: the agent sees the real files, every write lands on the upper.
296
319
  Review and press it down from the same runtime:
297
320
 
298
321
  ```bash
299
- SBX_RUNTIME=/tmp/sbx npx sbx diff [--agent <name>] # A/M/D, conflicts flagged
300
- SBX_RUNTIME=/tmp/sbx npx sbx commit [--skip-conflicts] # refuses on conflicts by default
301
- SBX_RUNTIME=/tmp/sbx npx sbx rollback # throw the paper away
322
+ npx sbx diff --name docs-bot # A/M/D, conflicts flagged
323
+ npx sbx commit --name docs-bot [--skip-conflicts] # refuses on conflicts by default
324
+ npx sbx rollback --name docs-bot # throw the paper away
302
325
  ```
303
326
 
327
+ (Without `--name`: `SBX_RUNTIME=/tmp/sbx npx sbx diff [--agent <name>]`, same for the others.)
328
+
304
329
  A path the project changed after the run started is a conflict: commit
305
330
  refuses all of it unless `--skip-conflicts`. `node_modules` is invisible to
306
331
  the layer (extend with `SBX_OVERLAY_IGNORE=a,b`). Commit strips setuid/setgid
@@ -319,12 +344,12 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
319
344
  `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
320
345
  verification. Only `ca.pem` enters the sandbox, never the key.
321
346
  - 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.
322
- - 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.
347
+ - 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.
323
348
  - 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`.
324
349
  - 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.
325
350
  - `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.
326
351
  - 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.
327
- - `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; 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. 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).
352
+ - `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).
328
353
  - `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
329
354
  - 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.
330
355
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.7.0",
3
+ "version": "0.9.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/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] [--hold <seconds|never>] [--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,13 @@ 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, paint, ANSI } from './prompt.js';
42
+ import { DEFAULT_POLL_MS } from './holds.js';
38
43
  import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
39
- import { assertAgentName, createRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
44
+ import { assertAgentName, createRuntime, namedRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
40
45
 
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> [...]';
46
+ const USAGE = 'usage: sbx [--help] | run [--mode ask|auto|trust] [--hold <seconds|never>] [--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
47
 
43
48
  /** Hold ids the CLI accepts: `h<n>` only. Anything else is a usage error, never a path. */
44
49
  const HOLD_ID_RE = /^h\d+$/;
@@ -60,8 +65,33 @@ function usage() {
60
65
  err(USAGE);
61
66
  process.exit(2);
62
67
  }
63
- /** `SBX_RUNTIME` or a usage error. @returns {string} */
64
- function needRuntime() {
68
+ /**
69
+ * The runtime a command addresses: `--name` (via `namedRuntime`) or
70
+ * `SBX_RUNTIME`, never both, never neither. Only `sbx run` creates the dirs.
71
+ *
72
+ * @param {string|undefined} name the `--name` value
73
+ * @param {boolean} [create] make the named dirs (run only)
74
+ * @returns {string} runtime dir
75
+ */
76
+ function needRuntime(name, create = false) {
77
+ if (name !== undefined) {
78
+ if (process.env.SBX_RUNTIME) {
79
+ err('give --name or SBX_RUNTIME, not both');
80
+ process.exit(2);
81
+ }
82
+ let dir;
83
+ try {
84
+ dir = namedRuntime(name, process.env, { create });
85
+ } catch (e) {
86
+ err(e instanceof Error ? e.message : String(e));
87
+ process.exit(2);
88
+ }
89
+ if (!create && !fs.existsSync(dir)) {
90
+ err(`no sandbox named ${name} (start one with 'sbx run --name ${name} -- …')`);
91
+ process.exit(1);
92
+ }
93
+ return dir;
94
+ }
65
95
  const runtime = process.env.SBX_RUNTIME;
66
96
  if (!runtime) usage();
67
97
  return runtime;
@@ -73,13 +103,13 @@ function needRuntime() {
73
103
  * @returns {{ runtime: string, agent: string, skipConflicts: boolean }}
74
104
  */
75
105
  function overlayArgs(rest, { skipConflicts = false } = {}) {
76
- const runtime = needRuntime();
77
- /** @type {{ agent?: string, 'skip-conflicts'?: boolean }} */
106
+ /** @type {{ name?: string, agent?: string, 'skip-conflicts'?: boolean }} */
78
107
  let flagValues;
79
108
  try {
80
109
  ({ values: flagValues } = parseArgs({
81
110
  args: rest,
82
111
  options: {
112
+ name: { type: 'string' },
83
113
  agent: { type: 'string' },
84
114
  'skip-conflicts': { type: 'boolean' },
85
115
  },
@@ -89,7 +119,8 @@ function overlayArgs(rest, { skipConflicts = false } = {}) {
89
119
  } catch {
90
120
  usage();
91
121
  }
92
- const agent = flagValues.agent ?? 'agent';
122
+ const runtime = needRuntime(flagValues.name);
123
+ const agent = flagValues.agent ?? flagValues.name ?? 'agent';
93
124
  const skip = flagValues['skip-conflicts'] ?? false;
94
125
  if (skip && !skipConflicts) usage();
95
126
  try {
@@ -105,15 +136,16 @@ function overlayArgs(rest, { skipConflicts = false } = {}) {
105
136
  * @returns {{ runtime: string, positionals: string[] }}
106
137
  */
107
138
  function decideArgs(rest) {
108
- const runtime = needRuntime();
109
139
  /** @type {string[]} */
110
140
  let positionals;
141
+ /** @type {{ name?: string }} */
142
+ let values;
111
143
  try {
112
- ({ positionals } = parseArgs({ args: rest, options: {}, strict: true, allowPositionals: true }));
144
+ ({ positionals, values } = parseArgs({ args: rest, options: { name: { type: 'string' } }, strict: true, allowPositionals: true }));
113
145
  } catch {
114
146
  usage();
115
147
  }
116
- return { runtime, positionals };
148
+ return { runtime: needRuntime(values.name), positionals };
117
149
  }
118
150
  /** Overlay failure on stderr, exit 1 (`process.exit` is already `never`). @param {unknown} e @returns {never} */
119
151
  function fail(e) {
@@ -134,6 +166,24 @@ if (!cmd || cmd === '--help' || cmd === '-h') {
134
166
  if (!Object.hasOwn(COMMANDS, /** @type {string} */ (cmd))) usage();
135
167
  await COMMANDS[/** @type {keyof typeof COMMANDS} */ (cmd)](args);
136
168
 
169
+ /**
170
+ * Library errors speak of runtimes and agents; for a named sandbox say what
171
+ * the user can do with the name.
172
+ *
173
+ * @param {string|undefined} name the `--name` value
174
+ * @param {string} msg the error message
175
+ * @returns {string} message in terms of the sandbox
176
+ */
177
+ function named(name, msg) {
178
+ if (name === undefined) return msg;
179
+ const pid = /is in use by pid (\d+)/.exec(msg);
180
+ if (pid) return `sandbox ${name} is already running (pid ${pid[1]}): pick another --name, or wait for it to end`;
181
+ if (msg.includes('uncommitted overlay changes')) {
182
+ return `sandbox ${name} has uncommitted changes: review with 'sbx diff --name ${name}', then 'sbx commit --name ${name}' or 'sbx rollback --name ${name}'`;
183
+ }
184
+ return msg;
185
+ }
186
+
137
187
  /**
138
188
  * One sandboxed run in this process. Reports every parked ask from the
139
189
  * queue's events (same process, so nothing is polled and no ask is missed),
@@ -147,13 +197,15 @@ async function run(args) {
147
197
  if (sep < 0) usage();
148
198
  const flags = args.slice(0, sep);
149
199
  const command = args.slice(sep + 1);
150
- /** @type {{ mode?: string, json?: boolean, overlay?: boolean }} */
200
+ /** @type {{ name?: string, mode?: string, hold?: string, json?: boolean, overlay?: boolean }} */
151
201
  let values;
152
202
  try {
153
203
  ({ values } = parseArgs({
154
204
  args: flags,
155
205
  options: {
206
+ name: { type: 'string' },
156
207
  mode: { type: 'string' },
208
+ hold: { type: 'string' },
157
209
  json: { type: 'boolean' },
158
210
  overlay: { type: 'boolean' },
159
211
  },
@@ -167,7 +219,7 @@ async function run(args) {
167
219
  /** @type {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} */
168
220
  let cfg;
169
221
  try {
170
- cfg = resolveConfig({ mode: values.mode });
222
+ cfg = resolveConfig({ mode: values.mode, hold: values.hold });
171
223
  } catch (e) {
172
224
  err(e instanceof Error ? e.message : String(e));
173
225
  process.exit(2);
@@ -185,7 +237,11 @@ async function run(args) {
185
237
  if (!command.length) usage();
186
238
  const json = values.json ?? false;
187
239
  const overlay = values.overlay ?? false;
188
- const runtime = process.env.SBX_RUNTIME || createRuntime();
240
+ const name = values.name;
241
+ if (name !== undefined) {
242
+ try { assertAgentName(name); } catch (e) { err(e instanceof Error ? e.message : String(e)); process.exit(2); }
243
+ }
244
+ const runtime = name !== undefined ? needRuntime(name, true) : (process.env.SBX_RUNTIME || createRuntime());
189
245
  const node = hostNode(process.execPath, process.env.HOME || '/root', process.cwd());
190
246
  if (node.refused) err(`barebox: not exposing Node at ${node.dir} (${node.refused}); the sandbox uses /usr/bin/node if present`);
191
247
  // Agent-controlled bytes, sanitized before they reach a terminal or a JSON consumer.
@@ -194,7 +250,19 @@ async function run(args) {
194
250
  for (const k of keys) if (c[k] != null) c[k] = safe(c[k]);
195
251
  return c;
196
252
  };
253
+ // A person at this terminal (stdin and stderr are TTYs, not --json) answers
254
+ // holds here; the file channel stays on, so `sbx approve` still works too.
255
+ const errColor = !!process.stderr.isTTY && !process.env.NO_COLOR;
256
+ const prompt = !json && process.stdin.isTTY && process.stderr.isTTY
257
+ ? createTerminalPrompt({
258
+ input: process.stdin,
259
+ output: process.stderr,
260
+ color: errColor,
261
+ answer: (id, decision, reason) => writeAnswer(runtimePaths(runtime), id, decision, reason),
262
+ })
263
+ : null;
197
264
  const emitAsk = (h) => {
265
+ if (prompt?.ask(h)) return;
198
266
  const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
199
267
  if (json) out(JSON.stringify({ ev: 'ask', ...c }));
200
268
  else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}`);
@@ -204,7 +272,13 @@ async function run(args) {
204
272
  if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
205
273
  else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
206
274
  };
207
- err(`runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
275
+ if (name !== undefined && errColor) {
276
+ // Colored line: only the dynamic name is sanitized; `err` would strip the escapes.
277
+ const n = safe(name);
278
+ console.error(`sandbox ${paint(true, ANSI.bold, n)}${ANSI.dim} (answer from another terminal: sbx approve --name ${n} <id>)${ANSI.reset}`);
279
+ } else err(name !== undefined
280
+ ? `sandbox ${name} (answer from another terminal: sbx approve --name ${name} <id>)`
281
+ : `runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
208
282
  /** @type {{ exit: number, diff: { path: string }[] } | null} */
209
283
  let result = null;
210
284
  try {
@@ -213,27 +287,33 @@ async function run(args) {
213
287
  .map((s) => s.trim()).filter(Boolean);
214
288
  result = await sandboxRun({
215
289
  runtime, proj: process.cwd(), command, mode, timeoutMs,
290
+ ...(name !== undefined ? { agent: name } : {}),
216
291
  allowLocal: cfg.localLlm, labels, secrets: cfg.secrets, env: cfg.env,
217
292
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
218
293
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
219
294
  overlay,
220
295
  ...(extraIgnore.length ? { overlayIgnore: ['node_modules', ...extraIgnore] } : {}),
221
- onEvent: (e) => { if (e.type === 'ask') emitAsk(e.ask); else emitDecided(e); },
296
+ onEvent: (e) => {
297
+ if (e.type === 'ask') emitAsk(e.ask);
298
+ else { prompt?.decided(e); emitDecided(e); }
299
+ },
222
300
  // With --json stdout is a pure event stream: agent output goes to
223
301
  // stderr so a parser never trips over it.
224
302
  ...(json ? { stdout: process.stderr, stderr: process.stderr } : {}),
225
303
  });
226
304
  } catch (e) {
227
- err(`run failed: ${e instanceof Error ? e.message : String(e)}`);
305
+ prompt?.close();
306
+ err(`run failed: ${named(name, e instanceof Error ? e.message : String(e))}`);
228
307
  process.exitCode = 1;
229
308
  return;
230
309
  }
310
+ prompt?.close();
231
311
  if (json) out(JSON.stringify({ ev: 'done', exit: result.exit }));
232
312
  else out(`done exit ${result.exit}`);
233
313
  if (overlay) {
234
314
  const n = result.diff.length;
235
315
  err(n
236
- ? `overlay: ${n} change(s) — review with: SBX_RUNTIME=${runtime} sbx diff`
316
+ ? `overlay: ${n} change(s) — review with: ${name !== undefined ? `sbx diff --name ${name}` : `SBX_RUNTIME=${runtime} sbx diff`}`
237
317
  : 'overlay: no changes');
238
318
  }
239
319
  process.exitCode = result.exit;
@@ -373,16 +453,90 @@ async function answerTarget(rest) {
373
453
  return { id, reason: ids.join(' ') || 'denied by user', paths };
374
454
  }
375
455
 
456
+ /**
457
+ * The one writer of answer files (`sbx approve`, `sbx deny`, the terminal prompt).
458
+ * The first answer wins: the file is created exclusively (hard link of a 0600
459
+ * tmp file), so a second answer for the same id writes nothing.
460
+ *
461
+ * @param {ReturnType<typeof runtimePaths>} paths runtime paths
462
+ * @param {string} id hold id
463
+ * @param {'allow'|'deny'} decision the answer
464
+ * @param {string} [reason] deny reason
465
+ * @returns {boolean} true when written, false when the hold was already answered
466
+ */
467
+ function writeAnswer(paths, id, decision, reason) {
468
+ const final = paths.answerFile(id);
469
+ fs.mkdirSync(path.dirname(final), { recursive: true });
470
+ const tmp = `${final}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
471
+ fs.writeFileSync(tmp, JSON.stringify(decision === 'allow' ? { decision } : { decision, reason }), { mode: 0o600 });
472
+ try {
473
+ fs.linkSync(tmp, final);
474
+ return true;
475
+ } catch (e) {
476
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'EEXIST') return false;
477
+ throw e;
478
+ } finally {
479
+ fs.unlinkSync(tmp);
480
+ }
481
+ }
482
+
483
+ /** @param {string} id hold id @returns {never} */
484
+ function alreadyAnswered(id) {
485
+ err(`${id} already answered`);
486
+ process.exit(1);
487
+ }
488
+
489
+ /**
490
+ * After our answer is linked, learn what the proxy did with it. The proxy
491
+ * writes `answers/<id>.stale` before it consumes an answer for a hold it no
492
+ * longer has, so once our answer file is gone the marker is the whole truth.
493
+ * Bounded at 4 poll intervals; a proxy that has not read it by then is
494
+ * reported, not guessed at.
495
+ *
496
+ * @param {ReturnType<typeof runtimePaths>} paths runtime paths
497
+ * @param {string} id hold id
498
+ * @returns {Promise<'settled'|'stale'|'unread'>} the outcome
499
+ */
500
+ async function outcomeOf(paths, id) {
501
+ const end = Date.now() + 4 * DEFAULT_POLL_MS;
502
+ while (fs.existsSync(paths.answerFile(id))) {
503
+ if (Date.now() > end) return 'unread';
504
+ await new Promise((r) => setTimeout(r, 10));
505
+ }
506
+ try {
507
+ fs.unlinkSync(paths.staleFile(id));
508
+ return 'stale';
509
+ } catch {
510
+ return 'settled';
511
+ }
512
+ }
513
+
514
+ /**
515
+ * @param {ReturnType<typeof runtimePaths>} paths runtime paths
516
+ * @param {string} id hold id
517
+ * @param {'allow'|'deny'} decision the answer
518
+ * @param {string} [reason] deny reason
519
+ * @returns {Promise<void>} resolves when the answer settled the hold (or the proxy has not read it yet); exits 1 otherwise
520
+ */
521
+ async function answerHold(paths, id, decision, reason) {
522
+ if (!writeAnswer(paths, id, decision, reason)) alreadyAnswered(id);
523
+ const outcome = await outcomeOf(paths, id);
524
+ if (outcome === 'stale') {
525
+ err(`${id} already decided`);
526
+ process.exit(1);
527
+ }
528
+ if (outcome === 'unread') err(`${id}: answer written, the proxy has not read it yet`);
529
+ out(`${decision === 'allow' ? 'approved' : 'denied'} ${id}`);
530
+ }
531
+
376
532
  /** @param {string[]} rest @returns {Promise<void>} */
377
533
  async function approve(rest) {
378
534
  const { id, paths } = await answerTarget(rest);
379
- writeFileAtomic(paths.answerFile(id), JSON.stringify({ decision: 'allow' }));
380
- out(`approved ${id}`);
535
+ await answerHold(paths, id, 'allow');
381
536
  }
382
537
 
383
538
  /** @param {string[]} rest @returns {Promise<void>} */
384
539
  async function deny(rest) {
385
540
  const { id, reason, paths } = await answerTarget(rest);
386
- writeFileAtomic(paths.answerFile(id), JSON.stringify({ decision: 'deny', reason }));
387
- out(`denied ${id}`);
541
+ await answerHold(paths, id, 'deny', reason);
388
542
  }
package/src/config.js CHANGED
@@ -7,7 +7,7 @@ import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { MODES } from './policy.js';
9
9
 
10
- const DEFAULTS = { mode: 'auto', holdTimeoutSec: 120, localLlm: [], labels: [], tenants: {} };
10
+ const DEFAULTS = { mode: 'auto', holdTimeoutSec: 'never', localLlm: [], labels: [], tenants: {} };
11
11
 
12
12
  /** One `host:port` (host without a colon, port 1-65535). @param {unknown} v @returns {boolean} */
13
13
  const isHostPort = (v) => {
@@ -137,11 +137,22 @@ export function loadConfig(env = process.env) {
137
137
  *
138
138
  * @param {object} [flags] values given on the command line
139
139
  * @param {string} [flags.mode] `--mode`
140
+ * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
140
141
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
141
142
  * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
142
143
  * @throws {Error} as {@link loadConfig}
143
144
  */
144
145
  export function resolveConfig(flags = {}, env = process.env) {
145
146
  const cfg = loadConfig(env);
146
- return { ...cfg, ...(flags.mode !== undefined ? { mode: flags.mode } : {}) };
147
+ let hold;
148
+ if (flags.hold !== undefined) {
149
+ hold = flags.hold === 'never' ? 'never' : /^\d+$/.test(flags.hold) ? Number(flags.hold) : flags.hold;
150
+ const bad = KEYS.holdTimeoutSec(hold);
151
+ if (bad) throw new Error(`--hold ${bad}`);
152
+ }
153
+ return {
154
+ ...cfg,
155
+ ...(flags.mode !== undefined ? { mode: flags.mode } : {}),
156
+ ...(hold !== undefined ? { holdTimeoutSec: hold } : {}),
157
+ };
147
158
  }
package/src/holds.js CHANGED
@@ -487,6 +487,11 @@ export function createHolds({ log, timeoutMs = 120000,
487
487
  for (const name of names) {
488
488
  if (!name.endsWith('.json')) continue;
489
489
  const id = name.slice(0, -'.json'.length);
490
+ // Not held: say so (the marker `sbx approve` reads) before the answer
491
+ // is consumed, so "answer gone" always means the marker is already there.
492
+ if (!queue.has(id)) {
493
+ try { writeFileAtomic(paths.staleFile(id), ''); } catch {}
494
+ }
490
495
  const text = consumeFile(paths.answerFile(id));
491
496
  if (text === null) continue;
492
497
  const norm = normalizeDecision(parseAnswer(text), { approveAlias: true });
package/src/launcher.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { spawn } from 'node:child_process';
6
6
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
7
  import { join, relative, dirname, delimiter } from 'node:path';
8
- import { assertAgentName, hostNode, isInside, realPathOf, runtimePaths } from './runtime.js';
8
+ import { assertAgentName, hostNode, isInside, realPathOf, runtimePaths, usrLinks } from './runtime.js';
9
9
  import { assertOverlaySupport, setupOverlay } from './overlay.js';
10
10
  import { configPath } from './config.js';
11
11
 
@@ -137,7 +137,8 @@ export function buildCaBundle(runtime, caFile) {
137
137
  }
138
138
 
139
139
  /**
140
- * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`,
140
+ * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`
141
+ * (and the host's `/bin`, `/sbin`, `/lib`, `/lib64`, mirrored),
141
142
  * its project and home read-only, the locked drawers masked, no network of
142
143
  * its own, and a single front door: anything sent to `localhost:<proxyPort>`
143
144
  * is carried out through this agent's socket to the proxy. The agent starts
@@ -203,13 +204,14 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
203
204
  const { bin: nodeBin, bind: nodeBind } = hostNode(nodeExec, home, proj);
204
205
  // Every path the sandbox binds in from the host: the locked drawers and mask folders are
205
206
  // hidden wherever they sit under one of these.
206
- const roots = [home, proj, '/etc', '/usr', ...(nodeBind ? [nodeBind] : [])];
207
+ const links = usrLinks();
208
+ const roots = [home, proj, '/etc', '/usr', ...links.bound, ...(nodeBind ? [nodeBind] : [])];
207
209
  const args = [
208
210
  '--unshare-pid', '--unshare-uts', '--unshare-ipc', '--unshare-net',
209
211
  '--die-with-parent',
210
212
  '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp',
211
213
  '--ro-bind', '/usr', '/usr',
212
- '--symlink', 'usr/lib64', '/lib64',
214
+ ...links.args,
213
215
  '--ro-bind', '/etc', '/etc',
214
216
  // The Node install first: a project or runtime inside it must win over it.
215
217
  // It never holds $HOME and is never inside $HOME, /usr or the project (then
@@ -292,7 +294,10 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
292
294
  }
293
295
  args.push(
294
296
  '--setenv', 'HOME', home,
295
- '--setenv', 'PATH', (!nodeBin || SYSTEM_PATH.includes(nodeBin) ? SYSTEM_PATH : [nodeBin, ...SYSTEM_PATH]).join(':'),
297
+ // ~/.local/bin (where `claude` installs) goes last, so it never shadows a system tool; no new
298
+ // exposure: the dir is already visible through the read-only $HOME bind.
299
+ '--setenv', 'PATH', [...(!nodeBin || SYSTEM_PATH.includes(nodeBin) ? [] : [nodeBin]), ...SYSTEM_PATH,
300
+ ...(existsSync(`${home}/.local/bin`) ? [`${home}/.local/bin`] : [])].join(':'),
296
301
  '--setenv', 'HTTP_PROXY', `http://127.0.0.1:${proxyPort}`,
297
302
  '--setenv', 'HTTPS_PROXY', `http://127.0.0.1:${proxyPort}`,
298
303
  '--setenv', 'http_proxy', `http://127.0.0.1:${proxyPort}`,
@@ -316,8 +321,10 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
316
321
  for (const [k, v] of Object.entries(env.placeholders ?? {})) args.push('--setenv', k, String(v));
317
322
  for (const [k, v] of Object.entries(extraEnv)) args.push('--setenv', k, String(v));
318
323
  const door = String(proxyPort);
324
+ // `-lf /dev/null` drops socat's own log: an early-closed connection prints harmless `E` lines.
325
+ // Safe because a bridge that failed to start is still caught below by the door probe (exit 99).
319
326
  const inner = 'ip link set lo up 2>/dev/null; ' +
320
- `socat TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
327
+ `socat -lf /dev/null TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
321
328
  `ok=; for i in $(seq 1 50); do (echo > /dev/tcp/127.0.0.1/${door}) 2>/dev/null && { ok=1; break; }; sleep 0.1; done; ` +
322
329
  '[ -n "$ok" ] || exit 99; exec "$@"';
323
330
  const child = spawn(bwrapBin(), [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
package/src/overlay.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  } from 'node:fs';
19
19
  import { join, dirname } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
- import { assertAgentName, hostNode, runtimeTempDir, runtimePaths, safe } from './runtime.js';
21
+ import { assertAgentName, hostNode, runtimeTempDir, runtimePaths, safe, usrLinks } from './runtime.js';
22
22
 
23
23
  /** One reviewed file change: what the sandbox did at `path`, and whether the project changed underneath it mid-run.
24
24
  *
@@ -476,8 +476,8 @@ function bwrapWalk({ lower, upper, work, ignore, scratch, stageDir = null, upper
476
476
  // extraction halfway helps nobody.
477
477
  // Mount order is the design, stated once here. bwrap applies mounts in
478
478
  // argument order, so a later mount lands on top of an earlier one:
479
- // a. host paths at their own paths, read-only — /usr (+ the /lib64
480
- // symlink), srcDir, and nodePrefix when node isn't under /usr;
479
+ // a. host paths at their own paths, read-only — /usr (+ the /bin /sbin
480
+ // /lib /lib64 links), srcDir, and nodePrefix when node isn't under /usr;
481
481
  // b. then everything the walk creates — the overlay over <merged>,
482
482
  // and the output folders.
483
483
  // A host bind placed after the overlay would hide it whenever the
@@ -490,7 +490,7 @@ function bwrapWalk({ lower, upper, work, ignore, scratch, stageDir = null, upper
490
490
  // `/` is correct, merely exposing the host read-only to our own walker.
491
491
  const res = spawnSync('bwrap',
492
492
  ['--die-with-parent', '--unshare-all', '--new-session',
493
- '--ro-bind', '/usr', '/usr', '--symlink', 'usr/lib64', '/lib64',
493
+ '--ro-bind', '/usr', '/usr', ...usrLinks().args,
494
494
  '--ro-bind', srcDir, srcDir,
495
495
  ...(underUsr ? [] : ['--ro-bind', nodePrefix, nodePrefix]),
496
496
  '--overlay-src', lower, '--overlay', upper, work, merged,
package/src/policy.js CHANGED
@@ -57,12 +57,33 @@ export const emptyMatcher = matcherFrom([]);
57
57
  export function buildTools(labelTools = {}, localLlm = []) {
58
58
  /** @type {Record<string, any>} */
59
59
  const models = {};
60
+ for (const k of modelKeys(localLlm)) models[k] = 'r';
61
+ return { ...TOOLS, ...models, ...labelTools };
62
+ }
63
+
64
+ /** @param {string[]} localLlm @returns {Set<string>} every model endpoint's tool key */
65
+ function modelKeys(localLlm) {
66
+ const keys = new Set();
60
67
  const add = (scheme, host, paths) => {
61
- for (const p of paths) models[emptyMatcher.match('POST', `${scheme}://${host}${p}`).key] = 'r';
68
+ for (const p of paths) keys.add(emptyMatcher.match('POST', `${scheme}://${host}${p}`).key);
62
69
  };
63
70
  for (const [host, paths] of Object.entries(MODEL_PATHS)) add('https', host, paths);
64
71
  for (const hp of localLlm) add('http', hp, LOCAL_LLM_PATHS);
65
- return { ...TOOLS, ...models, ...labelTools };
72
+ return keys;
73
+ }
74
+
75
+ /**
76
+ * The tool keys that are model calls (they skip the card floor). A label
77
+ * tool that shares a key wins in `buildTools`, so it is not a model here.
78
+ *
79
+ * @param {Record<string, any>} [labelTools] the label files' gate-file tools
80
+ * @param {string[]} [localLlm] `host:port` pairs of local model servers
81
+ * @returns {Set<string>} model tool keys
82
+ */
83
+ export function modelTools(labelTools = {}, localLlm = []) {
84
+ const keys = modelKeys(localLlm);
85
+ for (const k of Object.keys(labelTools)) keys.delete(k);
86
+ return keys;
66
87
  }
67
88
 
68
89
  /**
package/src/prompt.js ADDED
@@ -0,0 +1,140 @@
1
+ // prompt.js — the same-terminal question for `sbx run`. Turns an ask record
2
+ // into a plain-language question on `output` and reads one answer line from
3
+ // `input`. It never writes answer files itself: it calls `answer(id,
4
+ // decision, reason)`, which the CLI binds to its one answer writer.
5
+ //
6
+ // Stale vs fresh: a line is an answer only if it arrives while a question is
7
+ // open, and it answers THAT question's id. Input that arrives with no
8
+ // question open is dropped (so a `y` typed during h1 never approves h2), and
9
+ // once a hold is decided elsewhere nothing is written for it.
10
+ import { safe } from './runtime.js';
11
+
12
+ const BODY_CHARS = 200;
13
+ const EOL = /\r\n|\r|\n/;
14
+ const YES = new Set(['y', 'yes']);
15
+
16
+ // Plain ANSI. Escapes are added only around text that already went through
17
+ // `safe()`, which strips every escape from agent bytes; never paint raw text.
18
+ export const ANSI = { bold: '\x1b[1m', dim: '\x1b[2m', red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', cyan: '\x1b[36m', unbold: '\x1b[22m', reset: '\x1b[0m' };
19
+
20
+ /**
21
+ * Wrap already-sanitized text in escapes when `on`; plain text otherwise.
22
+ *
23
+ * @param {boolean} on whether color is enabled
24
+ * @param {string} codes one or more ANSI.* escapes
25
+ * @param {string} text sanitized text
26
+ * @returns {string} the painted text
27
+ */
28
+ export const paint = (on, codes, text) => (on ? `${codes}${text}${ANSI.reset}` : text);
29
+
30
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
31
+
32
+ /**
33
+ * Plain-language lines for one ask record. Every agent-controlled byte goes
34
+ * through `safe()`.
35
+ *
36
+ * @param {AskRecord} ask the parked request
37
+ * @param {number} [now] clock for the countdown, injectable
38
+ * @param {boolean} [color] paint with ANSI escapes (off by default)
39
+ * @returns {string[]} the question, one string per line
40
+ */
41
+ export function questionLines(ask, now = Date.now(), color = false) {
42
+ const { bold, dim, red, green, yellow, cyan, unbold } = ANSI;
43
+ const method = safe(ask.method).toUpperCase();
44
+ let host;
45
+ try { host = safe(new URL(ask.url).host); } catch { host = safe(ask.url); }
46
+ const verb = method === 'POST' ? 'SEND data to'
47
+ : method === 'PUT' || method === 'PATCH' ? 'CHANGE data on'
48
+ : method === 'DELETE' ? 'DELETE data on'
49
+ : `make a ${method} request to`;
50
+ const rule = safe(ask.rule);
51
+ const why = rule === 'flags.cardLike' ? 'it contains what looks like a card number'
52
+ : rule === 'flags.paymentPath' ? 'the address looks like a payment'
53
+ : ask.letter === 'w' ? 'a change (reversible: the vendor says it can be undone)'
54
+ : ask.letter === 'x' ? "a change barebox can't undo"
55
+ : rule;
56
+ const left = ask.expiresAt ? Math.max(0, Math.round((Date.parse(ask.expiresAt) - now) / 1000)) : null;
57
+ const name = safe(ask.agent) || 'agent';
58
+ const head = color
59
+ ? paint(true, yellow, `⏸ ${bold}${name}${unbold} wants to ${verb} ${host}`)
60
+ : `⏸ ${name} wants to ${verb} ${host}`;
61
+ const lines = [
62
+ head,
63
+ ` ${paint(color, bold, 'Why:')} ${why}`,
64
+ ` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${safe(ask.url)}`)}`,
65
+ ];
66
+ const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);
67
+ if (body) lines.push(` ${paint(color, bold, 'Data:')} ${paint(color, dim, body)}`);
68
+ const tail = `(hold ${safe(ask.id)})${left === null || Number.isNaN(left) ? '' : ` — no answer in ${left} s means No`}`;
69
+ lines.push(` ${paint(color, bold, 'Allow? [y/N]')} ${paint(color, dim, tail)}`);
70
+ return lines;
71
+ }
72
+
73
+ /**
74
+ * The terminal prompt. One question open at a time. `ask()` opens a question
75
+ * and returns true, or returns false when one is already open (or the prompt
76
+ * is closed) so the caller prints the plain `ask` line instead; `decided()`
77
+ * closes the question when the hold ended some other way, `close()` releases
78
+ * `input`.
79
+ *
80
+ * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
81
+ * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
82
+ */
83
+ export function createTerminalPrompt({ input, output, answer, color = false }) {
84
+ /** @type {AskRecord|null} */
85
+ let open = null;
86
+ let buf = '';
87
+ let closed = false;
88
+ const say = (/** @type {string} */ s) => { output.write(`${s}\n`); };
89
+
90
+ const onLine = (/** @type {string} */ line) => {
91
+ if (!open) return; // unreachable at runtime (onData checks); narrows the type for tsc
92
+ const { id } = open;
93
+ open = null; // closed before the write: one answer per question
94
+ const yes = YES.has(line.trim().toLowerCase());
95
+ try {
96
+ const written = answer(id, yes ? 'allow' : 'deny', yes ? undefined : 'denied at the terminal') !== false;
97
+ say(!written ? 'answered elsewhere'
98
+ : yes ? paint(color, ANSI.green + ANSI.bold, '✓ allowed') : paint(color, ANSI.red + ANSI.bold, '✗ denied'));
99
+ } catch {
100
+ // The hold ended (or the runtime went) before this write; the run goes on.
101
+ }
102
+ };
103
+
104
+ const onData = (/** @type {string|Buffer} */ chunk) => {
105
+ if (!open) return;
106
+ buf += String(chunk);
107
+ for (let m = EOL.exec(buf); m && open; m = EOL.exec(buf)) {
108
+ const line = buf.slice(0, m.index);
109
+ buf = buf.slice(m.index + m[0].length);
110
+ onLine(line);
111
+ }
112
+ };
113
+
114
+ input.setEncoding?.('utf8');
115
+ input.on('data', onData);
116
+
117
+ return {
118
+ ask(ask) {
119
+ if (closed || open) return false;
120
+ open = ask;
121
+ buf = ''; // a half-typed line from before the question is stale
122
+ for (const l of questionLines(open, Date.now(), color)) say(l);
123
+ return true;
124
+ },
125
+ decided(e) {
126
+ if (open?.id !== e.id) return;
127
+ open = null; // closed before anything else: no answer can follow
128
+ const why = safe(e.reason);
129
+ say(why === 'hold timeout' ? paint(color, ANSI.red, `timed out: ${safe(e.decision)}`)
130
+ : why === 'client gone' || why === 'proxy closing' ? paint(color, ANSI.red, `agent gone: ${safe(e.decision)}`)
131
+ : `answered elsewhere: ${safe(e.decision)}${why ? ` (${why})` : ''}`);
132
+ },
133
+ close() {
134
+ closed = true;
135
+ open = null;
136
+ input.removeListener('data', onData);
137
+ input.pause();
138
+ },
139
+ };
140
+ }
package/src/proxy.js CHANGED
@@ -21,7 +21,7 @@ import { ensureCA, certFor, HOST_RE } from './certs.js';
21
21
  import { createCardScanner } from './cardscan.js';
22
22
  import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from './holds.js';
23
23
  import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
24
- import { paymentPath, toolFor, buildTools, emptyMatcher } from './policy.js';
24
+ import { paymentPath, toolFor, buildTools, modelTools, emptyMatcher } from './policy.js';
25
25
  import { checkUpstream } from './wall.js';
26
26
  import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
27
27
  import { Gate } from 'bareguard';
@@ -37,6 +37,8 @@ const WORK_BODY_LIMIT = 65536;
37
37
  // Small teams: one proxy serves at most this many agents (the TCP door's
38
38
  // 'tcp' agent is not counted); more agents means another proxy.
39
39
  const MAX_AGENTS = 40;
40
+ // Agents that browse many hosts must not grow the proxy without limit: one TLS context per host, at most this many.
41
+ const MAX_MITM_CONTEXTS = 256;
40
42
  const EMPTY = Buffer.alloc(0);
41
43
  const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
42
44
  'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
@@ -137,6 +139,7 @@ export function createProxy(opts) {
137
139
  // One tools table and one matcher per runtime, shared by every gate.
138
140
  const matcher = labels?.matcher ?? emptyMatcher;
139
141
  const tools = buildTools(labels?.tools, [...allowLocal]);
142
+ const models = modelTools(labels?.tools, [...allowLocal]);
140
143
  if (!logFile) throw new Error('createProxy: logFile is required');
141
144
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
142
145
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -251,6 +254,10 @@ export function createProxy(opts) {
251
254
  /** @type {Set<import('node:http').ClientRequest>} */
252
255
  const upstreams = new Set();
253
256
  const agentServers = new Map();
257
+ // host -> the MITM SecureContext, built once from the minted cert. Certs are valid 825 days and never
258
+ // re-minted while their files exist, so an entry cannot go stale within this proxy's life.
259
+ /** @type {Map<string, import('node:tls').SecureContext>} */
260
+ const mitmContexts = new Map();
254
261
  /** @type {import('node:net').Server|null} */
255
262
  let tcp = null;
256
263
  let closed = false;
@@ -740,14 +747,16 @@ export function createProxy(opts) {
740
747
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
741
748
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
742
749
  endAsk: null };
750
+ // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
751
+ const tool = toolFor(matcher, tools, method, urlStr);
743
752
  let cardLike = false;
744
753
  if (hasBody) {
745
754
  if (await readWorkBody(ctx)) return;
746
755
  // Past 64 KB the body streams on unscanned (known gap).
747
- if (!ctx.over) cardLike = createCardScanner().push(Buffer.concat(ctx.chunks));
756
+ if (!ctx.over && !models.has(tool)) cardLike = createCardScanner().push(Buffer.concat(ctx.chunks));
748
757
  }
749
758
  // The body never goes in the action: bareguard writes the action to its audit file.
750
- const action = { type: 'net', tool: toolFor(matcher, tools, method, urlStr), url: urlStr, method, agent,
759
+ const action = { type: 'net', tool, url: urlStr, method, agent,
751
760
  cardLike, paymentPath: paymentPath(urlStr), rid };
752
761
  inflightCtx.set(rid, ctx);
753
762
  const g = await gateOf(agent);
@@ -963,16 +972,20 @@ export function createProxy(opts) {
963
972
  }
964
973
  // The cert is minted only for a TLS tunnel. The 200 is already sent, so a
965
974
  // failure cannot answer 502: it is logged as the deny it would have been.
966
- let creds;
967
- try {
968
- creds = await certFor(certDir, host);
969
- } catch (e) {
970
- log({ ev: 'deny', agent: agentOf(sock), code: 502, note: `no cert for ${host}: ${e.message}` });
971
- sock.destroy();
972
- return;
975
+ let secureContext = mitmContexts.get(host);
976
+ if (!secureContext) {
977
+ try {
978
+ secureContext = tls.createSecureContext(await certFor(certDir, host));
979
+ } catch (e) {
980
+ log({ ev: 'deny', agent: agentOf(sock), code: 502, note: `no cert for ${host}: ${e.message}` });
981
+ sock.destroy();
982
+ return;
983
+ }
984
+ if (!mitmContexts.has(host) && mitmContexts.size >= MAX_MITM_CONTEXTS) mitmContexts.delete(mitmContexts.keys().next().value);
985
+ mitmContexts.set(host, secureContext);
973
986
  }
974
987
  if (closed || sock.destroyed) return;
975
- const st = new tls.TLSSocket(sock, { isServer: true, key: creds.key, cert: creds.cert });
988
+ const st = new tls.TLSSocket(sock, { isServer: true, secureContext });
976
989
  st[AGENT] = agent;
977
990
  st[SECURE] = true;
978
991
  clients.add(st);
package/src/runtime.js CHANGED
@@ -89,6 +89,27 @@ export function hostNode(execPath, home, proj) {
89
89
  return { dir, bin, bind: visible ? null : dir, refused: null };
90
90
  }
91
91
 
92
+ /**
93
+ * The host's top-level `/bin`, `/sbin`, `/lib` and `/lib64`, as bwrap args that mirror them
94
+ * inside the sandbox. On a merged-/usr host they are symlinks into `/usr` (`/bin -> usr/bin`),
95
+ * recreated as the same links; a real directory (a non-merged distro) is bound read-only;
96
+ * a missing path is skipped. Without them `#!/bin/sh` scripts and Node's `exec` fail.
97
+ *
98
+ * @param {string} [prefix] prepended to each path when looking at the host (tests point it at a fake root); the inside paths are always `/bin` etc.
99
+ * @returns {{args: string[], bound: string[]}} `args` the bwrap args, to go right after the `/usr` bind; `bound` the real directories bound (they are sandbox roots, so the masks apply under them)
100
+ */
101
+ export function usrLinks(prefix = '') {
102
+ const args = [];
103
+ const bound = [];
104
+ for (const p of ['/bin', '/sbin', '/lib', '/lib64']) {
105
+ let st;
106
+ try { st = fs.lstatSync(prefix + p); } catch { continue; }
107
+ if (st.isSymbolicLink()) args.push('--symlink', fs.readlinkSync(prefix + p), p);
108
+ else if (st.isDirectory()) { args.push('--ro-bind', prefix + p, p); bound.push(p); }
109
+ }
110
+ return { args, bound };
111
+ }
112
+
92
113
  /**
93
114
  * Create a short-lived runtime dir: a short `sbx-` temp dir, keeping unix
94
115
  * socket paths under the ~108-char limit.
@@ -99,6 +120,41 @@ export function createRuntime() {
99
120
  return fs.mkdtempSync(path.join(os.tmpdir(), 'sbx-'));
100
121
  }
101
122
 
123
+ /**
124
+ * The runtime dir of a named sandbox (`sbx run --name <n>`): the name replaces
125
+ * a `SBX_RUNTIME` path for every command. `$XDG_RUNTIME_DIR/barebox/<n>` when
126
+ * that variable names an existing dir you own, else
127
+ * `<tmpdir>/sbx-<uid>/<n>`. The one function that maps a name to a dir.
128
+ *
129
+ * @param {string} name sandbox name (the agent-name rules)
130
+ * @param {NodeJS.ProcessEnv} [env] environment to read `XDG_RUNTIME_DIR` from
131
+ * @param {{ create?: boolean }} [opts] `create`: make the parent and runtime dirs owner-only (0700); off, nothing is touched
132
+ * @returns {string} the runtime dir
133
+ * @throws {Error} on a bad name, a socket path over the 107-byte cap, or a foreign-owned parent
134
+ */
135
+ export function namedRuntime(name, env = process.env, { create = false } = {}) {
136
+ assertAgentName(name);
137
+ const me = /** @type {number} */ (process.getuid?.());
138
+ const xdg = env.XDG_RUNTIME_DIR;
139
+ let usable = false;
140
+ try {
141
+ usable = !!xdg && path.isAbsolute(xdg) && fs.statSync(xdg).isDirectory() && fs.statSync(xdg).uid === me;
142
+ } catch {}
143
+ const parent = usable
144
+ ? path.join(/** @type {string} */ (xdg), 'barebox')
145
+ : path.join(os.tmpdir(), `sbx-${me}`);
146
+ const runtime = path.join(parent, name);
147
+ const sock = path.join(runtime, 'socks', `${name}.sock`);
148
+ if (sock.length > MAX_SOCK_PATH) {
149
+ throw new Error(`sandbox name ${name} makes the socket path too long (${sock.length} > ${MAX_SOCK_PATH}): use a shorter name or a shorter TMPDIR`);
150
+ }
151
+ if (create) {
152
+ ensurePrivateDir(parent);
153
+ ensurePrivateDir(runtime);
154
+ }
155
+ return runtime;
156
+ }
157
+
102
158
  /**
103
159
  * Create a temp dir inside the runtime tree: `mkdtemp` is a runtime-layout
104
160
  * writer, so it lives here, not in `overlay.js`. Used for the merged-view
@@ -278,7 +334,7 @@ export function shellQuote(s) {
278
334
  * Every path in a runtime dir. The one place that names them.
279
335
  *
280
336
  * @param {string} runtime runtime dir
281
- * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
337
+ * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, staleFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
282
338
  */
283
339
  export function runtimePaths(runtime) {
284
340
  const asksDir = path.join(runtime, 'asks');
@@ -290,6 +346,8 @@ export function runtimePaths(runtime) {
290
346
  answersDir,
291
347
  askFile: (id) => path.join(asksDir, `${id}.json`),
292
348
  answerFile: (id) => path.join(answersDir, `${id}.json`),
349
+ // The proxy's note that an answer for `id` arrived after the hold settled; written before the answer is consumed.
350
+ staleFile: (id) => path.join(answersDir, `${id}.stale`),
293
351
  heldDir,
294
352
  // A held request's body, spooled to disk while it waits for a decision.
295
353
  heldFile: (id) => path.join(heldDir, id),
package/types/config.d.ts CHANGED
@@ -34,12 +34,14 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
34
34
  *
35
35
  * @param {object} [flags] values given on the command line
36
36
  * @param {string} [flags.mode] `--mode`
37
+ * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
37
38
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
38
39
  * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
39
40
  * @throws {Error} as {@link loadConfig}
40
41
  */
41
42
  export function resolveConfig(flags?: {
42
43
  mode?: string | undefined;
44
+ hold?: string | undefined;
43
45
  }, env?: NodeJS.ProcessEnv): {
44
46
  mode: string;
45
47
  holdTimeoutSec: number | string;
@@ -10,7 +10,8 @@
10
10
  */
11
11
  export function buildCaBundle(runtime: string, caFile: string): string;
12
12
  /**
13
- * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`,
13
+ * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`
14
+ * (and the host's `/bin`, `/sbin`, `/lib`, `/lib64`, mirrored),
14
15
  * its project and home read-only, the locked drawers masked, no network of
15
16
  * its own, and a single front door: anything sent to `localhost:<proxyPort>`
16
17
  * is carried out through this agent's socket to the proxy. The agent starts
package/types/policy.d.ts CHANGED
@@ -8,6 +8,15 @@
8
8
  * @returns {Record<string, any>} tool name to letter
9
9
  */
10
10
  export function buildTools(labelTools?: Record<string, any>, localLlm?: string[]): Record<string, any>;
11
+ /**
12
+ * The tool keys that are model calls (they skip the card floor). A label
13
+ * tool that shares a key wins in `buildTools`, so it is not a model here.
14
+ *
15
+ * @param {Record<string, any>} [labelTools] the label files' gate-file tools
16
+ * @param {string[]} [localLlm] `host:port` pairs of local model servers
17
+ * @returns {Set<string>} model tool keys
18
+ */
19
+ export function modelTools(labelTools?: Record<string, any>, localLlm?: string[]): Set<string>;
11
20
  /**
12
21
  * The tool name for one request. A spec key (a label file documents it) is
13
22
  * used as is, even if the gate file lacks it (then the gate denies it:
@@ -0,0 +1,58 @@
1
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
2
+ /**
3
+ * Plain-language lines for one ask record. Every agent-controlled byte goes
4
+ * through `safe()`.
5
+ *
6
+ * @param {AskRecord} ask the parked request
7
+ * @param {number} [now] clock for the countdown, injectable
8
+ * @param {boolean} [color] paint with ANSI escapes (off by default)
9
+ * @returns {string[]} the question, one string per line
10
+ */
11
+ export function questionLines(ask: AskRecord, now?: number, color?: boolean): string[];
12
+ /**
13
+ * The terminal prompt. One question open at a time. `ask()` opens a question
14
+ * and returns true, or returns false when one is already open (or the prompt
15
+ * is closed) so the caller prints the plain `ask` line instead; `decided()`
16
+ * closes the question when the hold ended some other way, `close()` releases
17
+ * `input`.
18
+ *
19
+ * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
20
+ * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
21
+ */
22
+ export function createTerminalPrompt({ input, output, answer, color }: {
23
+ input: import("node:stream").Readable;
24
+ output: {
25
+ write: (s: string) => unknown;
26
+ };
27
+ color?: boolean;
28
+ answer: (id: string, decision: "allow" | "deny", reason?: string) => boolean | void;
29
+ }): {
30
+ ask: (ask: AskRecord) => boolean;
31
+ decided: (e: {
32
+ id: string;
33
+ decision: string;
34
+ reason?: string;
35
+ }) => void;
36
+ close: () => void;
37
+ };
38
+ export namespace ANSI {
39
+ let bold: string;
40
+ let dim: string;
41
+ let red: string;
42
+ let green: string;
43
+ let yellow: string;
44
+ let cyan: string;
45
+ let unbold: string;
46
+ let reset: string;
47
+ }
48
+ export function paint(on: boolean, codes: string, text: string): string;
49
+ export type AskRecord = {
50
+ id: string;
51
+ agent?: string;
52
+ method: string;
53
+ url: string;
54
+ rule: string;
55
+ letter: string;
56
+ bodyPreview?: string;
57
+ expiresAt?: string | null;
58
+ };
@@ -41,6 +41,19 @@ export function hostNode(execPath: string, home: string, proj?: string): {
41
41
  bind: string | null;
42
42
  refused: string | null;
43
43
  };
44
+ /**
45
+ * The host's top-level `/bin`, `/sbin`, `/lib` and `/lib64`, as bwrap args that mirror them
46
+ * inside the sandbox. On a merged-/usr host they are symlinks into `/usr` (`/bin -> usr/bin`),
47
+ * recreated as the same links; a real directory (a non-merged distro) is bound read-only;
48
+ * a missing path is skipped. Without them `#!/bin/sh` scripts and Node's `exec` fail.
49
+ *
50
+ * @param {string} [prefix] prepended to each path when looking at the host (tests point it at a fake root); the inside paths are always `/bin` etc.
51
+ * @returns {{args: string[], bound: string[]}} `args` the bwrap args, to go right after the `/usr` bind; `bound` the real directories bound (they are sandbox roots, so the masks apply under them)
52
+ */
53
+ export function usrLinks(prefix?: string): {
54
+ args: string[];
55
+ bound: string[];
56
+ };
44
57
  /**
45
58
  * Create a short-lived runtime dir: a short `sbx-` temp dir, keeping unix
46
59
  * socket paths under the ~108-char limit.
@@ -48,6 +61,21 @@ export function hostNode(execPath: string, home: string, proj?: string): {
48
61
  * @returns {string} the new runtime dir
49
62
  */
50
63
  export function createRuntime(): string;
64
+ /**
65
+ * The runtime dir of a named sandbox (`sbx run --name <n>`): the name replaces
66
+ * a `SBX_RUNTIME` path for every command. `$XDG_RUNTIME_DIR/barebox/<n>` when
67
+ * that variable names an existing dir you own, else
68
+ * `<tmpdir>/sbx-<uid>/<n>`. The one function that maps a name to a dir.
69
+ *
70
+ * @param {string} name sandbox name (the agent-name rules)
71
+ * @param {NodeJS.ProcessEnv} [env] environment to read `XDG_RUNTIME_DIR` from
72
+ * @param {{ create?: boolean }} [opts] `create`: make the parent and runtime dirs owner-only (0700); off, nothing is touched
73
+ * @returns {string} the runtime dir
74
+ * @throws {Error} on a bad name, a socket path over the 107-byte cap, or a foreign-owned parent
75
+ */
76
+ export function namedRuntime(name: string, env?: NodeJS.ProcessEnv, { create }?: {
77
+ create?: boolean;
78
+ }): string;
51
79
  /**
52
80
  * Create a temp dir inside the runtime tree: `mkdtemp` is a runtime-layout
53
81
  * writer, so it lives here, not in `overlay.js`. Used for the merged-view
@@ -127,7 +155,7 @@ export function shellQuote(s: string): string;
127
155
  * Every path in a runtime dir. The one place that names them.
128
156
  *
129
157
  * @param {string} runtime runtime dir
130
- * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
158
+ * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, staleFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
131
159
  */
132
160
  export function runtimePaths(runtime: string): {
133
161
  socket: (agent: string) => string;
@@ -135,6 +163,7 @@ export function runtimePaths(runtime: string): {
135
163
  answersDir: string;
136
164
  askFile: (id: string) => string;
137
165
  answerFile: (id: string) => string;
166
+ staleFile: (id: string) => string;
138
167
  heldDir: string;
139
168
  heldFile: (id: string) => string;
140
169
  certsDir: string;