@agentguard-run/burn 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +54 -1
- package/dist/src/cli.js +67 -9
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +10 -1
- package/dist/src/insights/i18n.d.ts +1 -0
- package/dist/src/insights/i18n.js +9 -7
- package/dist/src/insights/pricing.js +8 -2
- package/dist/src/insights/status-data.d.ts +6 -0
- package/dist/src/insights/status-data.js +65 -0
- package/dist/src/insights/status-fields.d.ts +74 -0
- package/dist/src/insights/status-fields.js +136 -0
- package/dist/src/insights/status-text.d.ts +107 -0
- package/dist/src/insights/status-text.js +36 -0
- package/dist/src/insights/tally.d.ts +3 -1
- package/dist/src/insights/tally.js +2 -2
- package/dist/src/telemetry-cli.d.ts +5 -0
- package/dist/src/telemetry-cli.js +57 -0
- package/docs/USAGE_AND_PRICING.md +4 -2
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0 (2026-10-07)
|
|
4
|
+
|
|
5
|
+
- Price Claude Haiku 5.5 (`claude-haiku-5-5`), released on October 7, 2026: 0.1, 0.01, 0.125, 0.2 and 0.5 USD per million tokens for fresh input, cache read, five-minute write, one-hour write and output on prompts up to 100,000 tokens, and five times each above that. Before this row its turns were unpriced.
|
|
6
|
+
- Claude Sonnet 5.5 cache reads drop to 0.1 USD per million tokens (0.05x base input), per Anthropic's October 7, 2026 change. Burn prices sessions at the current list price, so earlier Sonnet 5.5 sessions are repriced too.
|
|
7
|
+
- Offer one optional anonymous count after a successful interactive why report, sharing Spend consent and install ID; add telemetry controls and a query-free Next link.
|
|
8
|
+
|
|
9
|
+
- Add optional pace, API list cost, prefix rewrite and daily Spend status fields with a shared formatter, width fitting, panel details and localized Burn labels.
|
|
10
|
+
|
|
3
11
|
## 0.4.0 (2026-10-05)
|
|
4
12
|
|
|
5
13
|
- Add recorded launch trees and signed approval tallies. Tree shows active time
|
package/README.md
CHANGED
|
@@ -749,7 +749,7 @@ A provenance JSON beside the requested MP4 records the source recording's SHA256
|
|
|
749
749
|
|
|
750
750
|
Runtime observation and enforcement do not persist or render prompts, responses, file contents or tool inputs. The explicit developer `guard-candidates` command copies shell text already present in a ledger into a private review; only its `--rank` option can send that text to the selected provider.
|
|
751
751
|
`why` runs git only with `--commits`, and then reads commit hashes, times and co-author trailers on this computer and prints counts alone.
|
|
752
|
-
|
|
752
|
+
Status and pace make no telemetry calls. No provider-quota guesses. Account forecasts use only observed host percentages, never an invented allowance or cache weighting.
|
|
753
753
|
|
|
754
754
|
### Local live panel
|
|
755
755
|
|
|
@@ -787,3 +787,56 @@ output or transcript content. See [the live panel and September 20 evidence](doc
|
|
|
787
787
|
`agentguard-burn status` shows this UTC month’s recorded spawn stops and blocked shell commands. It reads Burn’s local ledger and plugin ledgers registered by either host, joins mirrored spawn receipts once, and excludes shadow decisions, approval holds and outcomes. Missing command history is unknown. Nothing is uploaded. Free installations see one Team line per UTC month. Counts update on later status calls without repeating that line.
|
|
788
788
|
|
|
789
789
|
Run `agentguard-burn quiet on`, or `node runtime/policy-cli.cjs quiet on` from the AgentGuard plugin directory, to dismiss the monthly summary, the `why` tip, the weekly STOP invitation and plugin version announcements on this machine. Both write the same flag file, `upgrade-moments/quiet`, and use `AGENTGUARD_HOME` or the default local AgentGuard home for it. `agentguard-burn quiet off` removes that file.
|
|
790
|
+
|
|
791
|
+
## Status line fields
|
|
792
|
+
|
|
793
|
+
The status line always starts with AgentGuard. Its default items remain sub-agent launches, session tokens, the token share sent to sub-agents when known, and plan usage when the host reports it. Optional fields use the same formatter in Burn and the Claude Code plugin. They read local transcripts, host usage and signed Spend files only. Codex has no external status slot.
|
|
794
|
+
|
|
795
|
+
Set `status_fields` to `pace,cost,cache,spend` in the plugin settings. Burn accepts the same comma list in `AGENTGUARD_STATUS_FIELDS`, or through the fields flag, which takes precedence even when empty. Unknown names are ignored, with one warning in the plugin panel. The default is empty.
|
|
796
|
+
|
|
797
|
+
- `pace` projects the time until the reported plan limit, using at least two rising samples from the last ten minutes, only when that limit would be reached before reset.
|
|
798
|
+
- `cost` estimates this session at Burn's API list prices, including recorded child sessions, and remains opt-in even without host plan limits.
|
|
799
|
+
- `cache` shows cache-write tokens attributed by Burn to large prefix rewrites in this session and their API list price estimate when available.
|
|
800
|
+
- `spend` shows today's signed local spend against an unscoped daily policy cap, only when both the local JSON policy and its verified ledger can be read.
|
|
801
|
+
|
|
802
|
+
Examples on a wide terminal:
|
|
803
|
+
|
|
804
|
+
```text
|
|
805
|
+
AgentGuard sub-agents 2 of 40 · tokens 686M of 5B · 33% to sub-agents · 5-hour 44% · limit in ~1h40m · /agentguard
|
|
806
|
+
AgentGuard sub-agents 2 of 40 · tokens 686M of 5B · 33% to sub-agents · 5-hour 44% · ≈$12.40 list · /agentguard
|
|
807
|
+
AgentGuard sub-agents 2 of 40 · tokens 686M of 5B · 33% to sub-agents · 5-hour 44% · cache waste 42M (≈$9.00 list) · /agentguard
|
|
808
|
+
AgentGuard sub-agents 2 of 40 · tokens 686M of 5B · 33% to sub-agents · 5-hour 44% · spend $3.20 of $10.00 list today · /agentguard
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
Dollar figures are API list price estimates, not a bill. Spend displays the cents recorded by the local policy, which may use configured unit prices. Pace rounds to ten minutes, always starts with `~`, and turns yellow below thirty minutes. Usage turns yellow at 70% and red at 90%, including daily spend. Optional fields are removed in this order when space runs out: pace, cost, cache, spend. Default labels then shorten so the line fits without wrapping. Open `/agentguard` for full values, reset times, enabled fields and any unknown-name warning. Extremely narrow slots clip the row; all values remain in the panel.
|
|
812
|
+
|
|
813
|
+
The Claude usage API reports context, rate-limit windows and a host cost value. Its API-key window behavior is not guaranteed by the reference or the installed host implementation, so cost does not become an automatic default. The cost field uses Burn's local price table, not that host cost value. Daily spend reads a local scope-wide JSON policy, verifies its signed ledger and uses UTC day boundaries. Selector-only caps, unreadable ledgers or failed signature checks and policies held only by a remote or in-memory application stay unavailable.
|
|
814
|
+
|
|
815
|
+
## Anonymous count (opt-in)
|
|
816
|
+
|
|
817
|
+
After the first successful interactive `why` report, Burn can ask once:
|
|
818
|
+
|
|
819
|
+
```text
|
|
820
|
+
Help us count real users? Sends one anonymous ping (random ID, Burn version, OS). Never your prompts, files or usage. [y/N]
|
|
821
|
+
```
|
|
822
|
+
|
|
823
|
+
Only `y` or `yes` enables counting. Enter, anything else or fifteen seconds without an answer records no. The report prints before the question. CI, noninteractive terminals, library imports and hooks never ask or send a Burn count. Consent and the anonymous install ID share Spend's local `install.json` under `AGENTGUARD_HOME` or the usual AgentGuard home. An existing shared consent decision or explicit environment switch is respected without another question.
|
|
824
|
+
|
|
825
|
+
A yes permits one best-effort attempt per install to `https://agentguard.run/api/beacon`, with a one-second timeout and ignored errors. It sends exactly these fields:
|
|
826
|
+
|
|
827
|
+
```json
|
|
828
|
+
{
|
|
829
|
+
"event": "burn_first_report",
|
|
830
|
+
"sdk_name": "@agentguard-run/burn",
|
|
831
|
+
"sdk_version": "<Burn version>",
|
|
832
|
+
"runtime": "<Node version>",
|
|
833
|
+
"os_family": "<OS family>",
|
|
834
|
+
"anonymous_install_id": "<random UUID shared with Spend>",
|
|
835
|
+
"ci_env_detected": false,
|
|
836
|
+
"tty": true
|
|
837
|
+
}
|
|
838
|
+
```
|
|
839
|
+
|
|
840
|
+
No prompts, files, paths, session IDs, model names or token counts are sent. Run `agentguard-burn telemetry status`, `agentguard-burn telemetry on` or `agentguard-burn telemetry off` to inspect or change the shared choice. `AGENTGUARD_TELEMETRY=1` enables it; `AGENTGUARD_NO_BEACON=1` always disables it, overriding every other setting. An attempted event stays marked so a network failure never causes repeated pings. Failed or missing local state makes counting best effort, never a requirement to use Burn.
|
|
841
|
+
|
|
842
|
+
The Next link is `https://agentguard.run/burn/next`, without query strings or an install ID. Opening it is an ordinary website visit and needs no CLI ping. See the [privacy page](https://agentguard.run/legal/privacy#anonymous-count) for server counting and retention.
|
package/dist/src/cli.js
CHANGED
|
@@ -87,7 +87,11 @@ const i18n_1 = require("./insights/i18n");
|
|
|
87
87
|
const ttl_1 = require("./insights/ttl");
|
|
88
88
|
const blocks_1 = require("./insights/blocks");
|
|
89
89
|
const cli_1 = require("./idle/cli");
|
|
90
|
+
const telemetry_cli_1 = require("./telemetry-cli");
|
|
91
|
+
const status_fields_1 = require("./insights/status-fields");
|
|
92
|
+
const status_data_1 = require("./insights/status-data");
|
|
90
93
|
const HOME = process.env.AGENTGUARD_HOME ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard');
|
|
94
|
+
let finishReportNaturally = false;
|
|
91
95
|
const PROXY_HOSTS = ['ollama', 'vllm', 'lm-studio', 'openai-compatible'];
|
|
92
96
|
/** The same flag file the AgentGuard plugin reads (runtime/upgrade-moments.cjs), so one switch silences both. */
|
|
93
97
|
const quietOn = () => (0, node_fs_1.existsSync)((0, upgrade_moments_1.quietFile)(HOME));
|
|
@@ -269,6 +273,10 @@ async function main(argv) {
|
|
|
269
273
|
const commitsValue = commits ? (0, render_2.commitsJson)(commits, transcript.state.forkHistoryBoundaryUnknown ? null : (0, render_2.sessionFigures)(transcript).attribution.totalTokens) : undefined;
|
|
270
274
|
show({ kind: 'command', command, values: { session: transcript.sessionId, observations: transcript.observations, diagnostics: transcript.diagnostics, attribution: (0, attribution_1.attributeTurns)((0, transcript_2.deduplicateTurns)(transcript.turns)).buckets, prices: (0, transcript_2.deduplicateTurns)(transcript.turns).map(turn => (0, pricing_1.priceTurn)(turn, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)))), ...(commitsValue ? { commits: commitsValue } : {}) } }, json ? JSON.stringify({ ...transcript, ...(treeSection ? { launchTree } : {}), ...(commitsValue ? { commits: commitsValue } : {}) }, null, 2) + '\n'
|
|
271
275
|
: (treeSection ? treeSection.trim() + '\n\n' : '') + (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)), { tips: !quietOn(), lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }), ...(commits ? { commits } : {}) }) + '\n', json);
|
|
276
|
+
if (require.main === module && !json && transcript.turns.length) {
|
|
277
|
+
finishReportNaturally = true;
|
|
278
|
+
await (0, telemetry_cli_1.countFirstReport)(require('../../package.json').version);
|
|
279
|
+
}
|
|
272
280
|
return 0;
|
|
273
281
|
}
|
|
274
282
|
case 'compare': {
|
|
@@ -411,13 +419,55 @@ async function main(argv) {
|
|
|
411
419
|
show({ kind: 'command', command, values: { rates: { ...pricing_1.MODEL_PRICING, ...rates } } }, (0, render_2.renderPricing)(rates) + '\n');
|
|
412
420
|
return 0;
|
|
413
421
|
}
|
|
414
|
-
case '
|
|
422
|
+
case 'telemetry': return (0, telemetry_cli_1.telemetryCommand)(rest);
|
|
423
|
+
case 'statusline': {
|
|
424
|
+
let fields = process.env.AGENTGUARD_STATUS_FIELDS ?? '', lang;
|
|
425
|
+
const selectors = [];
|
|
426
|
+
for (let i = 0; i < rest.length; i++) {
|
|
427
|
+
if (rest[i] === '--fields')
|
|
428
|
+
fields = rest[++i] ?? '';
|
|
429
|
+
else if (rest[i].startsWith('--fields='))
|
|
430
|
+
fields = rest[i].slice(9);
|
|
431
|
+
else if (rest[i] === '--lang')
|
|
432
|
+
lang = rest[++i];
|
|
433
|
+
else if (rest[i].startsWith('--lang='))
|
|
434
|
+
lang = rest[i].slice(7);
|
|
435
|
+
else
|
|
436
|
+
selectors.push(rest[i]);
|
|
437
|
+
}
|
|
438
|
+
const raw = !process.stdin.isTTY ? readStdinJson() : null;
|
|
439
|
+
const payload = (raw && typeof raw === 'object' ? raw : {});
|
|
440
|
+
const width = payload.columns ?? payload.terminal_width ?? process.stdout.columns ?? Number(process.env.COLUMNS || 80);
|
|
441
|
+
let location;
|
|
442
|
+
try {
|
|
443
|
+
location = (0, sessions_1.selectInsightTranscript)(payload.transcript_path || selectors[0] || payload.session_id);
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
process.stdout.write((0, status_fields_1.formatStatusFields)({ fields, width, failed: true }).text + '\n');
|
|
447
|
+
return 0;
|
|
448
|
+
}
|
|
449
|
+
const session = payload.session_id || location.sessionId;
|
|
450
|
+
const observation = (0, live_1.observeTool)(HOME, { ...payload, session_id: session, transcript_path: location.path }, location.host, (0, pre_tool_use_1.loadPolicy)(HOME));
|
|
451
|
+
const metrics = await (0, status_data_1.readStatusMetrics)(HOME, location.path, fields, process.env.PLUGIN_DATA || process.env.CLAUDE_PLUGIN_DATA, true);
|
|
452
|
+
const burn = (0, status_data_1.readStatusBurn)(HOME, session);
|
|
453
|
+
if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(HOME, 'sessions')) && metrics.totalTokens !== undefined)
|
|
454
|
+
burn.tokens.used = metrics.totalTokens;
|
|
455
|
+
const formatted = (0, status_fields_1.formatStatusFields)({ ...metrics, burn, fields, windows: observation.snapshot?.windows,
|
|
456
|
+
width,
|
|
457
|
+
lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }) });
|
|
458
|
+
const line = process.env.NO_COLOR !== undefined || noColor || formatted.clipped ? formatted.text : formatted.parts.map(part => {
|
|
459
|
+
const code = part.color === 'red' ? 31 : part.color === 'yellow' ? 33 : part.dim ? 2 : 0;
|
|
460
|
+
return code ? `\x1b[${code}m${part.text}\x1b[0m` : part.text;
|
|
461
|
+
}).join('');
|
|
462
|
+
show({ kind: 'command', command, values: { fields: formatted.enabled } }, line + '\n', true);
|
|
463
|
+
return 0;
|
|
464
|
+
}
|
|
415
465
|
case 'pace': {
|
|
416
|
-
const raw =
|
|
466
|
+
const raw = null;
|
|
417
467
|
const payload = raw && typeof raw === 'object' ? raw : {};
|
|
418
468
|
const location = (0, sessions_1.selectInsightTranscript)(payload.transcript_path || rest[0] || payload.session_id);
|
|
419
469
|
const observation = (0, live_1.observeTool)(HOME, { ...payload, session_id: payload.session_id || location.sessionId, transcript_path: location.path }, location.host, (0, pre_tool_use_1.loadPolicy)(HOME));
|
|
420
|
-
show({ kind: 'command', command, values: { snapshot: observation.snapshot ? { host: observation.snapshot.host, session: observation.snapshot.sessionId, pace: observation.snapshot.pace, forecast: observation.snapshot.forecast, lastTurnTokens: observation.snapshot.lastTurnTokens, windows: observation.snapshot.windows } : null } }, (observation.snapshot ? (0, live_1.renderStatusLine)(observation.snapshot) : 'AgentGuard pace unavailable: local usage metadata is not readable.') + '\n'
|
|
470
|
+
show({ kind: 'command', command, values: { snapshot: observation.snapshot ? { host: observation.snapshot.host, session: observation.snapshot.sessionId, pace: observation.snapshot.pace, forecast: observation.snapshot.forecast, lastTurnTokens: observation.snapshot.lastTurnTokens, windows: observation.snapshot.windows } : null } }, (observation.snapshot ? (0, live_1.renderStatusLine)(observation.snapshot) : 'AgentGuard pace unavailable: local usage metadata is not readable.') + '\n');
|
|
421
471
|
return observation.snapshot ? 0 : 1;
|
|
422
472
|
}
|
|
423
473
|
case 'hook': {
|
|
@@ -644,7 +694,7 @@ async function main(argv) {
|
|
|
644
694
|
return 0;
|
|
645
695
|
}
|
|
646
696
|
default:
|
|
647
|
-
show({ kind: 'command', command: 'help', values: { commands: ['tree', 'tally', 'ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|calendar|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
697
|
+
show({ kind: 'command', command: 'help', values: { commands: ['tree', 'tally', 'ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'telemetry', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|calendar|why|compare|rewrites|ttl|pace|statusline|pricing|telemetry|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
648
698
|
' ps [--json] local agent processes, held memory and workspace disk\n' +
|
|
649
699
|
' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
|
|
650
700
|
' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
|
|
@@ -666,7 +716,8 @@ async function main(argv) {
|
|
|
666
716
|
' rewrites [session|all] every full-prefix cache write with its cause, idle gap and list price\n' +
|
|
667
717
|
' ttl [session|all] one-hour cache lifetime counterfactual from your own idle gaps\n' +
|
|
668
718
|
' pace [session] ten-minute pace and next-hour projection\n' +
|
|
669
|
-
' statusline [session] one
|
|
719
|
+
' statusline [session] one local status line; fields via AGENTGUARD_STATUS_FIELDS or the fields flag\n' +
|
|
720
|
+
' telemetry status|on|off shared anonymous count preference\n' +
|
|
670
721
|
' pricing verified model rates and local overrides\n' +
|
|
671
722
|
' replay [files...] [--json] [--top N] [--min-tokens N]\n' +
|
|
672
723
|
' import-bench <run-dir> [--out <directory>] [--publisher-key-id ID] verify and convert a signed bundle\n' +
|
|
@@ -742,7 +793,14 @@ function exit(code) {
|
|
|
742
793
|
process.stdout.write('', done);
|
|
743
794
|
process.stderr.write('', done);
|
|
744
795
|
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
796
|
+
if (require.main === module)
|
|
797
|
+
run().then(
|
|
798
|
+
// Let the best-effort count request finish within its one-second deadline.
|
|
799
|
+
// The report has already been printed, and Node drains stdout on natural exit.
|
|
800
|
+
(code) => { if (finishReportNaturally)
|
|
801
|
+
process.exitCode = code;
|
|
802
|
+
else
|
|
803
|
+
exit(code); }, (error) => {
|
|
804
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
805
|
+
exit(4);
|
|
806
|
+
});
|
package/dist/src/index.d.ts
CHANGED
|
@@ -30,3 +30,5 @@ export { readHookSessions, renderHostHealth } from './status';
|
|
|
30
30
|
export { findingSignature, inflateHookSession, type PersistedSession } from './hook/pre-tool-use';
|
|
31
31
|
export { readLaunchTree, readLaunchTreeWithReceipts, buildLaunchTree, renderLaunchTree } from './insights/tree';
|
|
32
32
|
export { sessionTally, tallyEntries, readLedgerTallies, readLedgerDailyTallies, renderSessionTally, pluginLedgerDirectories, sessionLaunchReceipts, type SessionTally, type TallyCounts } from './insights/tally';
|
|
33
|
+
export { formatStatusFields, parseStatusFields, statusPace, statusColor, type StatusInput, type StatusMetrics } from './insights/status-fields';
|
|
34
|
+
export { readStatusBurn, readStatusMetrics } from './insights/status-data';
|
package/dist/src/index.js
CHANGED
|
@@ -15,7 +15,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.checkPolicyFile = exports.sessionTip = exports.MIN_FINISHED_SUBAGENTS = exports.decisionCostLine = exports.subagentCostLine = exports.finishedSubagents = exports.cloneReaderCursor = exports.restoreReaderCursor = exports.saveReaderCursor = exports.readSessionIncremental = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
|
|
18
|
-
exports.sessionLaunchReceipts = exports.pluginLedgerDirectories = exports.renderSessionTally = exports.readLedgerDailyTallies = exports.readLedgerTallies = exports.tallyEntries = exports.sessionTally = exports.renderLaunchTree = exports.buildLaunchTree = exports.readLaunchTreeWithReceipts = exports.readLaunchTree = exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.LAUNCH_TOOLS = exports.isLaunchTool = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.readSpawnAdmission = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
|
|
18
|
+
exports.parseStatusFields = exports.formatStatusFields = exports.sessionLaunchReceipts = exports.pluginLedgerDirectories = exports.renderSessionTally = exports.readLedgerDailyTallies = exports.readLedgerTallies = exports.tallyEntries = exports.sessionTally = exports.renderLaunchTree = exports.buildLaunchTree = exports.readLaunchTreeWithReceipts = exports.readLaunchTree = exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.LAUNCH_TOOLS = exports.isLaunchTool = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.readSpawnAdmission = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
|
|
19
|
+
exports.readStatusMetrics = exports.readStatusBurn = exports.statusColor = exports.statusPace = void 0;
|
|
19
20
|
__exportStar(require("./types"), exports);
|
|
20
21
|
var defaults_1 = require("./defaults");
|
|
21
22
|
Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
|
|
@@ -150,3 +151,11 @@ Object.defineProperty(exports, "readLedgerDailyTallies", { enumerable: true, get
|
|
|
150
151
|
Object.defineProperty(exports, "renderSessionTally", { enumerable: true, get: function () { return tally_1.renderSessionTally; } });
|
|
151
152
|
Object.defineProperty(exports, "pluginLedgerDirectories", { enumerable: true, get: function () { return tally_1.pluginLedgerDirectories; } });
|
|
152
153
|
Object.defineProperty(exports, "sessionLaunchReceipts", { enumerable: true, get: function () { return tally_1.sessionLaunchReceipts; } });
|
|
154
|
+
var status_fields_1 = require("./insights/status-fields");
|
|
155
|
+
Object.defineProperty(exports, "formatStatusFields", { enumerable: true, get: function () { return status_fields_1.formatStatusFields; } });
|
|
156
|
+
Object.defineProperty(exports, "parseStatusFields", { enumerable: true, get: function () { return status_fields_1.parseStatusFields; } });
|
|
157
|
+
Object.defineProperty(exports, "statusPace", { enumerable: true, get: function () { return status_fields_1.statusPace; } });
|
|
158
|
+
Object.defineProperty(exports, "statusColor", { enumerable: true, get: function () { return status_fields_1.statusColor; } });
|
|
159
|
+
var status_data_1 = require("./insights/status-data");
|
|
160
|
+
Object.defineProperty(exports, "readStatusBurn", { enumerable: true, get: function () { return status_data_1.readStatusBurn; } });
|
|
161
|
+
Object.defineProperty(exports, "readStatusMetrics", { enumerable: true, get: function () { return status_data_1.readStatusMetrics; } });
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { type CompareMetric, type InsightBucket, type InsightHost, type InsightObservations, type SessionCommits } from './types';
|
|
13
13
|
export type WhyLang = 'en' | 'es' | 'pt';
|
|
14
|
+
export { STATUS_TEXT } from './status-text';
|
|
14
15
|
/**
|
|
15
16
|
* The language of a flag value or locale: the part before '_', '-', '.' or '@',
|
|
16
17
|
* in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = void 0;
|
|
3
|
+
exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = exports.STATUS_TEXT = void 0;
|
|
4
4
|
exports.whyLangOf = whyLangOf;
|
|
5
5
|
exports.detectWhyLang = detectWhyLang;
|
|
6
6
|
/**
|
|
@@ -15,6 +15,8 @@ exports.detectWhyLang = detectWhyLang;
|
|
|
15
15
|
* locale, and each renderer receives the chosen language as an argument.
|
|
16
16
|
*/
|
|
17
17
|
const types_1 = require("./types");
|
|
18
|
+
var status_text_1 = require("./status-text");
|
|
19
|
+
Object.defineProperty(exports, "STATUS_TEXT", { enumerable: true, get: function () { return status_text_1.STATUS_TEXT; } });
|
|
18
20
|
/**
|
|
19
21
|
* The language of a flag value or locale: the part before '_', '-', '.' or '@',
|
|
20
22
|
* in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
|
|
@@ -89,7 +91,7 @@ const en = {
|
|
|
89
91
|
missingTtl: 'Cache TTL is missing for some writes; their dollars span the verified five-minute and one-hour rates.',
|
|
90
92
|
mixedRanges: 'Some bucket cache-write costs are ranges because mixed cache lifetimes are not attributed to individual buckets. Range endpoints are not additive across buckets.',
|
|
91
93
|
diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
|
|
92
|
-
tipFanout: share => `Next: sub-agents used ${share} of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/
|
|
94
|
+
tipFanout: share => `Next: sub-agents used ${share} of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: https://agentguard.run/burn/next`,
|
|
93
95
|
tipFanoutPlugin: share => `Next: sub-agents used ${share} of this session's tokens. Give related work to one sub-agent instead of several.`,
|
|
94
96
|
tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx agentguard-burn rewrites`,
|
|
95
97
|
tipSubagentModel: (count, model) => `Next: ${count} ${count === 1 ? 'sub-agent' : 'sub-agents'} ran on ${model}. For searching and reading logs, a smaller model does the job: set CLAUDE_CODE_SUBAGENT_MODEL=haiku, or put model: haiku in the sub-agent's definition.`,
|
|
@@ -159,7 +161,7 @@ const es = {
|
|
|
159
161
|
missingTtl: 'Algunas escrituras no tienen TTL de caché; su costo en dólares va de la tarifa verificada de cinco minutos a la de una hora.',
|
|
160
162
|
mixedRanges: 'Algunos costos de escritura en caché por categoría son rangos, porque las duraciones de caché mixtas no se atribuyen a categorías individuales. Los extremos de los rangos no se suman entre categorías.',
|
|
161
163
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
|
|
162
|
-
tipFanout: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: agentguard.run/
|
|
164
|
+
tipFanout: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: https://agentguard.run/burn/next`,
|
|
163
165
|
tipFanoutPlugin: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. Da el trabajo relacionado a un solo subagente en lugar de a varios.`,
|
|
164
166
|
tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx agentguard-burn rewrites`,
|
|
165
167
|
tipSubagentModel: (count, model) => `Próximo paso: ${plural(count, 'subagente usó', 'subagentes usaron')} ${model}. Para buscar y leer logs, un modelo más pequeño basta: define CLAUDE_CODE_SUBAGENT_MODEL=haiku, o pon model: haiku en la definición del subagente.`,
|
|
@@ -229,7 +231,7 @@ const pt = {
|
|
|
229
231
|
missingTtl: 'Algumas gravações não têm TTL de cache; o valor delas em dólares vai da tarifa verificada de cinco minutos à de uma hora.',
|
|
230
232
|
mixedRanges: 'Alguns custos de gravação em cache por categoria aparecem como faixas, porque durações de cache mistas não são atribuídas a categorias individuais. Os extremos das faixas não se somam entre categorias.',
|
|
231
233
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
|
|
232
|
-
tipFanout: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: agentguard.run/
|
|
234
|
+
tipFanout: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: https://agentguard.run/burn/next`,
|
|
233
235
|
tipFanoutPlugin: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. Dê o trabalho relacionado a um único subagente em vez de vários.`,
|
|
234
236
|
tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx agentguard-burn rewrites`,
|
|
235
237
|
tipSubagentModel: (count, model) => `Próximo passo: ${plural(count, 'subagente usou', 'subagentes usaram')} o ${model}. Para buscar e ler logs, um modelo menor dá conta: defina CLAUDE_CODE_SUBAGENT_MODEL=haiku, ou coloque model: haiku na definição do subagente.`,
|
|
@@ -371,7 +373,7 @@ const calendarEn = {
|
|
|
371
373
|
shortHistory: ['Claude Code deletes sessions older than 30 days by default.', 'Burn keeps each day\'s count whenever you run this, so the calendar grows.'],
|
|
372
374
|
saveFailed: 'Burn could not store the counts from this run.',
|
|
373
375
|
next: {
|
|
374
|
-
fanout: share => `Next: sub-agents used ${share} of these tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/
|
|
376
|
+
fanout: share => `Next: sub-agents used ${share} of these tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: https://agentguard.run/burn/next`,
|
|
375
377
|
fanoutPlugin: share => `Next: sub-agents used ${share} of these tokens. Give related work to one sub-agent instead of several.`,
|
|
376
378
|
why: 'Next: see where one session\'s tokens went: npx agentguard-burn why',
|
|
377
379
|
},
|
|
@@ -402,7 +404,7 @@ const calendarEs = {
|
|
|
402
404
|
shortHistory: ['Claude Code borra las sesiones de más de 30 días de forma predeterminada.', 'Burn guarda el conteo diario cada vez que lo ejecutas, y el calendario crece.'],
|
|
403
405
|
saveFailed: 'Burn no pudo guardar los conteos de esta ejecución.',
|
|
404
406
|
next: {
|
|
405
|
-
fanout: share => `Próximo paso: los subagentes usaron el ${share} de estos tokens. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: agentguard.run/
|
|
407
|
+
fanout: share => `Próximo paso: los subagentes usaron el ${share} de estos tokens. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: https://agentguard.run/burn/next`,
|
|
406
408
|
fanoutPlugin: share => `Próximo paso: los subagentes usaron el ${share} de estos tokens. Dale el trabajo relacionado a un solo subagente en vez de varios.`,
|
|
407
409
|
why: 'Próximo paso: a dónde fue cada token de una sesión: npx agentguard-burn why',
|
|
408
410
|
},
|
|
@@ -433,7 +435,7 @@ const calendarPt = {
|
|
|
433
435
|
shortHistory: ['O Claude Code apaga as sessões com mais de 30 dias por padrão.', 'O Burn salva a contagem diária a cada execução, então o calendário cresce.'],
|
|
434
436
|
saveFailed: 'O Burn não conseguiu salvar as contagens desta execução.',
|
|
435
437
|
next: {
|
|
436
|
-
fanout: share => `Próximo passo: os subagentes usaram ${share} destes tokens. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: agentguard.run/
|
|
438
|
+
fanout: share => `Próximo passo: os subagentes usaram ${share} destes tokens. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: https://agentguard.run/burn/next`,
|
|
437
439
|
fanoutPlugin: share => `Próximo passo: os subagentes usaram ${share} destes tokens. Dê o trabalho relacionado a um só subagente em vez de vários.`,
|
|
438
440
|
why: 'Próximo passo: para onde foi cada token de uma sessão: npx agentguard-burn why',
|
|
439
441
|
},
|
|
@@ -33,9 +33,15 @@ exports.MODEL_PRICING = Object.freeze({
|
|
|
33
33
|
'claude-opus-5-5': Object.freeze({ ...rates(4, 0.2, 5, 8, 20), verifiedAt: '2026-09-22' }),
|
|
34
34
|
'claude-opus-5': rates(5, 0.5, 6.25, 10, 25),
|
|
35
35
|
'claude-opus-4-8': rates(5, 0.5, 6.25, 10, 25),
|
|
36
|
-
// Verified 2026-
|
|
37
|
-
'
|
|
36
|
+
// Verified 2026-10-07: Anthropic halved Sonnet 5.5 cache hits to 0.05x base input ($0.10) on 2026-10-07.
|
|
37
|
+
// The pricing page's prompt caching section states it; its model table row still read $0.20 that day.
|
|
38
|
+
// Burn prices every session at the current list price, so earlier Sonnet 5.5 sessions use $0.10 too.
|
|
39
|
+
'claude-sonnet-5-5': Object.freeze({ ...rates(2, 0.1, 2.5, 4, 10), verifiedAt: '2026-10-07' }),
|
|
38
40
|
'claude-sonnet-5': rates(2, 0.2, 2.5, 4, 10),
|
|
41
|
+
// Verified 2026-10-07: Haiku 5.5 (released that day) is priced by prompt length: over 100,000 prompt
|
|
42
|
+
// tokens every category is 5x ($0.50 input, $0.05 cache hits, $0.625 and $1 cache writes, $2.50 output).
|
|
43
|
+
'claude-haiku-5-5': Object.freeze({ ...rates(0.1, 0.01, 0.125, 0.2, 0.5), verifiedAt: '2026-10-07',
|
|
44
|
+
longContext: Object.freeze({ aboveInputTokens: 100_000, inputMultiplier: 5, outputMultiplier: 5 }) }),
|
|
39
45
|
'claude-haiku-4-5-20251001': rates(1, 0.1, 1.25, 2, 5),
|
|
40
46
|
'gpt-6-astra': openaiRates(10, 1, 12.5, 50, 'https://developers.openai.com/api/docs/pricing'),
|
|
41
47
|
'gpt-6-sol': Object.freeze({ ...openaiRates(2, 0.2, 2.5, 10, 'https://developers.openai.com/api/docs/pricing'), verifiedAt: '2026-09-22' }),
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type StatusBurn, type StatusMetrics } from './status-fields';
|
|
2
|
+
export declare function readStatusBurn(home: string, sessionId: string): StatusBurn;
|
|
3
|
+
export declare function readStatusMetrics(home: string, session: string, fields: string, dataDir?: string, includeShare?: boolean): Promise<StatusMetrics & {
|
|
4
|
+
share?: number;
|
|
5
|
+
totalTokens?: number;
|
|
6
|
+
}>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readStatusBurn = readStatusBurn;
|
|
4
|
+
exports.readStatusMetrics = readStatusMetrics;
|
|
5
|
+
const node_fs_1 = require("node:fs");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
7
|
+
const spend_1 = require("@agentguard-run/spend");
|
|
8
|
+
const defaults_1 = require("../defaults");
|
|
9
|
+
const pre_tool_use_1 = require("../hook/pre-tool-use");
|
|
10
|
+
const gateway_1 = require("../gateway");
|
|
11
|
+
const session_1 = require("../state/session");
|
|
12
|
+
const sessions_1 = require("./sessions");
|
|
13
|
+
const transcript_1 = require("./transcript");
|
|
14
|
+
const live_1 = require("./live");
|
|
15
|
+
const render_1 = require("./render");
|
|
16
|
+
const status_fields_1 = require("./status-fields");
|
|
17
|
+
const tally_1 = require("./tally");
|
|
18
|
+
function readStatusBurn(home, sessionId) {
|
|
19
|
+
const present = (0, node_fs_1.existsSync)((0, node_path_1.join)(home, 'burn-policy.json'));
|
|
20
|
+
const policy = present ? (0, pre_tool_use_1.loadPolicy)(home, { notice: false }) : defaults_1.DEFAULT_POLICY;
|
|
21
|
+
const thresholds = policy.thresholds ?? defaults_1.DEFAULT_THRESHOLDS;
|
|
22
|
+
const state = (0, node_fs_1.existsSync)((0, node_path_1.join)(home, 'sessions')) ? new gateway_1.Gateway(home, { sign: false }).peek(sessionId)?.state : null;
|
|
23
|
+
const count = (minutes) => state ? (0, session_1.windowSum)(state.spawnsByActiveMinute, state.activeMinutes, minutes) : 0;
|
|
24
|
+
return { mode: present ? policy.mode : 'enforce',
|
|
25
|
+
burst: { count: count(thresholds.spawnRate.windowActiveMinutes), limit: thresholds.spawnRate.stop - 1 },
|
|
26
|
+
sustained: { count: count(thresholds.fanout.windowActiveMinutes ?? defaults_1.DEFAULT_THRESHOLDS.fanout.windowActiveMinutes), limit: thresholds.fanout.stop },
|
|
27
|
+
tokens: { used: state?.totalTokens ?? 0, limit: thresholds.sustained.stopTokens } };
|
|
28
|
+
}
|
|
29
|
+
async function readStatusMetrics(home, session, fields, dataDir, includeShare = false) {
|
|
30
|
+
const enabled = (0, status_fields_1.parseStatusFields)(fields).fields;
|
|
31
|
+
const result = {};
|
|
32
|
+
if (includeShare || enabled.includes('cost') || enabled.includes('cache'))
|
|
33
|
+
try {
|
|
34
|
+
const location = (0, sessions_1.selectInsightTranscript)(session);
|
|
35
|
+
const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId });
|
|
36
|
+
if (!transcript.state.forkHistoryBoundaryUnknown && transcript.turns.length) {
|
|
37
|
+
const rates = (0, live_1.readPricing)(home), figures = (0, render_1.sessionFigures)(transcript, rates);
|
|
38
|
+
result.totalTokens = figures.attribution.totalTokens;
|
|
39
|
+
const childTokens = figures.attribution.buckets.find(bucket => bucket.bucket === 'subagent_fanout')?.tokens ?? 0;
|
|
40
|
+
if (childTokens > 0 && figures.attribution.totalTokens > 0)
|
|
41
|
+
result.share = 100 * childTokens / figures.attribution.totalTokens;
|
|
42
|
+
result.cost = figures.totalUsd;
|
|
43
|
+
const rewrites = (0, render_1.rewriteReportJson)([transcript], rates);
|
|
44
|
+
result.cache = { tokens: rewrites.totals.cacheWriteTokens, usd: rewrites.totals.usd };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch { /* Missing or unknown transcript data stays unavailable. */ }
|
|
48
|
+
if (enabled.includes('spend')) {
|
|
49
|
+
const modified = (dir) => { try {
|
|
50
|
+
return (0, node_fs_1.statSync)((0, node_path_1.join)(dir, 'ledger/decisions.ndjson')).mtimeMs;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return 0;
|
|
54
|
+
} };
|
|
55
|
+
const directories = dataDir ? [dataDir] : (0, tally_1.pluginLedgerDirectories)(home, { prune: false }).sort((a, b) => modified(b) - modified(a));
|
|
56
|
+
for (const directory of directories) {
|
|
57
|
+
result.spend = await (0, spend_1.readLocalDailySpend)({ policyFile: (0, node_path_1.join)(directory, 'policy.json'), ledgerFile: (0, node_path_1.join)(directory, 'ledger/decisions.ndjson'), publicKeyFile: (0, node_path_1.join)(directory, 'public-key.hex') });
|
|
58
|
+
if (result.spend)
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
if (!result.spend)
|
|
62
|
+
result.spend = await (0, spend_1.readLocalDailySpend)({ policyFile: (0, node_path_1.join)(home, 'policy.json'), ledgerFile: (0, node_path_1.join)(home, 'decisions.ndjson'), publicKeyFile: (0, node_path_1.join)(home, 'signing-public.key') });
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type UsageWindow } from './pace';
|
|
2
|
+
import { STATUS_TEXT } from './status-text';
|
|
3
|
+
export declare const STATUS_FIELDS: readonly ["pace", "cost", "cache", "spend"];
|
|
4
|
+
export type StatusField = typeof STATUS_FIELDS[number];
|
|
5
|
+
export type StatusColor = 'yellow' | 'red' | null;
|
|
6
|
+
export interface StatusPart {
|
|
7
|
+
text: string;
|
|
8
|
+
color?: StatusColor | string;
|
|
9
|
+
background?: string;
|
|
10
|
+
bold?: boolean;
|
|
11
|
+
dim?: boolean;
|
|
12
|
+
field?: StatusField;
|
|
13
|
+
}
|
|
14
|
+
export interface StatusBurn {
|
|
15
|
+
mode: string;
|
|
16
|
+
burst: {
|
|
17
|
+
count: number;
|
|
18
|
+
limit: number;
|
|
19
|
+
};
|
|
20
|
+
sustained: {
|
|
21
|
+
count: number;
|
|
22
|
+
limit: number;
|
|
23
|
+
};
|
|
24
|
+
tokens: {
|
|
25
|
+
used: number;
|
|
26
|
+
limit: number;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface StatusMetrics {
|
|
30
|
+
cost?: {
|
|
31
|
+
min: number;
|
|
32
|
+
max: number;
|
|
33
|
+
} | null;
|
|
34
|
+
cache?: {
|
|
35
|
+
tokens: number;
|
|
36
|
+
usd: {
|
|
37
|
+
min: number;
|
|
38
|
+
max: number;
|
|
39
|
+
} | null;
|
|
40
|
+
} | null;
|
|
41
|
+
spend?: {
|
|
42
|
+
usedCents: number;
|
|
43
|
+
capCents: number;
|
|
44
|
+
resetsAt: number;
|
|
45
|
+
} | null;
|
|
46
|
+
}
|
|
47
|
+
export interface StatusInput extends StatusMetrics {
|
|
48
|
+
burn?: StatusBurn | null;
|
|
49
|
+
share?: number | null;
|
|
50
|
+
windows?: UsageWindow[];
|
|
51
|
+
fields?: string;
|
|
52
|
+
width?: number;
|
|
53
|
+
lang?: keyof typeof STATUS_TEXT;
|
|
54
|
+
now?: number;
|
|
55
|
+
failed?: boolean;
|
|
56
|
+
}
|
|
57
|
+
export declare function parseStatusFields(value?: string): {
|
|
58
|
+
fields: StatusField[];
|
|
59
|
+
unknown: string[];
|
|
60
|
+
};
|
|
61
|
+
export declare function statusColor(used: number, limit?: number): StatusColor;
|
|
62
|
+
export declare function statusCount(n: number): string;
|
|
63
|
+
export declare function statusPlans(windows?: UsageWindow[]): UsageWindow[];
|
|
64
|
+
export declare function statusPlan(windows?: UsageWindow[]): UsageWindow | undefined;
|
|
65
|
+
export declare function statusPace(windows?: UsageWindow[], now?: number): number | null;
|
|
66
|
+
export declare function formatStatusFields(input: StatusInput): {
|
|
67
|
+
text: string;
|
|
68
|
+
parts: StatusPart[];
|
|
69
|
+
panel: string[];
|
|
70
|
+
enabled: ("pace" | "spend" | "cost" | "cache")[];
|
|
71
|
+
unknown: string[];
|
|
72
|
+
dropped: ("pace" | "spend" | "cost" | "cache")[];
|
|
73
|
+
clipped: boolean;
|
|
74
|
+
};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.STATUS_FIELDS = void 0;
|
|
4
|
+
exports.parseStatusFields = parseStatusFields;
|
|
5
|
+
exports.statusColor = statusColor;
|
|
6
|
+
exports.statusCount = statusCount;
|
|
7
|
+
exports.statusPlans = statusPlans;
|
|
8
|
+
exports.statusPlan = statusPlan;
|
|
9
|
+
exports.statusPace = statusPace;
|
|
10
|
+
exports.formatStatusFields = formatStatusFields;
|
|
11
|
+
const pace_1 = require("./pace");
|
|
12
|
+
const status_text_1 = require("./status-text");
|
|
13
|
+
// Display order is most useful first. Remove from the opposite end on overflow.
|
|
14
|
+
exports.STATUS_FIELDS = ['pace', 'cost', 'cache', 'spend'];
|
|
15
|
+
function parseStatusFields(value = '') {
|
|
16
|
+
const names = [...new Set(String(value).slice(0, 1024).split(',').map(s => s.trim().toLowerCase()).filter(Boolean))];
|
|
17
|
+
return { fields: exports.STATUS_FIELDS.filter(field => names.includes(field)),
|
|
18
|
+
unknown: names.filter(name => !exports.STATUS_FIELDS.includes(name)).map(name => name.replace(/[^a-z0-9_]/g, '').slice(0, 32) || '?') };
|
|
19
|
+
}
|
|
20
|
+
function statusColor(used, limit = 100) {
|
|
21
|
+
return limit > 0 && used / limit >= .9 ? 'red' : limit > 0 && used / limit >= .7 ? 'yellow' : null;
|
|
22
|
+
}
|
|
23
|
+
function statusCount(n) {
|
|
24
|
+
if (!Number.isFinite(n))
|
|
25
|
+
return '0';
|
|
26
|
+
for (const [size, unit] of [[1e9, 'B'], [1e6, 'M'], [1e3, 'K']]) {
|
|
27
|
+
if (n >= size)
|
|
28
|
+
return (n / size).toFixed(n >= size * 10 ? 0 : 1).replace(/\.0$/, '') + unit;
|
|
29
|
+
}
|
|
30
|
+
return String(Math.round(n));
|
|
31
|
+
}
|
|
32
|
+
function money(value, range) {
|
|
33
|
+
return Math.abs(value.max - value.min) < .000001 ? `$${value.min.toFixed(2)}` : `$${value.min.toFixed(2)} ${range} $${value.max.toFixed(2)}`;
|
|
34
|
+
}
|
|
35
|
+
function duration(minutes) {
|
|
36
|
+
const n = Math.max(0, Math.round(minutes / 10) * 10);
|
|
37
|
+
return '~' + (n >= 60 ? `${Math.floor(n / 60)}h` : '') + (n % 60 || n < 60 ? `${n % 60}m` : '');
|
|
38
|
+
}
|
|
39
|
+
function statusPlans(windows = []) {
|
|
40
|
+
const latest = new Map();
|
|
41
|
+
for (const window of windows)
|
|
42
|
+
if (Number.isFinite(window.usedPercent) && window.usedPercent >= 0 && window.usedPercent <= 100 &&
|
|
43
|
+
(!latest.has(window.name) || latest.get(window.name).observedAt <= window.observedAt))
|
|
44
|
+
latest.set(window.name, window);
|
|
45
|
+
return [...latest.values()].sort((a, b) => b.usedPercent - a.usedPercent);
|
|
46
|
+
}
|
|
47
|
+
function statusPlan(windows = []) {
|
|
48
|
+
return statusPlans(windows)[0];
|
|
49
|
+
}
|
|
50
|
+
function statusPace(windows = [], now = Date.now()) {
|
|
51
|
+
const plan = statusPlan(windows);
|
|
52
|
+
if (!plan)
|
|
53
|
+
return null;
|
|
54
|
+
const same = windows.filter(w => w.name === plan.name && w.resetsAt === plan.resetsAt && w.pool === plan.pool && w.source === plan.source &&
|
|
55
|
+
w.windowMinutes === plan.windowMinutes && w.observedAt >= now - 600000 && w.observedAt <= now &&
|
|
56
|
+
w.resetsAt > now && Number.isFinite(w.usedPercent) && w.usedPercent >= 0 && w.usedPercent <= 100);
|
|
57
|
+
if (!same.some(w => w.observedAt < plan.observedAt && w.usedPercent < plan.usedPercent))
|
|
58
|
+
return null;
|
|
59
|
+
const minutes = (0, pace_1.forecastLimit)(same, now).minutes;
|
|
60
|
+
return minutes !== null && minutes < (plan.resetsAt - now) / 60000 ? minutes : null;
|
|
61
|
+
}
|
|
62
|
+
function formatStatusFields(input) {
|
|
63
|
+
const words = status_text_1.STATUS_TEXT[input.lang ?? 'en'], selected = parseStatusFields(input.fields);
|
|
64
|
+
const plans = statusPlans(input.windows), plan = plans[0], pace = statusPace(input.windows, input.now);
|
|
65
|
+
const planName = (window) => window.name === 'five_hour' ? words.fiveHour : window.name === 'seven_day' ? words.weekly : window.name.replace(/[^a-zA-Z0-9_]/g, '').replace(/_/g, ' ');
|
|
66
|
+
const age = (window) => {
|
|
67
|
+
const elapsed = (input.now ?? Date.now()) - window.observedAt;
|
|
68
|
+
return elapsed > 60000 ? words.ago.replace('{minutes}', String(Math.floor(elapsed / 60000))) : '';
|
|
69
|
+
};
|
|
70
|
+
const optional = new Map();
|
|
71
|
+
if (pace !== null)
|
|
72
|
+
optional.set('pace', { text: `${words.limit} ${duration(pace)}`, color: pace < 30 ? 'yellow' : null });
|
|
73
|
+
if (input.cost)
|
|
74
|
+
optional.set('cost', { text: `≈${money(input.cost, words.range)} ${words.list}` });
|
|
75
|
+
if (input.cache && input.cache.tokens > 0)
|
|
76
|
+
optional.set('cache', { text: `${words.cache} ${statusCount(input.cache.tokens)}${input.cache.usd ? ` (≈${money(input.cache.usd, words.range)} ${words.list})` : ''}` });
|
|
77
|
+
if (input.spend && input.spend.capCents >= 0)
|
|
78
|
+
optional.set('spend', { text: `${words.spend} $${(input.spend.usedCents / 100).toFixed(2)} ${words.of} $${(input.spend.capCents / 100).toFixed(2)} ${words.list} ${words.today}`,
|
|
79
|
+
color: input.spend.capCents === 0 ? 'red' : statusColor(input.spend.usedCents, input.spend.capCents) });
|
|
80
|
+
const enabled = selected.fields.filter(field => optional.has(field));
|
|
81
|
+
const dropped = [];
|
|
82
|
+
const width = Math.max(1, Number.isFinite(input.width) ? Math.floor(input.width) : 200);
|
|
83
|
+
function parts(short = 0) {
|
|
84
|
+
const out = [{ text: 'AgentGuard ', background: '#2abcb4', color: '#04201e', bold: true }];
|
|
85
|
+
const burn = input.burn;
|
|
86
|
+
if (!burn) {
|
|
87
|
+
out.push({ text: input.failed ? ` ${words.unavailable} · /agentguard` : ` ${words.starting}`, dim: true });
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
const ratio = (w) => w.limit ? w.count / w.limit : 0;
|
|
91
|
+
const win = ratio(burn.sustained) > ratio(burn.burst) ? burn.sustained : burn.burst;
|
|
92
|
+
const color = statusColor(win.count, win.limit);
|
|
93
|
+
out.push({ text: ` ${short > 1 ? 'a' : words.agents} ${win.count}${short ? '/' : ` ${words.of} `}${win.limit}`, color, dim: !color });
|
|
94
|
+
const add = (text, extra = {}) => out.push({ text: ` · ${text}`, dim: !extra.color, ...extra });
|
|
95
|
+
add(`${short > 1 ? 't' : words.tokens} ${statusCount(burn.tokens.used)}${short ? '/' : ` ${words.of} `}${statusCount(burn.tokens.limit)}`, { color: statusColor(burn.tokens.used, burn.tokens.limit) });
|
|
96
|
+
if (typeof input.share === 'number' && Number.isFinite(input.share))
|
|
97
|
+
add(`${Math.round(input.share)}% ${short ? words.sub : words.share}`);
|
|
98
|
+
if (plan)
|
|
99
|
+
add(`${short && plan.name === 'five_hour' ? '5h' : planName(plan)} ${Math.round(plan.usedPercent)}%${age(plan) ? ` (${age(plan)})` : ''}`, { color: statusColor(plan.usedPercent) });
|
|
100
|
+
for (const field of enabled)
|
|
101
|
+
if (!dropped.includes(field)) {
|
|
102
|
+
const { text, ...style } = optional.get(field);
|
|
103
|
+
add(text, { ...style, field });
|
|
104
|
+
}
|
|
105
|
+
if (burn.mode === 'shadow')
|
|
106
|
+
add(words.watching, { color: 'yellow' });
|
|
107
|
+
if (short < 2)
|
|
108
|
+
add('/agentguard');
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
let output = parts();
|
|
112
|
+
const length = () => output.reduce((sum, part) => sum + [...part.text].length, 0);
|
|
113
|
+
for (const field of [...enabled].reverse()) {
|
|
114
|
+
if (length() <= width)
|
|
115
|
+
break;
|
|
116
|
+
dropped.push(field);
|
|
117
|
+
output = parts();
|
|
118
|
+
}
|
|
119
|
+
for (let short = 1; length() > width && short <= 2; short++)
|
|
120
|
+
output = parts(short);
|
|
121
|
+
// Extremely narrow host slots cannot hold every value. Preserve the data in
|
|
122
|
+
// parts and ask the host to clip one row rather than wrap or invent numbers.
|
|
123
|
+
const fullText = output.map(part => part.text).join('');
|
|
124
|
+
const text = [...fullText].slice(0, width).join('');
|
|
125
|
+
const panel = [
|
|
126
|
+
...plans.map(window => `${words.plan} ${Math.round(window.usedPercent)}% (${planName(window)}). ${words.reset} ${Number.isFinite(window.resetsAt) ? new Date(window.resetsAt).toISOString() : words.none}.${age(window) ? ` ${words.lastRead} ${age(window)}.` : ''}`),
|
|
127
|
+
pace !== null ? `${words.limit} ${duration(pace)}.` : words.paceEmpty,
|
|
128
|
+
input.cost ? `${words.costLead} ≈ ${money(input.cost, words.range)} ${words.costFull}.` : words.costEmpty,
|
|
129
|
+
input.cache && input.cache.tokens > 0 ? `${words.cacheLead} ${input.cache.tokens.toLocaleString('en-US')} ${words.tokens}${input.cache.usd ? ` (≈ ${money(input.cache.usd, words.range)} ${words.costFull})` : ''}.` : words.cacheEmpty,
|
|
130
|
+
input.spend ? `${words.spendLead} $${(input.spend.usedCents / 100).toFixed(2)} ${words.of} $${(input.spend.capCents / 100).toFixed(2)} ${words.list} ${words.today}. ${words.reset} ${new Date(input.spend.resetsAt).toISOString()}.` : words.spendEmpty,
|
|
131
|
+
`${words.enabled} ${selected.fields.join(', ') || words.none}. ${words.change}`,
|
|
132
|
+
selected.unknown.length ? `${words.unknown} ${selected.unknown.join(', ')}.` : null,
|
|
133
|
+
dropped.length ? `${words.hidden} ${dropped.join(', ')}.` : null,
|
|
134
|
+
].filter((line) => line !== null);
|
|
135
|
+
return { text, parts: output, panel, enabled: selected.fields, unknown: selected.unknown, dropped, clipped: fullText !== text };
|
|
136
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export declare const STATUS_TEXT: {
|
|
2
|
+
en: {
|
|
3
|
+
ago: string;
|
|
4
|
+
lastRead: string;
|
|
5
|
+
range: string;
|
|
6
|
+
fiveHour: string;
|
|
7
|
+
agents: string;
|
|
8
|
+
tokens: string;
|
|
9
|
+
of: string;
|
|
10
|
+
share: string;
|
|
11
|
+
sub: string;
|
|
12
|
+
weekly: string;
|
|
13
|
+
limit: string;
|
|
14
|
+
cache: string;
|
|
15
|
+
spend: string;
|
|
16
|
+
today: string;
|
|
17
|
+
list: string;
|
|
18
|
+
watching: string;
|
|
19
|
+
unavailable: string;
|
|
20
|
+
starting: string;
|
|
21
|
+
costFull: string;
|
|
22
|
+
paceEmpty: string;
|
|
23
|
+
costEmpty: string;
|
|
24
|
+
cacheEmpty: string;
|
|
25
|
+
spendEmpty: string;
|
|
26
|
+
costLead: string;
|
|
27
|
+
cacheLead: string;
|
|
28
|
+
spendLead: string;
|
|
29
|
+
enabled: string;
|
|
30
|
+
none: string;
|
|
31
|
+
change: string;
|
|
32
|
+
unknown: string;
|
|
33
|
+
reset: string;
|
|
34
|
+
plan: string;
|
|
35
|
+
hidden: string;
|
|
36
|
+
};
|
|
37
|
+
es: {
|
|
38
|
+
ago: string;
|
|
39
|
+
lastRead: string;
|
|
40
|
+
range: string;
|
|
41
|
+
fiveHour: string;
|
|
42
|
+
agents: string;
|
|
43
|
+
tokens: string;
|
|
44
|
+
of: string;
|
|
45
|
+
share: string;
|
|
46
|
+
sub: string;
|
|
47
|
+
weekly: string;
|
|
48
|
+
limit: string;
|
|
49
|
+
cache: string;
|
|
50
|
+
spend: string;
|
|
51
|
+
today: string;
|
|
52
|
+
list: string;
|
|
53
|
+
watching: string;
|
|
54
|
+
unavailable: string;
|
|
55
|
+
starting: string;
|
|
56
|
+
costFull: string;
|
|
57
|
+
paceEmpty: string;
|
|
58
|
+
costEmpty: string;
|
|
59
|
+
cacheEmpty: string;
|
|
60
|
+
spendEmpty: string;
|
|
61
|
+
costLead: string;
|
|
62
|
+
cacheLead: string;
|
|
63
|
+
spendLead: string;
|
|
64
|
+
enabled: string;
|
|
65
|
+
none: string;
|
|
66
|
+
change: string;
|
|
67
|
+
unknown: string;
|
|
68
|
+
reset: string;
|
|
69
|
+
plan: string;
|
|
70
|
+
hidden: string;
|
|
71
|
+
};
|
|
72
|
+
pt: {
|
|
73
|
+
ago: string;
|
|
74
|
+
lastRead: string;
|
|
75
|
+
range: string;
|
|
76
|
+
fiveHour: string;
|
|
77
|
+
agents: string;
|
|
78
|
+
tokens: string;
|
|
79
|
+
of: string;
|
|
80
|
+
share: string;
|
|
81
|
+
sub: string;
|
|
82
|
+
weekly: string;
|
|
83
|
+
limit: string;
|
|
84
|
+
cache: string;
|
|
85
|
+
spend: string;
|
|
86
|
+
today: string;
|
|
87
|
+
list: string;
|
|
88
|
+
watching: string;
|
|
89
|
+
unavailable: string;
|
|
90
|
+
starting: string;
|
|
91
|
+
costFull: string;
|
|
92
|
+
paceEmpty: string;
|
|
93
|
+
costEmpty: string;
|
|
94
|
+
cacheEmpty: string;
|
|
95
|
+
spendEmpty: string;
|
|
96
|
+
costLead: string;
|
|
97
|
+
cacheLead: string;
|
|
98
|
+
spendLead: string;
|
|
99
|
+
enabled: string;
|
|
100
|
+
none: string;
|
|
101
|
+
change: string;
|
|
102
|
+
unknown: string;
|
|
103
|
+
reset: string;
|
|
104
|
+
plan: string;
|
|
105
|
+
hidden: string;
|
|
106
|
+
};
|
|
107
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.STATUS_TEXT = void 0;
|
|
4
|
+
// Display-only words shared with the Claude mod. No environment or I/O here.
|
|
5
|
+
exports.STATUS_TEXT = {
|
|
6
|
+
en: { ago: '{minutes}m ago', lastRead: 'Last read', range: 'to', fiveHour: '5-hour', agents: 'sub-agents', tokens: 'tokens', of: 'of', share: 'to sub-agents', sub: 'sub', weekly: 'weekly',
|
|
7
|
+
limit: 'limit in', cache: 'cache waste', spend: 'spend', today: 'today', list: 'list', watching: 'watching only',
|
|
8
|
+
unavailable: 'status unavailable', starting: 'starting', costFull: 'at API list price, not a bill',
|
|
9
|
+
paceEmpty: 'Pace needs two rising plan usage samples and a limit reached before reset.',
|
|
10
|
+
costEmpty: 'Session cost is unavailable because recorded usage or API list prices are missing.',
|
|
11
|
+
cacheEmpty: 'No large prefix rewrites are recorded in this session.',
|
|
12
|
+
spendEmpty: 'Spend is hidden without a readable daily cap and local spend record.',
|
|
13
|
+
costLead: 'Session cost:', cacheLead: 'Large prefix rewrites in this session:', spendLead: 'Daily policy spend:',
|
|
14
|
+
enabled: 'Optional status fields on:', none: 'none', change: 'Change status_fields in the AgentGuard plugin settings, or pass the fields flag to Burn statusline.',
|
|
15
|
+
unknown: 'Ignored unknown status fields:', reset: 'Resets at', plan: 'Plan usage:', hidden: 'Fields hidden to fit this width:' },
|
|
16
|
+
es: { ago: 'hace {minutes}min', lastRead: 'Última lectura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'a subagentes', sub: 'sub', weekly: 'semanal',
|
|
17
|
+
limit: 'límite en', cache: 'caché reescrita', spend: 'gasto', today: 'hoy', list: 'lista', watching: 'solo observando',
|
|
18
|
+
unavailable: 'estado no disponible', starting: 'iniciando', costFull: 'a precio de lista de la API, no es una factura',
|
|
19
|
+
paceEmpty: 'El ritmo necesita dos muestras crecientes del plan y alcanzar el límite antes del reinicio.',
|
|
20
|
+
costEmpty: 'El costo de la sesión no está disponible porque faltan datos de uso o precios de lista de la API.',
|
|
21
|
+
cacheEmpty: 'No hay reescrituras grandes del prefijo registradas en esta sesión.',
|
|
22
|
+
spendEmpty: 'El gasto se oculta sin un límite diario legible y un registro local del gasto.',
|
|
23
|
+
costLead: 'Costo de la sesión:', cacheLead: 'Reescrituras grandes del prefijo en esta sesión:', spendLead: 'Gasto diario de la política:',
|
|
24
|
+
enabled: 'Campos opcionales activos:', none: 'ninguno', change: 'Cambia status_fields en los ajustes del plugin AgentGuard o pasa la opción fields a Burn statusline.',
|
|
25
|
+
unknown: 'Campos de estado desconocidos ignorados:', reset: 'Se reinicia a las', plan: 'Uso del plan:', hidden: 'Campos ocultos para caber en este ancho:' },
|
|
26
|
+
pt: { ago: 'há {minutes}min', lastRead: 'Última leitura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'para subagentes', sub: 'sub', weekly: 'semanal',
|
|
27
|
+
limit: 'limite em', cache: 'cache regravado', spend: 'gasto', today: 'hoje', list: 'lista', watching: 'só observando',
|
|
28
|
+
unavailable: 'status indisponível', starting: 'iniciando', costFull: 'a preço de lista da API, não é uma fatura',
|
|
29
|
+
paceEmpty: 'O ritmo precisa de duas amostras crescentes do plano e atingir o limite antes da renovação.',
|
|
30
|
+
costEmpty: 'O custo da sessão está indisponível porque faltam dados de uso ou preços de lista da API.',
|
|
31
|
+
cacheEmpty: 'Não há regravações grandes do prefixo registradas nesta sessão.',
|
|
32
|
+
spendEmpty: 'O gasto fica oculto sem um limite diário legível e um registro local do gasto.',
|
|
33
|
+
costLead: 'Custo da sessão:', cacheLead: 'Regravações grandes do prefixo nesta sessão:', spendLead: 'Gasto diário da política:',
|
|
34
|
+
enabled: 'Campos opcionais ativos:', none: 'nenhum', change: 'Altere status_fields nas configurações do plugin AgentGuard ou passe a opção fields ao Burn statusline.',
|
|
35
|
+
unknown: 'Campos de status desconhecidos ignorados:', reset: 'Renova às', plan: 'Uso do plano:', hidden: 'Campos ocultos para caber nesta largura:' },
|
|
36
|
+
};
|
|
@@ -33,7 +33,9 @@ export declare function sessionLaunchReceipts(session: string, options?: {
|
|
|
33
33
|
data?: string;
|
|
34
34
|
}): Promise<Entry[]>;
|
|
35
35
|
export declare function tallyEntries(entries: Entry[], publicKeyHex: string, session: string): Promise<SessionTally>;
|
|
36
|
-
export declare function pluginLedgerDirectories(home?: string
|
|
36
|
+
export declare function pluginLedgerDirectories(home?: string, options?: {
|
|
37
|
+
prune?: boolean;
|
|
38
|
+
}): string[];
|
|
37
39
|
export declare function readLedgerTallies(data: string): Promise<SessionTally[]>;
|
|
38
40
|
/** Completion-day increments, so a resumed session's cumulative totals upload once. */
|
|
39
41
|
export declare function readLedgerDailyTallies(data: string): Promise<SessionTally[]>;
|
|
@@ -117,7 +117,7 @@ async function tallyEntries(entries, publicKeyHex, session) {
|
|
|
117
117
|
return failed(session);
|
|
118
118
|
return countedSession(entries, session);
|
|
119
119
|
}
|
|
120
|
-
function pluginLedgerDirectories(home = process.env.AGENTGUARD_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard')) {
|
|
120
|
+
function pluginLedgerDirectories(home = process.env.AGENTGUARD_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard'), options = {}) {
|
|
121
121
|
const dirs = new Set([process.env.PLUGIN_DATA || process.env.CLAUDE_PLUGIN_DATA || (0, node_path_1.join)(home, 'codex-plugin')]);
|
|
122
122
|
const registry = (0, node_path_1.join)(home, 'plugin-ledgers');
|
|
123
123
|
let files;
|
|
@@ -151,7 +151,7 @@ function pluginLedgerDirectories(home = process.env.AGENTGUARD_HOME || (0, node_
|
|
|
151
151
|
}
|
|
152
152
|
// Prune only the stale pointer, never its target. A concurrently replaced
|
|
153
153
|
// entry is retained. Unreadable or malformed neighbors do not stop discovery.
|
|
154
|
-
if ((0, node_fs_1.readFileSync)(entry, 'utf8') === text)
|
|
154
|
+
if (options.prune !== false && (0, node_fs_1.readFileSync)(entry, 'utf8') === text)
|
|
155
155
|
(0, node_fs_1.unlinkSync)(entry);
|
|
156
156
|
}
|
|
157
157
|
catch { /* One inaccessible entry must not hide healthy ledgers. */ }
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const COUNT_PROMPT = "Help us count real users? Sends one anonymous ping (random ID, Burn version, OS). Never your prompts, files or usage. [y/N]";
|
|
2
|
+
export declare function askToCount(timeoutMs?: number): Promise<boolean>;
|
|
3
|
+
/** Called only by the executable, after a successful human-readable why report. */
|
|
4
|
+
export declare function countFirstReport(version: string, ask?: typeof askToCount): Promise<void>;
|
|
5
|
+
export declare function telemetryCommand(args: string[]): number;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.COUNT_PROMPT = void 0;
|
|
4
|
+
exports.askToCount = askToCount;
|
|
5
|
+
exports.countFirstReport = countFirstReport;
|
|
6
|
+
exports.telemetryCommand = telemetryCommand;
|
|
7
|
+
const node_readline_1 = require("node:readline");
|
|
8
|
+
const spend_1 = require("@agentguard-run/spend");
|
|
9
|
+
exports.COUNT_PROMPT = 'Help us count real users? Sends one anonymous ping (random ID, Burn version, OS). Never your prompts, files or usage. [y/N]';
|
|
10
|
+
function askToCount(timeoutMs = 15000) {
|
|
11
|
+
return new Promise(resolve => {
|
|
12
|
+
const input = (0, node_readline_1.createInterface)({ input: process.stdin, output: process.stdout, terminal: true });
|
|
13
|
+
let done = false;
|
|
14
|
+
const finish = (answer = '') => {
|
|
15
|
+
if (done)
|
|
16
|
+
return;
|
|
17
|
+
done = true;
|
|
18
|
+
clearTimeout(timer);
|
|
19
|
+
input.close();
|
|
20
|
+
resolve(/^(y|yes)$/i.test(answer.trim()));
|
|
21
|
+
};
|
|
22
|
+
const timer = setTimeout(() => { process.stdout.write('\n'); finish(); }, timeoutMs);
|
|
23
|
+
input.once('close', () => finish());
|
|
24
|
+
input.once('SIGINT', () => finish());
|
|
25
|
+
input.question(exports.COUNT_PROMPT + ' ', finish);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Called only by the executable, after a successful human-readable why report. */
|
|
29
|
+
async function countFirstReport(version, ask = askToCount) {
|
|
30
|
+
try {
|
|
31
|
+
if (!(0, spend_1.telemetryInteractive)() || process.env.AGENTGUARD_HOOK === '1' || process.env.CLAUDE_PLUGIN_ROOT || process.env.PLUGIN_ROOT)
|
|
32
|
+
return;
|
|
33
|
+
if (!(0, spend_1.telemetryStatus)().enabled) {
|
|
34
|
+
if (!(0, spend_1.claimTelemetryConsent)())
|
|
35
|
+
return;
|
|
36
|
+
if (!await ask())
|
|
37
|
+
return;
|
|
38
|
+
(0, spend_1.enableTelemetry)();
|
|
39
|
+
}
|
|
40
|
+
(0, spend_1.recordTelemetryEvent)('burn_first_report', { sdkName: '@agentguard-run/burn', sdkVersion: version,
|
|
41
|
+
oncePerInstall: true, interactiveOnly: true });
|
|
42
|
+
}
|
|
43
|
+
catch { /* Counting never affects a report. */ }
|
|
44
|
+
}
|
|
45
|
+
function telemetryCommand(args) {
|
|
46
|
+
const action = args[0] ?? 'status';
|
|
47
|
+
if (args.length > 1 || !['status', 'on', 'off'].includes(action)) {
|
|
48
|
+
process.stderr.write('Usage: agentguard-burn telemetry status|on|off\n');
|
|
49
|
+
return 64;
|
|
50
|
+
}
|
|
51
|
+
const status = action === 'on' ? (0, spend_1.enableTelemetry)() : action === 'off' ? (0, spend_1.disableTelemetry)() : (0, spend_1.telemetryStatus)();
|
|
52
|
+
process.stdout.write(`Anonymous count: ${status.enabled ? 'on' : 'off'}. Shared with Spend.\n` +
|
|
53
|
+
'One Burn ping after a successful interactive why report: event=burn_first_report, sdk_name=@agentguard-run/burn, sdk_version=Burn version, runtime=Node version, os_family=OS, anonymous_install_id=random install ID, ci_env_detected=false, tty=true.\n' +
|
|
54
|
+
'Never prompts, files, paths, session IDs, token counts or model names.\n' +
|
|
55
|
+
'AGENTGUARD_NO_BEACON=1 always turns it off. AGENTGUARD_TELEMETRY=1 turns it on unless that off switch is set.\n');
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
@@ -57,7 +57,7 @@ The verdict names the exact setting: `"promptCacheTtl": "1h"` in `settings.json`
|
|
|
57
57
|
|
|
58
58
|
**Standard tier only.** Every row is the provider's standard per-token price. Faster tiers cost more (Claude's fast mode is a premium on Opus models; OpenAI's Ultrafast on GPT-6 Astra is six times the standard rate, at $60 in and $300 out per million tokens as of 2026-09-29), and the transcripts Burn reads do not say which tier a response ran on, so a session on one of those tiers is priced BELOW what it would cost. Batch and flex discounts are not applied either.
|
|
59
59
|
|
|
60
|
-
Every bundled row includes its exact model identifier, `sourceUrl` and `verifiedAt`. The rates were checked on 2026-09-17, except `claude-opus-5-5`, `gpt-6-sol` and `gpt-6-luna`, which were checked on 2026-09-22, and `claude-sonnet-5-5` and `
|
|
60
|
+
Every bundled row includes its exact model identifier, `sourceUrl` and `verifiedAt`. The rates were checked on 2026-09-17, except `claude-opus-5-5`, `gpt-6-sol` and `gpt-6-luna`, which were checked on 2026-09-22, `gpt-6.1-sol`, which was checked on 2026-09-29, and `claude-sonnet-5-5` and `claude-haiku-5-5`, which were checked on 2026-10-07. The runtime never downloads pricing. Run `agentguard-burn pricing` to inspect the installed table.
|
|
61
61
|
|
|
62
62
|
The Claude rows use the [official model price list](https://platform.claude.com/docs/en/about-claude/pricing). Amounts below are USD per million tokens in the order fresh input, cache read, five-minute write, one-hour write, output:
|
|
63
63
|
|
|
@@ -65,7 +65,9 @@ The Claude rows use the [official model price list](https://platform.claude.com/
|
|
|
65
65
|
* `claude-fable-5`: 10, 1, 12.5, 20, 50.
|
|
66
66
|
* `claude-opus-5-5`: 4, 0.2, 5, 8, 20.
|
|
67
67
|
* `claude-opus-5` and `claude-opus-4-8`: 5, 0.5, 6.25, 10, 25.
|
|
68
|
-
* `claude-sonnet-5-5
|
|
68
|
+
* `claude-sonnet-5-5`: 2, 0.1, 2.5, 4, 10. Anthropic halved its cache hits on 2026-10-07; Burn applies the current list price to every session, including earlier ones.
|
|
69
|
+
* `claude-sonnet-5`: 2, 0.2, 2.5, 4, 10.
|
|
70
|
+
* `claude-haiku-5-5`: 0.1, 0.01, 0.125, 0.2, 0.5 for prompts up to 100,000 tokens; every category is 5x above that (0.5, 0.05, 0.625, 1, 2.5).
|
|
69
71
|
* `claude-haiku-4-5-20251001`: 1, 0.1, 1.25, 2, 5.
|
|
70
72
|
|
|
71
73
|
The [OpenAI API price list](https://developers.openai.com/api/docs/pricing) supplies these standard rates in the order fresh input, cache read, cache write, output:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentguard-run/burn",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"homepage": "https://agentguard.run/burn",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@napi-rs/canvas": "^1.0.9",
|
|
65
|
-
"@agentguard-run/spend": "0.
|
|
65
|
+
"@agentguard-run/spend": "0.22.0",
|
|
66
66
|
"ajv": "8.17.1"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|