@bolt-cli/cli 0.0.0-stage → 0.13.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/lib/cli.js ADDED
@@ -0,0 +1,2637 @@
1
+ "use strict";
2
+ // bolt CLI entry: auth, run, build, balance, sessions + interactive REPL.
3
+ // Zero deps. Single backend (Bolt) only: no providers, no model picker.
4
+ const fs = require("fs");
5
+ const os = require("os");
6
+ const path = require("path");
7
+ const { spawn } = require("node:child_process");
8
+ const config = require("./config");
9
+ const api = require("./api");
10
+ const browser = require("./browser");
11
+ const output = require("./output");
12
+ const session = require("./session");
13
+ const ui = require("./ui");
14
+ const present = require("./present");
15
+ const agent = require("./agent");
16
+ const tools = require("./tools");
17
+ const bootstrap = require("./bootstrap");
18
+ const permissions = require("./permissions");
19
+ const memory = require("./memory");
20
+ const redact = require("./redact");
21
+ const replHistory = require("./history");
22
+ const doctor = require("./doctor");
23
+ const completion = require("./completion");
24
+ const exporter = require("./export");
25
+ const checkpoints = require("./checkpoints");
26
+ const cancel = require("./cancel");
27
+ const watch = require("./watch");
28
+ const updatecheck = require("./updatecheck");
29
+
30
+ const VERSION = require(path.join(__dirname, "..", "package.json")).version;
31
+
32
+ function help(topic) {
33
+ if (topic) {
34
+ const t = String(topic).toLowerCase();
35
+ if (t === "run") return `bolt run "<prompt>" [options] — single autonomous run\n\n --target, -t <domain> in-scope target\n --mode, -m <mode> offensive (default) | defensive\n --agent <name> sweep|probe|build|plan|validate|triage\n --tools agent loop (read, list, search, edit, shell)\n --max-iters <n> cap iterations (default 8, max 32)\n --format <fmt> text (default) | json | md\n --output <file> write the final answer to a file\n --budget <tokens> refuse to send when estimated input exceeds N tokens\n -p, --print print mode: final answer only\n -f, --file <path> attach file as evidence (repeatable)\n -s, --session <id> continue a session\n -c, --continue continue the most recent session\n --title <text> title for a new session\n --dry-run preview tokens/files/memory, spend nothing\n --allow-all approve every tool call (dangerous)\n\nExamples:\n bolt run "get admin endpoints" --target tesla.com --format json --output out.json\n bolt run "triage alert" --mode defensive -f alert.json --budget 8000\n`;
36
+ if (t === "build") return `bolt build "<what>" --target <domain> [--out ./bolt-out] [--format json] [--output report.md]\n\nBuild mode runs the agent loop and extracts fenced code blocks to disk.\nEvery write/edit is backed up first — bolt undo <path> restores.\n`;
37
+ if (t === "session") return `bolt session [list|show <id>|delete <id>|new] — local sessions at ~/.bolt/sessions/\n\n bolt session list\n bolt session show <id>\n bolt export <id> --format md|json|sarif [--output file]\n`;
38
+ if (t === "export") return `bolt export <id> [--format md|json|sarif] [--output file]\n\nmd for humans, json for scripts, sarif for CI code-scanning (GitHub compatible).\n`;
39
+ if (t === "doctor") return `bolt doctor — pre-flight checks: node version, auth, backend reachability, WSL, clipboard.\n\nExits non-zero when a check fails. Run before reporting bugs.\n`;
40
+ if (t === "update") return `bolt update — upgrade the globally installed CLI via npm (runs: npm install -g @bolt-cli/cli).\n\nThe check that notices a new release is automatic and quiet (12h cadence, BOLT_NO_UPDATE_CHECK=1 to disable); the upgrade itself always asks: run bolt update.\n`;
41
+ if (t === "completion") return `bolt completion <bash|zsh|fish|powershell> — print shell completions to stdout.\n\n bolt completion bash >> ~/.bashrc\n bolt completion zsh >> ~/.zshrc\n`;
42
+ if (t === "undo") return `bolt undo <path> — restore the last backup of a file written/edited by the agent.\n\nBackups live under ~/.bolt/backups/ (last 10 kept per file).\n`;
43
+ if (t === "templates") return `bolt templates [name] — printable lab runbooks shipped with Bolt.\n\n bolt templates list (ASLR probe, crash-offset pattern)\n bolt templates aslr-offset-probe.sh print to stdout\n bolt templates README the lab-only guide\n\nAuthorized lab work only; every script prints an authorization notice.\n`;
44
+ if (t === "watch") return `bolt watch <status|check|start|stop|events|policy|playbook|baseline|respond> — background defensive checks on this machine.\n\n bolt watch status watcher, daemon, and today's incidents\n bolt watch check [--no-triage] [--no-report] one pass now (exit 2 on high/critical)\n bolt watch start [--interval 300] detach the daemon (runs check every interval)\n bolt watch stop stop the daemon\n bolt watch events [n] recent local incidents (default 20)\n bolt watch policy [show|enable|disable|signal|threshold|interval|triage|phonehome]\n bolt watch playbook [list|<name> allow|off] authorize or revoke responses\n bolt watch baseline [reset] show or re-establish host baselines\n bolt watch respond <playbook> <arg> run one authorized response now\n\nChecks are deterministic and read-only (auth bursts, new listeners, watched-file changes, load/disk/memory). AI triage fires only for high/critical incidents (capped/day); only the blockIp playbook can fire automatically, and only when you allowed it. Everything is logged to ~/.bolt/watch/.\n`;
45
+ }
46
+ return `bolt v${VERSION} - authorized testing from your terminal
47
+
48
+ Install: npm install -g @bolt-cli/cli Update: npm update -g @bolt-cli/cli
49
+ Web: https://bolt.beerasafe.com Bugs: security@beerasafe.com
50
+
51
+ Usage:
52
+ bolt interactive agent (like opencode, Bolt backend only)
53
+ bolt login | signin sign in through your browser
54
+ bolt auth status | logout session info, sign out this machine
55
+ bolt run "<prompt>" [options] single autonomous run
56
+ bolt build "<what>" --target <domain> [--out ./bolt-out]
57
+ bolt -p "<prompt>" print mode: agent loop, final answer only
58
+ bolt session [list|show|delete|new]
59
+ bolt export <id> [--format md|json|sarif] [--output file]
60
+ bolt undo <path> restore last agent backup of a file
61
+ bolt templates [name] print lab runbooks (ASLR probe, offsets)
62
+ bolt watch <subcommand> background defensive checks (status|check|start|stop|…)
63
+ bolt doctor pre-flight checks (node, auth, backend, WSL)
64
+ bolt update upgrade the CLI via npm (notice appears when a release ships)
65
+ bolt completion <shell> shell completions (bash|zsh|fish|powershell)
66
+ bolt balance tokens, runs, spend
67
+ bolt help <command> per-command help (run|build|session|export|doctor|completion|undo|watch|templates|update)
68
+
69
+ Press Esc during any run to stop it (the session is saved). Out of tokens
70
+ stops the run at once with the top-up link — it never spins forever.
71
+
72
+ Sign-in options:
73
+ --url <app> backend (default: last used, BOLT_URL, else production)
74
+ --no-browser print the sign-in URL instead of opening it
75
+
76
+ Run options:
77
+ --target, -t <domain> in-scope target
78
+ --mode, -m <mode> offensive (default) | defensive
79
+ --agent <name> arm an agent (sweep|probe|build|plan|validate|triage)
80
+ --tools agent loop: read, list, search, edit files, shell
81
+ (interactive shows Allow / Always allow / Deny;
82
+ elevated commands get a shield card; piped runs deny)
83
+ --dry-run show what would be sent (tokens, files, memory)
84
+ without spending anything or touching the network
85
+ --allow-all approve every tool call without asking (dangerous)
86
+ --max-iters <n> cap agent-loop iterations (default 8)
87
+ --format <fmt> text (default) | json | md — machine-readable output
88
+ --output <file> write the final answer to a file
89
+ --budget <tokens> refuse to send when estimated input exceeds N tokens
90
+ -p, --print print mode (no approvals unless --allow-all)
91
+ --file, -f <path> attach file as evidence (repeatable)
92
+ --evidence <path> alias for --file
93
+ --session, -s <id> continue a session
94
+ --continue, -c continue the most recent session
95
+ --title <text> title for a new session
96
+ --out, -o <dir> save built files (build defaults ./bolt-out)
97
+
98
+ Examples:
99
+ bolt
100
+ bolt login
101
+ bolt doctor
102
+ bolt run "get admin endpoints on subdomains of tesla.com" --target tesla.com
103
+ bolt run "refactor src/auth.ts to use the new session store" --tools
104
+ bolt run "is this phish real?" --mode defensive -f ./mail.eml -c
105
+ bolt run "get admin endpoints" --target tesla.com --format json --output out.json
106
+ bolt -p "what does this repo do?" --allow-all
107
+ bolt build "nmap NSE script to detect exposed admin logins" --target tesla.com
108
+ bolt export <session-id> --format sarif --output findings.sarif
109
+ bolt completion bash >> ~/.bashrc
110
+ bolt undo src/auth.ts
111
+
112
+ bolt login opens your browser and receives a single-use code back on localhost,
113
+ so no password is ever typed into the terminal. The token lives at
114
+ ~/.bolt/config.json (mode 600). Env overrides: BOLT_URL, BOLT_TOKEN.
115
+ `;
116
+ }
117
+
118
+ function arg(args, ...names) {
119
+ for (const name of names) {
120
+ const i = args.indexOf(name);
121
+ if (i !== -1 && i + 1 < args.length) return args[i + 1];
122
+ }
123
+ return "";
124
+ }
125
+
126
+ function flag(args, ...names) {
127
+ return names.some((n) => args.includes(n));
128
+ }
129
+
130
+ function argAll(args, ...names) {
131
+ const out = [];
132
+ for (let i = 0; i < args.length; i += 1) {
133
+ if (names.includes(args[i]) && i + 1 < args.length) out.push(args[i + 1]);
134
+ }
135
+ return out;
136
+ }
137
+
138
+ function readStdin() {
139
+ return new Promise((resolve) => {
140
+ if (process.stdin.isTTY) return resolve("");
141
+ let data = "";
142
+ process.stdin.setEncoding("utf8");
143
+ process.stdin.on("data", (c) => (data += c));
144
+ process.stdin.on("end", () => resolve(data.trim()));
145
+ });
146
+ }
147
+
148
+ // Resolves which backend to talk to. Precedence: --url, then BOLT_URL,
149
+ // then whatever was last saved, then production. First run therefore hits
150
+ // the live backend with zero configuration; local dev opts in explicitly.
151
+ function resolveUrl(rest) {
152
+ const saved = config.load();
153
+ return (arg(rest, "--url") || process.env.BOLT_URL || saved.url || config.PRODUCTION_URL).replace(/\/$/, "");
154
+ }
155
+
156
+ /**
157
+ * `bolt signin` — authenticate in the browser, get the token back here.
158
+ *
159
+ * The CLI has no cookie jar and no way to ask for a password safely (a typed
160
+ * password is shell history and visible in the process list), so it uses the
161
+ * device flow: the terminal shows a short code, the user approves it in the
162
+ * browser, and polling redeems the token. No local server, no loopback
163
+ * navigation — it works over SSH and in containers too.
164
+ */
165
+ async function cmdSignin(rest) {
166
+ let url = resolveUrl(rest);
167
+
168
+ // Zero-config login: a stale loopback backend (an old dev default sitting
169
+ // in ~/.bolt/config.json) with nothing listening is not a choice, it is
170
+ // leftovers — probe it, and fall through to production with a notice
171
+ // instead of opening a dead authorize page. An explicit --url or BOLT_URL
172
+ // is always honored as-is, and so is a live local server.
173
+ const explicit = Boolean(arg(rest, "--url") || process.env.BOLT_URL);
174
+ if (!explicit && isLoopbackUrl(url) && !(await backendReachable(url))) {
175
+ console.log(`No local backend answering at ${url} — signing in to production instead.`);
176
+ url = config.PRODUCTION_URL;
177
+ }
178
+
179
+ // Explicit credentials still work, for scripted and headless use. The browser
180
+ // flow is the default because it is the one that needs no secret on the
181
+ // command line at all.
182
+ const data = await browser.signInWithBrowser({
183
+ url,
184
+ open: !flag(rest, "--no-browser"),
185
+ log: (line) => console.log(line),
186
+ // Same progress treatment as every other long-running command: a live
187
+ // spinner while the browser round trip is in flight, silent on pipes.
188
+ spinner: ui.createSpinner(),
189
+ });
190
+ return finishSignin(url, data);
191
+ }
192
+
193
+ function finishSignin(url, data) {
194
+ config.save({ url, token: data.token, expiresAt: data.expiresAt, email: data.email });
195
+ // Post-signin is the first thing a new user sees, so it gets the same
196
+ // treatment as the REPL: a real welcome card with what to do next. Piped
197
+ // output still gets a complete one-line summary.
198
+ const lines = [`${ui.c.success(ui.GLYPH.tick)} signed in as ${ui.c.bold(ui.c.primary(data.email || "your account"))}`];
199
+ lines.push(`${ui.c.muted("backend")} ${ui.c.primary(url)}`);
200
+ if (data.balance !== undefined) lines.push(`${ui.c.muted("balance")} ${ui.c.primary(`${data.balance} tokens`)}`);
201
+ if (data.expiresAt) lines.push(`${ui.c.muted("expires")} ${ui.c.muted(data.expiresAt)}`);
202
+ const w = ui.width();
203
+ const bar = `${ui.c.primary(ui.GLYPH.bar)} `;
204
+ const note = ui.bullets([
205
+ `${ui.c.bold("bolt")} opens the interactive session`,
206
+ `${ui.c.bold("bolt signin")} again to switch account`,
207
+ ])
208
+ .split("\n")
209
+ .join(`\n ${bar}`);
210
+ console.log("");
211
+ console.log(bar + ui.box({ title: "bolt", lines, w: w - 2 }));
212
+ console.log(` ${bar}${note}`);
213
+ console.log("");
214
+ }
215
+
216
+ /**
217
+ * Opencode-style entry: a missing token signs you in instead of stopping
218
+ * you. On an interactive terminal the browser flow starts automatically and
219
+ * the command continues once it completes; without a TTY (pipes, CI) there
220
+ * is nothing to open, so it stays an error telling you exactly what to run.
221
+ */
222
+ async function ensureAuth() {
223
+ const cfg = config.load();
224
+ if (cfg.token) return cfg;
225
+ if (!process.stdin.isTTY) throw new Error("Not logged in. Run: bolt login");
226
+ console.log("You're not signed in yet — opening the browser to sign you in.");
227
+ await cmdSignin([]);
228
+ const next = config.load();
229
+ if (!next.token) throw new Error("Sign-in did not complete. Run: bolt login");
230
+ return next;
231
+ }
232
+
233
+ async function cmdAuth(rest) {
234
+ // `bolt auth --url <app>` with no verb is treated as `auth login` rather than
235
+ // failing on an unknown subcommand.
236
+ const first = rest[0] && !rest[0].startsWith("-") ? rest[0] : "login";
237
+ if (first === "login") {
238
+ // `auth login` is the same browser flow as `signin`. There is no
239
+ // password path: a typed password is shell history and process-list
240
+ // visible, and the device hand-off needs none of it.
241
+ return cmdSignin(rest.filter((value) => value !== "login"));
242
+ }
243
+ if (first === "logout") {
244
+ config.clear();
245
+ console.log("Logged out (local token removed).");
246
+ return;
247
+ }
248
+ if (first !== "status") throw new Error(`Unknown auth command "${first}". Use: bolt auth status | login | logout`);
249
+ const cfg = config.load();
250
+ if (cfg.token) console.log(`Logged in to ${cfg.url}${cfg.expiresAt ? ` (expires ${cfg.expiresAt})` : ""}.`);
251
+ else console.log(`Not logged in. Run: bolt login`);
252
+ }
253
+
254
+ async function cmdBalance() {
255
+ const cfg = await ensureAuth();
256
+ const stats = await api.getStats(cfg.url, cfg.token);
257
+ console.log(`Balance: ${stats.balance} tokens | investigations this month: ${stats.prompts} | spent: ${stats.tokensSpent}`);
258
+ }
259
+
260
+ async function cmdSession(rest) {
261
+ const sub = rest[0] || "list";
262
+ if (sub === "list") {
263
+ const all = session.list();
264
+ if (!all.length) {
265
+ console.log("No sessions yet. bolt run starts one; bolt run -c continues the latest.");
266
+ return;
267
+ }
268
+ for (const s of all) console.log(`${s.id} ${s.turns} turn${s.turns === 1 ? "" : "s"} ${s.title}`);
269
+ return;
270
+ }
271
+ if (sub === "new") {
272
+ const s = session.create(rest.slice(1).join(" ") || "untitled");
273
+ console.log(`New session ${s.id}`);
274
+ return;
275
+ }
276
+ if (sub === "show") {
277
+ const id = rest[1] || "";
278
+ const s = id ? session.load(id) : null;
279
+ if (!s) throw new Error("Usage: bolt session show <id>");
280
+ for (const [i, t] of s.turns.entries()) {
281
+ console.log(`\n--- turn ${i + 1} [${t.mode}] ${t.at} ---\nQ: ${t.prompt}\nA: ${t.response.slice(0, 2000)}`);
282
+ if (t.tools && t.tools.length) {
283
+ console.log(`tools: ${t.tools.map((tool) => `${tool.tool}${tool.ok === false ? " (failed)" : ""}`).join(", ")}`);
284
+ }
285
+ if (t.redacted > 0) {
286
+ console.log(`scrubbed ${t.redacted} possible secret${t.redacted === 1 ? "" : "s"} from this turn before storing`);
287
+ }
288
+ }
289
+ if (!s.turns.length) console.log(`Session ${s.id} has no turns yet.`);
290
+ return;
291
+ }
292
+ if (sub === "delete") {
293
+ const id = rest[1] || "";
294
+ if (!id || !session.remove(id)) throw new Error("Usage: bolt session delete <id>");
295
+ console.log(`Deleted ${id}.`);
296
+ return;
297
+ }
298
+ throw new Error(`Unknown session command "${sub}". Use: list | show <id> | delete <id> | new`);
299
+ }
300
+
301
+ // Sentinel watch mode: background defensive checks on the operator's own
302
+ // machine. `bolt watch check` runs one pass (cron-friendly: exit 2 when a
303
+ // high/critical incident is present), `bolt watch start` detaches the daemon,
304
+ // `stop` ends it. Checks are deterministic and read-only; AI triage fires
305
+ // only for new high/critical incidents (capped per day); responses only run
306
+ // from playbooks the operator explicitly authorized.
307
+ async function cmdWatch(rest, opts = {}) {
308
+ const [subRaw, ...args] = rest;
309
+ const sub = String(subRaw || "status").toLowerCase();
310
+ if (sub === "status") return watchStatusCmd();
311
+ if (sub === "check") return watchCheckCmd({ triage: !flag(rest, "--no-triage"), report: !flag(rest, "--no-report"), setExitCode: opts.setExitCode !== false });
312
+ if (sub === "start") return watchStartCmd(args);
313
+ if (sub === "stop") return watchStopCmd();
314
+ if (sub === "events") return watchEventsCmd(args);
315
+ if (sub === "policy") return watchPolicyCmd(args);
316
+ if (sub === "playbook") return watchPlaybookCmd(args);
317
+ if (sub === "baseline") return watchBaselineCmd(args);
318
+ if (sub === "respond") return watchRespondCmd(args);
319
+ if (sub === "_daemon") return watchDaemonLoop(Math.min(3600, Math.max(60, Number(args[0]) || 300)));
320
+ throw new Error(`Unknown watch command "${subRaw}". ${help("watch").split("\n")[0]}`);
321
+ }
322
+
323
+ function watchStatusLines() {
324
+ const policy = watch.loadPolicy();
325
+ const pid = watch.readPid();
326
+ const events = watch.readEvents(null, 200);
327
+ const today = new Date().toISOString().slice(0, 10);
328
+ const todays = events.filter((e) => String(e.at || "").startsWith(today));
329
+ const highs = todays.filter((e) => e.severity === "high" || e.severity === "critical").length;
330
+ const triaged = todays.filter((e) => e.triaged).length;
331
+ const last = events.length ? events[events.length - 1] : null;
332
+ const signals = Object.entries(policy.signals || {}).filter(([, on]) => on).map(([name]) => name);
333
+ const lines = [
334
+ `${ui.c.muted("watch")} ${policy.enabled ? ui.c.success("on") : ui.c.muted("off")} ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted("daemon")} ${pid ? ui.c.success(`running (pid ${pid})`) : ui.c.muted("stopped")}`,
335
+ `${ui.c.muted("interval")} ${policy.intervalSec}s ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted("signals")} ${signals.length ? signals.join(", ") : "(none)"}`,
336
+ `${ui.c.muted("today")} ${todays.length} event${todays.length === 1 ? "" : "s"} (${highs} high/critical) ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted("triaged")} ${triaged}/${policy.triage.maxPerDay}`,
337
+ ];
338
+ if (last) lines.push(`${ui.c.muted("last")} ${ui.c.primary(last.title || last.signal || "event")} ${ui.c.muted(ui.relTime(last.at))}`);
339
+ const playbooks = watch.playbookStatus(policy).filter((p) => p.mode === "allow").map((p) => p.name);
340
+ lines.push(`${ui.c.muted("auto-response")} ${playbooks.length ? ui.c.warning(playbooks.join(", ")) : ui.c.muted("none — alerts only")}`);
341
+ lines.push(`${ui.c.muted("limits")} log + config watch only — not EDR/AV, not a SOC`);
342
+ return lines;
343
+ }
344
+
345
+ function watchStatusCmd() {
346
+ console.log("");
347
+ console.log(ui.box({ title: "watch", w: ui.width(), lines: watchStatusLines() }));
348
+ console.log("");
349
+ }
350
+
351
+ function watchEventsCmd(args) {
352
+ const n = Math.min(100, Math.max(1, Number(args[0]) || 20));
353
+ const events = watch.readEvents(null, n);
354
+ if (!events.length) {
355
+ ui.info("no watch events yet — run: bolt watch check");
356
+ return;
357
+ }
358
+ for (const e of events) {
359
+ const sev = e.severity === "critical" ? ui.c.error("CRIT") : e.severity === "high" ? ui.c.warning("HIGH") : ui.c.muted("info");
360
+ console.log(` ${sev} ${ui.c.primary(e.title || e.signal || "event")} ${ui.c.muted(ui.relTime(e.at))}${e.triaged ? ` ${ui.c.accent("triaged")}` : ""}`);
361
+ if (e.detail) console.log(` ${ui.c.muted(String(e.detail).slice(0, 220))}`);
362
+ }
363
+ }
364
+
365
+ // One full pass: check, record, triage, auto-respond (allow-listed only),
366
+ // report. Returns { incidents, highs, disabled } for the daemon loop.
367
+ // Exit codes are cron-shaped: 2 = high/critical present, 0 = clean.
368
+ async function watchCheckCmd({ triage = true, report = true, quiet = false, setExitCode = true } = {}) {
369
+ const policy = watch.loadPolicy();
370
+ if (!policy.enabled) {
371
+ if (!quiet) ui.info("watch is disabled — enable with: bolt watch policy enable");
372
+ return { incidents: [], highs: 0, disabled: false };
373
+ }
374
+ const baseline = watch.loadBaseline();
375
+ const { results, incidents, baselinePatch } = watch.runChecks(policy, baseline, watch.defaultIo());
376
+ watch.saveBaseline({ ...baseline, ...baselinePatch });
377
+ if (!quiet) {
378
+ for (const r of results) {
379
+ const mark = r.available === false ? ui.c.muted("n/a") : r.ok ? ui.c.success("ok") : ui.c.warning("!");
380
+ console.log(` ${mark} ${ui.c.muted(r.signal)} ${r.summary}`);
381
+ }
382
+ }
383
+ for (const inc of incidents) watch.appendEvent(null, { ...inc, triaged: false });
384
+ const highs = incidents.filter((i) => i.severity === "high" || i.severity === "critical");
385
+ if (!quiet) {
386
+ if (!incidents.length) ui.ok("clean — no incidents");
387
+ else ui.warn(`${incidents.length} incident${incidents.length === 1 ? "" : "s"} (${highs.length} high/critical)`);
388
+ }
389
+
390
+ // AI triage: new high/critical incidents only, capped per day. Triage is a
391
+ // normal defensive run tagged source=watch, so server quota applies on top.
392
+ const triagedTexts = new Map();
393
+ if (triage && highs.length) {
394
+ const today = new Date().toISOString().slice(0, 10);
395
+ const used = watch.readEvents(null, 500).filter((e) => String(e.at || "").startsWith(today) && e.triaged).length;
396
+ let remaining = Math.max(0, (policy.triage.maxPerDay || 3) - used);
397
+ const cfg = config.load();
398
+ for (const inc of highs) {
399
+ if (!policy.triage.severities.includes(inc.severity)) continue;
400
+ if (remaining <= 0) {
401
+ if (!quiet) ui.info(`triage cap reached (${policy.triage.maxPerDay}/day) — incident recorded, not sent`);
402
+ continue;
403
+ }
404
+ if (!cfg.token) {
405
+ if (!quiet) ui.info("not signed in — incident recorded locally (bolt login enables triage + alerts)");
406
+ continue;
407
+ }
408
+ remaining -= 1;
409
+ const out = await watchTriageIncident(cfg, inc);
410
+ triagedTexts.set(inc.fingerprint, out.text);
411
+ watch.appendEvent(null, { ...inc, triaged: out.ok, triageChars: out.text.length });
412
+ if (!quiet && out.ok) {
413
+ console.log("");
414
+ console.log(ui.box({ title: `triage · ${inc.fingerprint}`, w: ui.width(), lines: [out.text.slice(0, 3000)] }));
415
+ console.log("");
416
+ }
417
+ if (!quiet && !out.ok) ui.warn(`triage failed: ${out.text.slice(0, 200)}`);
418
+ }
419
+ }
420
+
421
+ // Automated response, narrowly scoped: only blockIp auto-fires, only from
422
+ // auth-burst incidents, only when explicitly allowed, IP parsed from the
423
+ // recorded detail. Everything else is alert-only, always.
424
+ const actions = [];
425
+ if (policy.playbooks.blockIp === "allow") {
426
+ for (const inc of highs) {
427
+ if (inc.signal !== "auth") continue;
428
+ const ip = (String(inc.detail || "").match(/(\d{1,3}(?:\.\d{1,3}){3})/) || [])[1] || "";
429
+ if (!ip) continue;
430
+ const res = watch.runPlaybook("blockIp", ip);
431
+ actions.push({ playbook: "blockIp", arg: ip, ok: res.ok, at: new Date().toISOString() });
432
+ watch.appendEvent(null, { severity: res.ok ? "high" : "info", signal: "action", title: `auto blockIp ${ip}: ${res.summary}`, detail: res.detail, fingerprint: `action:blockIp:${ip}`, triaged: false });
433
+ if (!quiet) (res.ok ? ui.ok : ui.warn)(`auto-response blockIp ${ip}: ${res.summary}`);
434
+ }
435
+ }
436
+
437
+ let disabled = false;
438
+ if (report) {
439
+ const cfg = config.load();
440
+ if (!cfg.token) {
441
+ if (!quiet) ui.info("not signed in — skipping phone-home (bolt login enables email + in-account alerts)");
442
+ } else if (policy.phoneHome) {
443
+ try {
444
+ const res = await reportWatch(cfg, policy, results, incidents, triagedTexts, actions);
445
+ disabled = res.disabled === true;
446
+ if (disabled && !quiet) ui.warn("this host was disabled server-side — stopping (re-enable in your account)");
447
+ } catch (error) {
448
+ if (!quiet) ui.warn(`phone-home failed (kept locally): ${error && error.message ? error.message : error}`);
449
+ }
450
+ }
451
+ }
452
+ process.exitCode = setExitCode ? (highs.length ? 2 : 0) : process.exitCode;
453
+ return { incidents, highs: highs.length, disabled };
454
+ }
455
+
456
+ async function watchTriageIncident(cfg, incident) {
457
+ const host = os.hostname();
458
+ const objective = `Sentinel watch triage on ${host}: ${incident.title}`;
459
+ const evidence = `Signal: ${incident.signal}\nObserved: ${incident.at}\nHost: ${host} (${process.platform})\nFingerprint: ${incident.fingerprint}\nDetail: ${incident.detail}\n\nDecide: likely benign, suspicious, or likely compromise? State confidence, the two most discriminating next READ-ONLY checks, and whether the operator should escalate now. Recommend no destructive action.`;
460
+ const clean = redact.redact(evidence);
461
+ const prompt = api.buildPrompt({ objective, evidence: clean.text, mode: "defensive" });
462
+ const stream = ui.createStream(ui.errWrite);
463
+ // Machine syntax that a drifted model emits (tool blocks, XML tags, think
464
+ // reasoning) must never reach the operator's screen, even in triage.
465
+ const filtered = agent.toolFenceWriter((t) => stream.write(t));
466
+ let text = "";
467
+ try {
468
+ await api.streamGenerate({ url: cfg.url, token: cfg.token, prompt, mode: "defensive", source: "watch", onToken: (t) => { text += t; filtered.write(t); } });
469
+ filtered.end();
470
+ stream.end();
471
+ return { ok: true, text: redact.redact(text).text };
472
+ } catch (error) {
473
+ try {
474
+ stream.end();
475
+ } catch {
476
+ // never lose the original error to teardown
477
+ }
478
+ const message = error && error.message ? error.message : String(error);
479
+ return { ok: false, text: message };
480
+ }
481
+ }
482
+
483
+ async function reportWatch(cfg, policy, results, incidents, triagedTexts, actions) {
484
+ const scrub = (s) => redact.redact(String(s || "")).text;
485
+ const payload = {
486
+ host: { id: watch.hostId(), name: os.hostname(), os: process.platform },
487
+ policyVersion: watch.POLICY_VERSION,
488
+ intervalSec: policy.intervalSec,
489
+ results: results.map((r) => ({ signal: r.signal, ok: r.ok, available: r.available !== false, summary: scrub(r.summary).slice(0, 500) })),
490
+ incidents: incidents.map((i) => ({
491
+ fingerprint: i.fingerprint,
492
+ severity: i.severity,
493
+ signal: i.signal,
494
+ title: scrub(i.title).slice(0, 200),
495
+ detail: scrub(i.detail).slice(0, 2000),
496
+ at: i.at,
497
+ triage: triagedTexts.has(i.fingerprint) ? scrub(triagedTexts.get(i.fingerprint)).slice(0, 4000) : null,
498
+ })),
499
+ actions: (actions || []).map((a) => ({ playbook: a.playbook, arg: scrub(a.arg).slice(0, 120), ok: a.ok, at: a.at })),
500
+ };
501
+ const res = await fetch(`${cfg.url.replace(/\/$/, "")}/api/bolt/watch/report`, {
502
+ method: "POST",
503
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${cfg.token}` },
504
+ body: JSON.stringify(payload),
505
+ });
506
+ const data = await res.json().catch(() => ({}));
507
+ if (!res.ok) throw new Error(data.error || `Report failed (HTTP ${res.status}).`);
508
+ return data;
509
+ }
510
+
511
+ async function watchStartCmd(args) {
512
+ const alive = watch.readPid();
513
+ if (alive) {
514
+ ui.ok(`watch daemon already running (pid ${alive})`);
515
+ return;
516
+ }
517
+ let intervalSec = watch.loadPolicy().intervalSec;
518
+ const at = args.indexOf("--interval");
519
+ if (at !== -1 && args[at + 1]) intervalSec = Math.min(3600, Math.max(60, Number(args[at + 1]) || intervalSec));
520
+ const child = spawn(process.execPath, [path.join(__dirname, "..", "bin", "bolt.js"), "watch", "_daemon", String(intervalSec)], {
521
+ detached: true,
522
+ stdio: "ignore",
523
+ windowsHide: true,
524
+ });
525
+ child.unref();
526
+ if (!child.pid) throw new Error("Could not start the daemon.");
527
+ watch.writePid(null, child.pid);
528
+ watch.logLine(null, `daemon started (pid ${child.pid}, interval ${intervalSec}s)`);
529
+ ui.ok(`watch daemon started (pid ${child.pid}, every ${intervalSec}s) — stop with: bolt watch stop`);
530
+ }
531
+
532
+ function watchStopCmd() {
533
+ const pid = watch.readPid();
534
+ if (!pid) {
535
+ watch.clearPid(null);
536
+ ui.info("watch daemon is not running");
537
+ return;
538
+ }
539
+ try {
540
+ process.kill(pid, "SIGTERM");
541
+ } catch {
542
+ // Already gone; clear the stale pid either way.
543
+ }
544
+ watch.clearPid(null);
545
+ watch.logLine(null, `daemon stopped (was pid ${pid})`);
546
+ ui.ok("watch daemon stopped");
547
+ }
548
+
549
+ async function watchDaemonLoop(intervalSec) {
550
+ watch.logLine(null, `daemon loop started (interval ${intervalSec}s)`);
551
+ for (;;) {
552
+ try {
553
+ const out = await watchCheckCmd({ triage: true, report: true, quiet: true });
554
+ if (out && out.disabled) {
555
+ watch.logLine(null, "disabled server-side — daemon exiting");
556
+ break;
557
+ }
558
+ } catch (error) {
559
+ watch.logLine(null, `check failed: ${error && error.message ? error.message : error}`);
560
+ }
561
+ await new Promise((resolve) => setTimeout(resolve, intervalSec * 1000));
562
+ }
563
+ watch.clearPid(null);
564
+ }
565
+
566
+ function watchPolicyCmd(args) {
567
+ const policy = watch.loadPolicy();
568
+ const [field, ...rest] = args;
569
+ if (!field || field === "show") {
570
+ console.log("");
571
+ console.log(ui.box({
572
+ title: "watch policy",
573
+ w: ui.width(),
574
+ lines: [
575
+ `${ui.c.muted("enabled")} ${policy.enabled ? ui.c.success("yes") : ui.c.muted("no")} ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted("interval")} ${policy.intervalSec}s ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted("phone-home")} ${policy.phoneHome ? "yes" : "no"}`,
576
+ `${ui.c.muted("signals")} ${Object.entries(policy.signals).map(([k, on]) => `${k}:${on ? ui.c.success("on") : ui.c.muted("off")}`).join(" ")}`,
577
+ `${ui.c.muted("thresholds")} auth ≥${policy.thresholds.authFails}/${policy.thresholds.authWindowMin}min · load >${policy.thresholds.loadMult}x · disk ≥${policy.thresholds.diskPct}% · mem ≥${policy.thresholds.memPct}%`,
578
+ `${ui.c.muted("triage")} ${policy.triage.enabled ? `${policy.triage.maxPerDay}/day, ${policy.triage.severities.join("+")}` : "off"} ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted("playbooks")} ${Object.entries(policy.playbooks).map(([k, v]) => `${k}:${v === "allow" ? ui.c.warning("allow") : "off"}`).join(" ")}`,
579
+ `${ui.c.muted("watching")} ${policy.watchPaths.length} paths · ${ui.c.muted("logs")} ${policy.authLogPaths.length} candidates`,
580
+ ],
581
+ }));
582
+ console.log("");
583
+ ui.info("change with: policy <enable|disable|signal|threshold|interval|triage|phonehome> …");
584
+ return;
585
+ }
586
+ if (field === "enable" || field === "disable") {
587
+ policy.enabled = field === "enable";
588
+ } else if (field === "signal" && rest.length >= 2) {
589
+ const [name, mode] = rest;
590
+ if (!Object.hasOwn(policy.signals, name)) throw new Error(`Unknown signal "${name}". Signals: ${Object.keys(policy.signals).join(", ")}`);
591
+ policy.signals[name] = mode === "on";
592
+ } else if (field === "threshold" && rest.length >= 2) {
593
+ const [name, value] = rest;
594
+ if (!Object.hasOwn(policy.thresholds, name)) throw new Error(`Unknown threshold "${name}". Thresholds: ${Object.keys(policy.thresholds).join(", ")}`);
595
+ const n = Number(value);
596
+ if (!Number.isFinite(n) || n <= 0) throw new Error(`Threshold "${name}" needs a positive number.`);
597
+ policy.thresholds[name] = n;
598
+ } else if (field === "interval" && rest[0]) {
599
+ policy.intervalSec = Math.min(3600, Math.max(60, Number(rest[0]) || policy.intervalSec));
600
+ } else if (field === "triage" && rest[0]) {
601
+ if (rest[0] === "off") policy.triage.enabled = false;
602
+ else {
603
+ policy.triage.enabled = true;
604
+ policy.triage.maxPerDay = Math.min(50, Math.max(1, Number(rest[0]) || policy.triage.maxPerDay));
605
+ }
606
+ } else if (field === "phonehome" && rest[0]) {
607
+ policy.phoneHome = rest[0] === "on";
608
+ } else {
609
+ throw new Error("Usage: bolt watch policy [show|enable|disable|signal <name> <on|off>|threshold <name> <n>|interval <sec>|triage <n|off>|phonehome <on|off>]");
610
+ }
611
+ watch.savePolicy(null, policy);
612
+ ui.ok("watch policy saved");
613
+ }
614
+
615
+ function watchPlaybookCmd(args) {
616
+ const policy = watch.loadPolicy();
617
+ const [name, mode] = args;
618
+ if (!name || name === "list") {
619
+ for (const row of watch.playbookStatus(policy)) {
620
+ console.log(` ${ui.c.primary(ui.c.bold(row.name))} ${row.mode === "allow" ? ui.c.warning("allow") : ui.c.muted("off")} ${ui.c.muted(row.desc)}`);
621
+ }
622
+ ui.info("authorize with: bolt watch playbook <name> allow — the daemon may then run it; revoke with: off");
623
+ return;
624
+ }
625
+ if (!watch.PLAYBOOKS[name]) throw new Error(`Unknown playbook "${name}". Playbooks: ${Object.keys(watch.PLAYBOOKS).join(", ")}`);
626
+ if (mode !== "allow" && mode !== "off") throw new Error(`Usage: bolt watch playbook ${name} <allow|off>`);
627
+ policy.playbooks[name] = mode;
628
+ watch.savePolicy(null, policy);
629
+ if (mode === "allow") ui.warn(`playbook "${name}" authorized — scan the usage first: ${watch.PLAYBOOKS[name].usage}. Only blockIp fires automatically (auth bursts); the rest run via: bolt watch respond ${name} <arg>`);
630
+ else ui.ok(`playbook "${name}" revoked`);
631
+ }
632
+
633
+ function watchBaselineCmd(args) {
634
+ if (args[0] === "reset") {
635
+ try {
636
+ fs.unlinkSync(watch.paths(null).baseline);
637
+ } catch {
638
+ // no baseline to clear
639
+ }
640
+ ui.ok("baseline cleared — next check re-establishes it (no findings on first pass)");
641
+ return;
642
+ }
643
+ const baseline = watch.loadBaseline();
644
+ const ports = Array.isArray(baseline.ports) ? baseline.ports : [];
645
+ const files = baseline.files && typeof baseline.files === "object" ? Object.keys(baseline.files) : [];
646
+ console.log(`${ui.c.muted("baseline")} ${baseline.updatedAt ? ui.relTime(baseline.updatedAt) : "(none yet)"} ${ui.c.muted(ui.GLYPH.dot)} ${ports.length} ports ${ui.c.muted(ui.GLYPH.dot)} ${files.length} files`);
647
+ if (ports.length) console.log(` ${ui.c.muted("ports")} ${ports.join(", ")}`);
648
+ }
649
+
650
+ // Explicit, operator-typed response: `bolt watch respond blockIp 1.2.3.4`.
651
+ // The playbook must already be authorized in policy (nothing runs on a bare
652
+ // typed command alone); the run is logged locally like any daemon action.
653
+ async function watchRespondCmd(args) {
654
+ const [name, arg] = args;
655
+ if (!name || !watch.PLAYBOOKS[name]) throw new Error(`Usage: bolt watch respond <${Object.keys(watch.PLAYBOOKS).join("|")}> <arg>`);
656
+ const policy = watch.loadPolicy();
657
+ if (policy.playbooks[name] !== "allow") throw new Error(`playbook "${name}" is not authorized — run first: bolt watch playbook ${name} allow`);
658
+ const res = watch.runPlaybook(name, arg);
659
+ watch.appendEvent(null, { severity: res.ok ? "high" : "info", signal: "action", title: `manual ${name} ${arg}: ${res.summary}`, detail: res.detail, fingerprint: `action:${name}:${Date.now()}`, triaged: false });
660
+ (res.ok ? ui.ok : ui.warn)(`${name} ${arg || ""}: ${res.summary}`);
661
+ if (!res.ok) ui.info(res.detail);
662
+ }
663
+
664
+ // REPL forgiveness: operators typing a shell habit ("bolt list") into the
665
+ // only when the rest starts with a known command word, so prose like "bolt
666
+ // cutters" is never mangled. Pure, tested.
667
+ function stripBoltPrefix(input) {
668
+ const m = String(input || "").match(/^bolt\s+(\S+)([\s\S]*)$/i);
669
+ if (!m) return { task: String(input || ""), stripped: false };
670
+ if (!/^(list|read|glob|grep|run|build|help|version|doctor)$/i.test(m[1])) {
671
+ return { task: String(input || ""), stripped: false };
672
+ }
673
+ return { task: `${m[1]}${m[2] || ""}`.trim(), stripped: true };
674
+ }
675
+
676
+ function positionalPrompt(rest) {
677
+ const skipValues = new Set(["--target", "-t", "--mode", "-m", "--agent", "--file", "-f", "--evidence", "--session", "-s", "--title", "--out", "-o", "--max-iters", "--format", "--output", "--budget", "--url"]);
678
+ return rest
679
+ .filter((a, i) => !a.startsWith("-") && !skipValues.has(rest[i - 1]))
680
+ .join(" ")
681
+ .trim();
682
+ }
683
+
684
+ // Agents: opencode-style presets, explicit opt-in. Arming one wraps the next
685
+ // objective with its template client-side; unarmed runs stay verbatim.
686
+ const AGENTS = {
687
+ sweep: {
688
+ desc: "subdomain enumeration via CT logs",
689
+ needsTarget: true,
690
+ make: (t, o) => `Enumerate subdomains of ${t} using certificate-transparency logs. List up to 150 hosts, one per line under FINDINGS as LOCATION entries, then a NOTES line with the CT caveat (only cert-issued hosts appear). Target: ${t}${o ? `\n\nOperator focus: ${o}` : ""}`,
691
+ },
692
+ probe: {
693
+ desc: "probe hosts, report HTTP 200s only",
694
+ needsTarget: false,
695
+ make: (t, o) => `Probe each host${t ? ` for ${t}` : " in the evidence"} with an https GET. Report ONLY hosts that return HTTP 200, one FINDINGS block each with LOCATION, EVIDENCE (status line), and NEXT. Others go in NOTES as one line.${o ? `\n\nOperator focus: ${o}` : ""}`,
696
+ },
697
+ build: {
698
+ desc: "build a complete runnable tool (nmap NSE, script, exploit)",
699
+ needsTarget: true,
700
+ make: (t, o) => `Build a complete runnable tool for ${t || "the target below"}: ${o || "an nmap NSE script to detect exposed admin login pages"}. Provide the full file(s), exact run commands, safe validation, expected output, cleanup, and stop conditions.`,
701
+ },
702
+ plan: {
703
+ desc: "authorized test plan with phases and stop conditions",
704
+ needsTarget: false,
705
+ make: (t, o) => `Write an authorized penetration test plan for ${t || "the target below"}. State in-scope assets, authorization boundary, prerequisites, test phases in order, non-destructive validation steps, evidence to capture, and stop conditions.${o ? `\n\nOperator focus: ${o}` : ""}`,
706
+ },
707
+ validate: {
708
+ desc: "prove or disprove a finding, least invasive test",
709
+ needsTarget: false,
710
+ make: (t, o) => `Prove or disprove the finding in the evidence against ${t || "the target"} with the least invasive test possible. Exact reproduction steps, request or command, impact confirmation, cleanup, and what to do if production could be affected.${o ? `\n\nFinding: ${o}` : ""}`,
711
+ },
712
+ triage: {
713
+ desc: "defensive alert triage (facts vs hypotheses)",
714
+ needsTarget: false,
715
+ make: (t, o) => `Triage the following. Separate observed facts from hypotheses with confidence, identify the most likely chain, list missing telemetry, and recommend three reversible next actions. Do not assume compromise without evidence.\n\n${o}`,
716
+ },
717
+ };
718
+
719
+ function applyAgent(name, objective, target) {
720
+ const agent = AGENTS[name];
721
+ if (!agent) throw new Error(`Unknown agent "${name}". Available: ${Object.keys(AGENTS).join(", ")}.`);
722
+ if (agent.needsTarget && !target) throw new Error(`Agent "${name}" needs --target <domain>.`);
723
+ return agent.make(target, objective);
724
+ }
725
+
726
+ const COMMANDS = [
727
+ ["/help", "commands, grouped (try /help <cmd>)"],
728
+ ["/status", "session dashboard: mode, tools, tokens"],
729
+ ["/sessions", "pick a saved session to resume"],
730
+ ["/keys", "keyboard shortcuts cheat sheet"],
731
+ ["/agents", "list task agents"],
732
+ ["/agent <name>", "arm an agent for the next prompt"],
733
+ ["/tools [on|off]", "local tools: read, list, search, edit, shell"],
734
+ ["/allow-all", "approve every tool call without asking (dangerous)"],
735
+ ["/permissions", "list always-allowed tools (revoke, clear)"],
736
+ ["/init", "explore this project and write BOLT.md"],
737
+ ["/resume [id]", "resume a saved session"],
738
+ ["/retry", "re-run the last prompt"],
739
+ ["/export [md|json|sarif]", "export this session to a file"],
740
+ ["/undo <path>", "restore last agent backup of a file"],
741
+ ["/templates [name]", "print lab runbooks (ASLR probe, crash offsets)"],
742
+ ["/doctor", "pre-flight checks (node, auth, backend)"],
743
+ ["/watch", "background sentinel status"],
744
+ ["/models", "show the backend (Bolt only)"],
745
+ ["/mode <m>", "offensive or defensive"],
746
+ ["/target <d>", "set in-scope target"],
747
+ ["/file <path>", "attach file as evidence"],
748
+ ["/clear", "clear attachments + disarm agent"],
749
+ ["/session [new|<id>]", "show, reset, or resume session"],
750
+ ["/copy", "copy last answer to clipboard"],
751
+ ["/balance", "token balance"],
752
+ ["/exit", "save session and quit"],
753
+ ];
754
+
755
+ // Slash commands that run with no further input. Picking one from the live
756
+ // palette executes it at once; entries with <args> or [args] only fill the
757
+ // prompt line so the operator can complete them.
758
+ const NO_ARG_COMMANDS = new Set(["/help", "/commands", "/status", "/sessions", "/keys", "/agents", "/models", "/balance", "/clear", "/exit", "/copy", "/allow-all", "/permissions", "/retry", "/doctor", "/watch", "/templates"]);
759
+
760
+ function isPaletteRunnable(label) {
761
+ if (!label || !label.startsWith("/")) return false;
762
+ if (label.startsWith("/agent ") && label.trim() !== "/agent <name>") return true;
763
+ if (/[<[].*[\]>]/.test(label)) return false;
764
+ return NO_ARG_COMMANDS.has(label.split(" ")[0]);
765
+ }
766
+
767
+ // Detects secret shapes in an argv-sourced prompt. Argv is visible in the
768
+ // process list (ps) and lands in shell history, so unlike piped stdin it
769
+ // exposes secrets to every other user on the machine - on a shared box or a
770
+ // CI runner with log collection, that is a disclosure. Returns warning text
771
+ // or "". The prompt is still scrubbed before sending either way.
772
+ function argvSecretWarning(positional) {
773
+ const text = String(positional || "");
774
+ if (!text.trim()) return "";
775
+ const hit = redact.redact(text);
776
+ if (hit.count === 0) return "";
777
+ return `your prompt looks like it contains a secret (${hit.count} match${hit.count === 1 ? "" : "es"}) - argv is visible in shell history and the process list. Pipe via stdin or use --file / @-mentions to keep it out of both. It was still scrubbed before sending.`;
778
+ }
779
+
780
+ function readEvidence(rest) {
781
+ const files = [...argAll(rest, "--file", "-f"), ...argAll(rest, "--evidence")];
782
+ const parts = [];
783
+ for (const f of files) {
784
+ const content = fs.readFileSync(f, "utf8").slice(0, 12000);
785
+ parts.push(`--- ${path.basename(f)} ---\n${content}`);
786
+ }
787
+ return parts.join("\n\n");
788
+ }
789
+
790
+ // Approval asker for tool calls, Claude Code / opencode style: an arrow-key
791
+ // dropdown with Allow once / Always allow / Deny. Elevated commands (sudo,
792
+ // system installs, service control) render a shield card explaining why they
793
+ // need admin. A throwaway readline is used for the text fallback only (never
794
+ // the REPL's own, which stays paused for the turn). Without a TTY there is
795
+ // nothing to ask, so the caller gets null and mutations are denied.
796
+ // Installer commands always get the explicit install prompt and never a
797
+ // silent approval - each install needs its own yes.
798
+ function makeAsker() {
799
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
800
+ const readline = require("node:readline/promises");
801
+ const canPick = () => ui.selectable([{ label: "x" }]);
802
+ return async (call) => {
803
+ const install = call && call.tool === "bash" ? bootstrap.isInstallCommand(call.command) : null;
804
+ const elevated = call && call.tool === "bash" ? permissions.isElevatedCommand(call.command) : false;
805
+ const reason = elevated && !install ? permissions.elevationReason(call.command) : "";
806
+ const label = tools.describeCall(call);
807
+
808
+ // Card header: what wants to run, and why it is sensitive.
809
+ if (install) {
810
+ console.log(` ${ui.c.warning("!")} ${ui.c.bold(`Install ${install.tool} via ${install.manager}?`)}`);
811
+ console.log(ui.c.muted(` ${install.installCmd}`));
812
+ console.log(ui.c.muted(" installs always ask - each one needs its own yes."));
813
+ } else if (elevated) {
814
+ console.log(` ${ui.c.warning("!")} ${ui.c.bold(label)}`);
815
+ console.log(` ${ui.c.warning("needs elevated privileges")} ${ui.c.muted(`- ${reason}`)}`);
816
+ if (call.command) console.log(ui.c.muted(` $ ${call.command.slice(0, 300)}`));
817
+ } else {
818
+ console.log(` ${ui.c.accent("?")} ${ui.c.bold(label)}`);
819
+ if (call.tool === "write" && call.content) {
820
+ const preview = String(call.content).split("\n").slice(0, 8).join("\n");
821
+ console.log(ui.c.muted(` ${preview.split("\n").length >= 8 ? `${preview}\n …` : preview}`));
822
+ }
823
+ if (call.tool === "edit" && call.oldString) {
824
+ console.log(ui.c.muted(` - ${String(call.oldString).split("\n").slice(0, 4).join("\n - ").slice(0, 400)}`));
825
+ console.log(ui.c.muted(` + ${String(call.newString || "").split("\n").slice(0, 4).join("\n + ").slice(0, 400)}`));
826
+ }
827
+ }
828
+
829
+ // Arrow-key dropdown first (industrial standard), text fallback when raw
830
+ // mode is unavailable (dumb terminals, VS Code without setRawMode).
831
+ if (canPick()) {
832
+ const title = install
833
+ ? `install ${install.tool}`
834
+ : elevated ? "elevated command - approve?" : "allow this action?";
835
+ const items = ui.permissionItems({ elevated: Boolean(elevated), install: Boolean(install) });
836
+ const decision = await ui.selectPermission({ title, items });
837
+ return decision;
838
+ }
839
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
840
+ try {
841
+ if (install) {
842
+ const answer = (await rl.question(` ${ui.c.accent("?")} ${bootstrap.installPromptText(install.tool, install.manager)} `)).trim().toLowerCase();
843
+ if (answer === "y" || answer === "yes") return "allow";
844
+ return "deny";
845
+ }
846
+ const answer = (await rl.question(` ${ui.c.accent("?")} Allow? ${ui.c.muted("[y]es / [a]lways / [n]o")} `)).trim().toLowerCase();
847
+ if (answer === "a" || answer === "always" || answer === "s" || answer === "session") return "always";
848
+ if (answer === "n" || answer === "no" || answer === "d" || answer === "deny") return "deny";
849
+ return "allow";
850
+ } finally {
851
+ rl.close();
852
+ }
853
+ };
854
+ }
855
+
856
+ // Dropdown for `ask` tool calls: the model asks, the operator picks.
857
+ // Falls back to a numbered text prompt when arrow keys are unavailable, and
858
+ // to "" (no answer) without a TTY so the loop degrades gracefully.
859
+ function makeAskQuestion() {
860
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
861
+ const readline = require("node:readline/promises");
862
+ return async ({ question, options, allowCustom = true }) => {
863
+ const list = Array.isArray(options) ? options.filter(Boolean) : [];
864
+ if (!list.length) return "";
865
+ console.log(` ${ui.c.accent("?")} ${ui.c.bold(String(question).slice(0, 300))}`);
866
+ if (ui.selectable(list.map((o) => ({ label: o })))) {
867
+ const rows = list.map((o) => ({ label: String(o) }));
868
+ if (allowCustom) rows.push({ label: "Type a custom answer…", hint: "free text" });
869
+ const picked = await ui.select({ title: "choose", items: rows });
870
+ if (picked < 0) return "";
871
+ // The trailing custom row drops into a text prompt so free-form answers
872
+ // (e.g. "let me type a custom target") stay answerable from the nice path.
873
+ if (allowCustom && picked === list.length) {
874
+ const rl2 = readline.createInterface({ input: process.stdin, output: process.stdout });
875
+ try {
876
+ const custom = (await rl2.question(` ${ui.c.accent("?")} custom answer ${ui.c.muted("(empty cancels)")} `)).trim();
877
+ return custom;
878
+ } finally {
879
+ rl2.close();
880
+ }
881
+ }
882
+ if (picked < list.length) return String(list[picked]);
883
+ return "";
884
+ }
885
+ list.forEach((o, i) => console.log(` ${ui.c.muted(`${i + 1}.`)} ${o}`));
886
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
887
+ try {
888
+ const raw = (await rl.question(` ${ui.c.accent("?")} pick ${ui.c.muted(`[1-${list.length}${allowCustom ? " or type your own" : ""}]`)} `)).trim();
889
+ const n = Number.parseInt(raw, 10);
890
+ if (Number.isFinite(n) && n >= 1 && n <= list.length) return String(list[n - 1]);
891
+ if (allowCustom && raw) return raw;
892
+ return "";
893
+ } finally {
894
+ rl.close();
895
+ }
896
+ };
897
+ }
898
+
899
+ // Renders tool activity as status cards (Claude Code style): one line per
900
+ // call, one line per result, dropdown questions as their own card. Raw
901
+ // ```tool JSON never reaches the terminal — agent.toolFenceWriter strips it.
902
+ function handleToolEvent(event) {
903
+ if (event.type === "ask") {
904
+ console.log(` ${ui.c.accent("?")} ${ui.c.bold(String(event.question || "choose").slice(0, 200))}`);
905
+ (event.options || []).forEach((o, i) => console.log(` ${ui.c.muted(`${i + 1}.`)} ${o}`));
906
+ return;
907
+ }
908
+ if (event.type === "answer") {
909
+ ui.ok(`chose ${ui.c.bold(String(event.answer || "").slice(0, 120))}`);
910
+ return;
911
+ }
912
+ if (event.type === "redacted") {
913
+ const n = Number(event.count) || 0;
914
+ if (n > 0) ui.info(`redacted ${n} possible secret${n === 1 ? "" : "s"} from the prompt before sending`);
915
+ return;
916
+ }
917
+ if (event.type === "call") {
918
+ if (!event.approved) {
919
+ if (event.reason && event.reason.startsWith("refused")) ui.warn(`blocked ${tools.describeCall(event.call)} — destructive, no approval path`);
920
+ else ui.info(`denied ${tools.describeCall(event.call)}`);
921
+ } else {
922
+ toolStarted.set(toolTimingKey(event.call), Date.now());
923
+ const elevated = event.call && event.call.tool === "bash" ? permissions.isElevatedCommand(event.call.command) : false;
924
+ ui.status(`${ui.c.accent(ui.GLYPH.dot)} ${ui.c.bold(tools.describeCall(event.call))}${elevated ? ` ${ui.c.warning("[elevated]")}` : ""}`);
925
+ }
926
+ return;
927
+ }
928
+ if (event.type === "result") {
929
+ const r = event.result || {};
930
+ const took = takeToolElapsed(event.call);
931
+ if (event.call.tool === "(parse error)") {
932
+ ui.warn(`tool request ignored: ${r.summary || "bad block"}`);
933
+ } else {
934
+ ui.status(` ${r.ok ? ui.c.success("ok") : ui.c.muted("FAILED")} ${ui.c.muted(r.summary || "")}${took}`);
935
+ }
936
+ }
937
+ }
938
+
939
+ // Start timestamps for approved tool calls, so the result row can carry an
940
+ // opencode-style elapsed time. Keyed by the rendered call description; a
941
+ // repeated call re-arms the timer, which is the honest behaviour for a map
942
+ // (the newest start wins). Unmatched results simply show no duration.
943
+ const toolStarted = new Map();
944
+
945
+ function toolTimingKey(call) {
946
+ try {
947
+ return tools.describeCall(call);
948
+ } catch {
949
+ return "";
950
+ }
951
+ }
952
+
953
+ function formatElapsed(ms) {
954
+ if (!Number.isFinite(ms) || ms < 0) return "";
955
+ if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`;
956
+ return `${(ms / 1000).toFixed(1)}s`;
957
+ }
958
+
959
+ function takeToolElapsed(call) {
960
+ const key = toolTimingKey(call);
961
+ if (!key || !toolStarted.has(key)) return "";
962
+ const ms = Date.now() - toolStarted.get(key);
963
+ toolStarted.delete(key);
964
+ const text = formatElapsed(ms);
965
+ return text ? ` ${ui.c.muted(`· ${text}`)}` : "";
966
+ }
967
+
968
+ function copyToClipboard(text) {
969
+ return new Promise((resolve) => {
970
+ const { execFile } = require("node:child_process");
971
+ const attempts =
972
+ process.platform === "darwin"
973
+ ? [["pbcopy", []]]
974
+ : process.platform === "win32"
975
+ ? [["clip", []]]
976
+ : [["xclip", ["-selection", "clipboard"]], ["xsel", ["--clipboard", "--input"]]];
977
+ let settled = false;
978
+ const finish = (value) => {
979
+ if (!settled) {
980
+ settled = true;
981
+ resolve(value);
982
+ }
983
+ };
984
+ const tryNext = (i) => {
985
+ if (i >= attempts.length) return finish({ ok: false, error: "no clipboard tool found (pbcopy, clip, xclip/xsel)" });
986
+ const [cmd, args] = attempts[i];
987
+ let child;
988
+ try {
989
+ child = execFile(cmd, args, { windowsHide: true }, (error) => {
990
+ if (error) tryNext(i + 1);
991
+ else finish({ ok: true });
992
+ });
993
+ } catch {
994
+ tryNext(i + 1);
995
+ return;
996
+ }
997
+ if (child.stdin) {
998
+ child.stdin.write(String(text));
999
+ child.stdin.end();
1000
+ }
1001
+ child.on("error", () => tryNext(i + 1));
1002
+ };
1003
+ tryNext(0);
1004
+ });
1005
+ }
1006
+
1007
+ // Adapts the streaming writer to the agent loop and strips raw tool fences.
1008
+ function loopStream(turn) {
1009
+ const filtered = agent.toolFenceWriter((line) => turn.write(line));
1010
+ return {
1011
+ begin: () => turn.begin(),
1012
+ write: (token) => filtered.write(token),
1013
+ end: () => {
1014
+ filtered.end();
1015
+ turn.end();
1016
+ },
1017
+ elapsed: () => turn.elapsed(),
1018
+ };
1019
+ }
1020
+
1021
+ function maxIters(rest) {
1022
+ const raw = arg(rest, "--max-iters");
1023
+ const n = Number.parseInt(raw || "", 10);
1024
+ return Number.isFinite(n) && n > 0 ? Math.min(n, 32) : agent.DEFAULT_MAX_ITERS;
1025
+ }
1026
+
1027
+ // Whether a scripted run would enter the agent loop. Split out so --dry-run
1028
+ // can preview the decision without a session or a backend.
1029
+ function dryRunTools(rest, buildMode) {
1030
+ return flag(rest, "--tools") || (buildMode && !flag(rest, "--no-tools"));
1031
+ }
1032
+
1033
+ function isLoopbackUrl(url) {
1034
+ try {
1035
+ const host = new URL(url).hostname.toLowerCase();
1036
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "0.0.0.0";
1037
+ } catch {
1038
+ return false;
1039
+ }
1040
+ }
1041
+
1042
+ // Any HTTP answer — even a 404 from an older backend — proves something is
1043
+ // listening. Only a network failure means dead.
1044
+ async function backendReachable(url) {
1045
+ try {
1046
+ const controller = new AbortController();
1047
+ const timer = setTimeout(() => controller.abort(), 5000);
1048
+ try {
1049
+ await fetch(`${url}/api/auth/providers`, { signal: controller.signal });
1050
+ return true;
1051
+ } finally {
1052
+ clearTimeout(timer);
1053
+ }
1054
+ } catch {
1055
+ return false;
1056
+ }
1057
+ }
1058
+
1059
+ async function executeTurn({ cfg, objective, mode, target, evidence, sess, onToken, memory: mem, signal }) {
1060
+ const history = sess ? session.contextBlock(sess) : "";
1061
+ const raw = api.buildPrompt({
1062
+ target, objective, evidence, history, memory: mem,
1063
+ session: sess ? sess.id : "", account: cfg.email || "",
1064
+ });
1065
+ const scrubbed = redact.redact(raw);
1066
+ // Even without the tool loop, a drifted model may emit machine syntax —
1067
+ // never show it to the operator.
1068
+ const filtered = onToken ? agent.toolFenceWriter(onToken) : null;
1069
+ const { text, done } = await api.streamGenerate({
1070
+ url: cfg.url, token: cfg.token, prompt: scrubbed.text, mode, signal,
1071
+ onToken: filtered ? (t) => filtered.write(t) : onToken,
1072
+ });
1073
+ if (filtered) filtered.end();
1074
+ if (sess) session.appendTurn(sess, { prompt: objective, response: text, mode, target });
1075
+ return { text, done, redactions: scrubbed.count };
1076
+ }
1077
+
1078
+ // Classifies a run failure for display. Returns "cancelled" |
1079
+ // "tokens" | "error". Callers must have already stopped the spinner
1080
+ // (turn.cancel()/end()) so the message is never painted over.
1081
+ function reportRunError(error) {
1082
+ if (!error) return "error";
1083
+ if (error.code === "CANCELLED" || cancel.isCancelError(error)) {
1084
+ ui.warn("Cancelled — session saved. Press Esc during a run to stop it; close the terminal only to quit entirely.");
1085
+ return "cancelled";
1086
+ }
1087
+ if (error.code === "INSUFFICIENT_TOKENS") {
1088
+ ui.err(String(error.message || "Out of tokens."));
1089
+ return "tokens";
1090
+ }
1091
+ ui.err(String(error.message || error));
1092
+ // Server-advised waits are informational only: the message above is
1093
+ // exactly what the backend sent, this just surfaces its retry time.
1094
+ if (error && Number.isFinite(Number(error.retryAfterSec)) && Number(error.retryAfterSec) > 0) {
1095
+ ui.info(`server advises retrying in ~${Math.ceil(Number(error.retryAfterSec))}s`);
1096
+ }
1097
+ return "error";
1098
+ }
1099
+
1100
+ function warnTruncated(done) {
1101
+ if (done && done.truncated) {
1102
+ ui.warn("Stopped early: the answer outgrew the remaining balance and was cut off. Top up, then re-run with a narrower objective.");
1103
+ }
1104
+ }
1105
+
1106
+ // Rough input-token estimate. Mirrors the web workspace estimator exactly
1107
+ // (see src/lib/utils.ts): ~4 chars per token, minimum 1.
1108
+ function estimateTokens(text) {
1109
+ return Math.max(1, Math.ceil(String(text || "").trim().length / 4));
1110
+ }
1111
+
1112
+ // Pure dry-run report: everything a run would send, spent nothing. Used by
1113
+ // --dry-run and by the tests. `contextSess` is an already-loaded session used
1114
+ // for history context only (never written).
1115
+ function buildDryRunReport({ objective, mode, target, evidence, contextSess, mem, useTools, iters }) {
1116
+ const history = contextSess ? session.contextBlock(contextSess) : "";
1117
+ const memoryText = mem && mem.text ? mem.text : "";
1118
+ const raw = useTools
1119
+ ? agent.buildAgentPrompt({ target, objective, evidence, history, memory: memoryText })
1120
+ : api.buildPrompt({ target, objective, evidence, history, memory: memoryText });
1121
+ const scrubbed = redact.redact(raw);
1122
+ const prompt = scrubbed.text;
1123
+ return {
1124
+ mode,
1125
+ target: target || "(none)",
1126
+ promptChars: prompt.length,
1127
+ inputTokens: estimateTokens(prompt),
1128
+ evidenceChars: String(evidence || "").length,
1129
+ historyChars: history.length,
1130
+ memoryChars: memoryText.length,
1131
+ redactions: scrubbed.count,
1132
+ useTools,
1133
+ iters,
1134
+ preview: prompt.slice(0, 1500),
1135
+ };
1136
+ }
1137
+
1138
+ function printDryRun(report, { mem, files, agentName, contextLabel }) {
1139
+ console.log(`dry run - nothing sent, nothing spent${contextLabel ? ` (${contextLabel})` : ""}`);
1140
+ console.log(` mode ${report.mode}`);
1141
+ console.log(` target ${report.target}`);
1142
+ console.log(` agent ${agentName || "(none)"}`);
1143
+ console.log(` files ${files.length ? files.join(", ") : "(none)"}`);
1144
+ console.log(` memory ${mem && mem.text ? `${mem.root} (${report.memoryChars} chars)` : "(no BOLT.md found)"}`);
1145
+ console.log(` evidence ${report.evidenceChars} chars${report.historyChars ? ` + ${report.historyChars} chars history` : ""}`);
1146
+ console.log(` prompt ${report.promptChars} chars ~ ${report.inputTokens} input tokens`);
1147
+ console.log(` tools ${report.useTools ? `agent loop, up to ${report.iters} iterations` : "single shot (no local tools)"}`);
1148
+ if (report.redactions > 0) console.log(` redacted ${report.redactions} possible secret${report.redactions === 1 ? "" : "s"} would be scrubbed before sending`);
1149
+ console.log(" preview ---");
1150
+ console.log(report.preview.length >= 1500 ? `${report.preview}\n …(truncated)` : report.preview);
1151
+ }
1152
+
1153
+ async function cmdRun(rest, { buildMode, printMode: forcePrint }) {
1154
+ const dryRun = flag(rest, "--dry-run");
1155
+ const printMode = Boolean(forcePrint) || flag(rest, "-p", "--print");
1156
+ // Dry runs spend nothing and touch neither the network nor the session
1157
+ // store, so they need no auth. Everything else authenticates first.
1158
+ const cfg = dryRun ? null : await ensureAuth();
1159
+ const argvPrompt = positionalPrompt(rest);
1160
+ // Local-exposure warning, not a send-path warning: this fires even though
1161
+ // the prompt is scrubbed before sending, because ps/shell history already
1162
+ // saw it. Stderr only, so print-mode stdout stays parseable.
1163
+ const argvWarning = argvSecretWarning(argvPrompt);
1164
+ if (argvWarning) ui.warn(argvWarning);
1165
+ let objective = argvPrompt;
1166
+ if (!objective) objective = await readStdin();
1167
+ if (!objective) throw new Error(buildMode ? 'Usage: bolt build "<what to build>" --target <domain> [--out ./bolt-out]' : 'Usage: bolt run "<prompt>" [--target <domain>]');
1168
+ const target = arg(rest, "--target", "-t");
1169
+ const mode = arg(rest, "--mode", "-m") || "offensive";
1170
+ if (mode !== "offensive" && mode !== "defensive") throw new Error("--mode must be offensive or defensive");
1171
+ const agentName = arg(rest, "--agent") || (buildMode ? "build" : "");
1172
+ if (agentName) objective = applyAgent(agentName, objective, target);
1173
+ const mentions = tools.resolveMentions(objective, process.cwd());
1174
+ const evidence = [readEvidence(rest), mentions.evidence].filter(Boolean).join("\n\n");
1175
+ const outDir = arg(rest, "--out", "-o") || (buildMode ? "./bolt-out" : "");
1176
+ const mem = memory.loadMemory(process.cwd());
1177
+ const useTools = printMode || dryRunTools(rest, buildMode) || (buildMode && !flag(rest, "--no-tools"));
1178
+ const iters = maxIters(rest);
1179
+ const format = (arg(rest, "--format") || "text").toLowerCase();
1180
+ if (!["text", "json", "md"].includes(format)) throw new Error('--format must be text | json | md');
1181
+ const outputFile = arg(rest, "--output") || "";
1182
+ const budgetRaw = arg(rest, "--budget");
1183
+ const budget = budgetRaw ? Number.parseInt(budgetRaw, 10) : 0;
1184
+ if (budgetRaw && !(Number.isFinite(budget) && budget > 0)) throw new Error("--budget must be a positive token count");
1185
+
1186
+ if (dryRun) {
1187
+ // Context-only session load for --session/--continue previews. Read-only:
1188
+ // no turn is appended and no new session is created.
1189
+ let contextSess = null;
1190
+ let contextLabel = "";
1191
+ const sid = arg(rest, "--session", "-s");
1192
+ if (sid) {
1193
+ contextSess = session.load(sid);
1194
+ if (!contextSess) throw new Error(`Session "${sid}" not found.`);
1195
+ contextLabel = `continuing ${sid}`;
1196
+ } else if (flag(rest, "--continue", "-c")) {
1197
+ contextSess = session.latest();
1198
+ contextLabel = contextSess ? `continuing ${contextSess.id}` : "no previous session";
1199
+ }
1200
+ const report = buildDryRunReport({
1201
+ objective, mode, target, evidence, contextSess,
1202
+ mem, useTools, iters,
1203
+ });
1204
+ printDryRun(report, { mem, files: mentions.files, agentName, contextLabel });
1205
+ return;
1206
+ }
1207
+
1208
+ let sess = null;
1209
+ const sid = arg(rest, "--session", "-s");
1210
+ if (sid) {
1211
+ sess = session.load(sid);
1212
+ if (!sess) throw new Error(`Session "${sid}" not found.`);
1213
+ } else if (flag(rest, "--continue", "-c")) {
1214
+ sess = session.latest();
1215
+ if (!sess) sess = session.create(arg(rest, "--title") || objective);
1216
+ } else {
1217
+ sess = session.create(arg(rest, "--title") || objective);
1218
+ }
1219
+
1220
+ // Budget guard: refuse before spending when the estimated input already
1221
+ // exceeds --budget. Estimate mirrors the dry-run report exactly.
1222
+ if (budget > 0) {
1223
+ const preview = buildDryRunReport({ objective, mode, target, evidence, contextSess: sess, mem, useTools, iters });
1224
+ if (preview.inputTokens > budget) {
1225
+ throw new Error(`Estimated input ~${preview.inputTokens} tokens exceeds --budget ${budget}. Trim evidence (--file), clear context, or raise the budget. Nothing was sent.`);
1226
+ }
1227
+ }
1228
+
1229
+ // Print mode keeps stdout to the final answer alone: every status line
1230
+ // below is skipped so piped output stays parseable.
1231
+ const announce = (fn) => {
1232
+ if (!printMode) fn();
1233
+ };
1234
+ announce(() => ui.status(`${ui.chip(mode, mode === "defensive" ? "info" : "warning")} ${ui.GLYPH.arrow} ${cfg.url} ${ui.GLYPH.dot} session ${sess.id}`));
1235
+ // Tools are opt-in for scripted runs (piped output must stay predictable)
1236
+ // but always on for builds, which are about changing files. Print mode
1237
+ // always runs the loop and prints only the final answer. (useTools/iters
1238
+ // were resolved above so --dry-run can preview them without a session.)
1239
+ const allowAll = flag(rest, "--allow-all", "-y", "--yes");
1240
+ announce(() => {
1241
+ if (allowAll) ui.warn("--allow-all: every tool call is approved without asking, including file edits and shell commands.");
1242
+ if (mem.text) ui.info(`project memory loaded (${mem.root})`);
1243
+ if (mentions.files.length) ui.info(`attached ${mentions.files.join(", ")}`);
1244
+ if (useTools && !process.stdin.isTTY && !allowAll) {
1245
+ ui.info("non-interactive: file writes, edits and shell commands will be denied (approve with --allow-all).");
1246
+ }
1247
+ });
1248
+ const live = ui.createStream(ui.write);
1249
+ const turn = present.streamingWriter(live);
1250
+ // Esc aborts the in-flight request instead of forcing a terminal kill.
1251
+ // Attached only while the run streams; detached in the finally below.
1252
+ // (No-op without a TTY, so piped output stays parseable.)
1253
+ const canceller = cancel.createCanceller();
1254
+ canceller.attach();
1255
+ let text = "";
1256
+ let done = null;
1257
+ let cancelled = false;
1258
+ try {
1259
+ if (useTools) {
1260
+ const alwaysStore = permissions.load();
1261
+ const persistAlways = (call) => {
1262
+ const next = permissions.allowAlways(permissions.load(), call);
1263
+ permissions.save(next);
1264
+ alwaysStore.always = next.always;
1265
+ announce(() => ui.ok(`remembered ${ui.c.bold(permissions.keyForCall(call))} - will not ask again (revoke with /permissions)`));
1266
+ };
1267
+ let loopResult;
1268
+ try {
1269
+ loopResult = await agent.runAgentLoop({
1270
+ cfg, objective, mode, target, evidence, sess,
1271
+ stream: printMode ? null : loopStream(turn),
1272
+ events: printMode ? null : handleToolEvent,
1273
+ policy: {
1274
+ allowAll,
1275
+ sessionAllowed: new Set(),
1276
+ ask: allowAll ? null : makeAsker(),
1277
+ askQuestion: printMode ? null : makeAskQuestion(),
1278
+ alwaysStore,
1279
+ persistAlways: allowAll ? null : persistAlways,
1280
+ },
1281
+ maxIters: iters,
1282
+ memory: mem.text,
1283
+ signal: canceller.signal,
1284
+ });
1285
+ } catch (error) {
1286
+ try {
1287
+ turn.cancel();
1288
+ } catch {
1289
+ // Teardown never masks the run error.
1290
+ }
1291
+ const kind = reportRunError(error);
1292
+ if (kind === "tokens") process.exitCode = 2;
1293
+ if (kind === "cancelled") cancelled = true;
1294
+ else if (kind === "error") process.exitCode = 1;
1295
+ return;
1296
+ }
1297
+ ({ text, done } = loopResult);
1298
+ if (loopResult.cancelled || canceller.cancelled) {
1299
+ try {
1300
+ turn.cancel();
1301
+ } catch {
1302
+ // ignore
1303
+ }
1304
+ ui.warn("Cancelled — session saved. Press Esc during a run to stop it; close the terminal only to quit entirely.");
1305
+ return;
1306
+ }
1307
+ cancelled = false;
1308
+ } else {
1309
+ turn.begin();
1310
+ let redactions = 0;
1311
+ try {
1312
+ ({ text, done, redactions } = await executeTurn({
1313
+ cfg, objective, mode, target, evidence, sess,
1314
+ onToken: turn.write,
1315
+ memory: mem.text,
1316
+ signal: canceller.signal,
1317
+ }));
1318
+ } catch (error) {
1319
+ try {
1320
+ turn.cancel();
1321
+ } catch {
1322
+ // Teardown never masks the run error.
1323
+ }
1324
+ const kind = reportRunError(error);
1325
+ if (kind === "tokens") process.exitCode = 2;
1326
+ if (kind === "cancelled") cancelled = true;
1327
+ else if (kind === "error") process.exitCode = 1;
1328
+ return;
1329
+ }
1330
+ turn.end();
1331
+ if (redactions > 0) announce(() => ui.info(`redacted ${redactions} possible secret${redactions === 1 ? "" : "s"} from the prompt before sending`));
1332
+ }
1333
+ } finally {
1334
+ canceller.detach();
1335
+ }
1336
+ if (cancelled || canceller.cancelled) return;
1337
+ warnTruncated(done);
1338
+ // Machine-readable output: --format json prints one JSON document with
1339
+ // the answer + run metadata; --output <file> additionally/alternatively
1340
+ // writes the final answer to disk. Status lines stay on stderr so stdout
1341
+ // (or the file) stays parseable.
1342
+ const emitFormatted = () => {
1343
+ if (outputFile) {
1344
+ try {
1345
+ fs.writeFileSync(path.resolve(outputFile), format === "json"
1346
+ ? JSON.stringify({ answer: text, session: sess.id, mode, target, done: done || {} }, null, 2) + "\n"
1347
+ : text + "\n");
1348
+ process.stderr.write(`bolt: wrote ${path.resolve(outputFile)}\n`);
1349
+ } catch (e) {
1350
+ throw new Error(`Cannot write --output ${outputFile}: ${e.message}`);
1351
+ }
1352
+ }
1353
+ if (format === "json") {
1354
+ console.log(JSON.stringify({ answer: text, session: sess.id, mode, target, done: done || {} }));
1355
+ return true;
1356
+ }
1357
+ return false;
1358
+ };
1359
+
1360
+ if (printMode && !buildMode) {
1361
+ if (!emitFormatted()) console.log(text);
1362
+ else if (outputFile) { /* json already on stdout, file also written */ }
1363
+ return;
1364
+ }
1365
+ if (done && done.remainingTokens !== undefined) {
1366
+ ui.status(`done ${ui.GLYPH.dot} ${present.turnFooter({ done, elapsed: turn.elapsed() })}`);
1367
+ }
1368
+
1369
+ if (buildMode || outDir) {
1370
+ const blocks = output.extractCodeBlocks(text);
1371
+ if (blocks.length && outDir) {
1372
+ const saved = output.saveTools(blocks, path.resolve(outDir));
1373
+ for (const f of saved) process.stderr.write(`bolt: saved ${f}\n`);
1374
+ } else if (buildMode && !blocks.length) {
1375
+ process.stderr.write("bolt: no fenced code blocks found — see raw output above.\n");
1376
+ }
1377
+ }
1378
+ if (format === "json" || outputFile) emitFormatted();
1379
+ }
1380
+
1381
+ async function cmdDoctor() {
1382
+ const cfg = config.load();
1383
+ const checks = await doctor.runDoctor({ url: cfg.url });
1384
+ console.log(doctor.formatDoctor(checks));
1385
+ const failed = checks.filter((c) => !c.ok);
1386
+ if (failed.length) {
1387
+ process.exitCode = 1;
1388
+ process.stderr.write(`bolt doctor: ${failed.length} check${failed.length === 1 ? "" : "s"} failing — see above.\n`);
1389
+ }
1390
+ }
1391
+
1392
+ // ── update ────────────────────────────────────────────────────────────────
1393
+ // `bolt update` shells npm to upgrade the globally installed package. npm's
1394
+ // launcher is a .cmd on Windows, so the child runs through a shell; stdio is
1395
+ // inherited so the npm progress bars show as they are.
1396
+ function cmdUpdate() {
1397
+ console.log(`running: npm install -g @bolt-cli/cli (current: v${VERSION})`);
1398
+ const child = spawn("npm", ["install", "-g", "@bolt-cli/cli"], { stdio: "inherit", shell: process.platform === "win32" });
1399
+ return new Promise((resolve) => {
1400
+ child.on("error", (error) => {
1401
+ ui.err(`update failed: ${error.message} - try: npm install -g @bolt-cli/cli`);
1402
+ resolve();
1403
+ });
1404
+ child.on("close", (code) => {
1405
+ if (code === 0) {
1406
+ // Restart into the new version before the next check: clear the
1407
+ // cached check so the fresh install re-verifies against the registry
1408
+ // instead of greeting itself with a stale notice.
1409
+ try {
1410
+ const cfg = config.load();
1411
+ config.save({ ...cfg, updateCheckedAt: 0, updateLatest: "" });
1412
+ } catch {
1413
+ // Cache hygiene is best-effort; the update itself already succeeded.
1414
+ }
1415
+ ui.ok("update complete - restart bolt to run the new version");
1416
+ } else {
1417
+ ui.err(`update failed (exit ${code}) - try: npm install -g @bolt-cli/cli`);
1418
+ }
1419
+ resolve();
1420
+ });
1421
+ });
1422
+ }
1423
+
1424
+ function cmdCompletion(rest) {
1425
+ const shell = rest[0] || "";
1426
+ if (!shell) throw new Error("Usage: bolt completion <bash|zsh|fish|powershell>");
1427
+ process.stdout.write(completion.completion(shell));
1428
+ }
1429
+
1430
+ // ── templates ─────────────────────────────────────────────────────────────
1431
+ // Printable lab runbooks shipped with the CLI (see cli/templates/README).
1432
+ // `bolt templates` lists; `bolt templates <name>` prints a script to stdout.
1433
+ const TEMPLATE_NOTES = {
1434
+ "aslr-offset-probe.sh":
1435
+ "sample an address across runs of a lab binary, estimate entropy, brute-force-attempt math",
1436
+ "crash-offset-pattern.sh":
1437
+ "cyclic pattern generator + offset lookup (EIP/RIP, hex little-endian or ASCII)",
1438
+ };
1439
+
1440
+ function templateDir() {
1441
+ return path.join(__dirname, "..", "templates");
1442
+ }
1443
+
1444
+ function cmdTemplates(rest) {
1445
+ const raw = rest.find((a) => !a.startsWith("-")) || "";
1446
+ const dir = templateDir();
1447
+ if (!raw) {
1448
+ const entries = fs
1449
+ .readdirSync(dir)
1450
+ .filter((f) => f !== "README.md" && !f.startsWith("."))
1451
+ .sort();
1452
+ console.log(`Lab templates — authorized lab work only, headers carry the authorization notice.\nPrint one with: bolt templates <name>\n`);
1453
+ if (!entries.length) {
1454
+ console.log(" (no templates found in the install)");
1455
+ return;
1456
+ }
1457
+ for (const f of entries) {
1458
+ const note = TEMPLATE_NOTES[f] || "";
1459
+ console.log(` ${f}${note ? ` — ${note}` : ""}`);
1460
+ }
1461
+ console.log(`\nFull guide: bolt templates README`);
1462
+ return;
1463
+ }
1464
+ const name = raw.split(/[\\/]/).pop();
1465
+ if (name.toLowerCase() === "readme.md" || name.toLowerCase() === "readme") {
1466
+ process.stdout.write(fs.readFileSync(path.join(dir, "README.md")));
1467
+ return;
1468
+ }
1469
+ const file = path.join(dir, name);
1470
+ if (!fs.existsSync(file)) {
1471
+ const known = Object.keys(TEMPLATE_NOTES).join(", ");
1472
+ throw new Error(`Unknown template "${name}". Available: README.md, ${known}`);
1473
+ }
1474
+ process.stdout.write(fs.readFileSync(file));
1475
+ }
1476
+
1477
+ function cmdExport(rest) {
1478
+ const id = rest.find((a) => !a.startsWith("-")) || "";
1479
+ if (!id) throw new Error("Usage: bolt export <session-id> [--format md|json|sarif] [--output file]");
1480
+ const sess = session.load(id);
1481
+ if (!sess) throw new Error(`Session "${id}" not found.`);
1482
+ const fmt = (arg(rest, "--format") || "md").toLowerCase();
1483
+ const dest = arg(rest, "--output", "-o") || "";
1484
+ const text = exporter.exportSession(sess, fmt);
1485
+ if (dest) {
1486
+ fs.writeFileSync(path.resolve(dest), text + "\n");
1487
+ process.stderr.write(`bolt: exported ${id} (${fmt}) to ${path.resolve(dest)}\n`);
1488
+ } else {
1489
+ console.log(text);
1490
+ }
1491
+ }
1492
+
1493
+ function cmdUndo(rest) {
1494
+ const target = rest.find((a) => !a.startsWith("-")) || "";
1495
+ if (!target) throw new Error("Usage: bolt undo <path>");
1496
+ const r = checkpoints.restore(process.cwd(), target);
1497
+ if (!r.ok) throw new Error(r.detail);
1498
+ ui.ok(r.detail);
1499
+ }
1500
+
1501
+ function printPalette(filter = "") {
1502
+ const q = filter.toLowerCase();
1503
+ const rows = COMMANDS.filter(([cmd]) => !q || cmd.toLowerCase().includes(q));
1504
+ if (!rows.length) {
1505
+ ui.info(`no command matches "${filter}". '/' lists everything.`);
1506
+ return;
1507
+ }
1508
+ const labelWidth = Math.max(...rows.map(([cmd]) => ui.visibleLength(cmd)));
1509
+ for (const [cmd, desc] of rows) {
1510
+ const pad = " ".repeat(Math.max(0, labelWidth - ui.visibleLength(cmd)) + 2);
1511
+ console.log(` ${ui.c.primary(ui.c.bold(cmd))}${pad}${ui.c.muted(desc)}`);
1512
+ }
1513
+ }
1514
+
1515
+ // Saved-session table for terminals without arrow-key picking: id plus the
1516
+ // same title/turns/age hint the picker shows. Pure rows in, console out.
1517
+ function printSessionTable(items) {
1518
+ const list = Array.isArray(items) ? items : [];
1519
+ if (!list.length) return;
1520
+ const idWidth = Math.max(...list.map((it) => ui.visibleLength(it.id || "")));
1521
+ for (const it of list) {
1522
+ console.log(` ${ui.c.primary(ui.c.bold((it.id || "").padEnd(idWidth)))} ${ui.c.muted(it.hint || "")}`);
1523
+ }
1524
+ }
1525
+
1526
+ // Numbered palette for terminals without arrow-key picking (no raw mode):
1527
+ // every row gets a stable number so the operator answers with one keystroke
1528
+ // instead of retyping the command. Pure rows in, console lines out.
1529
+ function printPaletteNumbered(items) {
1530
+ const list = Array.isArray(items) ? items : [];
1531
+ const numWidth = String(list.length).length;
1532
+ const labelWidth = list.length ? Math.max(...list.map((it) => ui.visibleLength(it.label))) : 0;
1533
+ list.forEach((it, i) => {
1534
+ const num = String(i + 1).padStart(numWidth, " ");
1535
+ const pad = " ".repeat(Math.max(0, labelWidth - ui.visibleLength(it.label)) + 2);
1536
+ console.log(` ${ui.c.muted(num)} ${ui.c.primary(ui.c.bold(it.label))}${pad}${ui.c.muted(it.hint || "")}`);
1537
+ });
1538
+ }
1539
+
1540
+ // Resolves one line of picker input against the listed rows. Pure, tested:
1541
+ // {action:"pick", index} for a valid number, {action:"filter", text} to
1542
+ // narrow, {action:"cancel"} for empty input or an out-of-range number.
1543
+ // A filter with no matches makes the caller drop the picker and run the
1544
+ // line as typed, so a real task is never swallowed by a stale choice.
1545
+ function resolvePalettePick(raw, items) {
1546
+ const text = String(raw || "").trim();
1547
+ const list = Array.isArray(items) ? items : [];
1548
+ if (!text) return { action: "cancel" };
1549
+ if (/^\d+$/.test(text)) {
1550
+ const index = Number.parseInt(text, 10) - 1;
1551
+ if (index >= 0 && index < list.length) return { action: "pick", index };
1552
+ return { action: "cancel" };
1553
+ }
1554
+ return { action: "filter", text: text.replace(/^\//, "") };
1555
+ }
1556
+
1557
+ // Grouped help box, opencode `?`-overlay style: four small menus with stable
1558
+ // numbers so the picker flow keeps working - the operator answers with a
1559
+ // number exactly like the flat list. Returns the flat row list for
1560
+ // pendingPalette. Pure rows in, console lines out.
1561
+ function printHelpBox() {
1562
+ const groups = present.helpGroups(COMMANDS);
1563
+ const flat = groups.flatMap((g) => g.rows.map(([cmd, desc]) => ({ label: cmd, hint: desc })));
1564
+ const numWidth = String(flat.length).length;
1565
+ const labelWidth = flat.length ? Math.max(...flat.map((it) => ui.visibleLength(it.label))) : 0;
1566
+ let n = 0;
1567
+ for (const g of groups) {
1568
+ console.log(` ${ui.c.accent(ui.c.bold(g.title))}`);
1569
+ for (const [cmd, desc] of g.rows) {
1570
+ n += 1;
1571
+ const num = String(n).padStart(numWidth, " ");
1572
+ const pad = " ".repeat(Math.max(0, labelWidth - ui.visibleLength(cmd)) + 2);
1573
+ console.log(` ${ui.c.muted(num)} ${ui.c.primary(ui.c.bold(cmd))}${pad}${ui.c.muted(desc)}`);
1574
+ }
1575
+ }
1576
+ return flat;
1577
+ }
1578
+
1579
+ // Keyboard cheat sheet, the `?` overlay for a line-based REPL: every key the
1580
+ // session actually honours, nothing aspirational.
1581
+ function printKeysBox() {
1582
+ const rows = [
1583
+ ["Tab", "complete commands, paths, agents, sessions"],
1584
+ ["/ then Enter", "filterable command palette"],
1585
+ ["@path + Tab", "attach a file, with path completion"],
1586
+ ["\\ at end of line", "continue on the next line (multiline tasks)"],
1587
+ ["up / down", "history (persisted across restarts)"],
1588
+ ["esc / ctrl-c", "stop the running turn"],
1589
+ ["ctrl-d", "save session and quit"],
1590
+ ];
1591
+ const keyWidth = Math.max(...rows.map(([k]) => k.length));
1592
+ console.log(
1593
+ ui.box({
1594
+ title: "keys",
1595
+ w: ui.width(),
1596
+ lines: rows.map(([k, d]) => `${ui.c.primary(ui.c.bold(k.padEnd(keyWidth)))} ${ui.c.muted(d)}`),
1597
+ }),
1598
+ );
1599
+ }
1600
+
1601
+ // Rotating operator tips for the welcome box. Pure: index selects, so tests
1602
+ // and the REPL (day-derived index) share the same picker.
1603
+ const TIPS = [
1604
+ "type / then Enter for the filterable command palette",
1605
+ "end a line with \\ to keep writing on the next line",
1606
+ "Tab completes /commands, @paths, and session ids",
1607
+ "/status shows mode, tools, tokens, and balance at a glance",
1608
+ "/sessions picks a saved session without typing its id",
1609
+ "a leading space keeps a line out of the history file",
1610
+ "/undo <path> restores the last agent backup of a file",
1611
+ ];
1612
+
1613
+ function pickTip(n) {
1614
+ return TIPS[((Number(n) || 0) % TIPS.length + TIPS.length) % TIPS.length];
1615
+ }
1616
+
1617
+ // Welcome lines for the REPL box. Hints adapt to terminal capability:
1618
+ // arrow-key verbs are only promised where raw mode exists, otherwise the
1619
+ // numbered picker is the path. Pure (ui.c degrades to identity), tested.
1620
+ function replWelcomeLines({ sid, host, cwd, tip, update }) {
1621
+ const lines = [
1622
+ `${ui.c.primary(ui.c.bold("bolt"))} ${ui.c.muted("interactive")} ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted("Bolt backend only - runs bill your token balance")}`,
1623
+ `${ui.c.muted("session")} ${ui.c.primary(sid)}`,
1624
+ ];
1625
+ if (host || cwd) {
1626
+ const where = [];
1627
+ if (host) where.push(`${ui.c.muted("backend")} ${host}`);
1628
+ if (cwd) where.push(`${ui.c.muted("cwd")} ${cwd}`);
1629
+ lines.push(where.join(` ${ui.c.muted(ui.GLYPH.dot)} `));
1630
+ }
1631
+ if (update) {
1632
+ lines.push("", `${ui.c.warning("update")} ${update}`);
1633
+ }
1634
+ lines.push(
1635
+ "",
1636
+ ui.bullets([
1637
+ "type a task and press enter to run it",
1638
+ `${ui.c.bold("/")} opens the command dropdown ${ui.c.muted(ui.GLYPH.dot)} type to filter, up/down to pick, ${ui.c.bold("Tab")} fills and keeps your place`,
1639
+ `${ui.c.bold("Tab")} completes commands and their arguments ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("@path")} attaches a file ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/help <cmd>")} detail`,
1640
+ `${ui.c.bold("/status")} dashboard ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/sessions")} resume ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("?")} help ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/keys")} shortcuts ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/help <cmd>")} detail`,
1641
+ `${ui.c.bold("/agents")} presets ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/target")} scope ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/init")} map repo ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/mode")} offensive or defensive`,
1642
+ `${ui.c.bold("/doctor")} health ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/export")} file ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/undo")} restore ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.bold("/exit")} save and quit`,
1643
+ ]),
1644
+ );
1645
+ if (tip) lines.push("", `${ui.c.muted("tip")} ${tip}`);
1646
+ return lines;
1647
+ }
1648
+
1649
+ // Short backend host for the welcome box ("beerasafe.com", never the full
1650
+ // URL with its path). "" when the URL is missing or malformed.
1651
+ function backendHost(url) {
1652
+ try {
1653
+ return new URL(String(url || "")).hostname || "";
1654
+ } catch {
1655
+ return "";
1656
+ }
1657
+ }
1658
+
1659
+ function printAgents() {
1660
+ const rows = Object.entries(AGENTS);
1661
+ const labelWidth = Math.max(...rows.map(([n]) => n.length));
1662
+ for (const [name, a] of rows) {
1663
+ const pad = " ".repeat(labelWidth - name.length + 2);
1664
+ console.log(` ${ui.c.accent(ui.c.bold(name))}${pad}${ui.c.muted(a.desc + (a.needsTarget ? " (needs /target)" : ""))}`);
1665
+ }
1666
+ }
1667
+
1668
+ function completeFileFrag(frag) {
1669
+ const slashAt = frag.lastIndexOf("/");
1670
+ const dirFrag = slashAt === -1 ? "" : frag.slice(0, slashAt);
1671
+ const base = slashAt === -1 ? frag : frag.slice(slashAt + 1);
1672
+ let entries;
1673
+ try {
1674
+ entries = fs.readdirSync(path.resolve(process.cwd(), dirFrag || "."), { withFileTypes: true });
1675
+ } catch {
1676
+ return [];
1677
+ }
1678
+ return entries
1679
+ .filter((entry) => entry.name.startsWith(base) && !entry.name.startsWith("."))
1680
+ .map((entry) => `${dirFrag ? `${dirFrag}/` : ""}${entry.name}${entry.isDirectory() ? "/" : ""}`);
1681
+ }
1682
+
1683
+ function completer(line) {
1684
+ // Tab-completes slash commands, their arguments, and agent names,
1685
+ // opencode-style. @-mentions and /file complete filesystem paths,
1686
+ // Claude Code style. /resume and /session complete saved session ids.
1687
+ const atMatch = line.match(/@([^\s@]*)$/);
1688
+ if (atMatch && !line.startsWith("/")) {
1689
+ const hits = completeFileFrag(atMatch[1]).map((h) => `@${h}`);
1690
+ return [hits, line];
1691
+ }
1692
+ if (line.startsWith("/agent ")) {
1693
+ const frag = line.slice(7).toLowerCase();
1694
+ const hits = Object.keys(AGENTS).filter((n) => n.startsWith(frag)).map((n) => `/agent ${n}`);
1695
+ return [hits.length ? hits : Object.keys(AGENTS).map((n) => `/agent ${n}`), line];
1696
+ }
1697
+ if (line.startsWith("/mode ")) {
1698
+ const frag = line.slice(6).trim().toLowerCase();
1699
+ const hits = ["offensive", "defensive"].filter((m) => m.startsWith(frag)).map((m) => `/mode ${m}`);
1700
+ return [hits.length ? hits : ["offensive", "defensive"].map((m) => `/mode ${m}`), line];
1701
+ }
1702
+ if (line.startsWith("/tools ")) {
1703
+ const frag = line.slice(7).trim().toLowerCase();
1704
+ const hits = ["on", "off"].filter((m) => m.startsWith(frag)).map((m) => `/tools ${m}`);
1705
+ return [hits.length ? hits : ["on", "off"].map((m) => `/tools ${m}`), line];
1706
+ }
1707
+ if (line.startsWith("/file ")) {
1708
+ const frag = line.slice(6);
1709
+ const hits = completeFileFrag(frag.trimStart()).map((h) => `/file ${h}`);
1710
+ return [hits, line];
1711
+ }
1712
+ if (line.startsWith("/undo ")) {
1713
+ const frag = line.slice(6).trimStart();
1714
+ const hits = completeFileFrag(frag).map((h) => `/undo ${h}`);
1715
+ return [hits, line];
1716
+ }
1717
+ if (line.startsWith("/export ")) {
1718
+ const frag = line.slice(8).trim().toLowerCase();
1719
+ const hits = ["md", "json", "sarif"].filter((f) => f.startsWith(frag)).map((f) => `/export ${f}`);
1720
+ return [hits, line];
1721
+ }
1722
+ if (line.startsWith("/templates ")) {
1723
+ const frag = line.slice(11).trim().toLowerCase();
1724
+ let names = ["README.md"];
1725
+ try {
1726
+ names = ["README.md", ...fs.readdirSync(templateDir()).filter((f) => f !== "README.md" && !f.startsWith("."))];
1727
+ } catch {
1728
+ // install without templates: README alone is still completable
1729
+ }
1730
+ const hits = names.filter((n) => n.toLowerCase().startsWith(frag)).map((n) => `/templates ${n}`);
1731
+ return [hits, line];
1732
+ }
1733
+ if (line.startsWith("/watch ")) {
1734
+ const frag = line.slice(7).trim().toLowerCase();
1735
+ const subs = ["status", "check", "start", "stop", "events", "policy", "playbook", "baseline", "respond"];
1736
+ const hits = subs.filter((s) => s.startsWith(frag)).map((s) => `/watch ${s}`);
1737
+ return [hits, line];
1738
+ }
1739
+ if (line.startsWith("/help ")) {
1740
+ const frag = line.slice(6).trim().toLowerCase();
1741
+ const bases = [...new Set(COMMANDS.map(([cmd]) => cmd.split(" ")[0]))];
1742
+ const hits = bases.filter((b) => b.slice(1).startsWith(frag)).map((b) => `/help ${b.slice(1)}`);
1743
+ return [hits, line];
1744
+ }
1745
+ if (line.startsWith("/resume ") || line.startsWith("/session ") || line.startsWith("/sessions ")) {
1746
+ const prefix = line.startsWith("/resume ") ? "/resume " : line.startsWith("/sessions ") ? "/sessions " : "/session ";
1747
+ const frag = line.slice(prefix.length).trim().toLowerCase();
1748
+ let ids = [];
1749
+ try {
1750
+ // Older/foreign session rows can lack an id; dropping them here beats
1751
+ // a TypeError in the middle of tab completion.
1752
+ ids = session.list().map((s) => (s && typeof s.id === "string" ? s.id : null)).filter(Boolean);
1753
+ } catch {
1754
+ ids = [];
1755
+ }
1756
+ const extra = prefix === "/session " ? ["new"] : [];
1757
+ const hits = [...extra, ...ids].filter((id) => id.toLowerCase().startsWith(frag)).map((id) => `${prefix}${id}`);
1758
+ return [hits, line];
1759
+ }
1760
+ if (line.startsWith("/permissions ")) {
1761
+ const frag = line.slice(13).trim().toLowerCase();
1762
+ const hits = ["list", "revoke ", "clear"].filter((m) => m.startsWith(frag)).map((m) => `/permissions ${m}`);
1763
+ return [hits.length ? hits : ["list", "revoke ", "clear"].map((m) => `/permissions ${m}`), line];
1764
+ }
1765
+ if (line.startsWith("/")) {
1766
+ // Completing an argument to a known command: delegate above; a trailing
1767
+ // space with no fragment lists that command's argument options.
1768
+ if (line.includes(" ")) return [[], line];
1769
+ const frag = line.split(" ")[0].toLowerCase();
1770
+ const seen = new Set();
1771
+ const hits = [];
1772
+ for (const [cmd] of COMMANDS) {
1773
+ const base = cmd.split(" ")[0];
1774
+ if (seen.has(base)) continue;
1775
+ seen.add(base);
1776
+ if (base.startsWith(frag)) hits.push(base);
1777
+ }
1778
+ // Agent names are also completable from a bare slash prefix.
1779
+ for (const name of Object.keys(AGENTS)) {
1780
+ const full = `/agent ${name}`;
1781
+ if (full.toLowerCase().startsWith(line.toLowerCase())) hits.push(full);
1782
+ }
1783
+ if (hits.length) return [hits, line];
1784
+ const all = COMMANDS.map(([c]) => c.split(" ")[0]).filter((c, i, arr) => arr.indexOf(c) === i);
1785
+ return [all, line];
1786
+ }
1787
+ return [[], line];
1788
+ }
1789
+
1790
+ // Rich completions with brief definitions for the palette and tests.
1791
+ // Matches the slash prefix against command names AND descriptions, plus
1792
+ // agent names and their descriptions. Plain hyphens only.
1793
+ function completeWithDescriptions(line) {
1794
+ const q = String(line || "").toLowerCase();
1795
+ if (!q.startsWith("/")) return [];
1796
+ const rows = present.paletteItems(COMMANDS, AGENTS);
1797
+ const frag = q.split(" ")[0];
1798
+ return rows
1799
+ .filter((it) => it.label.toLowerCase().startsWith(frag) || `${it.label} ${it.hint || ""}`.toLowerCase().includes(q.replace(/^\//, "")))
1800
+ .map((it) => ({ completion: it.label, description: it.hint || "" }));
1801
+ }
1802
+
1803
+ // Live palette filter used by the REPL and the tests. Matches slash
1804
+ // commands AND agents by name or description (case-insensitive).
1805
+ function filterPaletteItems(query) {
1806
+ return present.filterPalette(query, COMMANDS, AGENTS);
1807
+ }
1808
+
1809
+ async function cmdRepl() {
1810
+ const cfg = await ensureAuth();
1811
+ const { createInterface } = require("node:readline/promises");
1812
+ const rl = createInterface({ input: process.stdin, output: process.stdout, historySize: 100, completer });
1813
+ let mode = "offensive";
1814
+ let target = "";
1815
+ let armedAgent = "";
1816
+ let sess = session.create("interactive");
1817
+ const files = [];
1818
+ let balance = null;
1819
+ let lastAnswer = "";
1820
+ // Pending numbered palette (terminals without arrow-key picking): "/" lists
1821
+ // rows with numbers and this holds them until the next line answers.
1822
+ let pendingPalette = null;
1823
+ // Local tools (read, search, edit, shell) are on by default, Claude Code
1824
+ // style. Writes, edits and shell commands ask first; destructive commands
1825
+ // are refused outright. Session-wide approvals last until /exit.
1826
+ let toolsOn = true;
1827
+ let allowAll = false;
1828
+ const sessionAllowed = new Set();
1829
+ // Persistent always-allow store: "Always allow" survives restarts via
1830
+ // ~/.bolt/permissions.json (Claude Code / opencode style).
1831
+ const alwaysStore = permissions.load();
1832
+ const persistAlways = (call) => {
1833
+ const next = permissions.allowAlways(permissions.load(), call);
1834
+ permissions.save(next);
1835
+ alwaysStore.always = next.always;
1836
+ ui.ok(`remembered ${ui.c.bold(permissions.keyForCall(call))} - will not ask again (revoke with /permissions)`);
1837
+ };
1838
+ // Project memory (BOLT.md): loaded once per session, travels as context.
1839
+ // /init refreshes it after writing a new one (see below).
1840
+ let mem = memory.loadMemory(process.cwd());
1841
+ // Prompt history survives restarts via ~/.bolt/history. A leading space
1842
+ // keeps a line out of the file (shell convention, for pasted secrets).
1843
+ try {
1844
+ const saved = replHistory.load(null, 100);
1845
+ if (Array.isArray(rl.history)) rl.history.push(...saved);
1846
+ else rl.history = saved;
1847
+ } catch {
1848
+ // History is convenience; a broken file never blocks the session.
1849
+ }
1850
+
1851
+ // The prompt is the status line: mode, target, agent and attachments are
1852
+ // always visible, so a long interactive session can't drift out of sync with
1853
+ // what you think it's pointed at.
1854
+ const state = () => ({ sid: sess.id, mode, target, agent: armedAgent, files: files.length, balance, tools: toolsOn });
1855
+ const setPrompt = () => rl.setPrompt(present.promptLine(state()));
1856
+
1857
+ console.log("");
1858
+ for (const row of ui.LOGO) console.log(ui.c.primary(ui.c.bold(row)));
1859
+ // Update notice comes from the cache first (instant, no network); a stale
1860
+ // cache is refreshed in the background for the next session, and a newly
1861
+ // discovered update prints one line mid-session.
1862
+ const cachedUpdate = updatecheck.cachedNotice(VERSION);
1863
+ console.log(
1864
+ ui.box({
1865
+ title: `bolt v${VERSION}`,
1866
+ w: ui.width(),
1867
+ lines: replWelcomeLines({
1868
+ sid: sess.id,
1869
+ host: backendHost(cfg.url),
1870
+ cwd: process.cwd(),
1871
+ tip: pickTip(Math.floor(Date.now() / 86400000)),
1872
+ update: cachedUpdate || undefined,
1873
+ }),
1874
+ }),
1875
+ );
1876
+ console.log("");
1877
+ void updatecheck
1878
+ .refresh(VERSION, cachedUpdate ? {} : { onNotice: (notice) => console.log(`\n${ui.c.warning(`! ${notice}`)}`) })
1879
+ .catch(() => undefined);
1880
+
1881
+ // Balance is a nice-to-have in the prompt, so failure here must never block
1882
+ // the session.
1883
+ try {
1884
+ const stats = await api.getStats(cfg.url, cfg.token);
1885
+ balance = stats.balance;
1886
+ } catch {
1887
+ balance = null;
1888
+ }
1889
+ if (mem.text) ui.info(`project memory loaded from ${mem.root} (${mem.text.length} chars of BOLT.md context)`);
1890
+
1891
+ setPrompt();
1892
+ // stdin can reach EOF while we are awaiting balance above (piped input, or
1893
+ // Ctrl-D), which closes the interface underneath us.
1894
+ if (rl.closed) return;
1895
+ rl.prompt();
1896
+ // Multiline buffer: a trailing backslash continues the task on the next
1897
+ // line (multiline tasks without an editor). Fragments stay out of history;
1898
+ // the joined task is recorded once, complete. Continuation is disabled
1899
+ // while a numbered picker is pending, so a choice is never swallowed.
1900
+ let carried = "";
1901
+ for await (const line of rl) {
1902
+ if (rl.closed) break;
1903
+ let input = line.trim();
1904
+ if (!input && !carried) {
1905
+ rl.prompt();
1906
+ continue;
1907
+ }
1908
+ if (!pendingPalette && input.endsWith("\\")) {
1909
+ carried += `${input.slice(0, -1)}\n`;
1910
+ rl.setPrompt(`${ui.c.muted("... ")}`);
1911
+ rl.prompt();
1912
+ continue;
1913
+ }
1914
+ if (carried) {
1915
+ replHistory.append(`${carried}${line}`);
1916
+ input = `${carried}${input}`.trim();
1917
+ carried = "";
1918
+ setPrompt();
1919
+ } else {
1920
+ replHistory.append(line);
1921
+ }
1922
+ if (!input) {
1923
+ rl.prompt();
1924
+ continue;
1925
+ }
1926
+ // Shell habit: "bolt list" in the REPL means the task "list".
1927
+ const unprefixed = stripBoltPrefix(input);
1928
+ if (unprefixed.stripped) {
1929
+ input = unprefixed.task;
1930
+ ui.info(`treating that as "${input}" - the REPL takes tasks directly, no leading bolt needed`);
1931
+ if (!input) {
1932
+ rl.prompt();
1933
+ continue;
1934
+ }
1935
+ }
1936
+ // Numbered picker answer: a pending palette from "/" interprets this
1937
+ // line as a choice. Anything unresolvable cancels the picker and the
1938
+ // line is processed normally, so a choice is never swallowed.
1939
+ if (pendingPalette) {
1940
+ const rows = pendingPalette;
1941
+ pendingPalette = null;
1942
+ const pick = resolvePalettePick(input, rows);
1943
+ if (pick.action === "cancel") {
1944
+ rl.prompt();
1945
+ continue;
1946
+ }
1947
+ let item = null;
1948
+ let fallThrough = false;
1949
+ if (pick.action === "pick") {
1950
+ item = rows[pick.index] || null;
1951
+ } else {
1952
+ const next = present.filterPalette(pick.text, COMMANDS, AGENTS);
1953
+ if (next.length === 1) {
1954
+ item = next[0];
1955
+ } else if (next.length > 1) {
1956
+ printPaletteNumbered(next);
1957
+ ui.info("type the number to run it, /text to narrow, or anything else to cancel");
1958
+ pendingPalette = next;
1959
+ rl.prompt();
1960
+ continue;
1961
+ } else {
1962
+ // No match: drop the picker and run the line as typed, so a real
1963
+ // task is never swallowed by a stale choice.
1964
+ fallThrough = true;
1965
+ }
1966
+ }
1967
+ if (!item || item.label === "/") {
1968
+ if (!fallThrough) {
1969
+ rl.prompt();
1970
+ continue;
1971
+ }
1972
+ // else: no match — fall through and process the line normally.
1973
+ } else if (isPaletteRunnable(item.label)) {
1974
+ input = item.label;
1975
+ } else {
1976
+ rl.write(`${item.label.split(" <")[0].split(" [")[0]} `);
1977
+ rl.prompt();
1978
+ continue;
1979
+ }
1980
+ }
1981
+ if (input === "/exit" || input === ":q") {
1982
+ rl.close();
1983
+ console.log("");
1984
+ console.log(
1985
+ ui.box({
1986
+ title: "bolt",
1987
+ w: ui.width(),
1988
+ lines: [
1989
+ `${ui.c.success(ui.GLYPH.tick)} session ${ui.c.primary(sess.id)} saved ${ui.c.muted(ui.GLYPH.dot)} ${sess.turns.length} turn${sess.turns.length === 1 ? "" : "s"}`,
1990
+ `${ui.c.muted("resume with")} ${ui.c.primary("bolt run -c")}`,
1991
+ ],
1992
+ }),
1993
+ );
1994
+ console.log("");
1995
+ return;
1996
+ }
1997
+ // A bare slash opens the live filter-as-you-type palette: each row shows
1998
+ // the command name plus its brief definition, typing narrows it, up/down
1999
+ // moves, enter runs or fills, esc cancels. Without a TTY there are no
2000
+ // arrow keys, so fall back to the plain static list.
2001
+ if (input === "/") {
2002
+ const all = present.paletteItems(COMMANDS, AGENTS);
2003
+ if (!ui.selectable(all)) {
2004
+ printPaletteNumbered(all);
2005
+ ui.info("type the number to run it, /text to narrow, or anything else to cancel");
2006
+ pendingPalette = all;
2007
+ rl.prompt();
2008
+ continue;
2009
+ }
2010
+ rl.pause();
2011
+ const { item, tabFill } = await ui.selectLive({ title: "commands", items: all, initialFilter: "" });
2012
+ rl.resume();
2013
+ setPrompt();
2014
+ if (!item) {
2015
+ rl.prompt();
2016
+ continue;
2017
+ }
2018
+ if (tabFill) {
2019
+ rl.write(`${item.label.split(" <")[0].split(" [")[0]} `);
2020
+ rl.prompt();
2021
+ continue;
2022
+ }
2023
+ if (item.label === "/" || item.label === "/help") {
2024
+ printPalette("");
2025
+ rl.prompt();
2026
+ continue;
2027
+ }
2028
+ if (isPaletteRunnable(item.label)) {
2029
+ input = item.label;
2030
+ } else {
2031
+ rl.write(`${item.label.split(" <")[0].split(" [")[0]} `);
2032
+ rl.prompt();
2033
+ continue;
2034
+ }
2035
+ }
2036
+ if (input === "/help" || input === "/commands" || input === "?" || input.startsWith("/help ")) {
2037
+ // `/help <cmd>` prints the one-line detail; a bare call opens the
2038
+ // grouped box and arms the numbered picker like the flat list did.
2039
+ const topic = input.startsWith("/help ") ? input.slice(6).trim() : "";
2040
+ if (topic) {
2041
+ const detail = present.helpDetail(topic, COMMANDS);
2042
+ if (detail) console.log(` ${detail}`);
2043
+ else ui.info(`no command matches "${topic}" - /help lists everything`);
2044
+ rl.prompt();
2045
+ continue;
2046
+ }
2047
+ const flat = printHelpBox();
2048
+ ui.info("type the number to run it, /text to narrow, or anything else to cancel");
2049
+ pendingPalette = flat;
2050
+ rl.prompt();
2051
+ continue;
2052
+ }
2053
+ if (input === "/status") {
2054
+ console.log("");
2055
+ console.log(
2056
+ ui.box({
2057
+ title: "status",
2058
+ w: ui.width(),
2059
+ lines: present.statusLines({
2060
+ sid: sess.id,
2061
+ mode,
2062
+ target,
2063
+ agent: armedAgent,
2064
+ files: files.length,
2065
+ tools: toolsOn,
2066
+ balance,
2067
+ turns: sess.turns.length,
2068
+ memChars: mem.text ? mem.text.length : 0,
2069
+ cwd: process.cwd(),
2070
+ backend: backendHost(cfg.url),
2071
+ }),
2072
+ }),
2073
+ );
2074
+ console.log("");
2075
+ rl.prompt();
2076
+ continue;
2077
+ }
2078
+ if (input === "/keys") {
2079
+ console.log("");
2080
+ printKeysBox();
2081
+ console.log("");
2082
+ rl.prompt();
2083
+ continue;
2084
+ }
2085
+ if (input === "/sessions" || input.startsWith("/sessions ")) {
2086
+ const q = input.slice(9).trim().replace(/^\//, "");
2087
+ let all = [];
2088
+ try {
2089
+ all = session.list();
2090
+ } catch {
2091
+ all = [];
2092
+ }
2093
+ if (!all.length) {
2094
+ ui.info("no saved sessions yet - they appear after your first run");
2095
+ rl.prompt();
2096
+ continue;
2097
+ }
2098
+ const rows = present.sessionRows(all, sess.id);
2099
+ const items = q ? rows.filter((r) => `${r.label} ${r.hint || ""}`.toLowerCase().includes(q.toLowerCase())) : rows;
2100
+ if (!items.length) {
2101
+ ui.info(`no session matches "${q}"`);
2102
+ rl.prompt();
2103
+ continue;
2104
+ }
2105
+ if (!ui.selectable(items)) {
2106
+ printSessionTable(items);
2107
+ ui.info("resume with /session <id> (Tab completes)");
2108
+ rl.prompt();
2109
+ continue;
2110
+ }
2111
+ rl.pause();
2112
+ const { item, tabFill } = await ui.selectLive({ title: "sessions", items, initialFilter: q });
2113
+ rl.resume();
2114
+ setPrompt();
2115
+ if (!item || tabFill) {
2116
+ if (item && tabFill) rl.write(`${item.label.split(" <")[0].split(" [")[0]} `);
2117
+ rl.prompt();
2118
+ continue;
2119
+ }
2120
+ const loaded = session.load(item.id);
2121
+ if (!loaded) ui.err(`session "${item.id}" not found`);
2122
+ else {
2123
+ sess = loaded;
2124
+ setPrompt();
2125
+ ui.ok(`resumed ${ui.c.primary(sess.id)} ${ui.c.muted(ui.GLYPH.dot)} ${loaded.turns.length} turns`);
2126
+ }
2127
+ rl.prompt();
2128
+ continue;
2129
+ }
2130
+ // A partial command opens the live arrow-key palette instead of dumping
2131
+ // a static list: type to filter, backspace refines, up/down moves, enter
2132
+ // runs a complete command or fills the line for one needing args.
2133
+ const exactCommands = ["/exit", "/help", "/commands", "/status", "/sessions", "/keys", "/watch", "/agents", "/models", "/balance", "/clear", "/session", "/tools", "/allow-all", "/permissions", "/init", "/resume", "/copy", "/mode", "/target", "/file", "/agent", "/undo", "/retry", "/export", "/doctor", "/templates"];
2134
+ if (input.startsWith("/") && !input.includes(" ") && !exactCommands.includes(input)) {
2135
+ const q = input.slice(1);
2136
+ const all = present.paletteItems(COMMANDS, AGENTS);
2137
+ const items = present.filterPalette(q, COMMANDS, AGENTS);
2138
+ if (!items.length) {
2139
+ printPalette(q);
2140
+ rl.prompt();
2141
+ continue;
2142
+ }
2143
+ // Hand stdin to the picker, then run or fill the line.
2144
+ // Without arrow keys the numbered list above is the picker: the next
2145
+ // line answers it instead of swallowing the matches.
2146
+ if (!ui.selectable(all)) {
2147
+ printPaletteNumbered(items);
2148
+ ui.info("type the number to run it, /text to narrow, or anything else to cancel");
2149
+ pendingPalette = items;
2150
+ rl.prompt();
2151
+ continue;
2152
+ }
2153
+ rl.pause();
2154
+ const { item, tabFill } = await ui.selectLive({ title: "commands", items: all, initialFilter: q });
2155
+ rl.resume();
2156
+ setPrompt();
2157
+ if (!item) {
2158
+ rl.prompt();
2159
+ continue;
2160
+ }
2161
+ if (tabFill) {
2162
+ rl.write(`${item.label.split(" <")[0].split(" [")[0]} `);
2163
+ rl.prompt();
2164
+ continue;
2165
+ }
2166
+ if (item.label === "/" || item.label === "/help") {
2167
+ printPalette("");
2168
+ rl.prompt();
2169
+ continue;
2170
+ }
2171
+ if (isPaletteRunnable(item.label)) {
2172
+ input = item.label;
2173
+ } else {
2174
+ rl.write(`${item.label.split(" <")[0].split(" [")[0]} `);
2175
+ rl.prompt();
2176
+ continue;
2177
+ }
2178
+ }
2179
+ if (input === "/agents") {
2180
+ printAgents();
2181
+ rl.prompt();
2182
+ continue;
2183
+ }
2184
+ if (input === "/models" || input === "/model") {
2185
+ console.log(` ${ui.c.primary(ui.c.bold("bolt"))} ${ui.c.muted("the only backend - no providers, no model picker. Runs bill your token balance.")}`);
2186
+ rl.prompt();
2187
+ continue;
2188
+ }
2189
+ if (input.startsWith("/agent ")) {
2190
+ const name = input.slice(7).trim();
2191
+ if (!AGENTS[name]) {
2192
+ ui.err(`unknown agent "${name}"`);
2193
+ printAgents();
2194
+ } else {
2195
+ armedAgent = name;
2196
+ setPrompt();
2197
+ ui.ok(`armed ${ui.c.accent(ui.c.bold(name))} ${ui.c.muted(ui.GLYPH.dot)} ${ui.c.muted(AGENTS[name].desc)}`);
2198
+ }
2199
+ rl.prompt();
2200
+ continue;
2201
+ }
2202
+ if (input.startsWith("/mode ")) {
2203
+ const m = input.slice(6).trim();
2204
+ if (m !== "offensive" && m !== "defensive") ui.err("--mode must be offensive or defensive");
2205
+ else {
2206
+ mode = m;
2207
+ setPrompt();
2208
+ ui.ok(`mode ${ui.c.bold(m)}`);
2209
+ }
2210
+ rl.prompt();
2211
+ continue;
2212
+ }
2213
+ if (input.startsWith("/target ")) {
2214
+ target = input.slice(8).trim();
2215
+ setPrompt();
2216
+ if (target) ui.ok(`target ${ui.c.accent(ui.c.bold(target))}`);
2217
+ else ui.info("target cleared");
2218
+ rl.prompt();
2219
+ continue;
2220
+ }
2221
+ if (input.startsWith("/file ")) {
2222
+ const f = input.slice(6).trim();
2223
+ try {
2224
+ fs.accessSync(f, fs.constants.R_OK);
2225
+ files.push(f);
2226
+ setPrompt();
2227
+ ui.ok(`attached ${ui.c.bold(path.basename(f))}`);
2228
+ } catch {
2229
+ ui.err(`cannot read ${f}`);
2230
+ }
2231
+ rl.prompt();
2232
+ continue;
2233
+ }
2234
+ if (input === "/clear") {
2235
+ files.length = 0;
2236
+ armedAgent = "";
2237
+ setPrompt();
2238
+ ui.info("attachments cleared, agent disarmed");
2239
+ rl.prompt();
2240
+ continue;
2241
+ }
2242
+ if (input === "/copy") {
2243
+ if (!lastAnswer) {
2244
+ ui.info("nothing to copy yet - run something first");
2245
+ } else {
2246
+ const copied = await copyToClipboard(lastAnswer);
2247
+ if (copied.ok) ui.ok("copied last answer to clipboard");
2248
+ else ui.err(`copy failed: ${copied.error}`);
2249
+ }
2250
+ rl.prompt();
2251
+ continue;
2252
+ }
2253
+ if (input === "/doctor") {
2254
+ const checks = await doctor.runDoctor({ url: cfg.url });
2255
+ console.log(doctor.formatDoctor(checks));
2256
+ rl.prompt();
2257
+ continue;
2258
+ }
2259
+ if (input === "/watch" || input.startsWith("/watch ")) {
2260
+ const parts = input.split(/\s+/).slice(1);
2261
+ try {
2262
+ await cmdWatch(parts.length ? parts : ["status"], { setExitCode: false });
2263
+ } catch (error) {
2264
+ ui.err(error && error.message ? error.message : String(error));
2265
+ }
2266
+ rl.prompt();
2267
+ continue;
2268
+ }
2269
+ if (input === "/templates" || input.startsWith("/templates ")) {
2270
+ try {
2271
+ cmdTemplates(input.split(/\s+/).slice(1));
2272
+ } catch (error) {
2273
+ ui.err(error && error.message ? error.message : String(error));
2274
+ }
2275
+ rl.prompt();
2276
+ continue;
2277
+ }
2278
+ if (input === "/retry") {
2279
+ const last = sess.turns.length ? sess.turns[sess.turns.length - 1] : null;
2280
+ if (!last) {
2281
+ ui.info("nothing to retry yet");
2282
+ rl.prompt();
2283
+ continue;
2284
+ }
2285
+ input = last.prompt;
2286
+ // fall through to the normal run path below
2287
+ } else if (input.startsWith("/undo ")) {
2288
+ const target = input.slice(6).trim();
2289
+ if (!target) ui.err("usage: /undo <path>");
2290
+ else {
2291
+ const r = checkpoints.restore(process.cwd(), target);
2292
+ if (r.ok) ui.ok(r.detail);
2293
+ else ui.err(r.detail);
2294
+ }
2295
+ rl.prompt();
2296
+ continue;
2297
+ } else if (input === "/export" || input.startsWith("/export ")) {
2298
+ const fmt = (input.slice(7).trim() || "md").toLowerCase();
2299
+ try {
2300
+ const text = exporter.exportSession(sess, fmt);
2301
+ const dest = path.join(process.cwd(), `bolt-${sess.id}.${fmt === "sarif" ? "sarif.json" : fmt === "json" ? "json" : "md"}`);
2302
+ fs.writeFileSync(dest, text + "\n");
2303
+ ui.ok(`exported ${sess.id} (${fmt}) to ${dest}`);
2304
+ } catch (e) {
2305
+ ui.err(e.message);
2306
+ }
2307
+ rl.prompt();
2308
+ continue;
2309
+ }
2310
+ if (input === "/balance") {
2311
+ try {
2312
+ const stats = await api.getStats(cfg.url, cfg.token);
2313
+ balance = stats.balance;
2314
+ setPrompt();
2315
+ console.log(`${ui.c.muted("balance")} ${ui.c.primary(ui.c.bold(stats.balance))} ${ui.c.muted("tokens")} ${ui.c.muted(ui.GLYPH.dot)} spent ${ui.c.muted(stats.tokensSpent)} ${ui.c.muted(ui.GLYPH.dot)} ${stats.prompts} runs this month`);
2316
+ } catch (e) {
2317
+ ui.err(`balance failed: ${e.message}`);
2318
+ }
2319
+ rl.prompt();
2320
+ continue;
2321
+ }
2322
+ if (input === "/session" || input.startsWith("/session ")) {
2323
+ const argLine = input.slice(8).trim();
2324
+ if (!argLine) {
2325
+ console.log(`${ui.c.muted("session")} ${ui.c.primary(sess.id)} ${ui.c.muted(ui.GLYPH.dot)} ${sess.turns.length} turns ${ui.c.muted(ui.GLYPH.dot)} mode ${mode} ${ui.c.muted(ui.GLYPH.dot)} target ${target || "(none)"} ${ui.c.muted(ui.GLYPH.dot)} agent ${armedAgent || "(none)"}`);
2326
+ } else if (argLine === "new") {
2327
+ sess = session.create("interactive");
2328
+ files.length = 0;
2329
+ armedAgent = "";
2330
+ balance = null;
2331
+ setPrompt();
2332
+ ui.ok(`new session ${ui.c.primary(sess.id)}`);
2333
+ } else {
2334
+ const loaded = session.load(argLine);
2335
+ if (!loaded) ui.err(`session "${argLine}" not found`);
2336
+ else {
2337
+ sess = loaded;
2338
+ setPrompt();
2339
+ ui.ok(`resumed ${ui.c.primary(sess.id)} ${ui.c.muted(ui.GLYPH.dot)} ${loaded.turns.length} turns`);
2340
+ }
2341
+ }
2342
+ rl.prompt();
2343
+ continue;
2344
+ }
2345
+ if (input === "/tools" || input.startsWith("/tools ")) {
2346
+ const toolsArg = input.slice(6).trim().toLowerCase();
2347
+ if (toolsArg === "on") toolsOn = true;
2348
+ else if (toolsArg === "off") toolsOn = false;
2349
+ else toolsOn = !toolsOn;
2350
+ setPrompt();
2351
+ ui.ok(toolsOn ? "tools on — read, search, edit, shell (writes and shell ask first)" : "tools off — plain answers, no file or shell access");
2352
+ rl.prompt();
2353
+ continue;
2354
+ }
2355
+ if (input === "/allow-all") {
2356
+ allowAll = !allowAll;
2357
+ if (allowAll) ui.warn("allow-all ON: every tool call is approved without asking, including file edits and shell commands.");
2358
+ else ui.ok("allow-all off — writes, edits and shell commands ask first again.");
2359
+ rl.prompt();
2360
+ continue;
2361
+ }
2362
+ if (input === "/permissions" || input.startsWith("/permissions ")) {
2363
+ const sub = input.slice(12).trim();
2364
+ const store = permissions.load();
2365
+ if (!sub || sub === "list") {
2366
+ const keys = permissions.listAlways(store);
2367
+ if (!keys.length) ui.info("no always-allowed tools yet - pick Always allow when asked.");
2368
+ else {
2369
+ console.log(` ${ui.c.bold("always allowed")} ${ui.c.muted(`(${keys.length})`)}`);
2370
+ for (const k of keys) console.log(` ${ui.c.success("·")} ${k}`);
2371
+ console.log(` ${ui.c.muted("revoke one with /permissions revoke <key> - clear all with /permissions clear")}`);
2372
+ }
2373
+ } else if (sub === "clear") {
2374
+ permissions.save({ version: 1, always: {} });
2375
+ ui.ok("cleared all always-allowed tools - everything asks again.");
2376
+ } else if (sub.startsWith("revoke ")) {
2377
+ const key = sub.slice(7).trim();
2378
+ if (!key) ui.err("usage: /permissions revoke <key>");
2379
+ else {
2380
+ const next = permissions.revoke(store, key);
2381
+ permissions.save(next);
2382
+ ui.ok(`revoked ${ui.c.bold(key)}`);
2383
+ }
2384
+ } else {
2385
+ ui.err(`unknown /permissions command "${sub}" - use list, revoke <key>, or clear`);
2386
+ }
2387
+ rl.prompt();
2388
+ continue;
2389
+ }
2390
+ if (input === "/init") {
2391
+ const objective = "Explore this project: read its configs, entry points and README (follow imports a level or two), then write a concise BOLT.md at the project root covering what the project is, how to build/test/run it, key directories, and conventions. Keep it under 60 lines.";
2392
+ rl.pause();
2393
+ const live = ui.createStream(ui.write);
2394
+ const turn = present.streamingWriter(live);
2395
+ try {
2396
+ const alwaysStore = permissions.load();
2397
+ await agent.runAgentLoop({
2398
+ cfg, objective, mode, target, evidence: "", sess,
2399
+ stream: loopStream(turn),
2400
+ events: handleToolEvent,
2401
+ policy: {
2402
+ allowAll,
2403
+ sessionAllowed,
2404
+ ask: allowAll ? null : makeAsker(),
2405
+ askQuestion: makeAskQuestion(),
2406
+ alwaysStore,
2407
+ persistAlways: allowAll ? null : (call) => {
2408
+ const next = permissions.allowAlways(permissions.load(), call);
2409
+ permissions.save(next);
2410
+ alwaysStore.always = next.always;
2411
+ },
2412
+ },
2413
+ maxIters: agent.DEFAULT_MAX_ITERS,
2414
+ memory: mem.text,
2415
+ });
2416
+ ui.ok("init done — see BOLT.md");
2417
+ // /init just wrote the memory file: pick it up for the rest of the
2418
+ // session instead of waiting for a restart.
2419
+ mem = memory.loadMemory(process.cwd());
2420
+ } catch (e) {
2421
+ ui.err(e.message);
2422
+ } finally {
2423
+ rl.resume();
2424
+ }
2425
+ rl.prompt();
2426
+ continue;
2427
+ }
2428
+ if (input === "/resume" || input.startsWith("/resume ")) {
2429
+ const resumeArg = input.slice(7).trim();
2430
+ const resume = (id) => {
2431
+ const loaded = session.load(id);
2432
+ if (!loaded) {
2433
+ ui.err(`session "${id}" not found`);
2434
+ return;
2435
+ }
2436
+ sess = loaded;
2437
+ files.length = 0;
2438
+ armedAgent = "";
2439
+ setPrompt();
2440
+ ui.ok(`resumed ${ui.c.primary(sess.id)} ${ui.c.muted(ui.GLYPH.dot)} ${loaded.turns.length} turns`);
2441
+ };
2442
+ if (resumeArg) {
2443
+ resume(resumeArg);
2444
+ rl.prompt();
2445
+ continue;
2446
+ }
2447
+ const all = session.list();
2448
+ if (!all.length) {
2449
+ ui.info("no saved sessions yet");
2450
+ rl.prompt();
2451
+ continue;
2452
+ }
2453
+ if (!ui.selectable(all.map((s) => ({ label: s.id })))) {
2454
+ for (const s of all) console.log(` ${s.id} ${s.turns} turns ${s.title}`);
2455
+ rl.prompt();
2456
+ continue;
2457
+ }
2458
+ rl.pause();
2459
+ try {
2460
+ const items = all.map((s) => ({ label: s.id, hint: `${s.title} - ${s.turns} turns` }));
2461
+ const picked = await ui.select({ title: "sessions", items });
2462
+ if (picked >= 0) resume(items[picked].label);
2463
+ } finally {
2464
+ rl.resume();
2465
+ }
2466
+ setPrompt();
2467
+ rl.prompt();
2468
+ continue;
2469
+ }
2470
+ if (input.startsWith("/")) {
2471
+ ui.err(`unknown command ${input}`);
2472
+ ui.info("press / to open the command palette");
2473
+ rl.prompt();
2474
+ continue;
2475
+ }
2476
+ try {
2477
+ const parts = [];
2478
+ for (const f of files) {
2479
+ try {
2480
+ parts.push(`--- ${path.basename(f)} ---\n${fs.readFileSync(f, "utf8").slice(0, 12000)}`);
2481
+ } catch {
2482
+ ui.warn(`skipped unreadable ${f}`);
2483
+ }
2484
+ }
2485
+ // @-mentions inline files as evidence, Claude Code style.
2486
+ const mentions = tools.resolveMentions(input, process.cwd());
2487
+ if (mentions.files.length) ui.info(`attached ${mentions.files.join(", ")}`);
2488
+ const evidenceText = [parts.join("\n\n"), mentions.evidence].filter(Boolean).join("\n\n");
2489
+ let objective = input;
2490
+ if (armedAgent) objective = applyAgent(armedAgent, input, target);
2491
+ // Readline must not compete with the stream for the cursor, so it pauses
2492
+ // for the duration of the turn. The old code left it live, which is why
2493
+ // the prompt could interleave mid-answer.
2494
+ rl.pause();
2495
+ const live = ui.createStream(ui.write);
2496
+ const turn = present.streamingWriter(live);
2497
+ // Esc aborts the in-flight request; the session turn is still saved.
2498
+ const canceller = cancel.createCanceller();
2499
+ canceller.attach();
2500
+ try {
2501
+ let done = null;
2502
+ let settled = false;
2503
+ if (toolsOn) {
2504
+ let loopResult;
2505
+ try {
2506
+ loopResult = await agent.runAgentLoop({
2507
+ cfg, objective, mode, target, evidence: evidenceText, sess,
2508
+ stream: loopStream(turn),
2509
+ events: handleToolEvent,
2510
+ policy: {
2511
+ allowAll,
2512
+ sessionAllowed,
2513
+ ask: allowAll ? null : makeAsker(),
2514
+ askQuestion: makeAskQuestion(),
2515
+ alwaysStore,
2516
+ persistAlways: allowAll ? null : persistAlways,
2517
+ },
2518
+ maxIters: agent.DEFAULT_MAX_ITERS,
2519
+ memory: mem.text,
2520
+ signal: canceller.signal,
2521
+ });
2522
+ } catch (error) {
2523
+ try {
2524
+ turn.cancel();
2525
+ } catch {
2526
+ // Teardown never masks the run error.
2527
+ }
2528
+ reportRunError(error);
2529
+ settled = true;
2530
+ }
2531
+ if (!settled) {
2532
+ if ((loopResult && loopResult.cancelled) || canceller.cancelled) {
2533
+ try {
2534
+ turn.cancel();
2535
+ } catch {
2536
+ // ignore
2537
+ }
2538
+ ui.warn("Cancelled — session saved. Press Esc during a run to stop it; close the terminal only to quit entirely.");
2539
+ settled = true;
2540
+ } else if (loopResult) {
2541
+ lastAnswer = loopResult.text;
2542
+ done = loopResult.done;
2543
+ }
2544
+ }
2545
+ } else {
2546
+ turn.begin();
2547
+ let single;
2548
+ try {
2549
+ single = await executeTurn({
2550
+ cfg, objective, mode, target, evidence: evidenceText, sess,
2551
+ onToken: turn.write,
2552
+ memory: mem.text,
2553
+ signal: canceller.signal,
2554
+ });
2555
+ } catch (error) {
2556
+ try {
2557
+ turn.cancel();
2558
+ } catch {
2559
+ // Teardown never masks the run error.
2560
+ }
2561
+ reportRunError(error);
2562
+ single = null;
2563
+ }
2564
+ if (single) {
2565
+ turn.end();
2566
+ done = single.done;
2567
+ lastAnswer = single.text;
2568
+ if (single.redactions > 0) ui.info(`redacted ${single.redactions} possible secret${single.redactions === 1 ? "" : "s"} from the prompt before sending`);
2569
+ } else {
2570
+ settled = true;
2571
+ }
2572
+ }
2573
+ if (!settled) {
2574
+ warnTruncated(done);
2575
+ if (done && done.remainingTokens !== undefined) {
2576
+ if (done.remainingTokens !== balance) {
2577
+ balance = done.remainingTokens;
2578
+ setPrompt();
2579
+ }
2580
+ ui.status(present.turnFooter({ done, elapsed: turn.elapsed(), turns: sess.turns.length }));
2581
+ }
2582
+ }
2583
+ } finally {
2584
+ canceller.detach();
2585
+ rl.resume();
2586
+ }
2587
+ } catch (e) {
2588
+ ui.err(e.message);
2589
+ }
2590
+ rl.prompt();
2591
+ }
2592
+ }
2593
+
2594
+ async function run(argv) {
2595
+ const [cmd, ...rest] = argv;
2596
+ if (!cmd) {
2597
+ if (process.stdin.isTTY) return cmdRepl();
2598
+ // Piped input with no command: single non-interactive run.
2599
+ return cmdRun([], { buildMode: false });
2600
+ }
2601
+ if (flag(argv, "-h", "--help") && (cmd === "run" || cmd === "build" || cmd === "watch" || cmd === "session" || cmd === "auth" || cmd === "signin" || cmd === "-p" || cmd === "--print" || cmd === "export" || cmd === "doctor" || cmd === "completion" || cmd === "undo" || cmd === "update")) {
2602
+ console.log(help(cmd === "-p" || cmd === "--print" ? "run" : cmd));
2603
+ return;
2604
+ }
2605
+ if (cmd === "help") {
2606
+ console.log(help(rest[0] || ""));
2607
+ return;
2608
+ }
2609
+ if (flag([cmd], "--help", "-h")) {
2610
+ console.log(help());
2611
+ return;
2612
+ }
2613
+ if (flag([cmd], "-v", "--version")) {
2614
+ console.log(VERSION);
2615
+ return;
2616
+ }
2617
+ // `signin`/`login` are the spellings people try first; both open the browser.
2618
+ if (cmd === "signin" || cmd === "login") return cmdSignin(rest);
2619
+ if (cmd === "auth") return cmdAuth(rest);
2620
+ if (cmd === "balance") return cmdBalance();
2621
+ if (cmd === "run") return cmdRun(rest, { buildMode: false });
2622
+ // Print mode: the agent loop runs headless and only the final answer is
2623
+ // printed. Mutations are denied without --allow-all.
2624
+ if (cmd === "-p" || cmd === "--print") return cmdRun(rest, { buildMode: false, printMode: true });
2625
+ if (cmd === "build") return cmdRun(rest, { buildMode: true });
2626
+ if (cmd === "session") return cmdSession(rest);
2627
+ if (cmd === "doctor") return cmdDoctor();
2628
+ if (cmd === "update") return cmdUpdate();
2629
+ if (cmd === "completion") return cmdCompletion(rest);
2630
+ if (cmd === "export") return cmdExport(rest);
2631
+ if (cmd === "undo") return cmdUndo(rest);
2632
+ if (cmd === "templates") return cmdTemplates(rest);
2633
+ if (cmd === "watch") return cmdWatch(rest);
2634
+ throw new Error(`Unknown command "${cmd}".\n${help()}`);
2635
+ }
2636
+
2637
+ module.exports = { run, resolveUrl, isLoopbackUrl, backendReachable, completer, completeFileFrag, completeWithDescriptions, filterPaletteItems, isPaletteRunnable, COMMANDS, AGENTS, NO_ARG_COMMANDS, makeAsker, makeAskQuestion, handleToolEvent, estimateTokens, buildDryRunReport, printDryRun, dryRunTools, argvSecretWarning, cmdDoctor, cmdCompletion, cmdTemplates, cmdExport, cmdUndo, reportRunError, warnTruncated, stripBoltPrefix, printPaletteNumbered, resolvePalettePick, replWelcomeLines, printHelpBox, printSessionTable, printKeysBox, pickTip, TIPS, formatElapsed, backendHost };