barebox 0.7.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,25 @@ 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
+
7
26
  ## [0.7.0] - 2026-11-01
8
27
 
9
28
  ### 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
 
@@ -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
 
@@ -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`
@@ -227,8 +245,8 @@ hands the real value to the agent.
227
245
 
228
246
  `<runtime>/gate.jsonl` (`runtimePaths(runtime).audit`; `run()` returns it as
229
247
  `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
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
232
250
  it between runs (no proxy running) to start a new one.
233
251
  - Decisions: bareguard's gate lines carry the action (`method`, `url`, `tool`,
234
252
  `agent`, `rid`) and an `aid`.
@@ -281,7 +299,9 @@ Model endpoints are `r` (free in every mode): `api.anthropic.com`
281
299
  `POST /v1/chat/completions`, `/v1/responses` and `/v1/embeddings`; and on each
282
300
  `localLlm` host:port `POST /api/chat`, `/api/generate`, `/api/embed`,
283
301
  `/v1/chat/completions` and `/v1/completions` (over http or https). Any other path on
284
- those hosts is a normal `POST`.
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.
285
305
 
286
306
  Label folders are hidden inside the sandbox like the config file, so the agent
287
307
  cannot rewrite a letter. `run()` and `createProxy()` take `labels:
@@ -296,11 +316,13 @@ project: the agent sees the real files, every write lands on the upper.
296
316
  Review and press it down from the same runtime:
297
317
 
298
318
  ```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
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
302
322
  ```
303
323
 
324
+ (Without `--name`: `SBX_RUNTIME=/tmp/sbx npx sbx diff [--agent <name>]`, same for the others.)
325
+
304
326
  A path the project changed after the run started is a conflict: commit
305
327
  refuses all of it unless `--skip-conflicts`. `node_modules` is invisible to
306
328
  the layer (extend with `SBX_OVERLAY_IGNORE=a,b`). Commit strips setuid/setgid
@@ -319,12 +341,12 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
319
341
  `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
320
342
  verification. Only `ca.pem` enters the sandbox, never the key.
321
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.
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.
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.
323
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`.
324
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.
325
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.
326
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.
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).
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).
328
350
  - `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
329
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.
330
352
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.7.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/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, hostNode, 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,7 +229,11 @@ 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());
189
237
  const node = hostNode(process.execPath, process.env.HOME || '/root', process.cwd());
190
238
  if (node.refused) err(`barebox: not exposing Node at ${node.dir} (${node.refused}); the sandbox uses /usr/bin/node if present`);
191
239
  // Agent-controlled bytes, sanitized before they reach a terminal or a JSON consumer.
@@ -194,7 +242,17 @@ async function run(args) {
194
242
  for (const k of keys) if (c[k] != null) c[k] = safe(c[k]);
195
243
  return c;
196
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;
197
254
  const emitAsk = (h) => {
255
+ if (prompt?.ask(h)) return;
198
256
  const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
199
257
  if (json) out(JSON.stringify({ ev: 'ask', ...c }));
200
258
  else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}`);
@@ -204,7 +262,9 @@ async function run(args) {
204
262
  if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
205
263
  else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
206
264
  };
207
- 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>)`);
208
268
  /** @type {{ exit: number, diff: { path: string }[] } | null} */
209
269
  let result = null;
210
270
  try {
@@ -213,27 +273,33 @@ async function run(args) {
213
273
  .map((s) => s.trim()).filter(Boolean);
214
274
  result = await sandboxRun({
215
275
  runtime, proj: process.cwd(), command, mode, timeoutMs,
276
+ ...(name !== undefined ? { agent: name } : {}),
216
277
  allowLocal: cfg.localLlm, labels, secrets: cfg.secrets, env: cfg.env,
217
278
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
218
279
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
219
280
  overlay,
220
281
  ...(extraIgnore.length ? { overlayIgnore: ['node_modules', ...extraIgnore] } : {}),
221
- 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
+ },
222
286
  // With --json stdout is a pure event stream: agent output goes to
223
287
  // stderr so a parser never trips over it.
224
288
  ...(json ? { stdout: process.stderr, stderr: process.stderr } : {}),
225
289
  });
226
290
  } catch (e) {
227
- 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))}`);
228
293
  process.exitCode = 1;
229
294
  return;
230
295
  }
296
+ prompt?.close();
231
297
  if (json) out(JSON.stringify({ ev: 'done', exit: result.exit }));
232
298
  else out(`done exit ${result.exit}`);
233
299
  if (overlay) {
234
300
  const n = result.diff.length;
235
301
  err(n
236
- ? `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`}`
237
303
  : 'overlay: no changes');
238
304
  }
239
305
  process.exitCode = result.exit;
@@ -373,16 +439,49 @@ async function answerTarget(rest) {
373
439
  return { id, reason: ids.join(' ') || 'denied by user', paths };
374
440
  }
375
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
+
376
475
  /** @param {string[]} rest @returns {Promise<void>} */
377
476
  async function approve(rest) {
378
477
  const { id, paths } = await answerTarget(rest);
379
- writeFileAtomic(paths.answerFile(id), JSON.stringify({ decision: 'allow' }));
478
+ if (!writeAnswer(paths, id, 'allow')) alreadyAnswered(id);
380
479
  out(`approved ${id}`);
381
480
  }
382
481
 
383
482
  /** @param {string[]} rest @returns {Promise<void>} */
384
483
  async function deny(rest) {
385
484
  const { id, reason, paths } = await answerTarget(rest);
386
- writeFileAtomic(paths.answerFile(id), JSON.stringify({ decision: 'deny', reason }));
485
+ if (!writeAnswer(paths, id, 'deny', reason)) alreadyAnswered(id);
387
486
  out(`denied ${id}`);
388
487
  }
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,118 @@
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
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
17
+
18
+ /**
19
+ * Plain-language lines for one ask record. Every agent-controlled byte goes
20
+ * through `safe()`.
21
+ *
22
+ * @param {AskRecord} ask the parked request
23
+ * @param {number} [now] clock for the countdown, injectable
24
+ * @returns {string[]} the question, one string per line
25
+ */
26
+ export function questionLines(ask, now = Date.now()) {
27
+ const method = safe(ask.method).toUpperCase();
28
+ let host;
29
+ try { host = safe(new URL(ask.url).host); } catch { host = safe(ask.url); }
30
+ const verb = method === 'POST' ? 'SEND data to'
31
+ : method === 'PUT' || method === 'PATCH' ? 'CHANGE data on'
32
+ : method === 'DELETE' ? 'DELETE data on'
33
+ : `make a ${method} request to`;
34
+ const rule = safe(ask.rule);
35
+ const why = rule === 'flags.cardLike' ? 'it contains what looks like a card number'
36
+ : rule === 'flags.paymentPath' ? 'the address looks like a payment'
37
+ : ask.letter === 'w' ? 'a change (reversible: the vendor says it can be undone)'
38
+ : ask.letter === 'x' ? "a change barebox can't undo"
39
+ : rule;
40
+ const left = ask.expiresAt ? Math.max(0, Math.round((Date.parse(ask.expiresAt) - now) / 1000)) : null;
41
+ const lines = [
42
+ `⏸ ${safe(ask.agent) || 'agent'} wants to ${verb} ${host}`,
43
+ ` Why: ${why}`,
44
+ ` URL: ${method} ${safe(ask.url)}`,
45
+ ];
46
+ const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);
47
+ if (body) lines.push(` Data: ${body}`);
48
+ lines.push(` Allow? [y/N] (${safe(ask.id)})${left === null || Number.isNaN(left) ? '' : ` — no answer in ${left} s means No`}`);
49
+ return lines;
50
+ }
51
+
52
+ /**
53
+ * The terminal prompt. One question open at a time. `ask()` opens a question
54
+ * and returns true, or returns false when one is already open (or the prompt
55
+ * is closed) so the caller prints the plain `ask` line instead; `decided()`
56
+ * closes the question when the hold ended some other way, `close()` releases
57
+ * `input`.
58
+ *
59
+ * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
60
+ * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
61
+ */
62
+ export function createTerminalPrompt({ input, output, answer }) {
63
+ /** @type {AskRecord|null} */
64
+ let open = null;
65
+ let buf = '';
66
+ let closed = false;
67
+ const say = (/** @type {string} */ s) => { output.write(`${s}\n`); };
68
+
69
+ const onLine = (/** @type {string} */ line) => {
70
+ if (!open) return; // unreachable at runtime (onData checks); narrows the type for tsc
71
+ const { id } = open;
72
+ open = null; // closed before the write: one answer per question
73
+ const yes = YES.has(line.trim().toLowerCase());
74
+ try {
75
+ const written = answer(id, yes ? 'allow' : 'deny', yes ? undefined : 'denied at the terminal') !== false;
76
+ say(!written ? 'answered elsewhere' : yes ? '✓ allowed' : '✗ denied');
77
+ } catch {
78
+ // The hold ended (or the runtime went) before this write; the run goes on.
79
+ }
80
+ };
81
+
82
+ const onData = (/** @type {string|Buffer} */ chunk) => {
83
+ if (!open) return;
84
+ buf += String(chunk);
85
+ for (let m = EOL.exec(buf); m && open; m = EOL.exec(buf)) {
86
+ const line = buf.slice(0, m.index);
87
+ buf = buf.slice(m.index + m[0].length);
88
+ onLine(line);
89
+ }
90
+ };
91
+
92
+ input.setEncoding?.('utf8');
93
+ input.on('data', onData);
94
+
95
+ return {
96
+ ask(ask) {
97
+ if (closed || open) return false;
98
+ open = ask;
99
+ buf = ''; // a half-typed line from before the question is stale
100
+ for (const l of questionLines(open)) say(l);
101
+ return true;
102
+ },
103
+ decided(e) {
104
+ if (open?.id !== e.id) return;
105
+ open = null; // closed before anything else: no answer can follow
106
+ const why = safe(e.reason);
107
+ say(why === 'hold timeout' ? `timed out: ${safe(e.decision)}`
108
+ : why === 'client gone' || why === 'proxy closing' ? `agent gone: ${safe(e.decision)}`
109
+ : `answered elsewhere: ${safe(e.decision)}${why ? ` (${why})` : ''}`);
110
+ },
111
+ close() {
112
+ closed = true;
113
+ open = null;
114
+ input.removeListener('data', onData);
115
+ input.pause();
116
+ },
117
+ };
118
+ }
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
@@ -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,45 @@
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
+ * @returns {string[]} the question, one string per line
9
+ */
10
+ export function questionLines(ask: AskRecord, now?: number): string[];
11
+ /**
12
+ * The terminal prompt. One question open at a time. `ask()` opens a question
13
+ * and returns true, or returns false when one is already open (or the prompt
14
+ * is closed) so the caller prints the plain `ask` line instead; `decided()`
15
+ * closes the question when the hold ended some other way, `close()` releases
16
+ * `input`.
17
+ *
18
+ * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
19
+ * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
20
+ */
21
+ export function createTerminalPrompt({ input, output, answer }: {
22
+ input: import("node:stream").Readable;
23
+ output: {
24
+ write: (s: string) => unknown;
25
+ };
26
+ answer: (id: string, decision: "allow" | "deny", reason?: string) => boolean | void;
27
+ }): {
28
+ ask: (ask: AskRecord) => boolean;
29
+ decided: (e: {
30
+ id: string;
31
+ decision: string;
32
+ reason?: string;
33
+ }) => void;
34
+ close: () => void;
35
+ };
36
+ export type AskRecord = {
37
+ id: string;
38
+ agent?: string;
39
+ method: string;
40
+ url: string;
41
+ rule: string;
42
+ letter: string;
43
+ bodyPreview?: string;
44
+ expiresAt?: string | null;
45
+ };
@@ -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