@bolt-cli/cli 0.15.5 → 0.15.7

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/README.md CHANGED
@@ -84,6 +84,32 @@ bolt run "get admin endpoints on subdomains of tesla.com" --target tesla.com --t
84
84
 
85
85
  `bolt build` saves `*.nse`, `*.py`, `*.sh`, etc. into `--out` (default `./bolt-out`) so you can run them from your own Kali/WSL. Bolt does read-only checks server-side; it writes scripts, you execute them.
86
86
 
87
+ ## Build a real project in a folder
88
+
89
+ Open a VS Code integrated terminal (`Ctrl+``) in the directory where you want the project to live, then:
90
+
91
+ ```bash
92
+ bolt project "a small Flask API with /health and tests" --dir flask-api
93
+ ```
94
+
95
+ Bolt builds **on disk**, not in chat:
96
+
97
+ 1. Creates the project folder (and nested folders like `src/`, `tests/`) with the `mkdir` tool.
98
+ 2. Writes every source, config and README file with `write` (paths like `flask-api/src/index.js`).
99
+ 3. Installs dependencies and runs the project with `bash`, using `workdir` to stay inside the folder.
100
+ 4. Uses `list`/`glob` to prove the files exist and `bash` to capture the real run output.
101
+ 5. If a run fails, reads the error, fixes the file with `edit`/`write`, and runs it again.
102
+
103
+ The final answer reports the folder, the files created, the exact run command, and what the run actually printed — a pasted code fence is never treated as a deliverable in this mode.
104
+
105
+ - `--dir <folder>` (or `-d`) scopes every file to that folder inside the directory you launched `bolt` from. `../` escapes and absolute paths outside the project directory are refused before any tokens are spent.
106
+ - Omit `--dir` and Bolt picks a short descriptive folder name itself.
107
+ - Works from a plain terminal or the VS Code integrated terminal. No extension needed.
108
+ - On Windows, shell steps run through WSL when available, so Linux tooling (pip, nvm, cmake, …) works as expected.
109
+ - Every folder, file and command asks for approval unless you pass `--allow-all` or approve for the session. Every `write`/`edit` is backed up (`bolt undo <path>` restores).
110
+
111
+ In interactive mode, arm it with `/project <describe>` (or `/agent project` then your description) and the same build-on-disk flow runs in the REPL.
112
+
87
113
  ## Health, completions, export, undo
88
114
 
89
115
  ```bash
@@ -106,7 +132,7 @@ Colors and glyphs follow your terminal: full color on a TTY, plain text on pipes
106
132
  bolt
107
133
  ```
108
134
 
109
- Bare `bolt` opens an interactive agent on the Bolt backend only — no providers, no model picker. It reads, lists, and searches your project freely, and asks before editing files or running shell commands. Type `/` then Enter to browse commands: arrow keys pick where the terminal supports them, otherwise every row has a number — type it to run, `/text` to narrow, anything else to cancel. Tab completes, and `@path` attaches a file inline (Tab completes paths). `/agents` lists task agents, `/agent <name>` arms one for the next prompt, `/init` explores the project and writes `BOLT.md`, `/resume` picks a saved session back up, `/sessions` lists them in a picker with ages, `/retry` re-runs the last prompt, `/export` saves the session (`md|json|sarif`), `/undo <path>` restores a file, `/doctor` runs pre-flight checks, `/tools` toggles local tools, `/allow-all` skips every approval, `/permissions` manages always-allowed tools, `/status` shows the session dashboard, `?` (or `/keys`) shows the keyboard cheat sheet, and `/help <cmd>` explains one command. Also: `/help`, `/models`, `/mode`, `/target`, `/file`, `/clear`, `/session`, `/copy`, `/balance`, `/exit`.
135
+ Bare `bolt` opens an interactive agent on the Bolt backend only — no providers, no model picker. It reads, lists, and searches your project freely, and asks before editing files or running shell commands. Type `/` then Enter to browse commands: arrow keys pick where the terminal supports them, otherwise every row has a number — type it to run, `/text` to narrow, anything else to cancel. Tab completes, and `@path` attaches a file inline (Tab completes paths). `/agents` lists task agents, `/agent <name>` arms one for the next prompt, `/project <describe>` creates folders, writes files and runs the project in the current directory, `/init` explores the project and writes `BOLT.md`, `/resume` picks a saved session back up, `/sessions` lists them in a picker with ages, `/retry` re-runs the last prompt, `/export` saves the session (`md|json|sarif`), `/undo <path>` restores a file, `/doctor` runs pre-flight checks, `/tools` toggles local tools, `/allow-all` skips every approval, `/permissions` manages always-allowed tools, `/status` shows the session dashboard, `?` (or `/keys`) shows the keyboard cheat sheet, and `/help <cmd>` explains one command. Also: `/help`, `/models`, `/mode`, `/target`, `/file`, `/clear`, `/session`, `/copy`, `/balance`, `/exit`.
110
136
 
111
137
  Prompt history persists across restarts at `~/.bolt/history` (a leading space keeps a line out of the file — handy for pasted secrets). End a line with `\` to continue a long task on the next line. Answers render as terminal markdown (headings, bold, code, quotes, lists), and every tool call reports its elapsed time. When the model needs you to decide, it opens a dropdown; the last row is always "Type a custom answer…" so free text stays possible.
112
138
 
@@ -124,11 +150,12 @@ The agent loop works like Claude Code: the model requests local tools, the termi
124
150
  | `list` | list a directory | never asked |
125
151
  | `glob` | find files (`src/**/*.ts`) | never asked |
126
152
  | `grep` | search contents (regex) | never asked |
127
- | `write` | create/overwrite a file | asked (once or for the session) |
153
+ | `mkdir` | create a folder (and parents) | asked (once or for the session) |
154
+ | `write` | create/overwrite a file (parents created automatically) | asked (once or for the session) |
128
155
  | `edit` | exact-match replacement | asked (once or for the session) |
129
156
  | `bash` | shell command (120s cap) | asked, unless read-only (`git status`, `ls`, …) |
130
157
 
131
- Two hard rules, no overrides: writes, edits and the shell stay inside the directory you started `bolt` in (`../` escapes refused), and destructive commands (`mkfs`, `dd` to devices, fork bombs, shutdown, `chmod -R 777 /`, …) are refused outright. Raw tool JSON never litters the transcript — calls render as status lines. Without a TTY (`-p`, pipes) mutations are denied unless you pass `--allow-all`, which approves everything without asking.
158
+ Two hard rules, no overrides: `mkdir`, writes, edits and the shell stay inside the directory you started `bolt` in (`../` escapes refused), and destructive commands (`mkfs`, `dd` to devices, fork bombs, shutdown, `chmod -R 777 /`, …) are refused outright. Raw tool JSON never litters the transcript — calls render as status lines. Without a TTY (`-p`, pipes) mutations are denied unless you pass `--allow-all`, which approves everything without asking.
132
159
 
133
160
  Secrets never leave the machine by accident: likely secrets (AWS keys, GitHub/Slack tokens, private keys, `password = "…"` assignments in configs) are scrubbed from prompts and tool results before sending — the terminal tells you how many it redacted, and the model is told not to ask for them back.
134
161
 
package/lib/agent.js CHANGED
@@ -12,6 +12,7 @@ const session = require("./session");
12
12
  const tools = require("./tools");
13
13
  const toolparse = require("./toolparse");
14
14
  const redact = require("./redact");
15
+ const usage = require("./usage");
15
16
 
16
17
  const DEFAULT_MAX_ITERS = 16;
17
18
  const MAX_RESULT_CHARS = 4_000;
@@ -55,11 +56,14 @@ Tools:
55
56
  - list {path?} - list a directory (free, always allowed)
56
57
  - glob {pattern} - find files, e.g. {"tool": "glob", "pattern": "src/**/*.ts"}
57
58
  - grep {pattern, path?} - search file contents (regex, case-insensitive)
58
- - write {path, content} - create or overwrite a file (terminal asks first, backed up for undo)
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)
59
61
  - edit {path, oldString, newString} - exact unique replacement (terminal asks first, backed up for undo)
60
62
  - bash {command, workdir?} - run a shell command: recon, installs, builds, scanners, sudo-privileged commands (terminal asks first; destructive commands are refused outright)
61
63
  - ask {question, options[]} - ask the operator to choose (2-6 options). Use when scope, target or strategy is ambiguous instead of guessing.
62
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
+
63
67
  When you need the operator to decide, emit e.g.:
64
68
  \`\`\`tool
65
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"]}
@@ -72,7 +76,7 @@ Missing tools: if a result says a tool is missing, propose its install command a
72
76
  Security APIs: you may scaffold code that calls Shodan, Censys or VirusTotal - read keys only from env vars, never hardcode or log them.
73
77
  CTFs: you can work web, binary, mobile, RE and OSINT challenges with installed tooling - offer to install what is missing instead of stopping.
74
78
 
75
- 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. 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.`;
79
+ 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.`;
76
80
 
77
81
  // Sentinel envelope for the protocol body. The server strips this section
78
82
  // out of the untrusted case input and re-attaches it as trusted relay
@@ -142,6 +146,16 @@ function isPromiseOnlyReply(text) {
142
146
 
143
147
  const PROMISE_NUDGE = `Your last reply only announced what you would do - no tool block, no code and no result reached the operator. That is not an answer. Do the work NOW in this reply: emit a fenced tool block for each step, or give the finished deliverable as your answer. Do not describe the plan, do not announce intent, and do not ask what the task is - the ORIGINAL TASK is still in this message, above this note.`;
144
148
 
149
+ // A build reply that pastes a code fence but never called a tool produced no
150
+ // files on disk. In project/build mode that is a failure, not an answer.
151
+ const CODE_BLOCK_RE = /```(?!tool\b|ask\b|json\b)[a-zA-Z0-9+#._-]*\r?\n[\s\S]*?```/;
152
+ function isCodeOnlyProjectReply(text) {
153
+ const s = String(text || "").trim();
154
+ if (!s || s.length > 20_000) return false;
155
+ return CODE_BLOCK_RE.test(s);
156
+ }
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
+
145
159
  function buildFollowup({ iteration, calls, results, errors = [], seenDetails = null, maxIters = DEFAULT_MAX_ITERS, syntaxNote = null }) {
146
160
  const lines = [`TOOL_RESULTS for iteration ${iteration} (ground truth from this terminal - do not invent, continue the task):`];
147
161
  for (let i = 0; i < calls.length; i += 1) {
@@ -157,12 +171,12 @@ function buildFollowup({ iteration, calls, results, errors = [], seenDetails = n
157
171
  // Rejected blocks are fed back, not swallowed: without this the model
158
172
  // repeats unknown tool names, concludes the channel is broken, and refuses
159
173
  // work the terminal could have done. Every rejection restates the fix —
160
- // translate the intent into the eight tools above (recon via bash).
174
+ // translate the intent into the nine tools above (recon via bash).
161
175
  for (const error of errors) {
162
176
  lines.push(`- BLOCK REJECTED (${error.error || "bad block"}): ${truncateResult(error.raw || "", 200)}`);
163
177
  }
164
178
  if (errors.length) {
165
- lines.push("Those blocks named tools that do not exist here. Restate each intent with the eight tools above — DNS, HTTP, subdomain, and port work all go through bash (dig, nslookup, curl, nmap), never a bespoke tool name — then continue the task.");
179
+ lines.push("Those blocks named tools that do not exist here. Restate each intent with the nine tools above — DNS, HTTP, subdomain, and port work all go through bash (dig, nslookup, curl, nmap), never a bespoke tool name — then continue the task.");
166
180
  }
167
181
  // When calls arrived in drifted syntax (XML/JSON), say so once: the calls
168
182
  // were still parsed and executed, and the model is coached back to the
@@ -173,7 +187,7 @@ function buildFollowup({ iteration, calls, results, errors = [], seenDetails = n
173
187
  : "Continue with the next step, using more tools if needed, or give the final answer with no tool blocks.");
174
188
  // Restated every turn on purpose: without it the model reverts to refusing
175
189
  // local work it already performed. These results prove the channel works.
176
- lines.push("Local terminal tools (read, list, glob, grep, write, edit, bash, ask via ```tool blocks) remain available this turn - files, shell, recon, installs, and privileged commands through bash, with operator approval where needed. Never claim the local tools are unavailable.");
190
+ 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.");
177
191
  return lines.join("\n");
178
192
  }
179
193
 
@@ -199,7 +213,7 @@ function scrubOutbound(prompt) {
199
213
  * (Esc/Ctrl-C via lib/cancel.js). Resolves {text, done, iters, toolCalls,
200
214
  * cancelled}.
201
215
  */
202
- async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stream, events, policy, maxIters = DEFAULT_MAX_ITERS, memory = "", signal, session: sessionId, account }) {
216
+ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stream, events, policy, maxIters = DEFAULT_MAX_ITERS, projectMode = false, memory = "", signal, session: sessionId, account }) {
203
217
  const emit = (event) => {
204
218
  try {
205
219
  if (typeof events === "function") events(event);
@@ -224,6 +238,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
224
238
  let iters = 0;
225
239
  let nudged = false; // one silent-reply recovery per run
226
240
  let promiseNudged = false; // one promise-only recovery per run
241
+ let projectNudged = false; // one code-instead-of-files recovery per run
227
242
  let cancelled = false;
228
243
  const toolCalls = [];
229
244
  // Byte-identical tool results across the run collapse to a pointer line
@@ -245,6 +260,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
245
260
  break;
246
261
  }
247
262
  iters += 1;
263
+ const iterStarted = Date.now();
248
264
  if (stream) stream.begin();
249
265
  const collected = [];
250
266
  let turn;
@@ -279,6 +295,9 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
279
295
  if (stream) stream.end();
280
296
  text = collected.join("");
281
297
  done = turn.done;
298
+ // Per-inference accounting, captured before the tool phase so a slow
299
+ // approval dropdown is never blamed on the model's runtime.
300
+ const iterUsage = usage.usageFromDone(turn.done, Date.now() - iterStarted);
282
301
 
283
302
  // Model-agnostic extraction: fenced blocks first, but XML tool tags
284
303
  // (<tool_call>, <function_calls>, <invoke>...), bare JSON and unclosed
@@ -351,6 +370,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
351
370
  mode,
352
371
  target,
353
372
  tools: calls.map((call, i) => ({ tool: call.tool, ok: results[i] ? results[i].ok : false })),
373
+ usage: iterUsage,
354
374
  });
355
375
  }
356
376
  // Rejected blocks still deserve a follow-up turn: the model must see the
@@ -368,6 +388,12 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
368
388
  prompt = `${basePrompt}\n\n${PROMISE_NUDGE}`;
369
389
  continue;
370
390
  }
391
+ if (projectMode && isCodeOnlyProjectReply(visible) && !projectNudged && iters < maxIters) {
392
+ projectNudged = true;
393
+ emit({ type: "retry", reason: "code-only", message: "reply pasted code instead of writing files - creating the project on disk" });
394
+ prompt = `${basePrompt}\n\n${PROJECT_NUDGE}`;
395
+ continue;
396
+ }
371
397
  break; // normal final answer
372
398
  }
373
399
  // Empty reply — the classic "replied with nothing" failure. Nudge
@@ -382,6 +408,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
382
408
  }
383
409
  nudged = false;
384
410
  promiseNudged = false;
411
+ projectNudged = false;
385
412
 
386
413
  if (signal && signal.aborted) {
387
414
  cancelled = true;
@@ -407,4 +434,4 @@ function toolFenceWriter(write) {
407
434
  return toolparse.createMarkupFilter(write);
408
435
  }
409
436
 
410
- module.exports = { TOOL_PROTOCOL, TOOL_PROTOCOL_BODY, TERMINAL_BEGIN, TERMINAL_END, OUTPUT_DIRECTIVE, isPromiseOnlyReply, DEFAULT_MAX_ITERS, buildAgentPrompt, buildFollowup, runAgentLoop, truncateResult, summarizeDetail, toolFenceWriter, scrubOutbound };
437
+ module.exports = { TOOL_PROTOCOL, TOOL_PROTOCOL_BODY, TERMINAL_BEGIN, TERMINAL_END, OUTPUT_DIRECTIVE, isPromiseOnlyReply, isCodeOnlyProjectReply, DEFAULT_MAX_ITERS, buildAgentPrompt, buildFollowup, runAgentLoop, truncateResult, summarizeDetail, toolFenceWriter, scrubOutbound };
package/lib/cli.js CHANGED
@@ -12,6 +12,7 @@ const output = require("./output");
12
12
  const session = require("./session");
13
13
  const ui = require("./ui");
14
14
  const present = require("./present");
15
+ const usage = require("./usage");
15
16
  const agent = require("./agent");
16
17
  const tools = require("./tools");
17
18
  const bootstrap = require("./bootstrap");
@@ -32,8 +33,9 @@ const VERSION = require(path.join(__dirname, "..", "package.json")).version;
32
33
  function help(topic) {
33
34
  if (topic) {
34
35
  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 === "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|project|plan|validate|triage\n --dir, -d <folder> folder to build the project in (with --agent project)\n --tools agent loop (read, list, mkdir, write, 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
37
  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`;
38
+ if (t === "project") return `bolt project "<what to build>" [--dir <folder>] [--target <domain>] [--max-iters <n>]\n\nBuilds a real project in a folder under the directory you launched bolt from.\nThe agent creates folders (mkdir), writes every file (write), installs and runs\nthe project (bash), then reports the folder, files, run command and real output.\nNothing is pasted as code and left for you to assemble. Writes are backed up\n(bolt undo <path> restores); every folder/file and command asks first unless\nyou pass --allow-all or approve for the session. On Windows, shell steps run\nthrough WSL when available.\n\nExample:\n cd C:\\work\\my-projects\n bolt project "a small Flask API with /health and tests" --dir flask-api\n`;
37
39
  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
40
  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
41
  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`;
@@ -54,6 +56,7 @@ Usage:
54
56
  bolt auth status | logout session info, sign out this machine
55
57
  bolt run "<prompt>" [options] single autonomous run
56
58
  bolt build "<what>" --target <domain> [--out ./bolt-out]
59
+ bolt project "<what>" [--dir <folder>] scaffold a runnable project in a folder, then run it
57
60
  bolt -p "<prompt>" print mode: agent loop, final answer only
58
61
  bolt session [list|show|delete|new]
59
62
  bolt export <id> [--format md|json|sarif] [--output file]
@@ -64,7 +67,7 @@ Usage:
64
67
  bolt update upgrade the CLI via npm (notice appears when a release ships)
65
68
  bolt completion <shell> shell completions (bash|zsh|fish|powershell)
66
69
  bolt balance tokens, runs, spend
67
- bolt help <command> per-command help (run|build|session|export|doctor|completion|undo|watch|templates|update)
70
+ bolt help <command> per-command help (run|build|project|session|export|doctor|completion|undo|watch|templates|update)
68
71
 
69
72
  Press Esc during any run to stop it (the session is saved). Out of tokens
70
73
  stops the run at once with the top-up link — it never spins forever.
@@ -76,8 +79,9 @@ Sign-in options:
76
79
  Run options:
77
80
  --target, -t <domain> in-scope target
78
81
  --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
82
+ --agent <name> arm an agent (sweep|probe|build|project|plan|validate|triage)
83
+ --dir, -d <folder> folder to create files in (with --agent project)
84
+ --tools agent loop: read, list, mkdir, write, edit, shell
81
85
  (interactive shows Allow / Always allow / Deny;
82
86
  elevated commands get a shield card; piped runs deny)
83
87
  --dry-run show what would be sent (tokens, files, memory)
@@ -105,6 +109,7 @@ Examples:
105
109
  bolt run "get admin endpoints" --target tesla.com --format json --output out.json
106
110
  bolt -p "what does this repo do?" --allow-all
107
111
  bolt build "nmap NSE script to detect exposed admin logins" --target tesla.com
112
+ bolt project "a small Flask API with /health and tests" --dir flask-api
108
113
  bolt export <session-id> --format sarif --output findings.sarif
109
114
  bolt completion bash >> ~/.bashrc
110
115
  bolt undo src/auth.ts
@@ -674,7 +679,7 @@ function stripBoltPrefix(input) {
674
679
  }
675
680
 
676
681
  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"]);
682
+ const skipValues = new Set(["--target", "-t", "--mode", "-m", "--agent", "--file", "-f", "--evidence", "--session", "-s", "--title", "--out", "-o", "--dir", "-d", "--max-iters", "--format", "--output", "--budget", "--url"]);
678
683
  return rest
679
684
  .filter((a, i) => !a.startsWith("-") && !skipValues.has(rest[i - 1]))
680
685
  .join(" ")
@@ -699,6 +704,11 @@ const AGENTS = {
699
704
  needsTarget: true,
700
705
  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
706
  },
707
+ project: {
708
+ desc: "create a project folder, write its files, then run and verify it",
709
+ needsTarget: false,
710
+ make: (t, o) => `Build this project as real files on disk, not as code in chat: ${o || "a small runnable project"}. Work under the directory bolt launched in. First create a short descriptive project folder with mkdir (and nested folders such as src/, tests/ where useful), then write every source, config and README file with write using paths like "my-app/src/index.js". Install dependencies and run the project with bash, passing workdir so commands stay inside the project folder. Use list or glob to prove the files exist and bash to capture the real output. If a run fails, read the error, fix the file with edit or write, and run it again. Finish by reporting the folder path, the files created, the exact run command, and what the run actually printed. Do not paste the project as a code block and do not claim it runs unless bash proved it.${t ? `\nTarget or scope: ${t}` : ""}`,
711
+ },
702
712
  plan: {
703
713
  desc: "authorized test plan with phases and stop conditions",
704
714
  needsTarget: false,
@@ -723,14 +733,27 @@ function applyAgent(name, objective, target) {
723
733
  return agent.make(target, objective);
724
734
  }
725
735
 
736
+ // Validate the --dir flag against the same sandbox the write/mkdir tools use,
737
+ // then turn it into the note appended to the project agent's objective. Kept
738
+ // pure and exported so validation is testable without auth or a network call.
739
+ function resolveProjectDir(root, dirFlag) {
740
+ if (!dirFlag) return { ok: true, note: "" };
741
+ const checked = tools.resolveInRoot(root, dirFlag);
742
+ if (!checked.ok) return { ok: false, error: `--dir must be a folder inside the current project: ${checked.error}` };
743
+ const clean = String(dirFlag).replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
744
+ return { ok: true, folder: clean, note: `\n\nCreate the project in the folder "${clean}" under the current directory. Put every file inside that folder.` };
745
+ }
746
+
726
747
  const COMMANDS = [
727
748
  ["/help", "commands, grouped (try /help <cmd>)"],
728
749
  ["/status", "session dashboard: mode, tools, tokens"],
750
+ ["/stats", "session token + runtime accounting"],
729
751
  ["/sessions", "pick a saved session to resume"],
730
752
  ["/keys", "keyboard shortcuts cheat sheet"],
731
753
  ["/agents", "list task agents"],
732
754
  ["/agent <name>", "arm an agent for the next prompt"],
733
- ["/tools [on|off]", "local tools: read, list, search, edit, shell"],
755
+ ["/project <describe>", "create folders, write files and run the project"],
756
+ ["/tools [on|off]", "local tools: read, list, mkdir, write, edit, shell"],
734
757
  ["/allow-all", "approve every tool call without asking (dangerous)"],
735
758
  ["/permissions", "list always-allowed tools (revoke, clear)"],
736
759
  ["/init", "explore this project and write BOLT.md"],
@@ -755,7 +778,7 @@ const COMMANDS = [
755
778
  // Slash commands that run with no further input. Picking one from the live
756
779
  // palette executes it at once; entries with <args> or [args] only fill the
757
780
  // 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"]);
781
+ const NO_ARG_COMMANDS = new Set(["/help", "/commands", "/status", "/stats", "/sessions", "/keys", "/agents", "/models", "/balance", "/clear", "/exit", "/copy", "/allow-all", "/permissions", "/retry", "/doctor", "/watch", "/templates"]);
759
782
 
760
783
  function isPaletteRunnable(label) {
761
784
  if (!label || !label.startsWith("/")) return false;
@@ -1076,12 +1099,16 @@ async function executeTurn({ cfg, objective, mode, target, evidence, sess, onTok
1076
1099
  // Even without the tool loop, a drifted model may emit machine syntax —
1077
1100
  // never show it to the operator.
1078
1101
  const filtered = onToken ? agent.toolFenceWriter(onToken) : null;
1102
+ const startedAt = Date.now();
1079
1103
  const { text, done } = await api.streamGenerate({
1080
1104
  url: cfg.url, token: cfg.token, prompt: scrubbed.text, mode, signal,
1081
1105
  onToken: filtered ? (t) => filtered.write(t) : onToken,
1082
1106
  });
1083
1107
  if (filtered) filtered.end();
1084
- if (sess) session.appendTurn(sess, { prompt: objective, response: text, mode, target });
1108
+ if (sess) session.appendTurn(sess, {
1109
+ prompt: objective, response: text, mode, target,
1110
+ usage: usage.usageFromDone(done, Date.now() - startedAt),
1111
+ });
1085
1112
  return { text, done, redactions: scrubbed.count };
1086
1113
  }
1087
1114
 
@@ -1160,9 +1187,14 @@ function printDryRun(report, { mem, files, agentName, contextLabel }) {
1160
1187
  console.log(report.preview.length >= 1500 ? `${report.preview}\n …(truncated)` : report.preview);
1161
1188
  }
1162
1189
 
1163
- async function cmdRun(rest, { buildMode, printMode: forcePrint }) {
1190
+ async function cmdRun(rest, { buildMode, printMode: forcePrint, forceAgent } = {}) {
1164
1191
  const dryRun = flag(rest, "--dry-run");
1165
1192
  const printMode = Boolean(forcePrint) || flag(rest, "-p", "--print");
1193
+ // --dir is the folder the project agent must build into. Validate it before
1194
+ // auth/network: ../ escapes and absolute paths outside the project directory
1195
+ // are refused before a single token is spent.
1196
+ const dir = resolveProjectDir(process.cwd(), arg(rest, "--dir", "-d"));
1197
+ if (!dir.ok) throw new Error(dir.error);
1166
1198
  // Dry runs spend nothing and touch neither the network nor the session
1167
1199
  // store, so they need no auth. Everything else authenticates first.
1168
1200
  const cfg = dryRun ? null : await ensureAuth();
@@ -1174,17 +1206,24 @@ async function cmdRun(rest, { buildMode, printMode: forcePrint }) {
1174
1206
  if (argvWarning) ui.warn(argvWarning);
1175
1207
  let objective = argvPrompt;
1176
1208
  if (!objective) objective = await readStdin();
1177
- if (!objective) throw new Error(buildMode ? 'Usage: bolt build "<what to build>" --target <domain> [--out ./bolt-out]' : 'Usage: bolt run "<prompt>" [--target <domain>]');
1209
+ if (!objective) {
1210
+ if (buildMode) throw new Error('Usage: bolt build "<what to build>" --target <domain> [--out ./bolt-out]');
1211
+ if (forceAgent === "project" || arg(rest, "--agent") === "project") throw new Error('Usage: bolt project "<what to build>" [--dir <folder>]');
1212
+ throw new Error('Usage: bolt run "<prompt>" [--target <domain>]');
1213
+ }
1178
1214
  const target = arg(rest, "--target", "-t");
1179
1215
  const mode = arg(rest, "--mode", "-m") || "offensive";
1180
1216
  if (mode !== "offensive" && mode !== "defensive") throw new Error("--mode must be offensive or defensive");
1181
- const agentName = arg(rest, "--agent") || (buildMode ? "build" : "");
1182
- if (agentName) objective = applyAgent(agentName, objective, target);
1217
+ const agentName = arg(rest, "--agent") || forceAgent || (buildMode ? "build" : "");
1218
+ const dirNote = dir.note;
1219
+ if (agentName) objective = applyAgent(agentName, objective, target) + dirNote;
1220
+ else objective += dirNote;
1221
+ const projectMode = Boolean(buildMode || agentName === "project");
1183
1222
  const mentions = tools.resolveMentions(objective, process.cwd());
1184
1223
  const evidence = [readEvidence(rest), mentions.evidence].filter(Boolean).join("\n\n");
1185
1224
  const outDir = arg(rest, "--out", "-o") || (buildMode ? "./bolt-out" : "");
1186
1225
  const mem = memory.loadMemory(process.cwd());
1187
- const useTools = printMode || dryRunTools(rest, buildMode) || (buildMode && !flag(rest, "--no-tools"));
1226
+ const useTools = printMode || dryRunTools(rest, buildMode) || agentName === "project" || (buildMode && !flag(rest, "--no-tools"));
1188
1227
  const iters = maxIters(rest);
1189
1228
  const format = (arg(rest, "--format") || "text").toLowerCase();
1190
1229
  if (!["text", "json", "md"].includes(format)) throw new Error('--format must be text | json | md');
@@ -1265,6 +1304,7 @@ async function cmdRun(rest, { buildMode, printMode: forcePrint }) {
1265
1304
  let text = "";
1266
1305
  let done = null;
1267
1306
  let cancelled = false;
1307
+ let toolWroteFiles = false;
1268
1308
  try {
1269
1309
  if (useTools) {
1270
1310
  const alwaysStore = permissions.load();
@@ -1289,6 +1329,7 @@ async function cmdRun(rest, { buildMode, printMode: forcePrint }) {
1289
1329
  persistAlways: allowAll ? null : persistAlways,
1290
1330
  },
1291
1331
  maxIters: iters,
1332
+ projectMode,
1292
1333
  memory: mem.text,
1293
1334
  signal: canceller.signal,
1294
1335
  });
@@ -1305,6 +1346,7 @@ async function cmdRun(rest, { buildMode, printMode: forcePrint }) {
1305
1346
  return;
1306
1347
  }
1307
1348
  ({ text, done } = loopResult);
1349
+ toolWroteFiles = (loopResult.toolCalls || []).some((c) => (c.tool === "write" || c.tool === "mkdir") && c.ok);
1308
1350
  if (loopResult.cancelled || canceller.cancelled) {
1309
1351
  try {
1310
1352
  turn.cancel();
@@ -1377,11 +1419,13 @@ async function cmdRun(rest, { buildMode, printMode: forcePrint }) {
1377
1419
  }
1378
1420
 
1379
1421
  if (buildMode || outDir) {
1380
- const blocks = output.extractCodeBlocks(text);
1422
+ // When the agent already wrote files with tools, do not dump the same
1423
+ // code a second time into --out: the disk is the deliverable.
1424
+ const blocks = toolWroteFiles ? [] : output.extractCodeBlocks(text);
1381
1425
  if (blocks.length && outDir) {
1382
1426
  const saved = output.saveTools(blocks, path.resolve(outDir));
1383
1427
  for (const f of saved) process.stderr.write(`bolt: saved ${f}\n`);
1384
- } else if (buildMode && !blocks.length) {
1428
+ } else if (buildMode && !blocks.length && !toolWroteFiles) {
1385
1429
  process.stderr.write("bolt: no fenced code blocks found — see raw output above.\n");
1386
1430
  }
1387
1431
  }
@@ -2126,6 +2170,19 @@ async function cmdRepl() {
2126
2170
  rl.prompt();
2127
2171
  continue;
2128
2172
  }
2173
+ if (input === "/stats") {
2174
+ console.log("");
2175
+ console.log(
2176
+ ui.box({
2177
+ title: "stats",
2178
+ w: ui.width(),
2179
+ lines: present.statsLines({ ...usage.summarizeUsage(sess), sid: sess.id }),
2180
+ }),
2181
+ );
2182
+ console.log("");
2183
+ rl.prompt();
2184
+ continue;
2185
+ }
2129
2186
  if (input === "/keys") {
2130
2187
  console.log("");
2131
2188
  printKeysBox();
@@ -2181,7 +2238,7 @@ async function cmdRepl() {
2181
2238
  // A partial command opens the live arrow-key palette instead of dumping
2182
2239
  // a static list: type to filter, backspace refines, up/down moves, enter
2183
2240
  // runs a complete command or fills the line for one needing args.
2184
- 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"];
2241
+ const exactCommands = ["/exit", "/help", "/commands", "/status", "/stats", "/sessions", "/keys", "/watch", "/agents", "/models", "/balance", "/clear", "/session", "/tools", "/allow-all", "/permissions", "/init", "/resume", "/copy", "/mode", "/target", "/file", "/agent", "/project", "/undo", "/retry", "/export", "/doctor", "/templates"];
2185
2242
  if (input.startsWith("/") && !input.includes(" ") && !exactCommands.includes(input)) {
2186
2243
  const q = input.slice(1);
2187
2244
  const all = present.paletteItems(COMMANDS, AGENTS);
@@ -2518,6 +2575,19 @@ async function cmdRepl() {
2518
2575
  rl.prompt();
2519
2576
  continue;
2520
2577
  }
2578
+ if (input === "/project" || input.startsWith("/project ")) {
2579
+ // Arm the project agent and, when a description follows, run it right
2580
+ // away. The normal run path below creates folders, files and executes.
2581
+ const described = input.slice(8).trim();
2582
+ armedAgent = "project";
2583
+ setPrompt();
2584
+ ui.ok("project agent armed — Bolt will create folders, write files and run the project");
2585
+ if (!described) {
2586
+ rl.prompt();
2587
+ continue;
2588
+ }
2589
+ input = described;
2590
+ }
2521
2591
  if (input.startsWith("/")) {
2522
2592
  ui.err(`unknown command ${input}`);
2523
2593
  ui.info("press / to open the command palette");
@@ -2539,6 +2609,9 @@ async function cmdRepl() {
2539
2609
  const evidenceText = [parts.join("\n\n"), mentions.evidence].filter(Boolean).join("\n\n");
2540
2610
  let objective = input;
2541
2611
  if (armedAgent) objective = applyAgent(armedAgent, input, target);
2612
+ // A project-agent turn must build on disk, so enable the code-only
2613
+ // recovery nudge (pasted fences are not a deliverable in this mode).
2614
+ const projectMode = armedAgent === "project";
2542
2615
  // Readline must not compete with the stream for the cursor, so it pauses
2543
2616
  // for the duration of the turn. The old code left it live, which is why
2544
2617
  // the prompt could interleave mid-answer.
@@ -2567,6 +2640,7 @@ async function cmdRepl() {
2567
2640
  persistAlways: allowAll ? null : persistAlways,
2568
2641
  },
2569
2642
  maxIters: agent.DEFAULT_MAX_ITERS,
2643
+ projectMode,
2570
2644
  memory: mem.text,
2571
2645
  signal: canceller.signal,
2572
2646
  });
@@ -2649,7 +2723,7 @@ async function run(argv) {
2649
2723
  // Piped input with no command: single non-interactive run.
2650
2724
  return cmdRun([], { buildMode: false });
2651
2725
  }
2652
- 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")) {
2726
+ if (flag(argv, "-h", "--help") && (cmd === "run" || cmd === "build" || cmd === "project" || cmd === "watch" || cmd === "session" || cmd === "auth" || cmd === "signin" || cmd === "-p" || cmd === "--print" || cmd === "export" || cmd === "doctor" || cmd === "completion" || cmd === "undo" || cmd === "update")) {
2653
2727
  console.log(help(cmd === "-p" || cmd === "--print" ? "run" : cmd));
2654
2728
  return;
2655
2729
  }
@@ -2674,6 +2748,9 @@ async function run(argv) {
2674
2748
  // printed. Mutations are denied without --allow-all.
2675
2749
  if (cmd === "-p" || cmd === "--print") return cmdRun(rest, { buildMode: false, printMode: true });
2676
2750
  if (cmd === "build") return cmdRun(rest, { buildMode: true });
2751
+ // `bolt project` is the folder-first build: the agent creates the project
2752
+ // folder, writes files, runs it, and reports the real output.
2753
+ if (cmd === "project") return cmdRun(rest, { buildMode: false, forceAgent: "project" });
2677
2754
  if (cmd === "session") return cmdSession(rest);
2678
2755
  if (cmd === "doctor") return cmdDoctor();
2679
2756
  if (cmd === "update") return cmdUpdate();
@@ -2685,4 +2762,4 @@ async function run(argv) {
2685
2762
  throw new Error(`Unknown command "${cmd}".\n${help()}`);
2686
2763
  }
2687
2764
 
2688
- 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, updateOutcome };
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 };
package/lib/present.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // ids, the agent table) as opposed to ui.js, which is state-agnostic.
4
4
  const ui = require("./ui");
5
5
  const cancel = require("./cancel");
6
+ const usage = require("./usage");
6
7
 
7
8
  // Adapts an SSE token stream to the line-buffered styler in ui.js. The spinner
8
9
  // runs until the first real token arrives, then gets out of the way.
@@ -114,8 +115,8 @@ function filterPalette(query, commands, agents) {
114
115
  // menus (run, session, safety, system) instead of one flat list. Pure:
115
116
  // group membership is by command base, rows keep their COMMANDS text.
116
117
  const HELP_GROUPS = [
117
- ["Run", ["/agents", "/agent", "/mode", "/target", "/file", "/init", "/retry", "/resume"]],
118
- ["Session", ["/session", "/sessions", "/export", "/undo", "/clear", "/copy", "/balance", "/status"]],
118
+ ["Run", ["/agents", "/agent", "/project", "/mode", "/target", "/file", "/init", "/retry", "/resume"]],
119
+ ["Session", ["/session", "/sessions", "/stats", "/export", "/undo", "/clear", "/copy", "/balance", "/status"]],
119
120
  ["Tools & safety", ["/tools", "/allow-all", "/permissions", "/templates"]],
120
121
  ["System", ["/models", "/doctor", "/watch", "/keys", "/help", "/exit"]],
121
122
  ];
@@ -165,6 +166,28 @@ function statusLines({ sid, mode, target, agent, files, tools, balance, turns, m
165
166
  return rows;
166
167
  }
167
168
 
169
+ // Cumulative accounting rows for `/stats`. Mirrors the token/runtime columns
170
+ // of an autonomous-task console: in · cache · out, cost and wall time, folded
171
+ // across every inference in the saved session. Pure.
172
+ function statsLines({ sid, turns, inputTokens, outputTokens, cachedTokens, tokenCost, elapsedMs, cachedRuns, toolCalls, toolsOk } = {}) {
173
+ const rows = [];
174
+ if (sid) rows.push(`${ui.c.muted("session")} ${ui.c.primary(sid)}${turns !== undefined ? ` ${ui.c.muted(`${turns} turn${turns === 1 ? "" : "s"}`)}` : ""}`);
175
+ const tokens = [
176
+ `${ui.c.muted("in")} ${ui.c.accent(usage.formatTokens(inputTokens))}`,
177
+ `${ui.c.muted("cache")} ${ui.c.primary(usage.formatTokens(cachedTokens))}`,
178
+ `${ui.c.muted("out")} ${ui.c.success(usage.formatTokens(outputTokens))}`,
179
+ ];
180
+ rows.push(`${ui.c.muted("tokens")} ${tokens.join(` ${ui.c.muted(ui.GLYPH.dot)} `)}`);
181
+ const account = [`${ui.c.muted("cost")} ${ui.c.primary(tokenCost === undefined ? "0" : tokenCost)}`];
182
+ if (elapsedMs !== undefined) account.push(`${ui.c.muted("runtime")} ${ui.c.accent(usage.formatRuntime(elapsedMs))}`);
183
+ rows.push(account.join(` ${ui.c.muted(ui.GLYPH.dot)} `));
184
+ const work = [];
185
+ if (toolCalls !== undefined) work.push(`${ui.c.muted("tools")} ${toolCalls} call${toolCalls === 1 ? "" : "s"} · ${toolsOk || 0} ok`);
186
+ if (cachedRuns) work.push(`${ui.c.muted("cache hits")} ${cachedRuns}`);
187
+ if (work.length) rows.push(work.join(` ${ui.c.muted(ui.GLYPH.dot)} `));
188
+ return rows;
189
+ }
190
+
168
191
  // Session picker rows for `/sessions`, session-list style: newest
169
192
  // first, title plus turn count plus relative age in the hint, and the live
170
193
  // session flagged so resuming it is never a surprise. Pure.
@@ -179,4 +202,4 @@ function sessionRows(sessions, currentId) {
179
202
  });
180
203
  }
181
204
 
182
- module.exports = { streamingWriter, turnFooter, promptLine, commandItems, agentItems, paletteItems, filterPalette, helpGroups, helpDetail, statusLines, sessionRows };
205
+ module.exports = { streamingWriter, turnFooter, promptLine, commandItems, agentItems, paletteItems, filterPalette, helpGroups, helpDetail, statusLines, statsLines, sessionRows };
package/lib/session.js CHANGED
@@ -6,6 +6,7 @@ const fs = require("fs");
6
6
  const os = require("os");
7
7
  const path = require("path");
8
8
  const redact = require("./redact");
9
+ const usage = require("./usage");
9
10
 
10
11
  function dir() {
11
12
  return path.join(os.homedir(), ".bolt", "sessions");
@@ -101,6 +102,10 @@ function appendTurn(session, turn) {
101
102
  // Tool usage rides along so resumed-context digests can say what a turn
102
103
  // actually DID (`bash ok, edit ok, grep failed`) instead of plain prose.
103
104
  tools: Array.isArray(turn.tools) ? turn.tools.slice(0, 8).map((t) => ({ tool: t.tool, ok: t.ok })) : [],
105
+ // Cumulative accounting: normalized so a malformed payload can never
106
+ // poison the totals, and optional so sessions saved by older versions
107
+ // keep loading unchanged.
108
+ usage: turn.usage ? usage.usageFromDone(turn.usage, turn.usage.elapsedMs) : null,
104
109
  at: new Date().toISOString(),
105
110
  redacted,
106
111
  });
package/lib/toolparse.js CHANGED
@@ -22,7 +22,7 @@
22
22
  //
23
23
  // Zero deps. toolparse must not require tools.js (tools.js requires this).
24
24
 
25
- const TOOL_NAMES = ["read", "glob", "grep", "list", "write", "edit", "bash", "ask"];
25
+ const TOOL_NAMES = ["read", "glob", "grep", "list", "mkdir", "write", "edit", "bash", "ask"];
26
26
  const MAX_TOOL_BLOCKS = 6;
27
27
 
28
28
  const MAX_DEPTH = 3;
package/lib/tools.js CHANGED
@@ -67,6 +67,8 @@ function describeCall(call) {
67
67
  return `grep ${call.pattern || "(missing pattern)"}${call.path ? ` in ${call.path}` : ""}`;
68
68
  case "list":
69
69
  return `list ${call.path || "."}`;
70
+ case "mkdir":
71
+ return `mkdir ${call.path || "(missing path)"}`;
70
72
  case "write":
71
73
  return `write ${call.path || "(missing path)"} (${(call.content || "").length} chars)`;
72
74
  case "edit":
@@ -283,6 +285,22 @@ function applyEdit(root, filePath, oldString, newString) {
283
285
  return { ok: true, summary: "edited", detail: `Edited ${filePath}.` };
284
286
  }
285
287
 
288
+ // Explicit folder creation. writeFile already creates parent directories, but
289
+ // a build needs a `mkdir` the model can name directly — otherwise projects get
290
+ // flattened into one folder or the model gives up when it cannot "make a
291
+ // directory". Same sandbox as every other mutation: recursive creation is
292
+ // convenient, path traversal is not.
293
+ function makeDir(root, input) {
294
+ const target = resolveInRoot(root, input);
295
+ if (!target.ok) return { ok: false, summary: "refused", detail: target.error };
296
+ try {
297
+ fs.mkdirSync(target.path, { recursive: true });
298
+ } catch {
299
+ return { ok: false, summary: "mkdir failed", detail: `Cannot create directory ${input}.` };
300
+ }
301
+ return { ok: true, summary: "created", detail: `Created directory ${input}.` };
302
+ }
303
+
286
304
  function writeFile(root, filePath, content) {
287
305
  const target = resolveInRoot(root, filePath);
288
306
  if (!target.ok) return { ok: false, summary: "refused", detail: target.error };
@@ -466,8 +484,8 @@ function runBash(root, command, workdir) {
466
484
  }
467
485
 
468
486
  /**
469
- * Approval policy. Reads, searches and `ask` run free; writes, edits and
470
- * shell commands ask unless the operator allowed the tool for the session,
487
+ * Approval policy. Reads, searches and `ask` run free; mkdir, writes, edits
488
+ * and shell commands ask unless the operator allowed the tool for the session,
471
489
  * allowed it always (persisted in ~/.bolt/permissions.json), or passed
472
490
  * --allow-all. Without an asker (piped output, --print) mutations are denied
473
491
  * rather than guessed — the model is told so and works around it.
@@ -569,6 +587,8 @@ async function executeCall(call, ctx) {
569
587
  return grepFiles(root, call.pattern, call.path);
570
588
  case "list":
571
589
  return listDir(root, call.path);
590
+ case "mkdir":
591
+ return makeDir(root, call.path);
572
592
  case "write":
573
593
  return writeFile(root, call.path, call.content);
574
594
  case "edit":
@@ -601,6 +621,7 @@ module.exports = {
601
621
  checkApproval,
602
622
  executeCall,
603
623
  listDir,
624
+ makeDir,
604
625
  runBash,
605
626
  truncate,
606
627
  };
package/lib/usage.js ADDED
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * Cumulative token and runtime accounting for a local Bolt session. Pure:
4
+ * no I/O, no globals, so every rule is exercised directly by the tests.
5
+ *
6
+ * The server's `done` SSE event now carries `inputTokens` alongside the
7
+ * output/cost fields it always had. A cache hit reuses the whole prompt, so
8
+ * its cached-token share is the input it did not re-run.
9
+ */
10
+
11
+ function nonNeg(value) {
12
+ const n = Number(value);
13
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
14
+ }
15
+
16
+ /** Normalize a server `done` payload into a stored turn-usage record. */
17
+ function usageFromDone(done, elapsedMs = 0) {
18
+ const d = done && typeof done === "object" ? done : {};
19
+ const inputTokens = nonNeg(d.inputTokens);
20
+ return {
21
+ inputTokens,
22
+ outputTokens: nonNeg(d.outputTokens),
23
+ cachedTokens: d.cached ? inputTokens : 0,
24
+ tokenCost: nonNeg(d.tokenCost),
25
+ elapsedMs: nonNeg(elapsedMs),
26
+ cached: Boolean(d.cached),
27
+ };
28
+ }
29
+
30
+ /** Fold every turn's usage into one session-level summary. Missing usage on
31
+ * older sessions is simply skipped, so the command works on any saved file. */
32
+ function summarizeUsage(session) {
33
+ const turns = Array.isArray(session && session.turns) ? session.turns : [];
34
+ const total = {
35
+ turns: turns.length,
36
+ inputTokens: 0,
37
+ outputTokens: 0,
38
+ cachedTokens: 0,
39
+ tokenCost: 0,
40
+ elapsedMs: 0,
41
+ cachedRuns: 0,
42
+ toolCalls: 0,
43
+ toolsOk: 0,
44
+ };
45
+ for (const turn of turns) {
46
+ const u = turn && turn.usage;
47
+ if (u && typeof u === "object") {
48
+ total.inputTokens += nonNeg(u.inputTokens);
49
+ total.outputTokens += nonNeg(u.outputTokens);
50
+ total.cachedTokens += nonNeg(u.cachedTokens);
51
+ total.tokenCost += nonNeg(u.tokenCost);
52
+ total.elapsedMs += nonNeg(u.elapsedMs);
53
+ if (u.cached) total.cachedRuns += 1;
54
+ }
55
+ const tools = turn && Array.isArray(turn.tools) ? turn.tools : [];
56
+ for (const tool of tools) {
57
+ total.toolCalls += 1;
58
+ if (tool && tool.ok) total.toolsOk += 1;
59
+ }
60
+ }
61
+ return total;
62
+ }
63
+
64
+ function formatTokens(value) {
65
+ const n = nonNeg(value);
66
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
67
+ if (n >= 10_000) return `${Math.round(n / 1000)}k`;
68
+ if (n >= 1_000) return `${(n / 1000).toFixed(1)}k`;
69
+ return String(n);
70
+ }
71
+
72
+ /** Compact runtime the way a task console reads: 49.2s, 12m 30s, 2d 14h. */
73
+ function formatRuntime(ms) {
74
+ const n = nonNeg(ms);
75
+ if (n < 1000) return `${n}ms`;
76
+ const s = n / 1000;
77
+ if (s < 60) return `${s.toFixed(1)}s`;
78
+ const min = Math.floor(s / 60);
79
+ const sec = Math.floor(s % 60);
80
+ if (min < 60) return `${min}m ${sec}s`;
81
+ const hr = Math.floor(min / 60);
82
+ const remMin = min % 60;
83
+ if (hr < 24) return `${hr}h ${remMin}m`;
84
+ return `${Math.floor(hr / 24)}d ${hr % 24}h`;
85
+ }
86
+
87
+ module.exports = { usageFromDone, summarizeUsage, formatTokens, formatRuntime };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bolt-cli/cli",
3
- "version": "0.15.5",
3
+ "version": "0.15.7",
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",