@agentguard-run/burn 0.4.0 → 0.5.1
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 +19 -0
- package/README.md +85 -9
- package/dist/src/cli.js +120 -24
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +10 -1
- package/dist/src/insights/calendar-render.js +2 -1
- package/dist/src/insights/first-run.d.ts +12 -0
- package/dist/src/insights/first-run.js +17 -0
- 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/render.js +3 -2
- package/dist/src/insights/sessions.d.ts +4 -0
- package/dist/src/insights/sessions.js +18 -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/dist/src/version.d.ts +2 -0
- package/dist/src/version.js +5 -0
- package/docs/USAGE_AND_PRICING.md +4 -2
- package/package.json +2 -2
|
@@ -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' }),
|
|
@@ -26,6 +26,7 @@ const attribution_1 = require("./attribution");
|
|
|
26
26
|
const pricing_1 = require("./pricing");
|
|
27
27
|
const live_1 = require("./live");
|
|
28
28
|
const transcript_1 = require("./transcript");
|
|
29
|
+
const version_1 = require("../version");
|
|
29
30
|
const types_1 = require("./types");
|
|
30
31
|
const i18n_1 = require("./i18n");
|
|
31
32
|
const stop_text_1 = require("../stop-text");
|
|
@@ -329,7 +330,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
|
|
|
329
330
|
const money = (value) => (0, live_1.dollars)(value, text);
|
|
330
331
|
if (transcript.state.forkHistoryBoundaryUnknown)
|
|
331
332
|
return [
|
|
332
|
-
`AgentGuard why: ${transcript.sessionId}`,
|
|
333
|
+
`Burn ${version_1.BURN_VERSION} | AgentGuard why: ${transcript.sessionId}`,
|
|
333
334
|
text.forkUnavailable,
|
|
334
335
|
table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
|
|
335
336
|
...(options.commits ? ['', text.bought(options.commits, transcript.host, null)] : []),
|
|
@@ -354,7 +355,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
|
|
|
354
355
|
const perCommit = options.commits ? tokensPerCommit(attribution.totalTokens, options.commits) : null;
|
|
355
356
|
const bought = options.commits ? text.bought(options.commits, transcript.host, perCommit === null ? null : (0, exports.count)(perCommit)) : null;
|
|
356
357
|
return [
|
|
357
|
-
`AgentGuard why: ${transcript.sessionId}`,
|
|
358
|
+
`Burn ${version_1.BURN_VERSION} | AgentGuard why: ${transcript.sessionId}`,
|
|
358
359
|
text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
|
|
359
360
|
text.usage((0, exports.count)(totals.input), (0, exports.count)(totals.write), (0, exports.count)(totals.read), (0, exports.count)(totals.output)),
|
|
360
361
|
'', table(text.headers, rows), '',
|
|
@@ -9,6 +9,10 @@ export declare function transcriptRoots(): {
|
|
|
9
9
|
claude: string;
|
|
10
10
|
codex: string;
|
|
11
11
|
};
|
|
12
|
+
export declare class NoSessionsFoundError extends Error {
|
|
13
|
+
readonly lookedIn: string[];
|
|
14
|
+
constructor(lookedIn: string[]);
|
|
15
|
+
}
|
|
12
16
|
/** Local locators only. Never follows directory symlinks or reads message content. */
|
|
13
17
|
export declare function discoverInsightTranscripts(roots?: {
|
|
14
18
|
claude: string;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NoSessionsFoundError = void 0;
|
|
3
4
|
exports.transcriptRoots = transcriptRoots;
|
|
4
5
|
exports.discoverInsightTranscripts = discoverInsightTranscripts;
|
|
5
6
|
exports.transcriptFileLocation = transcriptFileLocation;
|
|
@@ -11,10 +12,22 @@ const node_fs_1 = require("node:fs");
|
|
|
11
12
|
const node_path_1 = require("node:path");
|
|
12
13
|
const node_os_1 = require("node:os");
|
|
13
14
|
const transcript_1 = require("./transcript");
|
|
15
|
+
const first_run_1 = require("./first-run");
|
|
14
16
|
/** Claude Code keeps one directory per project here, each session a JSONL file directly inside it; Codex keeps dated rollouts. */
|
|
15
17
|
function transcriptRoots() {
|
|
16
|
-
return {
|
|
18
|
+
return {
|
|
19
|
+
claude: (0, node_path_1.resolve)(process.env.CLAUDE_CONFIG_DIR || (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude'), 'projects'),
|
|
20
|
+
codex: (0, node_path_1.resolve)(process.env.CODEX_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), '.codex'), 'sessions'),
|
|
21
|
+
};
|
|
17
22
|
}
|
|
23
|
+
class NoSessionsFoundError extends Error {
|
|
24
|
+
lookedIn;
|
|
25
|
+
constructor(lookedIn) {
|
|
26
|
+
super(first_run_1.NO_SESSIONS_MESSAGE);
|
|
27
|
+
this.lookedIn = lookedIn;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.NoSessionsFoundError = NoSessionsFoundError;
|
|
18
31
|
/** Local locators only. Never follows directory symlinks or reads message content. */
|
|
19
32
|
function discoverInsightTranscripts(roots = transcriptRoots()) {
|
|
20
33
|
const found = [];
|
|
@@ -60,7 +73,10 @@ function selectInsightTranscript(session, locations) {
|
|
|
60
73
|
const file = requested ? transcriptFileLocation(requested) : null;
|
|
61
74
|
if (file)
|
|
62
75
|
return file;
|
|
63
|
-
const
|
|
76
|
+
const roots = transcriptRoots();
|
|
77
|
+
const candidates = locations ?? discoverInsightTranscripts(roots);
|
|
78
|
+
if (!session && candidates.length === 0)
|
|
79
|
+
throw new NoSessionsFoundError(Object.values(roots));
|
|
64
80
|
// With nothing requested, the newest top-level session wins. A subagent's own
|
|
65
81
|
// transcript (Claude Code keeps them under <session>/subagents/agent-*.jsonl) is
|
|
66
82
|
// often the newest file on disk, and read alone it reports 100% fan-out and
|
|
@@ -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
|
+
}
|