@bolt-cli/cli 0.15.5 → 0.15.6

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
@@ -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;
@@ -245,6 +246,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
245
246
  break;
246
247
  }
247
248
  iters += 1;
249
+ const iterStarted = Date.now();
248
250
  if (stream) stream.begin();
249
251
  const collected = [];
250
252
  let turn;
@@ -279,6 +281,9 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
279
281
  if (stream) stream.end();
280
282
  text = collected.join("");
281
283
  done = turn.done;
284
+ // Per-inference accounting, captured before the tool phase so a slow
285
+ // approval dropdown is never blamed on the model's runtime.
286
+ const iterUsage = usage.usageFromDone(turn.done, Date.now() - iterStarted);
282
287
 
283
288
  // Model-agnostic extraction: fenced blocks first, but XML tool tags
284
289
  // (<tool_call>, <function_calls>, <invoke>...), bare JSON and unclosed
@@ -351,6 +356,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
351
356
  mode,
352
357
  target,
353
358
  tools: calls.map((call, i) => ({ tool: call.tool, ok: results[i] ? results[i].ok : false })),
359
+ usage: iterUsage,
354
360
  });
355
361
  }
356
362
  // Rejected blocks still deserve a follow-up turn: the model must see the
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");
@@ -726,6 +727,7 @@ function applyAgent(name, objective, target) {
726
727
  const COMMANDS = [
727
728
  ["/help", "commands, grouped (try /help <cmd>)"],
728
729
  ["/status", "session dashboard: mode, tools, tokens"],
730
+ ["/stats", "session token + runtime accounting"],
729
731
  ["/sessions", "pick a saved session to resume"],
730
732
  ["/keys", "keyboard shortcuts cheat sheet"],
731
733
  ["/agents", "list task agents"],
@@ -755,7 +757,7 @@ const COMMANDS = [
755
757
  // Slash commands that run with no further input. Picking one from the live
756
758
  // palette executes it at once; entries with <args> or [args] only fill the
757
759
  // 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"]);
760
+ 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
761
 
760
762
  function isPaletteRunnable(label) {
761
763
  if (!label || !label.startsWith("/")) return false;
@@ -1076,12 +1078,16 @@ async function executeTurn({ cfg, objective, mode, target, evidence, sess, onTok
1076
1078
  // Even without the tool loop, a drifted model may emit machine syntax —
1077
1079
  // never show it to the operator.
1078
1080
  const filtered = onToken ? agent.toolFenceWriter(onToken) : null;
1081
+ const startedAt = Date.now();
1079
1082
  const { text, done } = await api.streamGenerate({
1080
1083
  url: cfg.url, token: cfg.token, prompt: scrubbed.text, mode, signal,
1081
1084
  onToken: filtered ? (t) => filtered.write(t) : onToken,
1082
1085
  });
1083
1086
  if (filtered) filtered.end();
1084
- if (sess) session.appendTurn(sess, { prompt: objective, response: text, mode, target });
1087
+ if (sess) session.appendTurn(sess, {
1088
+ prompt: objective, response: text, mode, target,
1089
+ usage: usage.usageFromDone(done, Date.now() - startedAt),
1090
+ });
1085
1091
  return { text, done, redactions: scrubbed.count };
1086
1092
  }
1087
1093
 
@@ -2126,6 +2132,19 @@ async function cmdRepl() {
2126
2132
  rl.prompt();
2127
2133
  continue;
2128
2134
  }
2135
+ if (input === "/stats") {
2136
+ console.log("");
2137
+ console.log(
2138
+ ui.box({
2139
+ title: "stats",
2140
+ w: ui.width(),
2141
+ lines: present.statsLines({ ...usage.summarizeUsage(sess), sid: sess.id }),
2142
+ }),
2143
+ );
2144
+ console.log("");
2145
+ rl.prompt();
2146
+ continue;
2147
+ }
2129
2148
  if (input === "/keys") {
2130
2149
  console.log("");
2131
2150
  printKeysBox();
@@ -2181,7 +2200,7 @@ async function cmdRepl() {
2181
2200
  // A partial command opens the live arrow-key palette instead of dumping
2182
2201
  // a static list: type to filter, backspace refines, up/down moves, enter
2183
2202
  // 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"];
2203
+ 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", "/undo", "/retry", "/export", "/doctor", "/templates"];
2185
2204
  if (input.startsWith("/") && !input.includes(" ") && !exactCommands.includes(input)) {
2186
2205
  const q = input.slice(1);
2187
2206
  const all = present.paletteItems(COMMANDS, AGENTS);
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.
@@ -115,7 +116,7 @@ function filterPalette(query, commands, agents) {
115
116
  // group membership is by command base, rows keep their COMMANDS text.
116
117
  const HELP_GROUPS = [
117
118
  ["Run", ["/agents", "/agent", "/mode", "/target", "/file", "/init", "/retry", "/resume"]],
118
- ["Session", ["/session", "/sessions", "/export", "/undo", "/clear", "/copy", "/balance", "/status"]],
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/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.6",
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",