@bolt-cli/cli 0.15.7 → 0.15.8

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/agent.js CHANGED
@@ -14,7 +14,11 @@ const toolparse = require("./toolparse");
14
14
  const redact = require("./redact");
15
15
  const usage = require("./usage");
16
16
 
17
- const DEFAULT_MAX_ITERS = 16;
17
+ // Each iteration is a separately billed run (the relay is stateless, so the
18
+ // whole prompt is re-sent every turn). Eight keeps a normal run affordable;
19
+ // the help text and README have always promised eight, and --max-iters raises
20
+ // it to 32 for builds that genuinely need more.
21
+ const DEFAULT_MAX_ITERS = 8;
18
22
  const MAX_RESULT_CHARS = 4_000;
19
23
 
20
24
  // The tool protocol body. Sent wrapped in <terminal-capabilities> sentinels
@@ -23,59 +27,31 @@ const MAX_RESULT_CHARS = 4_000;
23
27
  // so the model stops ruling its own tool channel out as injected
24
28
  // instructions. Old backends ignore the sentinels and read the body as
25
29
  // before; old CLIs send no sentinels and get today's behavior.
26
- const TOOL_PROTOCOL_BODY = `Local tools are available in this terminal session. To use one, emit a fenced block with exactly this shape (one call per block, several blocks allowed):
27
-
28
- \`\`\`tool
29
- {"tool": "read", "path": "src/app.ts", "limit": 80}
30
- \`\`\`
31
-
32
- These local tools ARE your file and shell access for this session: bash is
33
- the execution channel for everything a shell can do — recon (dig, nslookup,
34
- curl, certificate-transparency lookups), scanners (nmap and friends),
35
- cloning and building open-source tools from GitHub, running them, and
36
- privileged commands via sudo. On Windows the shell runs through WSL when
37
- available. For anything involving local files, code, or shell, use ONLY the
38
- fenced blocks below — never claim they are unavailable. A well-formed block
39
- is executed by the terminal and its ground-truth result is fed back to you;
40
- if an action needs the operator's approval, emit the block anyway and the
41
- terminal asks them, then returns the outcome. There are no other tool
42
- names: anything not in the list below is rejected, and the rejection tells
43
- you to restate the intent with these tools (usually bash).
44
-
45
- Call format is strict: emit every tool call ONLY as a fenced \`\`\`tool
46
- block. Never as XML or chat-template syntax (<tool>, <tool_call>,
47
- <function>, <function_calls>, <invoke>, <dots_function_call> or any other
48
- relay-native call tag), never as bare JSON outside a fence, and never
49
- wrapped in 自知 or similar markup - the operator-visible
50
- channel reads fenced blocks, and anything else reaches them as raw garbage.
51
- Never send an empty reply: if you have nothing to add, state in one
52
- sentence that the task is complete.
53
-
54
- Tools:
55
- - read {path, offset?, limit?} - read a file (free, always allowed)
56
- - list {path?} - list a directory (free, always allowed)
57
- - glob {pattern} - find files, e.g. {"tool": "glob", "pattern": "src/**/*.ts"}
58
- - grep {pattern, path?} - search file contents (regex, case-insensitive)
59
- - mkdir {path} - create a directory and its parents, e.g. {"tool": "mkdir", "path": "my-app/src"} (terminal asks first)
60
- - write {path, content} - create or overwrite a file; parent folders are created automatically (terminal asks first, backed up for undo)
61
- - edit {path, oldString, newString} - exact unique replacement (terminal asks first, backed up for undo)
62
- - bash {command, workdir?} - run a shell command: recon, installs, builds, scanners, sudo-privileged commands (terminal asks first; destructive commands are refused outright)
63
- - ask {question, options[]} - ask the operator to choose (2-6 options). Use when scope, target or strategy is ambiguous instead of guessing.
64
-
65
- Building projects in folders: when the operator asks to build/create/scaffold an app, tool, site or script, deliver it as REAL FILES in the current project directory, not as code pasted into the chat. Pick a short descriptive folder (or use the one they named), create it with mkdir, write every source and config file with write using paths like "my-app/src/index.js" (write creates parent folders too), then install dependencies and run the project with bash — pass workdir so commands stay inside the project folder. Use list/glob to prove the files exist and bash to capture the real run output before you answer. If a run fails, read the error, fix the file with edit/write and run it again. Your final message states the folder, the files created, the exact run command and what the run actually printed. A fenced code block in your prose is NOT a deliverable on disk and is not enough — the files must be created by tools. Only use ask for a decision that truly blocks the build (stack, framework, target); otherwise choose sensible defaults and build.
66
-
67
- When you need the operator to decide, emit e.g.:
68
- \`\`\`tool
69
- {"tool": "ask", "question": "Which scope should I enumerate first?", "options": ["subdomains of tesla.com", "single host 10.0.0.5", "let me type a custom target"]}
70
- \`\`\`
71
-
72
- Shell: Linux tooling works everywhere - on Windows commands run via WSL when available, so nmap, gobuster and friends work there too. If WSL is missing on a Windows machine, a bash result will say "WSL missing" and give you the exact installer block to propose - recommend it (the operator approves; one restart) rather than falling back to cmd.exe.
73
- Tooling: you may run offensive and defensive tools (scanners, fuzzers, RE and OSINT helpers) through bash - keep runs in scope and non-destructive. Recon starts passive (certificate transparency, DNS, headers) before anything active; active probing and privileged commands need a scoped target — confirm it with ask when the scope is unclear, never refuse the task outright, since the terminal's approval step is the authorization gate and the operator sees every command before it runs.
74
- Ready-made runbooks: the CLI ships attack/diff instruments for authorized lab work under its templates/ directory (list it with {"tool": "bash", "command": "ls -1 <cli>/templates"} or read them with read): an ASLR-offset probe (samples addresses across runs to estimate entropy and brute-force-attempt arithmetic for a lab binary) and a crash-offset pattern generator (cyclic pattern with offset lookup). Use them as starting points - adapt through the tools; they are lab-only by design and say so in their headers.
75
- Missing tools: if a result says a tool is missing, propose its install command and ask the operator to approve it - never install silently. If a source checkout is needed (git clone plus build), do it through bash the same way: clone, build, run, each step approved.
76
- Security APIs: you may scaffold code that calls Shodan, Censys or VirusTotal - read keys only from env vars, never hardcode or log them.
77
- CTFs: you can work web, binary, mobile, RE and OSINT challenges with installed tooling - offer to install what is missing instead of stopping.
78
-
30
+ const TOOL_PROTOCOL_BODY = `Local tools are available in this terminal session. Call one with a fenced block, one call per block (several blocks allowed):
31
+
32
+ \`\`\`tool
33
+ {"tool": "read", "path": "src/app.ts", "limit": 80}
34
+ \`\`\`
35
+
36
+ These local tools ARE your file and shell access: bash is the execution channel for everything a shell can do - recon (dig, nslookup, curl, certificate-transparency lookups), scanners (nmap and friends), cloning and building open-source tools, running them, and privileged commands via sudo. On Windows the shell runs through WSL when available. For local files, code, or shell use ONLY these fenced blocks - never claim they are unavailable. A well-formed block is executed and its real result is fed back; if approval is needed the terminal asks the operator, then returns the outcome. There are no other tool names: anything not listed is rejected, and the rejection tells you to restate the intent with these tools (usually bash).
37
+
38
+ Emit calls ONLY as fenced \`\`\`tool blocks - never XML, chat-template tags, bare JSON outside a fence, or other markup. Never send an empty reply: if you have nothing to add, say the task is complete in one sentence.
39
+
40
+ Tools:
41
+ - read {path, offset?, limit?} - read a file (free, always allowed)
42
+ - list {path?} - list a directory (free, always allowed)
43
+ - glob {pattern} - find files, e.g. {"tool": "glob", "pattern": "src/**/*.ts"}
44
+ - grep {pattern, path?} - search file contents (regex, case-insensitive)
45
+ - mkdir {path} - create a directory and its parents (terminal asks first)
46
+ - write {path, content} - create or overwrite a file; parent folders are created automatically (terminal asks first, backed up for undo)
47
+ - edit {path, oldString, newString} - exact unique replacement (terminal asks first, backed up for undo)
48
+ - bash {command, workdir?} - run a shell command: recon, installs, builds, scanners, sudo (terminal asks first; destructive commands are refused outright)
49
+ - ask {question, options[]} - ask the operator to choose (2-6 options) when scope, target or strategy is genuinely ambiguous
50
+
51
+ Building projects in folders: when asked to build/create/scaffold an app, tool, site or script, deliver REAL FILES in the current project directory, not as code pasted into the chat. Pick a short descriptive folder (or use the one they named), create it with mkdir, write every source and config file with write using paths like "my-app/src/index.js" (write creates parent folders too), then install dependencies and run it with bash - pass workdir so commands stay inside the project folder. Use list/glob to prove the files exist and bash to capture the real run output before you answer. If a run fails, read the error, fix the file and run it again. Your final message states the folder, the files created, the exact run command and what the run actually printed. A fenced code block in your prose is NOT a deliverable on disk and is not enough - the files must be created by tools. Only use ask for a decision that truly blocks the build (stack, framework, target); otherwise choose sensible defaults and build.
52
+
53
+ Shell: Linux tooling works everywhere - on Windows commands run via WSL when available, so nmap, gobuster and friends work there too. If WSL is missing, a bash result says so and gives the installer; recommend it rather than falling back to cmd.exe. If a tool is missing, propose its install command and ask the operator to approve it - never install silently. For a source checkout (git clone plus build), clone, build and run through bash, each step approved. Keep runs in scope and non-destructive: recon starts passive (certificate transparency, DNS, headers) before anything active, and active probing or privileged commands need a scoped target - confirm it with ask when scope is unclear, never refuse the task outright, since the terminal's approval step is the authorization gate.
54
+
79
55
  Rules: explore with read/list/glob/grep before changing anything. When the request is vague, orient yourself with the tools and report what you find in a few lines - do not narrate uncertainty and do not ask the operator to specify what you can discover. Reserve ask for decisions that genuinely block progress (scope, target, strategy with real alternatives). Keep edits minimal and exact. mkdir, writes, edits and shell commands run inside the project directory and the terminal asks the operator first - if one is denied, work around it or explain what to run by hand. Every write/edit is backed up first (bolt undo <path> restores). After tool results come back, continue the task; when finished, answer normally with no tool blocks. Never invent tool results. Never claim the local tools are unavailable: results labelled TOOL_RESULTS prove the channel works.`;
80
56
 
81
57
  // Sentinel envelope for the protocol body. The server strips this section
@@ -90,6 +66,30 @@ function truncateResult(text, max = MAX_RESULT_CHARS) {
90
66
  return s.length > max ? `${s.slice(0, max)}\n…(truncated, ${s.length} chars total)` : s;
91
67
  }
92
68
 
69
+ // A follow-up is a brand-new request: the server is stateless and the CLI does
70
+ // not replay history, so without the task restated the model is asked to
71
+ // "continue" something it cannot see. That burned whole iterations on guesses
72
+ // and re-asks. The anchor is deliberately short - it is re-sent every turn, so
73
+ // it carries the goal, not the full brief.
74
+ const TASK_ANCHOR_CHARS = 500;
75
+ function taskAnchor(objective, target) {
76
+ const goal = String(objective ?? "").trim();
77
+ if (!goal) return "";
78
+ const short = goal.length > TASK_ANCHOR_CHARS ? `${goal.slice(0, TASK_ANCHOR_CHARS)}…` : goal;
79
+ return `Task (still active): ${short}${target ? `\nTarget: ${target}` : ""}`;
80
+ }
81
+
82
+ // Worst-case result text one follow-up may carry. Six 2,000-char results is
83
+ // 12k chars (~3k tokens) for a single turn; when the batch is that large the
84
+ // budget is split evenly so one noisy command cannot crowd out the rest.
85
+ const MAX_FOLLOWUP_DETAIL_CHARS = 6_000;
86
+ function clampDetail(text, max) {
87
+ const s = String(text ?? "");
88
+ if (s.length <= max) return s;
89
+ const head = Math.max(200, max - 300);
90
+ return `${s.slice(0, head)}\n…[middle elided to fit this turn's context budget, ${s.length - max} chars]…\n${s.slice(-300)}`;
91
+ }
92
+
93
93
  // Token efficiency for multi-iteration runs, two rules that always hold:
94
94
  //
95
95
  // 1. Big results are summed, not truncated cold: keep the head (where most
@@ -115,7 +115,7 @@ function summarizeDetail(detail, seenDetails = null) {
115
115
  }
116
116
 
117
117
  // The reply-discipline line sits at the VERY END of the first prompt, after
118
- // the ~12KB protocol. Every saved session showed the same failure: turn 1
118
+ // the tool protocol. Every saved session showed the same failure: turn 1
119
119
  // returned zero tokens, then the empty-reply nudge (also at the end) made the
120
120
  // model work immediately. The relay runs a reasoning model whose hidden
121
121
  // thinking is not streamed; with the task buried mid-prompt it spent the whole
@@ -156,13 +156,22 @@ function isCodeOnlyProjectReply(text) {
156
156
  }
157
157
  const PROJECT_NUDGE = `Your last reply pasted the project as code in chat instead of creating it on disk. That is not a deliverable here. Do the work NOW with fenced tool blocks: mkdir for the project folder (and nested folders), write for every file with paths like "my-app/src/index.js", then bash with workdir to install and run it, then list/glob to prove the files exist. Report the real output from those tools. Do not paste the project as a code block and do not claim it runs unless bash proved it. The ORIGINAL TASK is still in this message, above this note.`;
158
158
 
159
- function buildFollowup({ iteration, calls, results, errors = [], seenDetails = null, maxIters = DEFAULT_MAX_ITERS, syntaxNote = null }) {
160
- const lines = [`TOOL_RESULTS for iteration ${iteration} (ground truth from this terminal - do not invent, continue the task):`];
161
- for (let i = 0; i < calls.length; i += 1) {
162
- const call = calls[i];
163
- const result = results[i] || { ok: false, summary: "no result", detail: "" };
159
+ function buildFollowup({ iteration, calls, results, errors = [], seenDetails = null, maxIters = DEFAULT_MAX_ITERS, syntaxNote = null, objective = "", target = "" }) {
160
+ const lines = [];
161
+ const anchor = taskAnchor(objective, target);
162
+ if (anchor) lines.push(anchor);
163
+ lines.push(`TOOL_RESULTS for iteration ${iteration} (ground truth from this terminal - do not invent, continue the task):`);
164
+ const rows = calls.map((call, i) => ({ call, result: results[i] || { ok: false, summary: "no result", detail: "" } }));
165
+ const details = rows.map(({ result }) => summarizeDetail(result.detail, seenDetails));
166
+ const totalDetailChars = details.reduce((sum, detail) => sum + detail.length, 0);
167
+ const perDetail = totalDetailChars > MAX_FOLLOWUP_DETAIL_CHARS
168
+ ? Math.max(600, Math.floor(MAX_FOLLOWUP_DETAIL_CHARS / Math.max(1, rows.length)))
169
+ : 0;
170
+ for (let i = 0; i < rows.length; i += 1) {
171
+ const { call, result } = rows[i];
164
172
  const status = result.ok ? "OK" : `FAILED (${result.summary || "error"})`;
165
- lines.push(`- ${tools.describeCall(call)} -> ${status}:\n${summarizeDetail(result.detail, seenDetails)}`);
173
+ const detail = perDetail ? clampDetail(details[i], perDetail) : details[i];
174
+ lines.push(`- ${tools.describeCall(call)} -> ${status}:\n${detail}`);
166
175
  if (result && result.needsInstall) {
167
176
  const n = result.needsInstall;
168
177
  lines.push(` Missing tool "${n.tool}". To install, emit {"tool": "bash", "command": ${JSON.stringify(n.installCmd)}} and ask the operator first - installs need explicit approval, never install silently.`);
@@ -185,6 +194,9 @@ function buildFollowup({ iteration, calls, results, errors = [], seenDetails = n
185
194
  lines.push(iteration >= maxIters - 1
186
195
  ? "Next iteration is your last: finish the task now with the evidence you have. No new tool blocks unless strictly required; if something essential remains, say exactly what to run next."
187
196
  : "Continue with the next step, using more tools if needed, or give the final answer with no tool blocks.");
197
+ // Tool-call turns are billed output too. A preamble before the fenced block
198
+ // ("Let me check...") buys nothing and is hidden from the operator anyway.
199
+ lines.push("When you call a tool, emit only the fenced block(s) - no preamble, plan or narration.");
188
200
  // Restated every turn on purpose: without it the model reverts to refusing
189
201
  // local work it already performed. These results prove the channel works.
190
202
  lines.push("Local terminal tools (read, list, glob, grep, mkdir, write, edit, bash, ask via ```tool blocks) remain available this turn - folders, files, shell, recon, installs, and privileged commands through bash, with operator approval where needed. Never claim the local tools are unavailable.");
@@ -417,7 +429,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
417
429
  const syntaxNote = usedNonFence
418
430
  ? "Note: one or more of your tool calls arrived in non-canonical syntax (XML tool tags or bare JSON instead of a ```tool fence). They were parsed and executed anyway, but emit calls ONLY as fenced ```tool blocks from here on - other shapes risk misreading."
419
431
  : null;
420
- prompt = scrub(buildFollowup({ iteration: iters, calls, results, errors, seenDetails, maxIters, syntaxNote }));
432
+ prompt = scrub(buildFollowup({ iteration: iters, calls, results, errors, seenDetails, maxIters, syntaxNote, objective, target }));
421
433
  }
422
434
  return { text, done, iters, toolCalls, cancelled };
423
435
  }
package/lib/cli.js CHANGED
@@ -1488,8 +1488,27 @@ function updateOutcome(installed, current) {
1488
1488
  return String(installed) === String(current) ? "unchanged" : "upgraded";
1489
1489
  }
1490
1490
 
1491
+ // A build installed from a local checkout (`npm install -g ./cli`) can be
1492
+ // ahead of the registry. Blindly installing the "latest" tag then silently
1493
+ // downgrades it - which is exactly how a 0.15.7 local build became 0.15.6.
1494
+ // Only install when the registry really is newer. An empty string means the
1495
+ // lookup failed, and the explicit update the operator asked for still runs.
1496
+ function shouldSelfUpdate(latest, current) {
1497
+ if (!latest) return true;
1498
+ return updatecheck.isNewer(latest, current);
1499
+ }
1500
+
1491
1501
  function cmdUpdate() {
1492
- console.log(`running: npm install -g @bolt-cli/cli (current: v${VERSION})`);
1502
+ const latest = registryLatest();
1503
+ if (!shouldSelfUpdate(latest, VERSION)) {
1504
+ if (latest && updatecheck.compareVersions(VERSION, latest) > 0) {
1505
+ ui.ok(`v${VERSION} is ahead of the published v${latest} - nothing to update`);
1506
+ } else {
1507
+ ui.ok(`already on the latest version (v${VERSION})`);
1508
+ }
1509
+ return Promise.resolve();
1510
+ }
1511
+ console.log(`running: npm install -g @bolt-cli/cli${latest ? ` (v${latest})` : ""} (current: v${VERSION})`);
1493
1512
  const inv = npmInvocation(["install", "-g", "@bolt-cli/cli"]);
1494
1513
  const child = spawn(inv.command, inv.args, { stdio: "inherit", windowsHide: true });
1495
1514
  return new Promise((resolve) => {
@@ -2762,4 +2781,4 @@ async function run(argv) {
2762
2781
  throw new Error(`Unknown command "${cmd}".\n${help()}`);
2763
2782
  }
2764
2783
 
2765
- module.exports = { run, resolveUrl, isLoopbackUrl, backendReachable, completer, completeFileFrag, completeWithDescriptions, filterPaletteItems, isPaletteRunnable, COMMANDS, AGENTS, NO_ARG_COMMANDS, resolveProjectDir, 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, updateOutcome };
2784
+ module.exports = { run, resolveUrl, isLoopbackUrl, backendReachable, completer, completeFileFrag, completeWithDescriptions, filterPaletteItems, isPaletteRunnable, COMMANDS, AGENTS, NO_ARG_COMMANDS, resolveProjectDir, 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, updateOutcome, shouldSelfUpdate };
package/lib/session.js CHANGED
@@ -169,8 +169,36 @@ function digestTurn(t, index, total) {
169
169
  return `Turn ${index + 1} of ${total} summary: ${head} | tools: ${toolText} | outcome: ${outcome}`;
170
170
  }
171
171
 
172
+ // A run writes one turn per agent iteration so /stats can show the tool work,
173
+ // but a user turn is the whole run, not each internal step. Replaying the
174
+ // internal `[tool follow-up N]` turns as conversation (as this used to) pushed
175
+ // the real question and answer out of the newest-two window and sent a page of
176
+ // tool-result digests on every resume. Collapse them into the run that owns
177
+ // them: the objective stays the question, the last non-empty response is the
178
+ // answer, and tool outcomes merge (bounded to the same 8 the writer keeps).
179
+ const INTERNAL_TURN_RE = /^\[tool follow-up \d+\]$/;
180
+ function logicalTurns(turns) {
181
+ const out = [];
182
+ for (const turn of Array.isArray(turns) ? turns : []) {
183
+ const prompt = String((turn && turn.prompt) || "");
184
+ if (INTERNAL_TURN_RE.test(prompt) && out.length) {
185
+ const last = out[out.length - 1];
186
+ const response = String((turn && turn.response) || "");
187
+ if (response.trim()) last.response = response;
188
+ if (Array.isArray(turn && turn.tools)) {
189
+ last.tools = [...(Array.isArray(last.tools) ? last.tools : []), ...turn.tools].slice(0, 8);
190
+ }
191
+ last.mode = (turn && turn.mode) || last.mode;
192
+ last.target = (turn && turn.target) || last.target;
193
+ continue;
194
+ }
195
+ out.push({ ...turn });
196
+ }
197
+ return out;
198
+ }
199
+
172
200
  function contextBlock(session, maxChars = 6000) {
173
- const turns = (session.turns || []).slice(-8);
201
+ const turns = logicalTurns(session.turns).slice(-8);
174
202
  if (!turns.length) return "";
175
203
  const older = turns.slice(0, -2);
176
204
  const recent = turns.slice(-2);
@@ -183,4 +211,4 @@ function contextBlock(session, maxChars = 6000) {
183
211
  return `Previous turns in this session (most recent last; older turns summarized, latest two in full):\n${joined}`;
184
212
  }
185
213
 
186
- module.exports = { create, load, save, appendTurn, list, latest, remove, contextBlock };
214
+ module.exports = { create, load, save, appendTurn, list, latest, remove, contextBlock, logicalTurns };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bolt-cli/cli",
3
- "version": "0.15.7",
3
+ "version": "0.15.8",
4
4
  "description": "Bolt terminal CLI — authorized testing and tool-building from your terminal or VS Code.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "commonjs",