barebox 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
 
7
+ ## [0.9.0] - 2026-11-03
8
+
9
+ ### Added
10
+
11
+ - `sbx run --hold <seconds|never>` sets how long a held request waits, per run, overriding the `holdTimeoutSec` config key.
12
+ - Terminal colors in the `sbx run` question and answers, only when stderr is a terminal and `NO_COLOR` is unset: yellow header with the agent name in bold, bold labels, cyan URL, dim data and hold id, green for allowed, red for denied or timed out. `--json` and piped output stay plain.
13
+ - The hold id shows in the question as `(hold hN)`.
14
+ - `sbx approve` and `sbx deny` on a hold that already ended print `<id> already decided` and exit 1; when the answer is written but the proxy has not read it yet, they print `<id>: answer written, the proxy has not read it yet`.
15
+ - `--name` for a sandbox that never ran exits 1 with `no sandbox named <n>` and creates nothing.
16
+ - Demo A (`examples/demo-a`): a scripted flight-booking run in ask, auto and trust modes, and a live driver (`--driver muse`) where you answer the holds. The README carries the measured numbers and a captioned demo.
17
+
18
+ ### Changed
19
+
20
+ - `sbx run` waits for your answer by default (was 120 s); `--hold <seconds|never>` sets a deadline per run, and the `holdTimeoutSec` config key sets one for all runs. The library's `createHolds`/`createProxy` default stays 120 s. Unattended runs need `--hold <seconds>`.
21
+
7
22
  ## [0.8.0] - 2026-11-02
8
23
 
9
24
  ### Added
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  ```
10
10
 
11
11
  > An agent runs on your machine with your real tools, every write is undoable, and nothing leaves the machine without passing a doorman. You're asked only when something irreversible is about to happen.
12
- > No root, no daemon, no image. One shared proxy, many thin sandboxes: ~8 MB each, 10 ms to start (M0 POC figure — unmeasured on the rewritten code, TODO re-measure).
12
+ > No root, no daemon, no image. One shared proxy, many thin sandboxes: ~8 MB each, about 0.7 s from `sbx run` to exit with the proxy included.
13
13
 
14
14
  <p align="center">
15
15
  <img src="https://img.shields.io/github/package-json/v/hamr0/barebox?label=version&color=2a4f8c" alt="version (auto from package.json)">
@@ -21,7 +21,7 @@
21
21
 
22
22
  Agents need real access to be useful — shell, files, network. Today you pick one of two bad options:
23
23
 
24
- - **Approve everything.** About forty prompts per task. People stop reading them, or switch prompts off.
24
+ - **Approve everything.** A prompt for nearly every command and edit. People stop reading them, or switch prompts off.
25
25
  - **Heavy isolation.** Docker or a VM: images, a daemon, root, and the agent can't use your installed toolchain. Most people skip it.
26
26
 
27
27
  Neither matches where the risk is. Reads are mostly harmless. File writes can be fixed. Only a few actions can't be undone: paying, sending, publishing, pushing. barebox asks about those and nothing else.
@@ -72,8 +72,8 @@ The agent works in your house:
72
72
  - **Walls** are [bubblewrap](https://github.com/containers/bubblewrap), unprivileged: separate net/pid/ipc/uts namespaces, read-only binds, tmpfs over locked paths.
73
73
  - **Identity** is the socket, not a header the agent could fake. One socket per agent, all into one proxy.
74
74
  - **HTTPS inspection** uses a local CA that exists only inside the sandbox; the proxy reads method, URL, headers and body, then forwards.
75
- - **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment paths (`/checkout`, `/payment`, `/orders`, `/purchase`; a list of payment domains is not built) → rwxmap labels for known APIs → every other request by its letter and the mode (`ask`, `auto`, `trust`; see `barebox.context.md`). The card and payment floor asks in every mode, `trust` included (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.
75
+ - **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment paths (`/checkout`, `/payment`, `/orders`, `/purchase`; a list of payment domains is not built) → rwxmap labels for known APIs → every other request by its letter and the mode (`ask`, `auto`, `trust`; see `barebox.context.md`). The card and payment floor asks in every mode, `trust` included (calls to the built-in model endpoints, Anthropic and OpenAI, and to a `localLlm` server are not card-scanned; a model API you label `r` yourself still is); card numbers are checked in bodies of 64 KB or less.
76
+ - **Approvals** are asked in the terminal where you ran `sbx run`, in plain words (`agent wants to SEND data to httpbin.org … Allow? [y/N]`); `y` allows, anything else denies. Name the sandbox (`sbx run --name docs-bot -- <cmd>`) and a second terminal can answer too (`sbx pending --name docs-bot`, `sbx approve <id> --name docs-bot`, `sbx deny <id> --name docs-bot`); the first answer wins. A hold waits until you answer by default; `sbx run --hold 120 -- <cmd>` (or the `holdTimeoutSec` config key) sets a deadline, and a timeout means deny, with a clear `403` reason. One held request per agent at a time: later ones wait in line (16 at most, then `429 hold queue full`), and any deadline counts from arrival. Unattended runs (cron, CI, no terminal) have nobody to answer, so pass `--hold <seconds>` or the first held request waits forever.
77
77
 
78
78
  ## Keys the agent never holds
79
79
 
@@ -98,11 +98,21 @@ Measured, not estimated. Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22.
98
98
  |---|---|---|
99
99
  | Memory per sandbox | **7.8 MB** mean, 8.0 MB max | ~100 MB (each sandbox runs its own proxy) |
100
100
  | Proxy | one shared: **about 95-160 MB** in normal use over HTTPS (10 to 40 agents, keep-alive tunnels open, no holds; plain HTTP alone is about 85-120 MB); **about 117 / 133-151 / 177-207 / 207-241 MB** at 10 / 20 / 30 / 40 agents in the full HTTPS worst case (each agent with 1 parked + 16 waiting + a filled body slot, every request in its own TLS tunnel). The low end is a quiet machine, the high end a busy one. HTTPS costs more because each live TLS session holds about 50 KB of OpenSSL state | one per sandbox |
101
- | Start + exit | **10 ms** (M0 POC; unmeasured on the rewrite, TODO re-measure) | 1.87-2.05 s |
101
+ | Start + exit | **0.70 s** median for `sbx run -- true`, proxy start to teardown (0.80 s with `--overlay`; 11 runs, quiet machine). The sandbox alone (bwrap) is 6 ms; Node's own start is 0.16 s of it | 1.87-2.05 s |
102
+ | One real agent | Claude Code peaks at **248 MB** inside vs 249 MB bare: barebox does not change the agent. barebox itself adds **about 91 MB** for the first agent (the `sbx` process with its proxy 83 MB, plus 8 MB of walls), then about 11 MB per further agent | not measured |
102
103
  | 10 agents | ~195-200 MB worst case (proxy + 10 x 8 MB) | ~1 GB |
103
104
  | 20 agents | ~295-310 MB worst case | ~2 GB |
104
105
  | 40 agents | ~525-560 MB worst case | not measured |
105
106
 
107
+ **What the demos show** (scripts in `examples/`, run by hand, every cell asserted):
108
+
109
+ ![Demo A: a real agent books a trip inside barebox. Reads and model calls go out free, a payment waits for a yes and only then gets the real key, a no never leaves the machine](assets/demo-a.gif)
110
+
111
+ The full 92-second take, captioned: [assets/demo-a.webm](assets/demo-a.webm).
112
+
113
+ - **Demo A, a real agent books a trip.** Meta's muse model (via Baseten) planned and booked a trip inside barebox in a recorded, unedited live run: 31 requests, **23 went out with no question** (3 searches, weather, exchange rate, and 18 model calls, one of them to a second model) and **8 stopped for a person** (payments, a hotel order, a car, a calendar entry, a chat message, a `DELETE`, an email). The real Stripe-style key reached the server once, after a yes; the agent only ever held a placeholder. Log, timing and captions: `docs/logs/m7-muse-runs/`.
114
+ - **Demo B, a prompt-injected agent.** In every mode (`ask`, `auto`, `trust`) all three exfiltration attempts fail: `~/.ssh` reads empty, the POST to the attacker's host is refused, a direct socket has no route. The good edits are committed and the injected agent's edits rolled back.
115
+
106
116
  barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents. Budget: shared proxy about 205-245 MB in the full HTTPS worst case at 40 agents, each extra sandbox 10 MB or less. 40 agents per proxy is the maximum and it is enforced: `addAgent` refuses the 41st with an error telling you to run another proxy. Above 40, run more proxies. Machine load moves the number. A long audit file does not: 205 MB of audit measured the same as 3 MB. Bypass attempts (`--noproxy`, unset proxy env, direct IP, host localhost) all fail closed, and a red-team script breaks each wall on purpose to prove the checks can fail. Setup, dead ends and why: [findings](docs/logs/findings.md).
107
117
 
108
118
  ## Roadmap
@@ -58,7 +58,7 @@ await proxy.close();
58
58
  When a request needs a decision (see "Modes and the gate" below), it parks.
59
59
  `sbx run` with a terminal (stdin and stderr are TTYs, no `--json`) asks in place:
60
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
61
+ preview, then `Allow? [y/N] (hold h3)`. `y` or `yes` allows; anything else, Enter
62
62
  included, denies with `denied at the terminal`. A line typed before a question
63
63
  appears answers nothing. Name the sandbox with `sbx run --name docs-bot`: the
64
64
  name is the agent name and picks the runtime dir
@@ -80,7 +80,7 @@ SBX_RUNTIME=/tmp/sbx npx sbx approve h1
80
80
  SBX_RUNTIME=/tmp/sbx npx sbx deny h2 "reason here"
81
81
  ```
82
82
 
83
- Held requests wait (default 120 s, `never` supported), counting from arrival:
83
+ Held requests wait, counting from arrival, until a deadline: the library's default is 120 s (`createHolds`/`createProxy`; `'never'` supported), while `sbx run` waits until answered by default (`holdTimeoutSec` `"never"`; `--hold <seconds|never>` or the config key sets a deadline):
84
84
  time spent in line and reading the body counts too, and a request past its
85
85
  deadline is denied `hold timeout` whether waiting, sending, or parked. Each
86
86
  agent holds at most one request being read or parked; later ones wait in
@@ -88,6 +88,9 @@ line, unread, in order — at most 16, the next gets `429 hold queue full`.
88
88
  Approve forwards, deny and timeout answer 403 with the reason. A held body is spooled to `<runtime>/held/<id>` (never kept in memory, deleted when the hold ends); one over `hold.maxBody` (default 50 MB) is denied `403 body too large to hold`. These commands
89
89
  need the proxy to be alive: with no live proxy on the runtime `sbx pending`,
90
90
  `approve` and `deny` exit 1 and say so, because nothing would read the answer.
91
+ `approve` and `deny` wait briefly to learn what the proxy did: an answer for a hold that already ended exits 1 with `<id> already decided`; if the proxy has not read it yet they print `answer written, the proxy has not read it yet` and still report `approved` / `denied`. `--name` for a sandbox that never ran exits 1 with `no sandbox named <n>` and creates nothing. The terminal question is colored only when stderr is a TTY and `NO_COLOR` is unset.
92
+
93
+ Unattended runs (cron, CI, no TTY, `--json`): nobody answers on the terminal, and `sbx run` waits forever by default, so a held request would hang the run. Pass `--hold <seconds>` (or set `holdTimeoutSec`) so a hold times out as a deny.
91
94
 
92
95
  ## One call: `run()` and `sbx run`
93
96
 
@@ -109,7 +112,7 @@ const { exit, asks, audit, diff, runtime } = await run({
109
112
  ```
110
113
 
111
114
  ```bash
112
- sbx run [--name <n>] [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]
115
+ sbx run [--name <n>] [--mode ask|auto|trust] [--hold <seconds|never>] [--json] [--overlay] -- <cmd> [...]
113
116
  ```
114
117
 
115
118
  `sbx run` uses the current directory as the project and `--name`'s runtime or
@@ -121,7 +124,7 @@ Its exit code mirrors the agent's.
121
124
 
122
125
  `sbx run` reads one optional config file,
123
126
  `${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`, with keys `mode`,
124
- `holdTimeoutSec` (positive integer or `"never"`), `heldBodyMaxMB`
127
+ `holdTimeoutSec` (positive integer or `"never"`; default `"never"`, overridden per run by `--hold`), `heldBodyMaxMB`
125
128
  (positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
126
129
  unknown key, bad value or bad JSON exits 2 naming the file and key. The file
127
130
  is hidden inside the sandbox wherever it resolves. The library does not read it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Lightweight local sandbox for AI agents: every write undoable, nothing leaves the machine without passing the doorman.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/src/cli.js CHANGED
@@ -13,7 +13,7 @@
13
13
  // `--name <n>` names the sandbox (agent name + runtime dir, runtime.js namedRuntime) and every
14
14
  // command takes `--name` instead of SBX_RUNTIME (both together: exit 2).
15
15
  //
16
- // sbx run [--mode ask|auto|trust] [--name <n>] [--json] [--overlay] -- <cmd> [...]
16
+ // sbx run [--mode ask|auto|trust] [--hold <seconds|never>] [--name <n>] [--json] [--overlay] -- <cmd> [...]
17
17
  // Runs one sandboxed agent start-to-finish in this process (project = cwd).
18
18
  // The runtime is SBX_RUNTIME when set, else a short temp dir (printed to
19
19
  // stderr so a second terminal can approve from it). With --json, stdout
@@ -38,11 +38,12 @@ 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 } from './prompt.js';
41
+ import { createTerminalPrompt, paint, ANSI } from './prompt.js';
42
+ import { DEFAULT_POLL_MS } from './holds.js';
42
43
  import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
43
44
  import { assertAgentName, createRuntime, namedRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
44
45
 
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)';
46
+ const USAGE = 'usage: sbx [--help] | run [--mode ask|auto|trust] [--hold <seconds|never>] [--name <n>] [--json] [--overlay] -- <cmd> [...] | pending|diff|rollback [--name <n>] | approve <id> [--name <n>] | deny <id> [reason] [--name <n>] | commit [--name <n>] [--skip-conflicts] (--name replaces SBX_RUNTIME; --agent stays for diff/commit/rollback)';
46
47
 
47
48
  /** Hold ids the CLI accepts: `h<n>` only. Anything else is a usage error, never a path. */
48
49
  const HOLD_ID_RE = /^h\d+$/;
@@ -78,12 +79,18 @@ function needRuntime(name, create = false) {
78
79
  err('give --name or SBX_RUNTIME, not both');
79
80
  process.exit(2);
80
81
  }
82
+ let dir;
81
83
  try {
82
- return namedRuntime(name, process.env, { create });
84
+ dir = namedRuntime(name, process.env, { create });
83
85
  } catch (e) {
84
86
  err(e instanceof Error ? e.message : String(e));
85
87
  process.exit(2);
86
88
  }
89
+ if (!create && !fs.existsSync(dir)) {
90
+ err(`no sandbox named ${name} (start one with 'sbx run --name ${name} -- …')`);
91
+ process.exit(1);
92
+ }
93
+ return dir;
87
94
  }
88
95
  const runtime = process.env.SBX_RUNTIME;
89
96
  if (!runtime) usage();
@@ -190,7 +197,7 @@ async function run(args) {
190
197
  if (sep < 0) usage();
191
198
  const flags = args.slice(0, sep);
192
199
  const command = args.slice(sep + 1);
193
- /** @type {{ name?: string, mode?: string, json?: boolean, overlay?: boolean }} */
200
+ /** @type {{ name?: string, mode?: string, hold?: string, json?: boolean, overlay?: boolean }} */
194
201
  let values;
195
202
  try {
196
203
  ({ values } = parseArgs({
@@ -198,6 +205,7 @@ async function run(args) {
198
205
  options: {
199
206
  name: { type: 'string' },
200
207
  mode: { type: 'string' },
208
+ hold: { type: 'string' },
201
209
  json: { type: 'boolean' },
202
210
  overlay: { type: 'boolean' },
203
211
  },
@@ -211,7 +219,7 @@ async function run(args) {
211
219
  /** @type {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} */
212
220
  let cfg;
213
221
  try {
214
- cfg = resolveConfig({ mode: values.mode });
222
+ cfg = resolveConfig({ mode: values.mode, hold: values.hold });
215
223
  } catch (e) {
216
224
  err(e instanceof Error ? e.message : String(e));
217
225
  process.exit(2);
@@ -244,10 +252,12 @@ async function run(args) {
244
252
  };
245
253
  // A person at this terminal (stdin and stderr are TTYs, not --json) answers
246
254
  // holds here; the file channel stays on, so `sbx approve` still works too.
255
+ const errColor = !!process.stderr.isTTY && !process.env.NO_COLOR;
247
256
  const prompt = !json && process.stdin.isTTY && process.stderr.isTTY
248
257
  ? createTerminalPrompt({
249
258
  input: process.stdin,
250
259
  output: process.stderr,
260
+ color: errColor,
251
261
  answer: (id, decision, reason) => writeAnswer(runtimePaths(runtime), id, decision, reason),
252
262
  })
253
263
  : null;
@@ -262,7 +272,11 @@ async function run(args) {
262
272
  if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
263
273
  else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
264
274
  };
265
- err(name !== undefined
275
+ if (name !== undefined && errColor) {
276
+ // Colored line: only the dynamic name is sanitized; `err` would strip the escapes.
277
+ const n = safe(name);
278
+ console.error(`sandbox ${paint(true, ANSI.bold, n)}${ANSI.dim} (answer from another terminal: sbx approve --name ${n} <id>)${ANSI.reset}`);
279
+ } else err(name !== undefined
266
280
  ? `sandbox ${name} (answer from another terminal: sbx approve --name ${name} <id>)`
267
281
  : `runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
268
282
  /** @type {{ exit: number, diff: { path: string }[] } | null} */
@@ -472,16 +486,57 @@ function alreadyAnswered(id) {
472
486
  process.exit(1);
473
487
  }
474
488
 
489
+ /**
490
+ * After our answer is linked, learn what the proxy did with it. The proxy
491
+ * writes `answers/<id>.stale` before it consumes an answer for a hold it no
492
+ * longer has, so once our answer file is gone the marker is the whole truth.
493
+ * Bounded at 4 poll intervals; a proxy that has not read it by then is
494
+ * reported, not guessed at.
495
+ *
496
+ * @param {ReturnType<typeof runtimePaths>} paths runtime paths
497
+ * @param {string} id hold id
498
+ * @returns {Promise<'settled'|'stale'|'unread'>} the outcome
499
+ */
500
+ async function outcomeOf(paths, id) {
501
+ const end = Date.now() + 4 * DEFAULT_POLL_MS;
502
+ while (fs.existsSync(paths.answerFile(id))) {
503
+ if (Date.now() > end) return 'unread';
504
+ await new Promise((r) => setTimeout(r, 10));
505
+ }
506
+ try {
507
+ fs.unlinkSync(paths.staleFile(id));
508
+ return 'stale';
509
+ } catch {
510
+ return 'settled';
511
+ }
512
+ }
513
+
514
+ /**
515
+ * @param {ReturnType<typeof runtimePaths>} paths runtime paths
516
+ * @param {string} id hold id
517
+ * @param {'allow'|'deny'} decision the answer
518
+ * @param {string} [reason] deny reason
519
+ * @returns {Promise<void>} resolves when the answer settled the hold (or the proxy has not read it yet); exits 1 otherwise
520
+ */
521
+ async function answerHold(paths, id, decision, reason) {
522
+ if (!writeAnswer(paths, id, decision, reason)) alreadyAnswered(id);
523
+ const outcome = await outcomeOf(paths, id);
524
+ if (outcome === 'stale') {
525
+ err(`${id} already decided`);
526
+ process.exit(1);
527
+ }
528
+ if (outcome === 'unread') err(`${id}: answer written, the proxy has not read it yet`);
529
+ out(`${decision === 'allow' ? 'approved' : 'denied'} ${id}`);
530
+ }
531
+
475
532
  /** @param {string[]} rest @returns {Promise<void>} */
476
533
  async function approve(rest) {
477
534
  const { id, paths } = await answerTarget(rest);
478
- if (!writeAnswer(paths, id, 'allow')) alreadyAnswered(id);
479
- out(`approved ${id}`);
535
+ await answerHold(paths, id, 'allow');
480
536
  }
481
537
 
482
538
  /** @param {string[]} rest @returns {Promise<void>} */
483
539
  async function deny(rest) {
484
540
  const { id, reason, paths } = await answerTarget(rest);
485
- if (!writeAnswer(paths, id, 'deny', reason)) alreadyAnswered(id);
486
- out(`denied ${id}`);
541
+ await answerHold(paths, id, 'deny', reason);
487
542
  }
package/src/config.js CHANGED
@@ -7,7 +7,7 @@ import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { MODES } from './policy.js';
9
9
 
10
- const DEFAULTS = { mode: 'auto', holdTimeoutSec: 120, localLlm: [], labels: [], tenants: {} };
10
+ const DEFAULTS = { mode: 'auto', holdTimeoutSec: 'never', localLlm: [], labels: [], tenants: {} };
11
11
 
12
12
  /** One `host:port` (host without a colon, port 1-65535). @param {unknown} v @returns {boolean} */
13
13
  const isHostPort = (v) => {
@@ -137,11 +137,22 @@ export function loadConfig(env = process.env) {
137
137
  *
138
138
  * @param {object} [flags] values given on the command line
139
139
  * @param {string} [flags.mode] `--mode`
140
+ * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
140
141
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
141
142
  * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
142
143
  * @throws {Error} as {@link loadConfig}
143
144
  */
144
145
  export function resolveConfig(flags = {}, env = process.env) {
145
146
  const cfg = loadConfig(env);
146
- return { ...cfg, ...(flags.mode !== undefined ? { mode: flags.mode } : {}) };
147
+ let hold;
148
+ if (flags.hold !== undefined) {
149
+ hold = flags.hold === 'never' ? 'never' : /^\d+$/.test(flags.hold) ? Number(flags.hold) : flags.hold;
150
+ const bad = KEYS.holdTimeoutSec(hold);
151
+ if (bad) throw new Error(`--hold ${bad}`);
152
+ }
153
+ return {
154
+ ...cfg,
155
+ ...(flags.mode !== undefined ? { mode: flags.mode } : {}),
156
+ ...(hold !== undefined ? { holdTimeoutSec: hold } : {}),
157
+ };
147
158
  }
package/src/holds.js CHANGED
@@ -487,6 +487,11 @@ export function createHolds({ log, timeoutMs = 120000,
487
487
  for (const name of names) {
488
488
  if (!name.endsWith('.json')) continue;
489
489
  const id = name.slice(0, -'.json'.length);
490
+ // Not held: say so (the marker `sbx approve` reads) before the answer
491
+ // is consumed, so "answer gone" always means the marker is already there.
492
+ if (!queue.has(id)) {
493
+ try { writeFileAtomic(paths.staleFile(id), ''); } catch {}
494
+ }
490
495
  const text = consumeFile(paths.answerFile(id));
491
496
  if (text === null) continue;
492
497
  const norm = normalizeDecision(parseAnswer(text), { approveAlias: true });
package/src/prompt.js CHANGED
@@ -13,6 +13,20 @@ const BODY_CHARS = 200;
13
13
  const EOL = /\r\n|\r|\n/;
14
14
  const YES = new Set(['y', 'yes']);
15
15
 
16
+ // Plain ANSI. Escapes are added only around text that already went through
17
+ // `safe()`, which strips every escape from agent bytes; never paint raw text.
18
+ export const ANSI = { bold: '\x1b[1m', dim: '\x1b[2m', red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', cyan: '\x1b[36m', unbold: '\x1b[22m', reset: '\x1b[0m' };
19
+
20
+ /**
21
+ * Wrap already-sanitized text in escapes when `on`; plain text otherwise.
22
+ *
23
+ * @param {boolean} on whether color is enabled
24
+ * @param {string} codes one or more ANSI.* escapes
25
+ * @param {string} text sanitized text
26
+ * @returns {string} the painted text
27
+ */
28
+ export const paint = (on, codes, text) => (on ? `${codes}${text}${ANSI.reset}` : text);
29
+
16
30
  /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
17
31
 
18
32
  /**
@@ -21,9 +35,11 @@ const YES = new Set(['y', 'yes']);
21
35
  *
22
36
  * @param {AskRecord} ask the parked request
23
37
  * @param {number} [now] clock for the countdown, injectable
38
+ * @param {boolean} [color] paint with ANSI escapes (off by default)
24
39
  * @returns {string[]} the question, one string per line
25
40
  */
26
- export function questionLines(ask, now = Date.now()) {
41
+ export function questionLines(ask, now = Date.now(), color = false) {
42
+ const { bold, dim, red, green, yellow, cyan, unbold } = ANSI;
27
43
  const method = safe(ask.method).toUpperCase();
28
44
  let host;
29
45
  try { host = safe(new URL(ask.url).host); } catch { host = safe(ask.url); }
@@ -38,14 +54,19 @@ export function questionLines(ask, now = Date.now()) {
38
54
  : ask.letter === 'x' ? "a change barebox can't undo"
39
55
  : rule;
40
56
  const left = ask.expiresAt ? Math.max(0, Math.round((Date.parse(ask.expiresAt) - now) / 1000)) : null;
57
+ const name = safe(ask.agent) || 'agent';
58
+ const head = color
59
+ ? paint(true, yellow, `⏸ ${bold}${name}${unbold} wants to ${verb} ${host}`)
60
+ : `⏸ ${name} wants to ${verb} ${host}`;
41
61
  const lines = [
42
- `⏸ ${safe(ask.agent) || 'agent'} wants to ${verb} ${host}`,
43
- ` Why: ${why}`,
44
- ` URL: ${method} ${safe(ask.url)}`,
62
+ head,
63
+ ` ${paint(color, bold, 'Why:')} ${why}`,
64
+ ` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${safe(ask.url)}`)}`,
45
65
  ];
46
66
  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`}`);
67
+ if (body) lines.push(` ${paint(color, bold, 'Data:')} ${paint(color, dim, body)}`);
68
+ const tail = `(hold ${safe(ask.id)})${left === null || Number.isNaN(left) ? '' : ` — no answer in ${left} s means No`}`;
69
+ lines.push(` ${paint(color, bold, 'Allow? [y/N]')} ${paint(color, dim, tail)}`);
49
70
  return lines;
50
71
  }
51
72
 
@@ -56,10 +77,10 @@ export function questionLines(ask, now = Date.now()) {
56
77
  * closes the question when the hold ended some other way, `close()` releases
57
78
  * `input`.
58
79
  *
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
80
+ * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
60
81
  * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
61
82
  */
62
- export function createTerminalPrompt({ input, output, answer }) {
83
+ export function createTerminalPrompt({ input, output, answer, color = false }) {
63
84
  /** @type {AskRecord|null} */
64
85
  let open = null;
65
86
  let buf = '';
@@ -73,7 +94,8 @@ export function createTerminalPrompt({ input, output, answer }) {
73
94
  const yes = YES.has(line.trim().toLowerCase());
74
95
  try {
75
96
  const written = answer(id, yes ? 'allow' : 'deny', yes ? undefined : 'denied at the terminal') !== false;
76
- say(!written ? 'answered elsewhere' : yes ? '✓ allowed' : '✗ denied');
97
+ say(!written ? 'answered elsewhere'
98
+ : yes ? paint(color, ANSI.green + ANSI.bold, '✓ allowed') : paint(color, ANSI.red + ANSI.bold, '✗ denied'));
77
99
  } catch {
78
100
  // The hold ended (or the runtime went) before this write; the run goes on.
79
101
  }
@@ -97,15 +119,15 @@ export function createTerminalPrompt({ input, output, answer }) {
97
119
  if (closed || open) return false;
98
120
  open = ask;
99
121
  buf = ''; // a half-typed line from before the question is stale
100
- for (const l of questionLines(open)) say(l);
122
+ for (const l of questionLines(open, Date.now(), color)) say(l);
101
123
  return true;
102
124
  },
103
125
  decided(e) {
104
126
  if (open?.id !== e.id) return;
105
127
  open = null; // closed before anything else: no answer can follow
106
128
  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)}`
129
+ say(why === 'hold timeout' ? paint(color, ANSI.red, `timed out: ${safe(e.decision)}`)
130
+ : why === 'client gone' || why === 'proxy closing' ? paint(color, ANSI.red, `agent gone: ${safe(e.decision)}`)
109
131
  : `answered elsewhere: ${safe(e.decision)}${why ? ` (${why})` : ''}`);
110
132
  },
111
133
  close() {
package/src/runtime.js CHANGED
@@ -334,7 +334,7 @@ export function shellQuote(s) {
334
334
  * Every path in a runtime dir. The one place that names them.
335
335
  *
336
336
  * @param {string} runtime runtime dir
337
- * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
337
+ * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, staleFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
338
338
  */
339
339
  export function runtimePaths(runtime) {
340
340
  const asksDir = path.join(runtime, 'asks');
@@ -346,6 +346,8 @@ export function runtimePaths(runtime) {
346
346
  answersDir,
347
347
  askFile: (id) => path.join(asksDir, `${id}.json`),
348
348
  answerFile: (id) => path.join(answersDir, `${id}.json`),
349
+ // The proxy's note that an answer for `id` arrived after the hold settled; written before the answer is consumed.
350
+ staleFile: (id) => path.join(answersDir, `${id}.stale`),
349
351
  heldDir,
350
352
  // A held request's body, spooled to disk while it waits for a decision.
351
353
  heldFile: (id) => path.join(heldDir, id),
package/types/config.d.ts CHANGED
@@ -34,12 +34,14 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
34
34
  *
35
35
  * @param {object} [flags] values given on the command line
36
36
  * @param {string} [flags.mode] `--mode`
37
+ * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
37
38
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
38
39
  * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
39
40
  * @throws {Error} as {@link loadConfig}
40
41
  */
41
42
  export function resolveConfig(flags?: {
42
43
  mode?: string | undefined;
44
+ hold?: string | undefined;
43
45
  }, env?: NodeJS.ProcessEnv): {
44
46
  mode: string;
45
47
  holdTimeoutSec: number | string;
package/types/prompt.d.ts CHANGED
@@ -5,9 +5,10 @@
5
5
  *
6
6
  * @param {AskRecord} ask the parked request
7
7
  * @param {number} [now] clock for the countdown, injectable
8
+ * @param {boolean} [color] paint with ANSI escapes (off by default)
8
9
  * @returns {string[]} the question, one string per line
9
10
  */
10
- export function questionLines(ask: AskRecord, now?: number): string[];
11
+ export function questionLines(ask: AskRecord, now?: number, color?: boolean): string[];
11
12
  /**
12
13
  * The terminal prompt. One question open at a time. `ask()` opens a question
13
14
  * and returns true, or returns false when one is already open (or the prompt
@@ -15,14 +16,15 @@ export function questionLines(ask: AskRecord, now?: number): string[];
15
16
  * closes the question when the hold ended some other way, `close()` releases
16
17
  * `input`.
17
18
  *
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
+ * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
19
20
  * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
20
21
  */
21
- export function createTerminalPrompt({ input, output, answer }: {
22
+ export function createTerminalPrompt({ input, output, answer, color }: {
22
23
  input: import("node:stream").Readable;
23
24
  output: {
24
25
  write: (s: string) => unknown;
25
26
  };
27
+ color?: boolean;
26
28
  answer: (id: string, decision: "allow" | "deny", reason?: string) => boolean | void;
27
29
  }): {
28
30
  ask: (ask: AskRecord) => boolean;
@@ -33,6 +35,17 @@ export function createTerminalPrompt({ input, output, answer }: {
33
35
  }) => void;
34
36
  close: () => void;
35
37
  };
38
+ export namespace ANSI {
39
+ let bold: string;
40
+ let dim: string;
41
+ let red: string;
42
+ let green: string;
43
+ let yellow: string;
44
+ let cyan: string;
45
+ let unbold: string;
46
+ let reset: string;
47
+ }
48
+ export function paint(on: boolean, codes: string, text: string): string;
36
49
  export type AskRecord = {
37
50
  id: string;
38
51
  agent?: string;
@@ -155,7 +155,7 @@ export function shellQuote(s: string): string;
155
155
  * Every path in a runtime dir. The one place that names them.
156
156
  *
157
157
  * @param {string} runtime runtime dir
158
- * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
158
+ * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, staleFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
159
159
  */
160
160
  export function runtimePaths(runtime: string): {
161
161
  socket: (agent: string) => string;
@@ -163,6 +163,7 @@ export function runtimePaths(runtime: string): {
163
163
  answersDir: string;
164
164
  askFile: (id: string) => string;
165
165
  answerFile: (id: string) => string;
166
+ staleFile: (id: string) => string;
166
167
  heldDir: string;
167
168
  heldFile: (id: string) => string;
168
169
  certsDir: string;