@bolt-cli/cli 0.15.4 → 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 +40 -3
- package/lib/cli.js +22 -3
- package/lib/present.js +25 -2
- package/lib/session.js +5 -0
- package/lib/usage.js +87 -0
- package/package.json +1 -1
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;
|
|
@@ -117,7 +118,7 @@ function summarizeDetail(detail, seenDetails = null) {
|
|
|
117
118
|
// thinking is not streamed; with the task buried mid-prompt it spent the whole
|
|
118
119
|
// reply there and emitted nothing. This says, in the position that demonstrably
|
|
119
120
|
// works, to answer visibly now - removing the wasted ~30s inference entirely.
|
|
120
|
-
const OUTPUT_DIRECTIVE = `The operator's task above is still active - do it in THIS reply. Emit operator-visible text only: either
|
|
121
|
+
const OUTPUT_DIRECTIVE = `The operator's task above is still active - do it in THIS reply. Emit operator-visible text only: either the finished answer or a fenced tool block. Do NOT announce what you will do, describe your plan, or say "I'll create it" - do it now in the same reply. Internal reasoning and hidden thinking are NOT delivered to the operator and leave them staring at an empty screen - do not spend the reply on them. A progress line alone is not an answer. Never end a turn with only a promise or with no visible output.`;
|
|
121
122
|
|
|
122
123
|
function buildAgentPrompt({ target, objective, evidence, history, memory, session, account }) {
|
|
123
124
|
return `${api.buildPrompt({ target, objective, evidence, history, memory, session, account })}\n\n${TOOL_PROTOCOL}\n\n${OUTPUT_DIRECTIVE}`;
|
|
@@ -125,6 +126,23 @@ function buildAgentPrompt({ target, objective, evidence, history, memory, sessio
|
|
|
125
126
|
|
|
126
127
|
const EMPTY_REPLY_NUDGE = `Your previous reply arrived at this terminal empty - no prose and no tool block. That is a protocol failure, not an answer. The ORIGINAL TASK is still in this message, above this note: do it now. Do not ask what the task is, do not ask for a target, and do not describe what you could do. Do not re-send internal reasoning, 自知 blocks or tool call syntax in any other shape. Either continue the task with one or more \`\`\`tool blocks, or give the finished answer in plain prose.`;
|
|
127
128
|
|
|
129
|
+
// A reply like "I'll create a Python port scanner for you." has prose, so the
|
|
130
|
+
// loop used to call it a final answer and stop — 49s and 1,677 tokens spent to
|
|
131
|
+
// announce work that never happened. Detect the promise-only shape and keep
|
|
132
|
+
// going; a deliverable (code fence) or a tool call is what ends a run.
|
|
133
|
+
const PROMISE_VERBS = "(?:create|write|build|make|run|check|scan|generate|produce|start|set up|install|read|look|try|do|fix|add|find|get|show|give|continue|proceed|execute|prepare|analy[sz]e|design|implement|test|deploy|compil[e]|open|load|fetch|query|list|search|inspect|review|report|explain|summari[sz]e)";
|
|
134
|
+
const PROMISE_RE = new RegExp(`(?:I'?ll|I will|I'?m going to|I shall|let me|now I(?:'ll| will)?)\\s+${PROMISE_VERBS}\\b`, "i");
|
|
135
|
+
|
|
136
|
+
function isPromiseOnlyReply(text) {
|
|
137
|
+
const s = String(text || "").trim();
|
|
138
|
+
if (!s || s.length > 300) return false;
|
|
139
|
+
// A code block or tool syntax is a deliverable, even if short.
|
|
140
|
+
if (/```|~~~|<(?:tool|function|invoke)\b/i.test(s)) return false;
|
|
141
|
+
return PROMISE_RE.test(s);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
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.`;
|
|
145
|
+
|
|
128
146
|
function buildFollowup({ iteration, calls, results, errors = [], seenDetails = null, maxIters = DEFAULT_MAX_ITERS, syntaxNote = null }) {
|
|
129
147
|
const lines = [`TOOL_RESULTS for iteration ${iteration} (ground truth from this terminal - do not invent, continue the task):`];
|
|
130
148
|
for (let i = 0; i < calls.length; i += 1) {
|
|
@@ -206,6 +224,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
|
|
|
206
224
|
let done = null;
|
|
207
225
|
let iters = 0;
|
|
208
226
|
let nudged = false; // one silent-reply recovery per run
|
|
227
|
+
let promiseNudged = false; // one promise-only recovery per run
|
|
209
228
|
let cancelled = false;
|
|
210
229
|
const toolCalls = [];
|
|
211
230
|
// Byte-identical tool results across the run collapse to a pointer line
|
|
@@ -227,6 +246,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
|
|
|
227
246
|
break;
|
|
228
247
|
}
|
|
229
248
|
iters += 1;
|
|
249
|
+
const iterStarted = Date.now();
|
|
230
250
|
if (stream) stream.begin();
|
|
231
251
|
const collected = [];
|
|
232
252
|
let turn;
|
|
@@ -261,6 +281,9 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
|
|
|
261
281
|
if (stream) stream.end();
|
|
262
282
|
text = collected.join("");
|
|
263
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);
|
|
264
287
|
|
|
265
288
|
// Model-agnostic extraction: fenced blocks first, but XML tool tags
|
|
266
289
|
// (<tool_call>, <function_calls>, <invoke>...), bare JSON and unclosed
|
|
@@ -333,13 +356,26 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
|
|
|
333
356
|
mode,
|
|
334
357
|
target,
|
|
335
358
|
tools: calls.map((call, i) => ({ tool: call.tool, ok: results[i] ? results[i].ok : false })),
|
|
359
|
+
usage: iterUsage,
|
|
336
360
|
});
|
|
337
361
|
}
|
|
338
362
|
// Rejected blocks still deserve a follow-up turn: the model must see the
|
|
339
363
|
// rejection and restate its intent, or it concludes the channel is broken
|
|
340
364
|
// and refuses work the terminal could have done. maxIters still bounds us.
|
|
341
365
|
if (!calls.length && !errors.length) {
|
|
342
|
-
|
|
366
|
+
const visible = cleaned.trim();
|
|
367
|
+
if (visible) {
|
|
368
|
+
// "I'll create the script for you." is prose but not a result. The
|
|
369
|
+
// loop must not reward it with a stop — keep the original task alive
|
|
370
|
+
// and demand the deliverable in this reply.
|
|
371
|
+
if (isPromiseOnlyReply(visible) && !promiseNudged && iters < maxIters) {
|
|
372
|
+
promiseNudged = true;
|
|
373
|
+
emit({ type: "retry", reason: "promise-only", message: "reply announced work without doing it - continuing with the original task" });
|
|
374
|
+
prompt = `${basePrompt}\n\n${PROMISE_NUDGE}`;
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
break; // normal final answer
|
|
378
|
+
}
|
|
343
379
|
// Empty reply — the classic "replied with nothing" failure. Nudge
|
|
344
380
|
// once; a second consecutive silent reply stops the run honestly.
|
|
345
381
|
// Resend the original objective WITH the note: a bare nudge costs two
|
|
@@ -351,6 +387,7 @@ async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stre
|
|
|
351
387
|
continue;
|
|
352
388
|
}
|
|
353
389
|
nudged = false;
|
|
390
|
+
promiseNudged = false;
|
|
354
391
|
|
|
355
392
|
if (signal && signal.aborted) {
|
|
356
393
|
cancelled = true;
|
|
@@ -376,4 +413,4 @@ function toolFenceWriter(write) {
|
|
|
376
413
|
return toolparse.createMarkupFilter(write);
|
|
377
414
|
}
|
|
378
415
|
|
|
379
|
-
module.exports = { TOOL_PROTOCOL, TOOL_PROTOCOL_BODY, TERMINAL_BEGIN, TERMINAL_END, OUTPUT_DIRECTIVE, DEFAULT_MAX_ITERS, buildAgentPrompt, buildFollowup, runAgentLoop, truncateResult, summarizeDetail, toolFenceWriter, scrubOutbound };
|
|
416
|
+
module.exports = { TOOL_PROTOCOL, TOOL_PROTOCOL_BODY, TERMINAL_BEGIN, TERMINAL_END, OUTPUT_DIRECTIVE, isPromiseOnlyReply, 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");
|
|
@@ -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, {
|
|
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