barebox 0.13.0 → 0.14.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,13 @@ 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.14.0] - 2026-11-30
8
+
9
+ ### Security
10
+
11
+ - A call to a built-in model endpoint (Anthropic, OpenAI) is free only with this run's key: a key header holding a bound secret placeholder, or a key a human allowed in this run. Any other key, or none, is a plain `POST` that asks in `ask` and `auto` (the question shows only the key's last 4 characters), passes in `trust` and keeps the card floor. An allow is remembered by SHA-256 in the proxy's memory for this run only; a deny is not remembered, and parallel calls with one unknown key share one ask (at most 16 waiting per agent, then 429; only a person's answer or the hold timeout denies them, a client that goes lets the next one ask). The question says `no key` or `not this run's` when there is no last 4 to show. A floor question says when the body was read but no recipient, amount or currency field was recognised. `localLlm` endpoints stay free. Key bytes are never logged or written to the audit.
12
+ - A request with an `Upgrade` header (WebSocket, h2c) and a `CONNECT` inside a tunnel are refused at once with `403 denied: upgrade` / `403 denied: connect`, in every mode and for every host, and never resolved or dialed. Before, an upgrade was forwarded as a `GET` and an inner `CONNECT` closed the socket with no reason and no log line. WebSocket is not supported.
13
+
7
14
  ## [0.13.0] - 2026-11-30
8
15
 
9
16
  ### Docs
package/README.md CHANGED
@@ -8,8 +8,8 @@
8
8
  barebox
9
9
  ```
10
10
 
11
- > A lightweight sandbox you spawn per agent, to control what it may do. Reads pass, file writes can be undone, and anything irreversible (pay, send, publish, push) waits for your yes.
12
- > Many sandboxes, one proxy, one gate, one audit file. Up to 40 agents per proxy: for a laptop or a small VPS, not for big swarms.
11
+ > A safe, lightweight sandbox for agents that spawns in under a second. Reads pass, file writes can be undone, and anything that can't be undone (pay, send, publish, push) waits for your yes.
12
+ > For solo devs and small teams: up to 40 sandboxes share one proxy, one gate and one audit file.
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)">
@@ -19,165 +19,95 @@
19
19
 
20
20
  <img src="assets/demo.gif" width="800" alt="A scripted agent books a trip inside barebox: the search goes out free, a payment asks and gets the real key only after a yes, an email is allowed, a second payment is denied and never leaves, an unanswered upload is denied after 8 s, then the report of what barebox decided">
21
21
 
22
- A scripted agent, real barebox (v0.12.0), one unedited take: a free search, a payment allowed (the real key goes in only after the yes), an email allowed, an unexpected second payment denied (403, nothing left), an upload nobody answered denied after 8 s, then the report from barebox's audit log. Record and render it yourself (needs ffmpeg): `bash examples/demo-gif/record.sh && node examples/demo-gif/render.mjs examples/demo-gif/take examples/demo-gif/captions.json assets/demo.gif`.
22
+ ## What you get
23
23
 
24
- With a real model: Meta's muse books a trip, a live unedited run (Nov 3). 31 requests, 23 went out with no question, 8 stopped for a person (3 allowed, 5 denied); the real payment key reached the server once, after a yes. Captioned take: [assets/demo-a.webm](assets/demo-a.webm).
24
+ - **Spawn in 0.7 s,** about 8 MB per sandbox. No root, no daemon, no image: the agent uses your installed tools.
25
+ - **Three modes, one flag:** `ask`, `auto` (default), `trust`.
26
+ - **Your payment and email domains ask in every mode,** `trust` included. List them once in the config file.
27
+ - **Keys the agent never holds:** it gets a placeholder, and the real key goes in only after the gate allows the request.
28
+ - **Up to 40 sandboxes share one proxy,** in about 95-245 MB for all of them.
29
+ - **One config file** (`~/.config/barebox/config.json`) and **one audit file** (`gate.jsonl`).
25
30
 
26
- **Replay it** (Linux, from a clone; needs network, httpbin.org stands in for the real services):
31
+ **[The guide](https://github.com/hamr0/barebox/blob/main/docs/wiki/guide.md)** covers every setting, what is and isn't blocked, how asks work, and all the numbers.
27
32
 
28
- ```
29
- git clone https://github.com/hamr0/barebox && cd barebox && npm install
30
- bash examples/demo-a/run.sh # Demo A scripted: book a trip, all three modes, every cell asserted
31
- bash examples/demo-a/run.sh --driver muse --live --mode auto # the live run above; needs BASETEN_API_KEY, you answer the holds
32
- bash examples/demo-b/run.sh # Demo B: a prompt-injected agent tries 3 exfiltrations in every mode
33
- ```
34
-
35
- ## How it works
33
+ ## Quick start
36
34
 
37
35
  ```
38
- agent (your real node, python, git, claude ...)
39
- |
40
- +-----+-------- bwrap sandbox (unprivileged, one per agent) --------+
41
- | files: your project, read-only + an undo layer (--overlay) |
42
- | locked: ~/.ssh, cloud creds, token files -> empty |
43
- | network: none of its own; 127.0.0.1:3128 -> its unix socket |
44
- +-----+-------------------------------------------------------------+
45
- | one unix socket per agent (the socket is the identity, not a header)
46
- v
47
- ONE proxy, HTTP and HTTPS -> ONE gate (bareguard) -> world
48
- | |
49
- | '-> gate.jsonl, one audit line per decision
50
- '-> held request: asks you in the terminal, forwards or 403
36
+ npm install -g barebox
37
+ sbx run -- claude # auto mode: reads and model calls pass, sends ask
38
+ sbx run --mode ask --overlay -- node agent.js
39
+ sbx diff && sbx commit # keep the file changes, or: sbx rollback
51
40
  ```
52
41
 
53
- - **Walls:** [bubblewrap](https://github.com/containers/bubblewrap), no root, no daemon, no image. The agent uses your installed tools.
54
- - **One proxy for all sandboxes**, plain HTTP and HTTPS. HTTPS is read through a local CA that exists only inside the sandbox, so the gate sees method, URL, headers and body.
55
- - **One gate decides every request** by its letter and the mode (below). It is a simple policy for spawning sandboxed agents on the fly: one flag, no rule files.
56
- - **One audit file**, `<runtime>/gate.jsonl`, one JSON line per decision in [bareguard](https://github.com/hamr0/bareguard)'s shape. It is append-only, so `tail -f` it, pipe it to `jq`, or ship it to your log stack.
57
-
58
- ## r, w, x and the three modes
59
-
60
- Every request gets one letter:
61
-
62
- | Letter | What | How barebox gets the letter |
63
- |---|---|---|
64
- | `r` | reads, changes nothing | `GET`, `HEAD`, and calls to model APIs (Anthropic, OpenAI, a `localLlm`) |
65
- | `w` | a change that can be set back | only where an [rwxmap](https://github.com/hamr0/rwxmap) label for that API says so |
66
- | `x` | can't be undone: send, pay, publish, push, delete | every other `POST`, `PUT`, `PATCH`, `DELETE`; any other method is denied |
67
-
68
- File writes are a separate layer: with `--overlay` every change lands on an undo layer, and at the end you `sbx diff`, `sbx commit` or `sbx rollback`.
42
+ ## Modes
69
43
 
70
- The mode (`sbx run --mode ...`) picks which letters pass without asking:
44
+ | Mode | `r` read<br>GET, HEAD, model calls | `w` reversible<br>where an [rwxmap](https://github.com/hamr0/rwxmap) label says so | `x` can't be undone<br>every other POST, PUT, PATCH, DELETE |
45
+ |---|---|---|---|
46
+ | `ask` | free | asks | asks |
47
+ | `auto` (default) | free | free | asks |
48
+ | `trust` | free | free | free |
71
49
 
72
- | Mode | Passes | Asks |
73
- |---|---|---|
74
- | `ask` | `r` | `w`, `x` |
75
- | `auto` (default) | `r`, `w` | `x` |
76
- | `trust` | `r`, `w`, `x` | nothing |
77
-
78
- **The floor asks in every mode, `trust` included:** a card number (Luhn) in a body of 64 KB or less, or a payment path (`/checkout`, `/payment`, `/orders`, `/purchase`).
79
-
80
- **Your own pay and send domains ask too.** List the payment and email or chat domains you use under `floor` in `~/.config/barebox/config.json`. Any write (a method other than `GET` or `HEAD`) to a listed domain asks in every mode, `trust` included; reads keep their letter and mode. barebox ships **no built-in entries**: it promises only what you list.
50
+ **Asks in every mode, `trust` included:** a card number in the body, a payment path (`/checkout`, `/payment`, `/orders`, `/purchase`), and any write to a domain you listed under `floor`:
81
51
 
82
52
  ```json
83
53
  {
84
54
  "floor": {
85
- "pay": ["api.stripe.com", "*.paypal.com", "*.adyen.com", "*.adyenpayments.com", "connect.squareup.com"],
86
- "send": ["api.sendgrid.com", "api.mailgun.net", "api.postmarkapp.com", "api.resend.com", "hooks.slack.com",
87
- "POST slack.com/api/chat.postMessage",
88
- "POST gmail.googleapis.com/gmail/v1/users/{userId}/messages/send",
89
- "POST api.twilio.com/2010-04-01/Accounts/{sid}/Messages.json"]
55
+ "pay": ["api.stripe.com", "*.paypal.com"],
56
+ "send": ["api.sendgrid.com", "POST slack.com/api/chat.postMessage"]
90
57
  }
91
58
  }
92
59
  ```
93
60
 
94
- An entry is a host, `*.domain` (subdomains only, never the bare domain), or `"METHOD host/path"` for one endpoint on a shared host, so other writes there keep their letter. The question names the recipient, amount and currency found in the body by common field names (`to`, `email`, `amount`, `currency` and a few more), each labelled with where it sits in the body, so a decoy field cannot hide the real one: up to 5 fields of a kind are all listed; more than 5 lists none ("more than 5 fields"), because then barebox cannot tell you which is the real one. An endpoint entry matches the path however it is spelled: upper or lower case, `%XX` for a plain letter, digit or `-._~`, and `;params` on a segment all hit (`%2F` does not). Known limit: a suffix such as `.json` is a different path, so list the suffix you use. `sbx pending` shows the same floor entry and the recipient, amount and currency lines under each held request. When the body cannot be read (over 64 KB, multipart, an encoding barebox does not decode, bad JSON) the question says so and still asks; nothing is denied for that. A listed domain can't be loosened by a mode.
95
-
96
- ## What it blocks by default
97
-
98
- | Blocked | How |
99
- |---|---|
100
- | Keys and credentials: `~/.ssh`, `~/.gnupg`, `~/.password-store`, `~/secrets`, keyrings, browser profiles, `~/.aws`, `~/.azure`, `~/.config/gcloud`, `~/.kube`, `~/.docker`, `~/.config/gh`, `~/.config/op`, `~/.netrc`, `~/.npmrc`, `~/.pypirc`, `~/.git-credentials`, `~/.cargo/credentials.toml` | masked inside the sandbox: they read as empty |
101
- | Your environment | cleared; only a short safe list (`TERM`, `LANG`, `LC_*`, `TZ`, `USER`, `SHELL`, ...) and names you list in `env.pass` get in (names like `*_TOKEN`, `*_KEY` are refused; set a harmless one such as `XKB_KEYMAP` with `env.set`) |
102
- | Any network but the proxy | the sandbox has no network of its own. `--noproxy`, unset proxy env, a direct IP or a raw socket fail closed; UDP and non-HTTP traffic are denied |
103
- | Private and local addresses | the proxy checks every resolved IP (IPv6 spellings of IPv4 included) and refuses private ranges and names that don't resolve |
104
- | Real API keys | the agent holds a per-run placeholder; the proxy swaps in the real key after the gate allows the request, over HTTPS, and only for the key's bound hosts (see below) |
105
- | Answering its own questions | the ask and answer files live outside the sandbox and are masked from it |
106
-
107
- ## What you see
108
-
109
- A held request asks in the terminal where you ran `sbx run` (`y` allows, anything else denies):
61
+ Then a payment stops like this, with the recipient, amount and currency pulled from the body:
110
62
 
111
63
  ```
112
- ⏸ auto-agent-1 wants to SEND data to httpbin.org
113
- Why: the address looks like a payment
114
- URL: POST https://httpbin.org/anything/v1/payment_intents
115
- Data: {"amount":35000,"currency":"usd"}
64
+ ⏸ agent wants to SEND data to api.stripe.com
65
+ Why: a payment to a domain you listed (api.stripe.com)
66
+ URL: POST https://api.stripe.com/v1/payment_intents
67
+ To: customer.email=buyer@example.com
68
+ Amount: amount=35000
69
+ Currency: currency=usd
116
70
  Allow? [y/N] (hold h1)
117
- y
118
- → sent ✓ allowed
119
71
  ```
120
72
 
121
- Name the sandbox (`--name docs-bot`) and a second terminal can answer too: `sbx pending --name docs-bot`, `sbx approve h1 --name docs-bot`. A hold waits until you answer at a terminal; without one (cron, CI, `--json`, stdin or stderr redirected) it is denied after 3 minutes. `--hold <seconds|never>` or `holdTimeoutSec` changes either, and a timeout is a deny. One held request per agent at a time; up to 16 more wait in line.
73
+ `y` allows it, anything else denies it (403, nothing leaves). An answer counts for that one request; nothing is saved. One held request per agent at a time; up to 16 more wait in line, plus up to 16 model calls waiting behind one new-key question; past either, `429`.
122
74
 
123
- Demo A's end-of-run summary (from the recorded take):
75
+ ## Blocked by default
124
76
 
125
- ```
126
- -- what barebox decided:
127
- total 31 requests to the network: 23 free, 8 held for you (3 allowed, 5 denied) (model calls included)
128
- search 3 free
129
- pay 1 held: 1 allowed
130
- POST /anything/hotels/checkout 1 held: 0 allowed, 1 denied
131
- DELETE /anything/bookings/old-123 1 held: 0 allowed, 1 denied
132
- model calls 18 free (labelled read-only)
133
- key swaps 1 (the real test key went into the header only after your yes; the agent only ever had the placeholder)
134
- ```
135
-
136
- An audit line from `gate.jsonl` (a POST held, then denied on timeout):
77
+ - **Credential files** (`~/.ssh`, `~/.aws`, `~/.kube`, `~/.docker`, `~/.config/gh`, `~/.netrc`, `~/.npmrc`, keyrings, browser profiles, ...) read as empty.
78
+ - **Your environment** is cleared; only names you pass get in, and names like `*_TOKEN` and `*_KEY` are refused.
79
+ - **Any network but the proxy:** a direct IP, a raw socket or `--noproxy` fails. UDP is denied.
80
+ - **Private and local addresses,** checked after DNS on every resolved IP.
81
+ - **Real API keys,** swapped in only after a yes, only over HTTPS, only to the key's own hosts.
82
+ - **The agent answering its own asks,** and reading the config file.
137
83
 
138
- ```json
139
- {"ts":"2026-11-03T21:41:04.869Z","seq":8,"aid":"1a541f36","phase":"gate","action":{"type":"net","tool":"http.POST","url":"https://httpbin.org/post","method":"POST","agent":"rdme","rid":"r2"},"decision":"deny","rule":"rwx.ask","reason":"hold timeout"}
140
- ```
84
+ ## Not blocked yet
141
85
 
142
- ## Keys the agent never holds
143
-
144
- ```json
145
- {
146
- "secrets": {
147
- "STRIPE_API_KEY": { "fromEnv": "REAL_STRIPE_KEY", "hosts": ["api.stripe.com"] }
148
- }
149
- }
150
- ```
86
+ barebox is a guardrail against mistakes and prompt-injected agents, not a VM. Known gaps (details in [the guide](https://github.com/hamr0/barebox/blob/main/docs/wiki/guide.md#what-it-does-not-block)):
151
87
 
152
- In `~/.config/barebox/config.json`. Inside, `$STRIPE_API_KEY` is a random placeholder, new each run, and the agent uses it like the key (`curl -H "Authorization: Bearer $STRIPE_API_KEY" ...`). The real value goes into the request header only after the gate allows it, only to `api.stripe.com`, only over HTTPS. Anywhere else the placeholder is refused (`403 denied: secret.host`, `secret.scheme`, `secret.url`).
88
+ - data in a `GET` URL, and data hidden in a hostname (DNS resolves before the gate);
89
+ - bodies over 64 KB are not scanned for card numbers;
90
+ - `~/.claude` stays readable.
153
91
 
154
92
  ## Numbers
155
93
 
156
- Measured, not estimated: Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22. Method and raw runs: [findings](docs/logs/findings.md).
157
-
158
- | | barebox | [srt](https://github.com/anthropic-experimental/sandbox-runtime) 0.0.81 |
159
- |---|---|---|
160
- | Memory per sandbox | **7.8 MB** mean, 8.0 MB max | ~100 MB (a proxy per sandbox) |
161
- | Shared proxy, normal use (HTTPS, 10-40 agents) | **95-160 MB** | one per sandbox |
162
- | Shared proxy, worst case (HTTPS, every agent with a held request, a full line and a full body slot) | **117 / 133-151 / 177-207 / 207-241 MB** at 10 / 20 / 30 / 40 agents | |
163
- | Total, worst case (proxy + walls) | ~195-200 MB at 10, ~295-310 MB at 20, ~525-560 MB at 40 agents | ~1 GB at 10, ~2 GB at 20 |
164
- | Start to exit, `sbx run -- true` | **0.70 s** median (0.80 s with `--overlay`; bwrap alone 6 ms) | 1.87-2.05 s |
165
- | One real agent (Claude Code) | 248 MB inside vs 249 MB bare; barebox adds ~91 MB for the first agent, ~11 MB per further one | not measured |
166
- | Agents per proxy | **40 max**, enforced (the 41st is refused; run another proxy) | |
167
- | Demo B, 3 exfiltration attempts | **3 of 3 blocked** in every mode | |
94
+ Measured on Fedora with Node 22 ([all numbers](https://github.com/hamr0/barebox/blob/main/docs/wiki/guide.md#numbers)):
168
95
 
169
- Ranges run from a quiet machine to a busy one.
96
+ - **0.70 s** start to exit, vs 1.87-2.05 s for [srt](https://github.com/anthropic-experimental/sandbox-runtime);
97
+ - **~8 MB** per sandbox, vs ~100 MB for srt (a proxy each);
98
+ - **95-160 MB** for the shared proxy in normal use at 10-40 agents, and at most 245 MB in the worst case;
99
+ - **40 agents** per proxy, enforced;
100
+ - **3 of 3** exfiltration attempts blocked in every mode (Demo B).
170
101
 
171
- ## Known limits
102
+ ## Demos
172
103
 
173
- barebox is a guardrail against mistakes and prompt-injected agents, not a security boundary against a determined attacker: the kernel is shared, so use a VM for that. Known gaps, each with a planned fix in [the PRD](docs/product/agent-sandbox-prd.md) (section 10):
104
+ ```
105
+ git clone https://github.com/hamr0/barebox && cd barebox && npm install
106
+ bash examples/demo-a/run.sh # book a trip, all three modes, every cell asserted
107
+ bash examples/demo-b/run.sh # a prompt-injected agent tries 3 exfiltrations in every mode
108
+ ```
174
109
 
175
- - Data in a `GET` URL goes out free: reads are `r`.
176
- - The proxy resolves DNS before the gate decides, so data hidden in a hostname can leak.
177
- - Model API calls pass with any key, an attacker's included.
178
- - Bodies over 64 KB are not scanned for card numbers. `gzip` and `deflate` bodies are decoded for the scan (up to 64 KB of output); `br`, `zstd` and bodies that fail to decode are scanned as sent, so a card inside their compressed bytes is not found.
179
- - `~/.claude` stays readable: Claude Code's tokens refresh themselves.
180
- - Writes over local sockets (a Postgres, a Docker daemon) are not on the undo layer.
110
+ The GIF above is a scripted agent in real barebox, one unedited take. In a live run with a real model (Meta's muse), 31 requests went out: 23 with no question, and 8 stopped for a person (3 allowed, 5 denied). The real payment key reached the server once, after a yes ([video](assets/demo-a.webm)).
181
111
 
182
112
  ## Install
183
113
 
@@ -71,7 +71,11 @@ after the run), and every other command takes `--name docs-bot` instead of
71
71
 
72
72
  A second terminal can answer at the same time through the file checkpoint
73
73
  (`<runtime>/asks` + `<runtime>/answers`); the first answer wins and the
74
- prompt prints `✓ answered elsewhere (allowed)` or `✗ answered elsewhere (<reason>)` when the proxy decides. A write that fails prints `✗ not sent (<code>), try again:` with the same question, and the next line typed retries; the hold also stays open for another terminal or its deadline:
74
+ prompt prints `✓ answered elsewhere (allowed)` or
75
+ `✗ answered elsewhere (<reason>)` when the proxy decides. A write that fails
76
+ prints `✗ not sent (<code>), try again:` with the same question, and the next
77
+ line typed retries; the hold also stays open for another terminal or its
78
+ deadline:
75
79
 
76
80
  ```bash
77
81
  npx sbx pending --name docs-bot
@@ -163,7 +167,10 @@ and `sbx approve|deny` work as above, and the ask carries the gate's `rule`
163
167
  (`rwx.ask`, `flags.cardLike`, `flags.paymentPath`) and `letter`. A request
164
168
  with a body of 64 KB or less is read in the agent's working slot before the
165
169
  gate decides. Denials read `403 denied: <rule>[: reason]` (a human or timeout
166
- denial reads `denied: <reason>`).
170
+ denial reads `denied: <reason>`). Two refusals never reach the gate, in every mode and for every host, model hosts
171
+ included: a request with an `Upgrade` header (WebSocket, h2c) is answered `403 denied: upgrade`, and a `CONNECT` inside
172
+ a tunnel `403 denied: connect`. Nothing is resolved, gated or dialed; each leaves one `deny` line in the proxy's own
173
+ log with the agent and target (no headers).
167
174
 
168
175
  `createProxy` takes `gateFor(agent, { humanChannel, tools })`, called once per agent,
169
176
  returning a bareguard `Gate` or any object with `async check(action)` that
@@ -179,6 +186,9 @@ still inside a `check()`.
179
186
  `localLlm` (config key; `allowLocal` on `run()` and `createProxy()`) is an
180
187
  array of `"host:port"` strings. Only those exact pairs pass the wall's
181
188
  private/loopback check, never link-local (cloud metadata).
189
+ An entry names no scheme and drops a default port, so `localhost:80` also
190
+ matches an https server on `localhost` (port 443), and `127.0.0.1:443` over
191
+ plain http is not matched (it asks as a plain POST); use a non-default port.
182
192
 
183
193
  ## Keys the agent never holds
184
194
 
@@ -311,6 +321,14 @@ those hosts is a normal `POST`. A host written with a trailing dot
311
321
  `paymentPath` mark still applies): a model call carries the whole conversation,
312
322
  and a card number in it must not kill the agent.
313
323
 
324
+ A call to a built-in model endpoint (Anthropic, OpenAI) is a model call only with this run's key:
325
+ a key header (`x-api-key`, or `Authorization` without `Bearer `) that holds a bound secret placeholder, or a key
326
+ a human already allowed in this run. Any other key, or none, makes it a plain `http.POST` (`x`): it asks in `ask`
327
+ and `auto`, passes in `trust`, and the card floor applies. The ask shows only the key's last 4 characters; an allow
328
+ remembers the key's SHA-256 in the proxy's memory for this run (nothing is stored, a deny is not remembered, and
329
+ parallel calls with one unknown key share one ask: they wait behind it, at most 16 waiting per agent, past that 429 `hold queue full`; only a person's answer or the hold timeout denies them, a client that goes or a full hold line lets the next one ask). With no key the question says `a model call with no key`; with a key under 8 characters it shows no last 4. The audit action carries `modelKey: "other"`, never key bytes.
330
+ `localLlm` endpoints are always model calls, with no key check.
331
+
314
332
  Label folders are hidden inside the sandbox like the config file, so the agent
315
333
  cannot rewrite a letter. `run()` and `createProxy()` take `labels:
316
334
  { matcher, tools }` (what `loadLabels` returns); omitted means no labels and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.13.0",
3
+ "version": "0.14.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
@@ -38,8 +38,8 @@ import { resolveConfig } from './config.js';
38
38
  import { loadLabels } from './labels.js';
39
39
  import { MODES } from './policy.js';
40
40
  import { run as sandboxRun } from './run.js';
41
- import { createTerminalPrompt, paint, ANSI, effectLines, floorTail } from './prompt.js';
42
- import { DEFAULT_POLL_MS } from './holds.js';
41
+ import { createTerminalPrompt, paint, ANSI, effectLines, floorTail, keyTail } from './prompt.js';
42
+ import { DEFAULT_POLL_MS, writeTmpFile } from './holds.js';
43
43
  import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
44
44
  import { assertAgentName, createRuntime, namedRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
45
45
 
@@ -271,7 +271,7 @@ async function run(args) {
271
271
  if (prompt?.ask(h)) { prompted.add(h.id); return; }
272
272
  const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
273
273
  if (json) out(JSON.stringify({ ev: 'ask', ...c }));
274
- else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}${floorTail(h)}`);
274
+ else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}${floorTail(h)}${keyTail(h)}`);
275
275
  };
276
276
  const emitDecided = (e) => {
277
277
  if (!json && prompted.delete(e.id)) return;
@@ -426,7 +426,7 @@ async function pending(rest) {
426
426
  // Agent-controlled bytes (URL, rule, body preview): sanitized before
427
427
  // they reach the approver's terminal (see `safe`).
428
428
  const body = safe(h.bodyPreview).replace(/\s+/g, ' ').slice(0, 200);
429
- out(`${safe(h.id)} ${safe(h.agent)} ${safe(h.method)} ${safe(h.url)} (${waiting}s) rule=${safe(h.rule)}${floorTail(h)} body=${body}`);
429
+ out(`${safe(h.id)} ${safe(h.agent)} ${safe(h.method)} ${safe(h.url)} (${waiting}s) rule=${safe(h.rule)}${floorTail(h)}${keyTail(h)} body=${body}`);
430
430
  for (const line of effectLines(h.effect, false)) out(line);
431
431
  }
432
432
  process.exit(0);
@@ -474,9 +474,7 @@ async function answerTarget(rest) {
474
474
  */
475
475
  function writeAnswer(paths, id, decision, reason) {
476
476
  const final = paths.answerFile(id);
477
- fs.mkdirSync(path.dirname(final), { recursive: true });
478
- const tmp = `${final}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
479
- fs.writeFileSync(tmp, JSON.stringify(decision === 'allow' ? { decision } : { decision, reason }), { mode: 0o600 });
477
+ const tmp = writeTmpFile(final, JSON.stringify(decision === 'allow' ? { decision } : { decision, reason }));
480
478
  try {
481
479
  fs.linkSync(tmp, final);
482
480
  return true;
package/src/holds.js CHANGED
@@ -119,6 +119,8 @@ const MAX_WAITING_PER_AGENT = 16;
119
119
  * @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
120
120
  * @property {{ kind: 'pay'|'send'|string, entry: string }} [floor] present when the request hit a domain the user listed in config `floor` (kind: which list, entry: the matching entry)
121
121
  * @property {import('./effect.js').Effect} [effect] present on a floor request with a body: the recipient, amount and currency fields found in it (values masked for card numbers), or why it was not read
122
+ * @property {string} [keyLast4] present on a model call whose key is not this run's: the key's last 4 characters (never more)
123
+ * @property {'none'|'other'} [modelKey] present on a model call whose key is not this run's: 'none' (no key header) or 'other' (a key, possibly too short for a last 4)
122
124
  * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
123
125
  * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
124
126
  */
@@ -130,20 +132,32 @@ const MAX_WAITING_PER_AGENT = 16;
130
132
  */
131
133
 
132
134
  /**
133
- * Atomic write: tmp file + rename, so readers never see a partial payload.
135
+ * Write `text` to a fresh 0600 temp file next to `file` (parent made on demand).
136
+ * The caller renames or links it into place.
134
137
  *
135
- * @param {string} file destination path
138
+ * @param {string} file destination path the temp file sits beside
136
139
  * @param {string} text content
137
- * @returns {void}
140
+ * @returns {string} path of the temp file
138
141
  */
139
- export function writeFileAtomic(file, text) {
142
+ export function writeTmpFile(file, text) {
140
143
  fs.mkdirSync(path.dirname(file), { recursive: true });
141
144
  const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
142
145
  // 0600, not the 0644 default: asks carry the audit trail and unredacted
143
146
  // body previews, and answers carry the decision. (Umask can only remove
144
147
  // bits from 0600, never add group/other access.)
145
148
  fs.writeFileSync(tmp, text, { mode: 0o600 });
146
- fs.renameSync(tmp, file);
149
+ return tmp;
150
+ }
151
+
152
+ /**
153
+ * Atomic write: tmp file + rename, so readers never see a partial payload.
154
+ *
155
+ * @param {string} file destination path
156
+ * @param {string} text content
157
+ * @returns {void}
158
+ */
159
+ export function writeFileAtomic(file, text) {
160
+ fs.renameSync(writeTmpFile(file, text), file);
147
161
  }
148
162
 
149
163
  let consumeN = 0;
@@ -236,8 +250,8 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
236
250
  * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
237
251
  * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
238
252
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
239
- * @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
240
- * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
253
+ * @param {(entry: object, reason: string, answered: boolean) => void} opts.onDeny refuse the parked request; `answered`: a person's answer or the hold timeout ended it (not a cancel, a close or a channel failure)
254
+ * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, wait: (agent: string) => (() => void)|null, pending: () => HeldRequest[], close: () => void }} queue handle
241
255
  */
242
256
  export function createHolds({ log, timeoutMs = 120000,
243
257
  maxBody = DEFAULT_HOLD_MAX_BODY, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
@@ -309,7 +323,9 @@ export function createHolds({ log, timeoutMs = 120000,
309
323
  * @type {Map<string, { holder: object|null, line: Array<object> }>}
310
324
  */
311
325
  const slots = new Map();
312
- /** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }>} */
326
+ /** Requests waiting behind another request's open model-key ask, by agent. @type {Map<string, number>} */
327
+ const waits = new Map();
328
+ /** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }>} */
313
329
  const handleState = new WeakMap();
314
330
 
315
331
  /**
@@ -337,7 +353,7 @@ export function createHolds({ log, timeoutMs = 120000,
337
353
  if (!s.holder && s.line.length === 0) slots.delete(agent);
338
354
  }
339
355
  }
340
- st.onExpire(reason);
356
+ st.onExpire(reason, true);
341
357
  }
342
358
 
343
359
  /**
@@ -387,6 +403,8 @@ export function createHolds({ log, timeoutMs = 120000,
387
403
  truncated: entry.bodyBytes > ASK_BODY_LIMIT,
388
404
  ...(entry.floor ? { floor: entry.floor } : {}),
389
405
  ...(entry.effect ? { effect: entry.effect } : {}),
406
+ ...(entry.keyLast4 ? { keyLast4: entry.keyLast4 } : {}),
407
+ ...(entry.modelKey ? { modelKey: entry.modelKey } : {}),
390
408
  waitingSec: 0,
391
409
  // ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
392
410
  expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
@@ -412,7 +430,7 @@ export function createHolds({ log, timeoutMs = 120000,
412
430
  try { fs.unlinkSync(paths.heldFile(id)); } catch {}
413
431
  }
414
432
 
415
- function settle(id, approved, reason) {
433
+ function settle(id, approved, reason, answered = false) {
416
434
  const h = queue.get(id);
417
435
  if (!h) return `unknown ${id}`;
418
436
  queue.delete(id);
@@ -426,7 +444,7 @@ export function createHolds({ log, timeoutMs = 120000,
426
444
  } else {
427
445
  dropBody(id);
428
446
  log({ ev: 'decide', id, agent: h.agent, decision, reason });
429
- onDeny(h, reason);
447
+ onDeny(h, reason, answered);
430
448
  }
431
449
  onEvent?.({ type: 'decided', id, decision, reason: reason || undefined });
432
450
  return approved ? `approved ${id}` : `denied ${id}`;
@@ -460,15 +478,17 @@ export function createHolds({ log, timeoutMs = 120000,
460
478
  if (!useFiles) {
461
479
  /** @type {{ decision?: unknown, reason?: unknown } | null} */
462
480
  let raw = null;
481
+ let failed = false;
463
482
  try {
464
483
  raw = await onAsk(ask);
465
484
  } catch (e) {
485
+ failed = true;
466
486
  const msg = e instanceof Error ? e.message : String(e);
467
487
  raw = { decision: 'deny', reason: `onAsk failed: ${msg}` };
468
488
  }
469
489
  const norm = normalizeDecision(raw);
470
490
  if (norm && norm.decision === 'allow') settle(entry.id, true, '');
471
- else settle(entry.id, false, norm?.reason ?? 'denied');
491
+ else settle(entry.id, false, norm?.reason ?? 'denied', !failed && norm !== null);
472
492
  }
473
493
  }
474
494
 
@@ -507,7 +527,7 @@ export function createHolds({ log, timeoutMs = 120000,
507
527
  log({ ev: 'stale-answer', id, note: 'unknown or already-settled id; ignored' });
508
528
  continue;
509
529
  }
510
- settle(id, norm.decision === 'allow', norm.reason ?? '');
530
+ settle(id, norm.decision === 'allow', norm.reason ?? '', true);
511
531
  }
512
532
  }
513
533
 
@@ -525,7 +545,7 @@ export function createHolds({ log, timeoutMs = 120000,
525
545
  * parks nothing and returns `null`. Without `slot`, parks exactly as
526
546
  * before, without limit.
527
547
  *
528
- * The entry also carries `floor` and `effect` for a floor request (ask file only).
548
+ * The entry also carries `floor` and `effect` for a floor request, and `keyLast4` / `modelKey` for a model call with another key (ask file only).
529
549
  * It carries the masked `preview` and the full `bodyBytes`, never
530
550
  * the body itself (the proxy spooled it to `heldFile(id)`). `finish` is
531
551
  * the proxy's resolver for the request's pending ask: the queue never
@@ -534,7 +554,7 @@ export function createHolds({ log, timeoutMs = 120000,
534
554
  * @param {object} entry queue entry
535
555
  * @returns {string|null} hold id, or null for a finished slot
536
556
  */
537
- add({ agent, method, url, preview = '', bodyBytes = 0, effect, floor, sock, note, letter, finish, slot, arrivedAt }) {
557
+ add({ agent, method, url, preview = '', bodyBytes = 0, effect, floor, keyLast4, modelKey, sock, note, letter, finish, slot, arrivedAt }) {
538
558
  const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
539
559
  const s = slots.get(agent);
540
560
  if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
@@ -542,10 +562,10 @@ export function createHolds({ log, timeoutMs = 120000,
542
562
  const ms = deadlineMs();
543
563
  const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
544
564
  const entry = {
545
- id, agent, method, url, preview, bodyBytes, effect, floor, sock, note, letter, finish, t0,
565
+ id, agent, method, url, preview, bodyBytes, effect, floor, keyLast4, modelKey, sock, note, letter, finish, t0,
546
566
  slot: null,
547
567
  timer: ms === null ? null
548
- : setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
568
+ : setTimeout(() => settle(id, false, 'hold timeout', true), Math.max(0, ms - (Date.now() - t0))),
549
569
  };
550
570
  // Unref: a parked `never` hold must not keep the process alive by itself.
551
571
  if (entry.timer?.unref) entry.timer.unref();
@@ -566,7 +586,7 @@ export function createHolds({ log, timeoutMs = 120000,
566
586
  /**
567
587
  * Ask for this agent's hold slot before reading a held request's body.
568
588
  * @param {string} agent
569
- * @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
589
+ * @param {{ onReady: () => void, onExpire: (reason: string, answered?: boolean) => void }} cbs
570
590
  * The handle's `id` is the id its hold will have (empty when `full`), so
571
591
  * the body file can be named before the hold parks.
572
592
  * @returns {{ state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }}
@@ -577,7 +597,7 @@ export function createHolds({ log, timeoutMs = 120000,
577
597
  // receives that same object as `slot`, so holder comparisons use it.
578
598
  // The one deadline timer lives here, armed below for 'now' and
579
599
  // 'queued' alike; expiry runs through `expireReservation` only.
580
- /** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
600
+ /** @type {{ agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
581
601
  const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false, id: '' };
582
602
  const s0 = slots.get(agent);
583
603
  /** @type {'now'|'queued'|'full'} */
@@ -635,7 +655,7 @@ export function createHolds({ log, timeoutMs = 120000,
635
655
  removeAskFile(id);
636
656
  dropBody(id);
637
657
  log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
638
- onDeny(h, 'client gone');
658
+ onDeny(h, 'client gone', false);
639
659
  onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
640
660
  },
641
661
 
@@ -647,6 +667,29 @@ export function createHolds({ log, timeoutMs = 120000,
647
667
 
648
668
  dropBody,
649
669
 
670
+ /**
671
+ * A place among the agent's waiters (requests waiting behind an open model-key ask), bounded
672
+ * by the same MAX_WAITING_PER_AGENT as the hold line. The one owner of that count.
673
+ *
674
+ * @param {string} agent agent name
675
+ * @returns {(() => void)|null} the release (idempotent), or null when the agent already has the maximum waiting
676
+ */
677
+ wait(agent) {
678
+ const n = waits.get(agent) ?? 0;
679
+ if (n >= MAX_WAITING_PER_AGENT) {
680
+ log({ ev: 'hold-queue-full', agent, waiting: true });
681
+ return null;
682
+ }
683
+ waits.set(agent, n + 1);
684
+ let done = false;
685
+ return () => {
686
+ if (done) return;
687
+ done = true;
688
+ const left = (waits.get(agent) ?? 1) - 1;
689
+ if (left > 0) waits.set(agent, left); else waits.delete(agent);
690
+ };
691
+ },
692
+
650
693
  pending() { return [...queue.values()].map(pub); },
651
694
 
652
695
  close() {
package/src/launcher.js CHANGED
@@ -268,7 +268,7 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
268
268
  // same real path, so it is subsumed here.
269
269
  const same = bases.findIndex(([realBase]) => realRt === realBase);
270
270
  if (same >= 0) {
271
- const what = same === 0 ? 'HOME' : same === 1 ? 'the project dir' : roots[same] === nodeBind ? 'the Node install dir' : roots[same];
271
+ const what = roots[same] === home ? 'HOME' : roots[same] === proj ? 'the project dir' : roots[same] === nodeBind ? 'the Node install dir' : roots[same];
272
272
  throw new Error(`launch: runtime must not be ${what} itself (its sockets cannot be hidden there)`);
273
273
  }
274
274
  // Mask the sandbox-visible spelling join(root, relative(realRoot, realRt)):
package/src/prompt.js CHANGED
@@ -29,7 +29,7 @@ export const ANSI = { bold: '\x1b[1m', dim: '\x1b[2m', red: '\x1b[31m', green: '
29
29
  */
30
30
  export const paint = (on, codes, text) => (on ? `${codes}${text}${ANSI.reset}` : text);
31
31
 
32
- /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect }} AskRecord */
32
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect, keyLast4?: string, modelKey?: 'none'|'other' }} AskRecord */
33
33
 
34
34
  /**
35
35
  * The `To:` / `Amount:` / `Currency:` lines of a floor request, or one `Effect:` line saying why none was read.
@@ -45,6 +45,7 @@ export function effectLines(effect, color) {
45
45
  if (effect.notRead !== null) return [` ${paint(color, bold, 'Effect:')} not read (${safe(effect.notRead)})`];
46
46
  /** @type {[string, { path: string, value: string }[]][]} */
47
47
  const rows = [['To:', effect.recipient], ['Amount:', effect.amount], ['Currency:', effect.currency]];
48
+ if (rows.every(([, f]) => !f.length)) return [` ${paint(color, bold, 'Effect:')} body read, no recipient, amount or currency field recognised`];
48
49
  return rows.filter(([, f]) => f.length).map(([label, f]) => {
49
50
  const shown = f.length > LIST_MAX
50
51
  ? `more than ${LIST_MAX} fields (not listed: too many to tell the real one)`
@@ -63,6 +64,17 @@ export function floorTail(ask) {
63
64
  return ask.floor ? ` floor=${safe(ask.floor.kind)} entry=${safe(ask.floor.entry)}` : '';
64
65
  }
65
66
 
67
+ /**
68
+ * The ` key=…<last 4>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); ` key=none` or ` key=other` when there is no last 4 to show; empty unless the ask is a model call with another key.
69
+ *
70
+ * @param {AskRecord} ask the parked request
71
+ * @returns {string} the tail, or ''
72
+ */
73
+ export function keyTail(ask) {
74
+ if (ask.keyLast4) return ` key=…${safe(ask.keyLast4)}`;
75
+ return ask.modelKey ? ` key=${ask.modelKey}` : '';
76
+ }
77
+
66
78
  /**
67
79
  * Plain-language lines for one ask record. Every agent-controlled byte goes
68
80
  * through `safe()`.
@@ -86,6 +98,9 @@ export function questionLines(ask, now = Date.now(), color = false) {
86
98
  ? `${ask.floor.kind === 'send' ? 'a send' : 'a payment'} to ${isEndpoint(ask.floor.entry) ? 'an endpoint' : 'a domain'} you listed (${safe(ask.floor.entry)})`
87
99
  : rule === 'flags.cardLike' ? 'it contains what looks like a card number'
88
100
  : rule === 'flags.paymentPath' ? 'the address looks like a payment'
101
+ : ask.keyLast4 ? `a model call with a key that is not this run's (…${safe(ask.keyLast4)})`
102
+ : ask.modelKey === 'none' ? 'a model call with no key'
103
+ : ask.modelKey ? "a model call with a key that is not this run's"
89
104
  : ask.letter === 'w' ? 'a change (reversible: the vendor says it can be undone)'
90
105
  : ask.letter === 'x' ? "a change barebox can't undo"
91
106
  : rule;
package/src/proxy.js CHANGED
@@ -43,6 +43,8 @@ const MAX_AGENTS = 40;
43
43
  // Agents that browse many hosts must not grow the proxy without limit: one TLS context per host, at most this many.
44
44
  const MAX_MITM_CONTEXTS = 256;
45
45
  const EMPTY = Buffer.alloc(0);
46
+ /** The request headers that carry a model API key (M12). */
47
+ const KEY_HEADERS = ['x-api-key', 'authorization'];
46
48
  const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
47
49
  'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
48
50
 
@@ -144,6 +146,8 @@ export function createProxy(opts) {
144
146
  const matcher = labels?.matcher ?? emptyMatcher;
145
147
  const tools = buildTools(labels?.tools, [...allowLocal]);
146
148
  const models = modelTools(labels?.tools, [...allowLocal]);
149
+ // The built-in endpoints only: a `localLlm` server is free without a key check (M12).
150
+ const builtinModels = modelTools(labels?.tools, []);
147
151
  const modelEndpoints = modelList([...allowLocal]);
148
152
  const floors = floorList(floor ?? {});
149
153
  if (!logFile) throw new Error('createProxy: logFile is required');
@@ -282,9 +286,10 @@ export function createProxy(opts) {
282
286
  } catch {}
283
287
  }
284
288
 
285
- // Pre-HTTP raw sockets only (CONNECT line, oversized head, walled CONNECT, cert failure).
286
- function denyRaw(sock, code, note) {
287
- log({ ev: 'deny', agent: agentOf(sock), code, note });
289
+ // Raw sockets: pre-HTTP (CONNECT line, oversized head, walled CONNECT, cert failure) and the
290
+ // upgrade / inner CONNECT refusals below. `url` is the target, for the proxy log only.
291
+ function denyRaw(sock, code, note, url) {
292
+ log({ ev: 'deny', agent: agentOf(sock), code, note, ...(url ? { url } : {}) });
288
293
  if (sock.destroyed) return;
289
294
  try { sock.end(`HTTP/1.1 ${code} ${note}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${note}\n`); }
290
295
  catch {}
@@ -439,7 +444,7 @@ export function createProxy(opts) {
439
444
  // A parked request's pending ask ends here: handleRequest, awaiting
440
445
  // its gate, then forwards or refuses.
441
446
  onApprove: (h) => h.finish({ decision: 'allow' }),
442
- onDeny: (h, reason) => h.finish({ decision: 'deny', reason }),
447
+ onDeny: (h, reason, answered) => h.finish({ decision: 'deny', reason, answered }),
443
448
  }) : null;
444
449
  } catch (e) {
445
450
  releaseClaim();
@@ -479,6 +484,53 @@ export function createProxy(opts) {
479
484
  return e.p;
480
485
  }
481
486
 
487
+ /**
488
+ * M12: SHA-256 of the model keys a human allowed in this run. `rememberKey` is the one writer; it
489
+ * lives with the proxy, so it is gone with it. A key's bytes are never kept, logged or asked.
490
+ *
491
+ * @type {Set<string>}
492
+ */
493
+ const allowedKeys = new Set();
494
+ /** @param {string} hash */
495
+ const rememberKey = (hash) => { allowedKeys.add(hash); };
496
+ /**
497
+ * M12: one open ask per unknown key. Parallel calls with that key wait on it instead of asking again.
498
+ *
499
+ * @type {Map<string, Promise<'allow'|'deny'|'none'>>}
500
+ */
501
+ const keyAsks = new Map();
502
+
503
+ /**
504
+ * The model key of a header: `x-api-key`, or `Authorization` without a leading `Bearer `.
505
+ * @param {Record<string, string | string[] | undefined>} headers @param {string} name @returns {string}
506
+ */
507
+ function keyIn(headers, name) {
508
+ const v = headers[name];
509
+ const raw = String((Array.isArray(v) ? v[0] : v) ?? '');
510
+ return (name === 'authorization' ? raw.replace(/^Bearer\s+/i, '') : raw).trim();
511
+ }
512
+
513
+ /**
514
+ * M12: is this built-in model call carrying a key that is not this run's? A key header is the
515
+ * run's when it holds a bound placeholder or its hash was allowed; every other key is "other".
516
+ * With no key header at all the call is "other" too, with nothing to remember.
517
+ *
518
+ * @param {Record<string, string | string[] | undefined>} headers the request headers
519
+ * @param {{ header: string, bound: boolean }[]} found the request's placeholders
520
+ * @returns {null | { hash: string | null, last4: string }} null: the run's key; else the key's hash and last 4 characters (null and '' for no key)
521
+ */
522
+ function otherKey(headers, found) {
523
+ const present = KEY_HEADERS.filter((h) => keyIn(headers, h));
524
+ if (!present.length) return { hash: null, last4: '' };
525
+ for (const h of present) {
526
+ if (found.some((f) => f.bound && f.header === h)) continue;
527
+ const key = keyIn(headers, h);
528
+ const hash = crypto.createHash('sha256').update(key).digest('hex');
529
+ if (!allowedKeys.has(hash)) return { hash, last4: key.length >= 8 ? key.slice(-4) : '' };
530
+ }
531
+ return null;
532
+ }
533
+
482
534
  /**
483
535
  * Requests inside `gate.check()`, by `rid`: how the human channel finds
484
536
  * the request an ask is about. handleRequest sets and deletes each entry
@@ -508,6 +560,10 @@ export function createProxy(opts) {
508
560
  * @property {string|null} heldId id of the held body file, once spooled
509
561
  * @property {((reason: string) => void)|null} endAsk end a not-yet-parked ask as a denial
510
562
  * @property {Buffer|null} decodedHead copy of the first 4 KB of a gzip/deflate body, decoded (the ask preview)
563
+ * @property {'none'|'other'|''} modelKey 'none' (no key header) or 'other' for a model call whose key is not this run's; '' otherwise
564
+ * @property {string} keyLast4 last 4 characters of a model key that is not this run's ('' when none): shown in the ask, never the key
565
+ * @property {string|null} askRule the rule the human channel was asked about (null: not asked)
566
+ * @property {boolean} answered a person's answer or the hold timeout ended the ask (set by the hold's `finish`); false for a cancel, a close or a failure
511
567
  * @property {import('./effect.js').Effect|null} effect the recipient/amount/currency fields found in the body of a floor request (ask file only, never the audit); null when there is none
512
568
  */
513
569
 
@@ -522,6 +578,7 @@ export function createProxy(opts) {
522
578
  const ctx = inflightCtx.get(String(event?.action?.rid));
523
579
  if (!ctx) return { decision: 'deny', reason: 'request gone' };
524
580
  ctx.asked = true;
581
+ ctx.askRule = event.rule ?? null;
525
582
  return holdRequest(ctx, event);
526
583
  }
527
584
 
@@ -546,18 +603,20 @@ export function createProxy(opts) {
546
603
  let dead = false;
547
604
  /** @type {import('node:fs').WriteStream|null} */
548
605
  let ws = null;
549
- /** @param {{ decision: 'allow' | 'deny', reason?: string }} d */
606
+ /** @param {{ decision: 'allow' | 'deny', reason?: string, answered?: boolean }} d */
550
607
  const finish = (d) => {
551
608
  if (settled) return;
552
609
  settled = true;
553
610
  ctx.endAsk = null;
554
- resolve(d);
611
+ const { answered, ...rest } = d; // the one place `answered` is set: present only when true
612
+ ctx.answered = answered === true;
613
+ resolve(ctx.answered ? d : rest);
555
614
  };
556
- /** @param {string} reason @param {number} [status] */
557
- const refuse = (reason, status) => {
615
+ /** @param {string} reason @param {number} [status] @param {boolean} [answered] the hold timeout ended it */
616
+ const refuse = (reason, status, answered) => {
558
617
  if (settled) return; // a late failure must not rewrite the settled deny's status
559
618
  if (status) ctx.status = status;
560
- finish({ decision: 'deny', reason });
619
+ finish({ decision: 'deny', reason, answered });
561
620
  };
562
621
  const abort = () => {
563
622
  if (dead) return;
@@ -576,7 +635,7 @@ export function createProxy(opts) {
576
635
  if (!sock || sock.destroyed) { refuse('client gone'); return; }
577
636
  const slot = queue.reserve(agent, {
578
637
  onReady: () => stream(),
579
- onExpire: (why) => { abort(); refuse(why); },
638
+ onExpire: (why, answered) => { abort(); refuse(why, undefined, answered); },
580
639
  });
581
640
  if (slot.state === 'full') { ctx.freeWork(); refuse('hold queue full', 429); return; }
582
641
  ctx.endAsk = (why) => fail(why);
@@ -618,6 +677,8 @@ export function createProxy(opts) {
618
677
  preview: bodyPreview(ctx.decodedHead ?? ctx.tee.head), bodyBytes: ctx.tee.bytes,
619
678
  effect: ctx.effect ?? undefined,
620
679
  ...(event.action?.floor ? { floor: { kind: String(event.action.floor), entry: String(event.action.floorEntry) } } : {}),
680
+ ...(ctx.keyLast4 ? { keyLast4: ctx.keyLast4 } : {}),
681
+ ...(ctx.modelKey ? { modelKey: ctx.modelKey } : {}),
621
682
  sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
622
683
  slot, arrivedAt: slot.arrivedAt }) !== null;
623
684
  };
@@ -748,7 +809,53 @@ export function createProxy(opts) {
748
809
  /** @type {() => void} */
749
810
  let free = () => {};
750
811
  const freeWork = () => { if (!freed) { freed = true; free(); } };
812
+ // M12: the open ask this request leads for its unknown model key, if any (see `keyAsks`).
813
+ /** @type {((r: 'allow'|'deny'|'none') => void) | null} */
814
+ let settleKey = null;
751
815
  try {
816
+ // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
817
+ let tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
818
+ // M12: a call to a built-in model endpoint is a model call only with this run's key; any
819
+ // other key (or none) makes it a plain `x` POST. Parallel calls with one unknown key wait
820
+ // for the one open ask instead of asking again.
821
+ let unknownKey = null;
822
+ if (builtinModels.has(tool)) {
823
+ for (;;) {
824
+ unknownKey = otherKey(creq.headers, found);
825
+ const open = unknownKey?.hash ? keyAsks.get(unknownKey.hash) : undefined;
826
+ if (!open) break;
827
+ // A waiter holds a place among the agent's waiters (the queue owns the count), and loses it
828
+ // when its client goes or the ask ends.
829
+ const release = holds ? holds.wait(agent) : () => {};
830
+ if (!release) {
831
+ discard(creq);
832
+ denyRes(cres, 429, 'denied: hold queue full');
833
+ return;
834
+ }
835
+ /** @type {() => void} */
836
+ let onGone = () => {};
837
+ const gone = new Promise((r) => { onGone = () => r('gone'); cres.once('close', onGone); });
838
+ const r = await Promise.race([open, gone]);
839
+ cres.off('close', onGone);
840
+ release();
841
+ if (r === 'gone') { discard(creq); return; }
842
+ if (r === 'deny') {
843
+ discard(creq);
844
+ denyRes(cres, 403, 'denied: model key');
845
+ return;
846
+ }
847
+ }
848
+ if (unknownKey) {
849
+ tool = `http.${method}`;
850
+ if (unknownKey.hash) {
851
+ const hash = unknownKey.hash;
852
+ /** @type {(r: 'allow'|'deny'|'none') => void} */
853
+ let resolveAsk = () => {};
854
+ keyAsks.set(hash, new Promise((r) => { resolveAsk = r; }));
855
+ settleKey = (r) => { settleKey = null; keyAsks.delete(hash); resolveAsk(r); };
856
+ }
857
+ }
858
+ }
752
859
  if (hasBody) {
753
860
  free = await takeWorkSlot(agent, cres);
754
861
  } else creq.resume();
@@ -763,9 +870,7 @@ export function createProxy(opts) {
763
870
  /** @type {RequestCtx} */
764
871
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
765
872
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
766
- endAsk: null, decodedHead: null, effect: null };
767
- // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
768
- const tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
873
+ endAsk: null, decodedHead: null, effect: null, keyLast4: unknownKey?.last4 ?? '', modelKey: unknownKey ? (unknownKey.hash ? 'other' : 'none') : '', askRule: null, answered: false };
769
874
  let cardLike = false;
770
875
  if (hasBody) {
771
876
  if (await readWorkBody(ctx)) return;
@@ -780,10 +885,18 @@ export function createProxy(opts) {
780
885
  // The body never goes in the action: bareguard writes the action to its audit file.
781
886
  const action = { type: 'net', tool, url: urlStr, method, agent,
782
887
  cardLike, paymentPath: paymentPath(urlStr), rid,
888
+ ...(unknownKey ? { modelKey: 'other' } : {}),
783
889
  ...(floorHit ? { floor: floorHit.kind, floorEntry: floorHit.entry } : {}) };
784
890
  inflightCtx.set(rid, ctx);
785
891
  const g = await gateOf(agent);
786
892
  const d = await decideAction(g, action);
893
+ // M12: a human's answer about an unknown key (not a card or floor ask) is the key's answer.
894
+ if (settleKey) {
895
+ const keyAsk = ctx.asked && !String(ctx.askRule).startsWith('flags.');
896
+ if (keyAsk && d.outcome === 'allow' && unknownKey?.hash) rememberKey(unknownKey.hash);
897
+ // Only a person's answer or the hold timeout denies the waiters; a cancel, a close or a failure lets the next one ask.
898
+ settleKey(!keyAsk ? 'none' : d.outcome === 'allow' ? 'allow' : ctx.answered ? 'deny' : 'none');
899
+ }
787
900
  if (d.outcome === 'allow') {
788
901
  const common = { agent, method, url: urlStr, headers: withSecrets(ctx.headers), cres,
789
902
  ...(d.aid ? { rec: { gate: g, action, aid: d.aid } } : {}) };
@@ -810,6 +923,7 @@ export function createProxy(opts) {
810
923
  denyRes(cres, ctx.status ?? 403, why);
811
924
  }
812
925
  } finally {
926
+ settleKey?.('none');
813
927
  inflightCtx.delete(rid);
814
928
  freeWork();
815
929
  }
@@ -933,6 +1047,15 @@ export function createProxy(opts) {
933
1047
  server.on('clientError', (err, sock) => {
934
1048
  try { sock.destroy(); } catch {}
935
1049
  });
1050
+ // A protocol upgrade (WebSocket, h2c) and a CONNECT inside a tunnel are refused at once, in
1051
+ // every mode and for every host: nothing is resolved, gated or dialed. Without these
1052
+ // listeners node would forward the upgrade as a GET, or close the socket with no reason.
1053
+ server.on('upgrade', (creq, sock) => {
1054
+ const t = creq.url || '';
1055
+ const host = creq.headers.host ?? '';
1056
+ denyRaw(sock, 403, 'denied: upgrade', /^https?:\/\//i.test(t) ? t : `${sock[SECURE] === true ? 'https' : 'http'}://${host}${t}`);
1057
+ });
1058
+ server.on('connect', (creq, sock) => { denyRaw(sock, 403, 'denied: connect', creq.url || ''); });
936
1059
 
937
1060
  // Dispatch: one CONNECT line, or plain HTTP straight into the same server.
938
1061
  function admit(sock, agent) {
package/types/holds.d.ts CHANGED
@@ -46,6 +46,8 @@ export function bodyPreview(head: Buffer): string;
46
46
  * @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
47
47
  * @property {{ kind: 'pay'|'send'|string, entry: string }} [floor] present when the request hit a domain the user listed in config `floor` (kind: which list, entry: the matching entry)
48
48
  * @property {import('./effect.js').Effect} [effect] present on a floor request with a body: the recipient, amount and currency fields found in it (values masked for card numbers), or why it was not read
49
+ * @property {string} [keyLast4] present on a model call whose key is not this run's: the key's last 4 characters (never more)
50
+ * @property {'none'|'other'} [modelKey] present on a model call whose key is not this run's: 'none' (no key header) or 'other' (a key, possibly too short for a last 4)
49
51
  * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
50
52
  * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
51
53
  */
@@ -54,6 +56,15 @@ export function bodyPreview(head: Buffer): string;
54
56
  *
55
57
  * @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
56
58
  */
59
+ /**
60
+ * Write `text` to a fresh 0600 temp file next to `file` (parent made on demand).
61
+ * The caller renames or links it into place.
62
+ *
63
+ * @param {string} file destination path the temp file sits beside
64
+ * @param {string} text content
65
+ * @returns {string} path of the temp file
66
+ */
67
+ export function writeTmpFile(file: string, text: string): string;
57
68
  /**
58
69
  * Atomic write: tmp file + rename, so readers never see a partial payload.
59
70
  *
@@ -99,8 +110,8 @@ export function normalizeDecision(input: {
99
110
  * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
100
111
  * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
101
112
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
102
- * @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
103
- * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
113
+ * @param {(entry: object, reason: string, answered: boolean) => void} opts.onDeny refuse the parked request; `answered`: a person's answer or the hold timeout ended it (not a cancel, a close or a channel failure)
114
+ * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, wait: (agent: string) => (() => void)|null, pending: () => HeldRequest[], close: () => void }} queue handle
104
115
  */
105
116
  export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, onEvent, onApprove, onDeny }: {
106
117
  log: (o: Record<string, unknown>) => void;
@@ -111,13 +122,13 @@ export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, o
111
122
  pollMs?: number | undefined;
112
123
  onEvent?: OnEvent | null | undefined;
113
124
  onApprove: (entry: object) => void;
114
- onDeny: (entry: object, reason: string) => void;
125
+ onDeny: (entry: object, reason: string, answered: boolean) => void;
115
126
  }): {
116
127
  add: (entry: object) => string | null;
117
128
  dropBody: (id: string) => void;
118
129
  reserve: (agent: string, cbs: {
119
130
  onReady: () => void;
120
- onExpire: (reason: string) => void;
131
+ onExpire: (reason: string, answered?: boolean) => void;
121
132
  }) => {
122
133
  state: "now" | "queued" | "full";
123
134
  id: string;
@@ -126,6 +137,7 @@ export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, o
126
137
  };
127
138
  abandon: (id: string) => void;
128
139
  abandonSocket: (sock: object) => void;
140
+ wait: (agent: string) => (() => void) | null;
129
141
  pending: () => HeldRequest[];
130
142
  close: () => void;
131
143
  };
@@ -232,6 +244,14 @@ export type AskPayload = {
232
244
  * present on a floor request with a body: the recipient, amount and currency fields found in it (values masked for card numbers), or why it was not read
233
245
  */
234
246
  effect?: import("./effect.js").Effect | undefined;
247
+ /**
248
+ * present on a model call whose key is not this run's: the key's last 4 characters (never more)
249
+ */
250
+ keyLast4?: string | undefined;
251
+ /**
252
+ * present on a model call whose key is not this run's: 'none' (no key header) or 'other' (a key, possibly too short for a last 4)
253
+ */
254
+ modelKey?: "none" | "other" | undefined;
235
255
  /**
236
256
  * 0 at park; readers use the file mtime for a live value
237
257
  */
package/types/prompt.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect }} AskRecord */
1
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect, keyLast4?: string, modelKey?: 'none'|'other' }} AskRecord */
2
2
  /**
3
3
  * The `To:` / `Amount:` / `Currency:` lines of a floor request, or one `Effect:` line saying why none was read.
4
4
  * Up to LIST_MAX fields are all listed; more than that lists none (too many to tell the real one).
@@ -15,6 +15,13 @@ export function effectLines(effect: AskRecord["effect"], color: boolean): string
15
15
  * @returns {string} the tail, or ''
16
16
  */
17
17
  export function floorTail(ask: AskRecord): string;
18
+ /**
19
+ * The ` key=…<last 4>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); ` key=none` or ` key=other` when there is no last 4 to show; empty unless the ask is a model call with another key.
20
+ *
21
+ * @param {AskRecord} ask the parked request
22
+ * @returns {string} the tail, or ''
23
+ */
24
+ export function keyTail(ask: AskRecord): string;
18
25
  /**
19
26
  * Plain-language lines for one ask record. Every agent-controlled byte goes
20
27
  * through `safe()`.
@@ -77,4 +84,6 @@ export type AskRecord = {
77
84
  entry: string;
78
85
  };
79
86
  effect?: import("./effect.js").Effect;
87
+ keyLast4?: string;
88
+ modelKey?: "none" | "other";
80
89
  };