@agentguard-run/burn 0.5.1 → 0.6.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 +16 -0
- package/README.md +78 -1
- package/dist/src/cli.js +150 -4
- package/dist/src/display-mode.d.ts +12 -0
- package/dist/src/display-mode.js +67 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +12 -1
- package/dist/src/insights/compact-replay.d.ts +97 -0
- package/dist/src/insights/compact-replay.js +414 -0
- package/dist/src/insights/compact-settings.d.ts +30 -0
- package/dist/src/insights/compact-settings.js +122 -0
- package/dist/src/insights/i18n.d.ts +19 -0
- package/dist/src/insights/i18n.js +82 -1
- package/dist/src/insights/render.d.ts +13 -1
- package/dist/src/insights/render.js +32 -19
- package/dist/src/insights/simple-data.d.ts +20 -0
- package/dist/src/insights/simple-data.js +229 -0
- package/dist/src/insights/simple-render.d.ts +26 -0
- package/dist/src/insights/simple-render.js +92 -0
- package/dist/src/insights/simple-text.d.ts +33 -0
- package/dist/src/insights/simple-text.js +44 -0
- package/dist/src/insights/status-fields.d.ts +7 -2
- package/dist/src/insights/status-fields.js +18 -1
- package/dist/src/insights/status-text.d.ts +18 -0
- package/dist/src/insights/status-text.js +6 -0
- package/dist/src/insights/week-render.d.ts +4 -0
- package/dist/src/insights/week-render.js +31 -0
- package/dist/src/insights/week.d.ts +75 -0
- package/dist/src/insights/week.js +253 -0
- package/dist/src/live-panel.d.ts +2 -1
- package/dist/src/live-panel.js +29 -2
- package/docs/OCT5_VERIFICATION.md +1 -1
- package/docs/simple-views.md +17 -0
- package/fixtures/burn-week-v1.json +1 -0
- package/package.json +3 -3
|
@@ -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 = exports.STATUS_TEXT = void 0;
|
|
3
|
+
exports.WEEK_TEXT = exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = exports.SIMPLE_TEXT = exports.STATUS_TEXT = void 0;
|
|
4
4
|
exports.whyLangOf = whyLangOf;
|
|
5
5
|
exports.detectWhyLang = detectWhyLang;
|
|
6
6
|
/**
|
|
@@ -17,6 +17,8 @@ exports.detectWhyLang = detectWhyLang;
|
|
|
17
17
|
const types_1 = require("./types");
|
|
18
18
|
var status_text_1 = require("./status-text");
|
|
19
19
|
Object.defineProperty(exports, "STATUS_TEXT", { enumerable: true, get: function () { return status_text_1.STATUS_TEXT; } });
|
|
20
|
+
var simple_text_1 = require("./simple-text");
|
|
21
|
+
Object.defineProperty(exports, "SIMPLE_TEXT", { enumerable: true, get: function () { return simple_text_1.SIMPLE_TEXT; } });
|
|
20
22
|
/**
|
|
21
23
|
* The language of a flag value or locale: the part before '_', '-', '.' or '@',
|
|
22
24
|
* in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
|
|
@@ -441,3 +443,82 @@ const calendarPt = {
|
|
|
441
443
|
},
|
|
442
444
|
};
|
|
443
445
|
exports.CALENDAR_TEXT = { en: calendarEn, es: calendarEs, pt: calendarPt };
|
|
446
|
+
// The required price caveat stays literal beside every dollar figure in every language.
|
|
447
|
+
const WEEK_PRICE = 'API list price, not a bill';
|
|
448
|
+
exports.WEEK_TEXT = {
|
|
449
|
+
en: {
|
|
450
|
+
labels: { history_resent: 'Re-sent history', reread_files: 'Re-read files', subagent_fanout: 'Sub-agent fan-out', wrong_model: 'Sub-agents on the main model', reloads_idle: 'Reloads after a pause', reloads_model_switch: 'Reloads after a model switch', reloads: 'Full reloads' },
|
|
451
|
+
fixes: {
|
|
452
|
+
history_resent: 'Run /compact at a natural break, or /clear between unrelated tasks.',
|
|
453
|
+
reread_files: 'Name the file and the lines Claude needs, so it reads less of each file again.',
|
|
454
|
+
subagent_fanout: 'Give related work to one sub-agent instead of several.',
|
|
455
|
+
wrong_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.",
|
|
456
|
+
reloads_idle: 'Run /compact before a break, so the reload after it is smaller.',
|
|
457
|
+
reloads_model_switch: 'Pick your model when you start, or switch at a break, right after /compact.',
|
|
458
|
+
reloads: 'See the cause of each reload: npx agentguard-burn rewrites',
|
|
459
|
+
},
|
|
460
|
+
title: (start, end) => `AgentGuard week: Mon ${start} to Sun ${end} (UTC)`,
|
|
461
|
+
summary: (tokens, usd) => `${tokens} tokens${usd === null ? '' : ` | ${usd} at ${WEEK_PRICE}`}`,
|
|
462
|
+
spent: usd => `${usd} spent on waste causes (${WEEK_PRICE}).`,
|
|
463
|
+
shares: (useful, waste, unattributed, priced) => `Useful work ${useful} of ${priced ? 'spend' : 'tokens'} | Waste causes ${waste} | Not attributed ${unattributed}`,
|
|
464
|
+
row: (label, share, usd, tokens) => `${label}: ${share} | ${usd === null ? `${tokens} tokens` : `${usd} (${WEEK_PRICE})`}`,
|
|
465
|
+
wrongModel: (tokens, delta) => `Sub-agents on the main model: ${tokens} tokens. On Haiku 5.5 they would have cost ${delta} less (${WEEK_PRICE}).`,
|
|
466
|
+
next: (label, fix) => `Top waste cause: ${label}. Next: ${fix}`,
|
|
467
|
+
noCause: 'No waste cause stands out this week.',
|
|
468
|
+
tokenBasis: 'Shares are by tokens this week because a model has no list price.',
|
|
469
|
+
privacy: 'Nothing here leaves this computer unless you turn on weekly sharing in the AgentGuard plugin.',
|
|
470
|
+
incomplete: 'This UTC week is still in progress and is not saved for sharing.',
|
|
471
|
+
excluded: (forks, undated) => `Not counted: ${forks} forked histories with an unknown boundary; ${undated} tokens without a time.`,
|
|
472
|
+
saveFailed: 'Burn could not save this week for sharing.',
|
|
473
|
+
},
|
|
474
|
+
es: {
|
|
475
|
+
labels: { history_resent: 'Historial reenviado', reread_files: 'Archivos releídos', subagent_fanout: 'Uso de varios subagentes', wrong_model: 'Subagentes con el modelo principal', reloads_idle: 'Recargas después de una pausa', reloads_model_switch: 'Recargas después de cambiar de modelo', reloads: 'Recargas completas' },
|
|
476
|
+
fixes: {
|
|
477
|
+
history_resent: 'Ejecuta /compact en una pausa natural, o /clear entre tareas que no estén relacionadas.',
|
|
478
|
+
reread_files: 'Indica el archivo y las líneas que Claude necesita, para que vuelva a leer menos de cada archivo.',
|
|
479
|
+
subagent_fanout: 'Dale el trabajo relacionado a un solo subagente en vez de varios.',
|
|
480
|
+
wrong_model: 'Para buscar y leer registros, un modelo más pequeño sirve: configura CLAUDE_CODE_SUBAGENT_MODEL=haiku, o pon model: haiku en la definición del subagente.',
|
|
481
|
+
reloads_idle: 'Ejecuta /compact antes de una pausa, para que la siguiente recarga sea más pequeña.',
|
|
482
|
+
reloads_model_switch: 'Elige el modelo al empezar, o cámbialo en una pausa, justo después de /compact.',
|
|
483
|
+
reloads: 'Ve la causa de cada recarga: npx agentguard-burn rewrites',
|
|
484
|
+
},
|
|
485
|
+
title: (start, end) => `AgentGuard week: lun ${start} a dom ${end} (UTC)`,
|
|
486
|
+
summary: (tokens, usd) => `${tokens} tokens${usd === null ? '' : ` | ${usd} (${WEEK_PRICE})`}`,
|
|
487
|
+
spent: usd => `${usd} destinados a causas de desperdicio (${WEEK_PRICE}).`,
|
|
488
|
+
shares: (useful, waste, unattributed, priced) => `Trabajo útil ${useful} de ${priced ? 'gasto' : 'tokens'} | Causas de desperdicio ${waste} | Sin atribuir ${unattributed}`,
|
|
489
|
+
row: (label, share, usd, tokens) => `${label}: ${share} | ${usd === null ? `${tokens} tokens` : `${usd} (${WEEK_PRICE})`}`,
|
|
490
|
+
wrongModel: (tokens, delta) => `Subagentes con el modelo principal: ${tokens} tokens. Con Haiku 5.5 habrían costado ${delta} menos (${WEEK_PRICE}).`,
|
|
491
|
+
next: (label, fix) => `Principal causa de desperdicio: ${label}. Próximo paso: ${fix}`,
|
|
492
|
+
noCause: 'Ninguna causa de desperdicio destaca esta semana.',
|
|
493
|
+
tokenBasis: 'Las proporciones se calculan por tokens esta semana porque un modelo no tiene precio de lista.',
|
|
494
|
+
privacy: 'Nada de esto sale de esta computadora a menos que actives el envío semanal en el plugin de AgentGuard.',
|
|
495
|
+
incomplete: 'Esta semana UTC sigue en curso y no se guarda para compartir.',
|
|
496
|
+
excluded: (forks, undated) => `Sin contar: ${forks} historiales bifurcados sin un punto de corte conocido; ${undated} tokens sin fecha.`,
|
|
497
|
+
saveFailed: 'Burn no pudo guardar esta semana para compartir.',
|
|
498
|
+
},
|
|
499
|
+
pt: {
|
|
500
|
+
labels: { history_resent: 'Histórico reenviado', reread_files: 'Arquivos relidos', subagent_fanout: 'Uso de vários subagentes', wrong_model: 'Subagentes no modelo principal', reloads_idle: 'Recargas após uma pausa', reloads_model_switch: 'Recargas após trocar de modelo', reloads: 'Recargas completas' },
|
|
501
|
+
fixes: {
|
|
502
|
+
history_resent: 'Execute /compact em uma pausa natural, ou /clear entre tarefas sem relação.',
|
|
503
|
+
reread_files: 'Indique o arquivo e as linhas de que o Claude precisa, para que ele releia menos de cada arquivo.',
|
|
504
|
+
subagent_fanout: 'Dê o trabalho relacionado a um só subagente em vez de vários.',
|
|
505
|
+
wrong_model: 'Para buscar e ler registros, um modelo menor resolve: configure CLAUDE_CODE_SUBAGENT_MODEL=haiku, ou coloque model: haiku na definição do subagente.',
|
|
506
|
+
reloads_idle: 'Execute /compact antes de uma pausa, para que a próxima recarga seja menor.',
|
|
507
|
+
reloads_model_switch: 'Escolha o modelo ao começar, ou troque em uma pausa, logo após /compact.',
|
|
508
|
+
reloads: 'Veja a causa de cada recarga: npx agentguard-burn rewrites',
|
|
509
|
+
},
|
|
510
|
+
title: (start, end) => `AgentGuard week: seg ${start} a dom ${end} (UTC)`,
|
|
511
|
+
summary: (tokens, usd) => `${tokens} tokens${usd === null ? '' : ` | ${usd} (${WEEK_PRICE})`}`,
|
|
512
|
+
spent: usd => `${usd} gastos em causas de desperdício (${WEEK_PRICE}).`,
|
|
513
|
+
shares: (useful, waste, unattributed, priced) => `Trabalho útil ${useful} de ${priced ? 'gasto' : 'tokens'} | Causas de desperdício ${waste} | Sem atribuição ${unattributed}`,
|
|
514
|
+
row: (label, share, usd, tokens) => `${label}: ${share} | ${usd === null ? `${tokens} tokens` : `${usd} (${WEEK_PRICE})`}`,
|
|
515
|
+
wrongModel: (tokens, delta) => `Subagentes no modelo principal: ${tokens} tokens. No Haiku 5.5 teriam custado ${delta} menos (${WEEK_PRICE}).`,
|
|
516
|
+
next: (label, fix) => `Principal causa de desperdício: ${label}. Próximo passo: ${fix}`,
|
|
517
|
+
noCause: 'Nenhuma causa de desperdício se destaca nesta semana.',
|
|
518
|
+
tokenBasis: 'As proporções usam tokens nesta semana porque um modelo não tem preço de tabela.',
|
|
519
|
+
privacy: 'Nada daqui sai deste computador a menos que você ative o compartilhamento semanal no plugin do AgentGuard.',
|
|
520
|
+
incomplete: 'Esta semana UTC ainda está em andamento e não é salva para compartilhar.',
|
|
521
|
+
excluded: (forks, undated) => `Fora da conta: ${forks} históricos bifurcados sem um limite conhecido; ${undated} tokens sem data.`,
|
|
522
|
+
saveFailed: 'O Burn não conseguiu salvar esta semana para compartilhar.',
|
|
523
|
+
},
|
|
524
|
+
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DollarRange, type PricingTable, type TurnPrice } from './pricing';
|
|
2
|
-
import { type AttributionSummary, type CommitsStatus, type InsightBucket, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence, type SessionCommits } from './types';
|
|
2
|
+
import { type AttributionSummary, type BucketAttribution, type CommitsStatus, type InsightBucket, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence, type SessionCommits } from './types';
|
|
3
3
|
import { type WhyLang } from './i18n';
|
|
4
4
|
export declare function sumPrices(values: Array<DollarRange | null>): DollarRange | null;
|
|
5
5
|
export declare function totalTokens(turn: InsightTurn): number;
|
|
@@ -19,6 +19,7 @@ export interface SessionFigures {
|
|
|
19
19
|
totalUsd: DollarRange | null;
|
|
20
20
|
}
|
|
21
21
|
export declare function sessionFigures(transcript: InsightTranscript, rates?: PricingTable): SessionFigures;
|
|
22
|
+
export declare function bucketPrice(turn: InsightTurn, allocation: BucketAttribution, rates: PricingTable): DollarRange | null;
|
|
22
23
|
/** Left-aligned columns two spaces apart; widths follow the widest cell, so translated labels widen their column. */
|
|
23
24
|
export declare function table(headers: string[], rows: string[][]): string;
|
|
24
25
|
/** Token counts in en-US digits in every language. */
|
|
@@ -28,6 +29,8 @@ export declare const share: (tokens: number, total: number) => string;
|
|
|
28
29
|
export declare const WHY_TIP_HIDE_LINE: string;
|
|
29
30
|
/** A model id as people say it: claude-opus-5-5 is Opus 5.5 and claude-haiku-4-5-20251001 is Haiku 4.5. Any other id prints as it is. */
|
|
30
31
|
export declare function modelLabel(model: string): string;
|
|
32
|
+
/** The model with the most output tokens, then the most responses; null when no response names one. */
|
|
33
|
+
export declare function dominantModel(turns: InsightTurn[]): string | null;
|
|
31
34
|
/** What the coach tip is chosen from: each cause's measured size in this session, and the facts its action line quotes. */
|
|
32
35
|
export interface WhyTipInput {
|
|
33
36
|
/** The table's session total, children included. */
|
|
@@ -63,6 +66,8 @@ export interface WhyTipInput {
|
|
|
63
66
|
medianPerCall: number;
|
|
64
67
|
};
|
|
65
68
|
}
|
|
69
|
+
/** A main model with a smaller Claude model below it, the one CLAUDE_CODE_SUBAGENT_MODEL=haiku names. */
|
|
70
|
+
export declare const HAS_SMALLER_MODEL: RegExp;
|
|
66
71
|
/**
|
|
67
72
|
* Where the tip is shown: `why` itself, or the AgentGuard plugin. The fan-out
|
|
68
73
|
* tip points `why` readers to the plugin; someone the plugin shows it to already
|
|
@@ -82,7 +87,14 @@ export type TipContext = 'why' | 'plugin';
|
|
|
82
87
|
* the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
|
|
83
88
|
* In the plugin context only the share tip's second sentence changes.
|
|
84
89
|
*/
|
|
90
|
+
export declare function whyTipCause(input: WhyTipInput): 'subagents' | 'reloads' | 'conversation' | 'setup' | null;
|
|
85
91
|
export declare function whyTip(input: WhyTipInput, lang?: WhyLang, context?: TipContext): string | null;
|
|
92
|
+
/** Cache-write dollars and observations by rewrite cause, also used by the weekly view. */
|
|
93
|
+
export declare function rewriteCausePrices(turns: InsightTurn[], rewrites: RewriteEvidence[], rates?: PricingTable): Map<RewriteCause, {
|
|
94
|
+
usd: number;
|
|
95
|
+
count: number;
|
|
96
|
+
longestIdleMs: number | null;
|
|
97
|
+
}>;
|
|
86
98
|
/**
|
|
87
99
|
* What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
|
|
88
100
|
* rows are the table's own. The setup and the re-read conversation split each
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.PROOF_MINIMUM = exports.PROOF_WINDOW = exports.WHY_TIP_HIDE_LINE = exports.share = exports.count = void 0;
|
|
3
|
+
exports.PROOF_MINIMUM = exports.PROOF_WINDOW = exports.HAS_SMALLER_MODEL = exports.WHY_TIP_HIDE_LINE = exports.share = exports.count = void 0;
|
|
4
4
|
exports.sumPrices = sumPrices;
|
|
5
5
|
exports.totalTokens = totalTokens;
|
|
6
6
|
exports.sessionFigures = sessionFigures;
|
|
7
|
+
exports.bucketPrice = bucketPrice;
|
|
7
8
|
exports.table = table;
|
|
8
9
|
exports.modelLabel = modelLabel;
|
|
10
|
+
exports.dominantModel = dominantModel;
|
|
11
|
+
exports.whyTipCause = whyTipCause;
|
|
9
12
|
exports.whyTip = whyTip;
|
|
13
|
+
exports.rewriteCausePrices = rewriteCausePrices;
|
|
10
14
|
exports.whyTipInput = whyTipInput;
|
|
11
15
|
exports.whyTipLine = whyTipLine;
|
|
12
16
|
exports.unfinishedSubagents = unfinishedSubagents;
|
|
@@ -91,7 +95,7 @@ function dominantModel(turns) {
|
|
|
91
95
|
return [...byModel].sort(([a, x], [b, y]) => y.output - x.output || y.responses - x.responses || (a < b ? -1 : a > b ? 1 : 0))[0]?.[0] ?? null;
|
|
92
96
|
}
|
|
93
97
|
/** A main model with a smaller Claude model below it, the one CLAUDE_CODE_SUBAGENT_MODEL=haiku names. */
|
|
94
|
-
|
|
98
|
+
exports.HAS_SMALLER_MODEL = /^claude-(?:opus|fable|sonnet)-/;
|
|
95
99
|
/**
|
|
96
100
|
* The coach: one next step, for the largest cause that stands out in this
|
|
97
101
|
* session; null when none does, never a generic line. A cause stands out at the
|
|
@@ -105,8 +109,8 @@ const HAS_SMALLER_MODEL = /^claude-(?:opus|fable|sonnet)-/;
|
|
|
105
109
|
* the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
|
|
106
110
|
* In the plugin context only the share tip's second sentence changes.
|
|
107
111
|
*/
|
|
108
|
-
function
|
|
109
|
-
const { totalTokens, totalUsd } = input
|
|
112
|
+
function whyTipCause(input) {
|
|
113
|
+
const { totalTokens, totalUsd } = input;
|
|
110
114
|
const priced = totalUsd !== null && midpoint(totalUsd) > 0;
|
|
111
115
|
const tokenShare = (tokens) => totalTokens > 0 ? tokens / totalTokens : 0;
|
|
112
116
|
const { subagents, reloads, conversation, setup } = input;
|
|
@@ -122,10 +126,14 @@ function whyTip(input, lang = 'en', context = 'why') {
|
|
|
122
126
|
if (size !== null && (largest === null || size > largest.size))
|
|
123
127
|
largest = { cause, size };
|
|
124
128
|
}
|
|
125
|
-
|
|
129
|
+
return largest?.cause ?? null;
|
|
130
|
+
}
|
|
131
|
+
function whyTip(input, lang = 'en', context = 'why') {
|
|
132
|
+
const { totalTokens, totalUsd } = input, text = i18n_1.WHY_TEXT[lang];
|
|
133
|
+
switch (whyTipCause(input)) {
|
|
126
134
|
case 'subagents': {
|
|
127
135
|
const { mainModel, onMainModel = 0, onMainModelShare = 0 } = input.subagents;
|
|
128
|
-
return mainModel && onMainModel > 0 && onMainModelShare >= 0.5 && HAS_SMALLER_MODEL.test(mainModel)
|
|
136
|
+
return mainModel && onMainModel > 0 && onMainModelShare >= 0.5 && exports.HAS_SMALLER_MODEL.test(mainModel)
|
|
129
137
|
? text.tipSubagentModel(onMainModel, modelLabel(mainModel))
|
|
130
138
|
: (context === 'plugin' ? text.tipFanoutPlugin : text.tipFanout)((0, exports.share)(input.subagents.tokens, totalTokens));
|
|
131
139
|
}
|
|
@@ -142,6 +150,23 @@ function whyTip(input, lang = 'en', context = 'why') {
|
|
|
142
150
|
default: return null;
|
|
143
151
|
}
|
|
144
152
|
}
|
|
153
|
+
/** Cache-write dollars and observations by rewrite cause, also used by the weekly view. */
|
|
154
|
+
function rewriteCausePrices(turns, rewrites, rates = {}) {
|
|
155
|
+
// The rewrite cause with the largest cache-write list price, then the most rewrites, then precedence.
|
|
156
|
+
const byId = new Map(turns.map(turn => [turn.id, turn]));
|
|
157
|
+
const causes = new Map();
|
|
158
|
+
for (const rewrite of rewrites) {
|
|
159
|
+
const turn = byId.get(rewrite.turnId);
|
|
160
|
+
const price = turn ? (0, pricing_1.priceTurn)({ ...turn, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 }, rates).usd : null;
|
|
161
|
+
const row = causes.get(rewrite.cause) ?? { usd: 0, count: 0, longestIdleMs: null };
|
|
162
|
+
row.usd += price ? midpoint(price) : 0;
|
|
163
|
+
row.count++;
|
|
164
|
+
if (rewrite.idleMs !== undefined)
|
|
165
|
+
row.longestIdleMs = Math.max(row.longestIdleMs ?? 0, rewrite.idleMs);
|
|
166
|
+
causes.set(rewrite.cause, row);
|
|
167
|
+
}
|
|
168
|
+
return causes;
|
|
169
|
+
}
|
|
145
170
|
/**
|
|
146
171
|
* What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
|
|
147
172
|
* rows are the table's own. The setup and the re-read conversation split each
|
|
@@ -176,19 +201,7 @@ function whyTipInput(figures, rates = {}, bucketUsd) {
|
|
|
176
201
|
onMainTokens += tokens;
|
|
177
202
|
}
|
|
178
203
|
}
|
|
179
|
-
|
|
180
|
-
const byId = new Map(turns.map(turn => [turn.id, turn]));
|
|
181
|
-
const causes = new Map();
|
|
182
|
-
for (const rewrite of attribution.rewrites) {
|
|
183
|
-
const turn = byId.get(rewrite.turnId);
|
|
184
|
-
const price = turn ? (0, pricing_1.priceTurn)({ ...turn, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 }, rates).usd : null;
|
|
185
|
-
const row = causes.get(rewrite.cause) ?? { usd: 0, count: 0, longestIdleMs: null };
|
|
186
|
-
row.usd += price ? midpoint(price) : 0;
|
|
187
|
-
row.count++;
|
|
188
|
-
if (rewrite.idleMs !== undefined)
|
|
189
|
-
row.longestIdleMs = Math.max(row.longestIdleMs ?? 0, rewrite.idleMs);
|
|
190
|
-
causes.set(rewrite.cause, row);
|
|
191
|
-
}
|
|
204
|
+
const causes = rewriteCausePrices(turns, attribution.rewrites, rates);
|
|
192
205
|
const [cause, top] = [...causes].sort(([a, x], [b, y]) => y.usd - x.usd || y.count - x.count || types_1.REWRITE_CAUSES.indexOf(a) - types_1.REWRITE_CAUSES.indexOf(b))[0] ?? [null, null];
|
|
193
206
|
// Setup and re-read conversation, split at the first call's context.
|
|
194
207
|
const rewritten = new Set(attribution.rewrites.map(rewrite => rewrite.turnId));
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { UsageWindow } from './pace';
|
|
2
|
+
import { type TranscriptLocation } from './sessions';
|
|
3
|
+
export type BillingKind = 'subscription' | 'metered' | 'unknown';
|
|
4
|
+
export interface SimpleUsage {
|
|
5
|
+
billing: BillingKind;
|
|
6
|
+
now: number;
|
|
7
|
+
windows: UsageWindow[];
|
|
8
|
+
spentTodayUsd: number | null;
|
|
9
|
+
paceUsdPerHour: number | null;
|
|
10
|
+
}
|
|
11
|
+
/** Recognize explicit host metadata, never credential contents or a model-name guess. */
|
|
12
|
+
export declare function billingKind(value: unknown): BillingKind;
|
|
13
|
+
/** Only allowlisted numbers and the billing category are persisted, under a path digest. */
|
|
14
|
+
export declare function recordSimpleHost(home: string, file: string, payload: unknown, now?: number): void;
|
|
15
|
+
export declare function readSimpleUsage(home: string, options?: {
|
|
16
|
+
location?: TranscriptLocation;
|
|
17
|
+
payload?: unknown;
|
|
18
|
+
now?: number;
|
|
19
|
+
locations?: TranscriptLocation[];
|
|
20
|
+
}): SimpleUsage;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.billingKind = billingKind;
|
|
4
|
+
exports.recordSimpleHost = recordSimpleHost;
|
|
5
|
+
exports.readSimpleUsage = readSimpleUsage;
|
|
6
|
+
/** Host-reported amounts only. API list-price calculations never enter this view. */
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_path_1 = require("node:path");
|
|
10
|
+
const history_1 = require("./history");
|
|
11
|
+
const live_1 = require("./live");
|
|
12
|
+
const sessions_1 = require("./sessions");
|
|
13
|
+
const transcript_1 = require("./transcript");
|
|
14
|
+
const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(value).digest('hex');
|
|
15
|
+
const amount = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
16
|
+
const observationPath = (home, file) => (0, node_path_1.join)(home, 'display-observations', hash(file) + '.json');
|
|
17
|
+
/** Recognize explicit host metadata, never credential contents or a model-name guess. */
|
|
18
|
+
function billingKind(value) {
|
|
19
|
+
const raw = (0, history_1.object)(value), billing = (0, history_1.object)(raw.billing), limits = (0, history_1.object)(raw.rate_limits);
|
|
20
|
+
const values = [billing.type, raw.billing_type, raw.billingType, raw.auth_type, raw.plan_type, limits.plan_type];
|
|
21
|
+
if (values.some(v => ['subscription', 'stripe_subscription', 'pro', 'max', 'team', 'enterprise', 'plus', 'business'].includes(String(v))))
|
|
22
|
+
return 'subscription';
|
|
23
|
+
if (values.some(v => ['api_key', 'api-key', 'usage_credits', 'usage-credit', 'pay_as_you_go', 'prepaid', 'metered'].includes(String(v))))
|
|
24
|
+
return 'metered';
|
|
25
|
+
// Claude's named plan windows are positive evidence. Absence proves nothing.
|
|
26
|
+
if ((0, live_1.hostWindows)(limits, 'claude-statusline', Date.now()).length)
|
|
27
|
+
return 'subscription';
|
|
28
|
+
return 'unknown';
|
|
29
|
+
}
|
|
30
|
+
function readObservation(home, file) {
|
|
31
|
+
try {
|
|
32
|
+
const raw = (0, history_1.object)(JSON.parse((0, node_fs_1.readFileSync)(observationPath(home, file), 'utf8')));
|
|
33
|
+
if (raw.schema === 1)
|
|
34
|
+
return { schema: 1, billing: raw.billing === 'subscription' || raw.billing === 'metered' ? raw.billing : 'unknown',
|
|
35
|
+
costs: (Array.isArray(raw.costs) ? raw.costs : []).flatMap(value => {
|
|
36
|
+
const row = (0, history_1.object)(value);
|
|
37
|
+
return amount(row.at) && amount(row.usd) ? [{ at: row.at, usd: row.usd }] : [];
|
|
38
|
+
}) };
|
|
39
|
+
}
|
|
40
|
+
catch { /* No observation yet. */ }
|
|
41
|
+
return { schema: 1, billing: 'unknown', costs: [] };
|
|
42
|
+
}
|
|
43
|
+
/** Only allowlisted numbers and the billing category are persisted, under a path digest. */
|
|
44
|
+
function recordSimpleHost(home, file, payload, now = Date.now()) {
|
|
45
|
+
const billing = billingKind(payload), cost = (0, history_1.object)((0, history_1.object)(payload).cost).total_cost_usd;
|
|
46
|
+
if (billing === 'unknown' && !amount(cost))
|
|
47
|
+
return;
|
|
48
|
+
try {
|
|
49
|
+
const previous = readObservation(home, file);
|
|
50
|
+
const costs = previous.costs.filter(row => row.at <= now && row.at >= now - 86_400_000);
|
|
51
|
+
if (amount(cost))
|
|
52
|
+
costs.push({ at: now, usd: cost });
|
|
53
|
+
const value = { schema: 1, billing: billing === 'unknown' ? previous.billing : billing, costs: costs.slice(-2048) };
|
|
54
|
+
const path = observationPath(home, file), temporary = path + '.' + (0, node_crypto_1.randomUUID)() + '.tmp';
|
|
55
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.join)(home, 'display-observations'), { recursive: true, mode: 0o700 });
|
|
56
|
+
(0, node_fs_1.writeFileSync)(temporary, JSON.stringify(value), { mode: 0o600 });
|
|
57
|
+
(0, node_fs_1.renameSync)(temporary, path);
|
|
58
|
+
}
|
|
59
|
+
catch { /* Read-only homes still get an honest unavailable display. */ }
|
|
60
|
+
}
|
|
61
|
+
// A live panel may refresh twice a second. Unchanged transcripts are scanned once.
|
|
62
|
+
// Only numerical metadata survives a scan, never messages or tool arguments.
|
|
63
|
+
const metadataCache = new Map();
|
|
64
|
+
function metadata(location) {
|
|
65
|
+
const info = (0, node_fs_1.statSync)(location.path), signature = `${info.ino}:${info.size}:${info.mtimeMs}`;
|
|
66
|
+
const cached = metadataCache.get(location.path);
|
|
67
|
+
if (cached?.signature === signature)
|
|
68
|
+
return cached.value;
|
|
69
|
+
const value = { billing: 'unknown', windows: [], charges: [], firstAt: null, incomplete: false };
|
|
70
|
+
const kinds = new Set(), charges = new Map(), scan = { malformed: 0 };
|
|
71
|
+
let state;
|
|
72
|
+
let chunk = '', line = 0;
|
|
73
|
+
let quotaRows = [];
|
|
74
|
+
const flushCodex = () => {
|
|
75
|
+
if (!chunk)
|
|
76
|
+
return;
|
|
77
|
+
const parsed = (0, transcript_1.parseInsightTranscript)(chunk, { host: 'codex', sessionId: location.sessionId, state });
|
|
78
|
+
state = parsed.state;
|
|
79
|
+
const accepted = new Set(parsed.acceptedQuotaLineNumbers);
|
|
80
|
+
for (const row of quotaRows)
|
|
81
|
+
if (accepted.has(row.line))
|
|
82
|
+
value.windows.push(...(0, live_1.hostWindows)(row.limits, 'codex-transcript', row.at));
|
|
83
|
+
for (const turn of parsed.updatedTurns)
|
|
84
|
+
charges.set(turn.id, { id: turn.id, at: turn.at ?? null, usd: null });
|
|
85
|
+
chunk = '';
|
|
86
|
+
line = 0;
|
|
87
|
+
quotaRows = [];
|
|
88
|
+
};
|
|
89
|
+
for (const raw of (0, history_1.jsonRows)(location.path, scan)) {
|
|
90
|
+
const payload = (0, history_1.object)(raw.payload), message = (0, history_1.object)(raw.message);
|
|
91
|
+
const at = (0, history_1.timestamp)(raw.timestamp ?? payload.timestamp);
|
|
92
|
+
if (at !== null)
|
|
93
|
+
value.firstAt = Math.min(value.firstAt ?? at, at);
|
|
94
|
+
const kind = billingKind(raw.type === 'session_meta' || location.host === 'codex' ? payload : raw);
|
|
95
|
+
if (kind !== 'unknown')
|
|
96
|
+
kinds.add(kind);
|
|
97
|
+
if (location.host === 'codex') {
|
|
98
|
+
if (at !== null && payload.rate_limits)
|
|
99
|
+
quotaRows.push({ line, at, limits: payload.rate_limits });
|
|
100
|
+
chunk += JSON.stringify(raw) + '\n';
|
|
101
|
+
line++;
|
|
102
|
+
if (chunk.length >= 1024 * 1024)
|
|
103
|
+
flushCodex();
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (at !== null && ['system', 'rate_limit_event', 'status'].includes(String(raw.type)))
|
|
107
|
+
value.windows.push(...(0, live_1.hostWindows)(raw.rate_limits, 'claude-statusline', at));
|
|
108
|
+
if (raw.type !== 'assistant' || raw.isApiErrorMessage === true)
|
|
109
|
+
continue;
|
|
110
|
+
const id = typeof message.id === 'string' ? (0, transcript_1.providerResponseIdentity)(location.host, message.id) : typeof raw.uuid === 'string' ? hash(location.path + raw.uuid) : null;
|
|
111
|
+
if (!id) {
|
|
112
|
+
value.incomplete = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const usd = amount(raw.costUSD) ? raw.costUSD : null, previous = charges.get(id);
|
|
116
|
+
charges.set(id, { id, at: previous?.at !== null && previous?.at !== undefined ? Math.min(previous.at, at ?? previous.at) : at,
|
|
117
|
+
usd: previous?.usd !== null && previous?.usd !== undefined ? Math.max(previous.usd, usd ?? previous.usd) : usd });
|
|
118
|
+
}
|
|
119
|
+
flushCodex();
|
|
120
|
+
value.billing = kinds.size === 1 ? [...kinds][0] : 'unknown';
|
|
121
|
+
value.charges = [...charges.values()];
|
|
122
|
+
value.incomplete ||= scan.malformed > 0 || Boolean(state?.forkHistoryBoundaryUnknown) || kinds.size > 1;
|
|
123
|
+
// Bound long-lived panels without writing a second transcript index.
|
|
124
|
+
if (metadataCache.size >= 128)
|
|
125
|
+
metadataCache.delete(metadataCache.keys().next().value);
|
|
126
|
+
metadataCache.set(location.path, { signature, value });
|
|
127
|
+
return value;
|
|
128
|
+
}
|
|
129
|
+
function readSimpleUsage(home, options = {}) {
|
|
130
|
+
const now = options.now ?? Date.now();
|
|
131
|
+
const result = { billing: billingKind(options.payload), now,
|
|
132
|
+
windows: (0, live_1.hostWindows)((0, history_1.object)(options.payload).rate_limits, 'claude-statusline', now), spentTodayUsd: null, paceUsdPerHour: null };
|
|
133
|
+
let location = options.location;
|
|
134
|
+
try {
|
|
135
|
+
location ??= (0, sessions_1.selectInsightTranscript)(undefined, options.locations);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return result;
|
|
139
|
+
}
|
|
140
|
+
let selected;
|
|
141
|
+
try {
|
|
142
|
+
selected = metadata(location);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
const observation = readObservation(home, location.path), currentKind = billingKind(options.payload);
|
|
148
|
+
result.billing = currentKind !== 'unknown' ? currentKind : selected.billing !== 'unknown' ? selected.billing : observation.billing;
|
|
149
|
+
result.windows = [...selected.windows, ...(0, live_1.hostWindows)((0, history_1.object)(options.payload).rate_limits, 'claude-statusline', now)];
|
|
150
|
+
try {
|
|
151
|
+
const pace = JSON.parse((0, node_fs_1.readFileSync)((0, live_1.pacePath)(home, location.sessionId), 'utf8'));
|
|
152
|
+
if (pace?.schema === 1 && pace.cursor?.pathDigest === hash(location.path) && !pace.parser?.forkHistoryBoundaryUnknown && Array.isArray(pace.windows))
|
|
153
|
+
result.windows.push(...pace.windows);
|
|
154
|
+
}
|
|
155
|
+
catch { /* A why report can precede the first statusline observation. */ }
|
|
156
|
+
result.windows = result.windows.filter(w => amount(w.observedAt) && w.observedAt <= now && w.observedAt >= now - 600_000 && amount(w.resetsAt) && w.resetsAt > now && amount(w.usedPercent) && w.usedPercent <= 100);
|
|
157
|
+
if (result.billing === 'unknown' && result.windows.some(w => w.source === 'claude-statusline'))
|
|
158
|
+
result.billing = 'subscription';
|
|
159
|
+
if (result.billing !== 'metered')
|
|
160
|
+
return result;
|
|
161
|
+
const today = new Date(now);
|
|
162
|
+
today.setHours(0, 0, 0, 0);
|
|
163
|
+
const start = today.getTime(), charges = new Map();
|
|
164
|
+
let cumulative = 0, cumulativePace = 0, paceKnown = true, covered = false;
|
|
165
|
+
const locations = options.locations ?? (0, sessions_1.discoverInsightTranscripts)();
|
|
166
|
+
const groups = [];
|
|
167
|
+
const firstObserved = new Map(), owners = new Map();
|
|
168
|
+
for (const item of [...new Map([location, ...locations].filter(l => l.host === location.host && !(0, sessions_1.isSessionSidecar)(l)).map(l => [l.path, l])).values()]) {
|
|
169
|
+
let data;
|
|
170
|
+
try {
|
|
171
|
+
data = metadata(item);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return result;
|
|
175
|
+
}
|
|
176
|
+
groups.push({ item, data });
|
|
177
|
+
for (const row of data.charges) {
|
|
178
|
+
owners.set(row.id, (owners.get(row.id) ?? 0) + 1);
|
|
179
|
+
if (row.at !== null)
|
|
180
|
+
firstObserved.set(row.id, Math.min(firstObserved.get(row.id) ?? row.at, row.at));
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
for (const { item, data } of groups) {
|
|
184
|
+
const host = readObservation(home, item.path);
|
|
185
|
+
const billing = item.path === location.path ? result.billing : data.billing === 'unknown' ? host.billing : data.billing;
|
|
186
|
+
if (billing === 'subscription')
|
|
187
|
+
continue;
|
|
188
|
+
// A copied response cannot become today's spending by acquiring a new timestamp.
|
|
189
|
+
const rows = data.charges.map(row => ({ ...row, at: firstObserved.get(row.id) ?? row.at })).filter(row => row.at === null || row.at >= start && row.at <= now);
|
|
190
|
+
if (!rows.length && !data.incomplete)
|
|
191
|
+
continue;
|
|
192
|
+
if (billing !== 'metered' || data.incomplete || rows.some(row => row.at === null))
|
|
193
|
+
return result;
|
|
194
|
+
if (rows.some(row => row.usd === null)) {
|
|
195
|
+
// A host's session total may include its helpers. Unknown overlap stays unknown.
|
|
196
|
+
if (rows.some(row => owners.get(row.id) > 1) || groups.some(group => group.item.path !== item.path
|
|
197
|
+
&& (group.item.path.startsWith(item.path.replace(/\.jsonl$/, '') + '/') || item.path.startsWith(group.item.path.replace(/\.jsonl$/, '') + '/'))))
|
|
198
|
+
return result;
|
|
199
|
+
// A cumulative host total covers today only when the recorded session starts today.
|
|
200
|
+
// Never prorate a lifetime cost across midnight, nor confuse it with a daily bill.
|
|
201
|
+
const samples = host.costs.filter(row => row.at >= start && row.at <= now).sort((a, b) => a.at - b.at);
|
|
202
|
+
const last = samples.at(-1);
|
|
203
|
+
if (!last || last.at < now - 60_000 || data.firstAt === null || data.firstAt < start)
|
|
204
|
+
return result;
|
|
205
|
+
cumulative += last.usd;
|
|
206
|
+
covered = true;
|
|
207
|
+
const before = samples.filter(row => row.at <= now - 600_000 && row.at >= now - 660_000).at(-1);
|
|
208
|
+
if (before && last.usd >= before.usd && last.at > before.at)
|
|
209
|
+
cumulativePace += (last.usd - before.usd) / ((last.at - before.at) / 60_000);
|
|
210
|
+
else
|
|
211
|
+
paceKnown = false;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
covered ||= rows.length > 0;
|
|
215
|
+
for (const row of rows) {
|
|
216
|
+
const previous = charges.get(row.id);
|
|
217
|
+
if (!previous || row.usd > previous.usd)
|
|
218
|
+
charges.set(row.id, row);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (!covered)
|
|
222
|
+
return result;
|
|
223
|
+
const values = [...charges.values()];
|
|
224
|
+
result.spentTodayUsd = cumulative + values.reduce((sum, row) => sum + row.usd, 0);
|
|
225
|
+
const perMinute = cumulativePace + values.filter(row => row.at > now - 600_000).reduce((sum, row) => sum + row.usd, 0) / 10;
|
|
226
|
+
// The recent pace per hour, never extrapolated to a day total: a short burst is not a forecast.
|
|
227
|
+
result.paceUsdPerHour = paceKnown ? perMinute * 60 : null;
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Canvas } from '../canvas';
|
|
2
|
+
import type { FrameOptions } from '../frames';
|
|
3
|
+
import { type WhyLang } from './i18n';
|
|
4
|
+
import type { SimpleUsage } from './simple-data';
|
|
5
|
+
import type { CompactReplayReport } from './compact-replay';
|
|
6
|
+
import type { PricingTable } from './pricing';
|
|
7
|
+
import type { InsightTranscript } from './types';
|
|
8
|
+
/** One action, from the very same cause and thresholds as the detailed report. */
|
|
9
|
+
export declare function simpleNextStep(transcript: InsightTranscript, rates?: PricingTable, lang?: WhyLang): string | null;
|
|
10
|
+
/** A replay saving describes recorded usage, never a change in plan-limit percentage. */
|
|
11
|
+
export declare function simpleReplayStep(report: CompactReplayReport, lang?: WhyLang, minimumPercent?: number): string | null;
|
|
12
|
+
export declare function simpleLines(usage: SimpleUsage, options?: {
|
|
13
|
+
lang?: WhyLang;
|
|
14
|
+
next?: string | null;
|
|
15
|
+
}): string[];
|
|
16
|
+
export declare function renderSimple(usage: SimpleUsage, options?: {
|
|
17
|
+
lang?: WhyLang;
|
|
18
|
+
next?: string | null;
|
|
19
|
+
line?: boolean;
|
|
20
|
+
title?: string;
|
|
21
|
+
}): string;
|
|
22
|
+
export declare function renderSimpleReplay(usage: SimpleUsage, report: CompactReplayReport, lang?: WhyLang, tips?: boolean): string;
|
|
23
|
+
export declare function renderSimplePanel(usage: SimpleUsage, options?: FrameOptions & {
|
|
24
|
+
lang?: WhyLang;
|
|
25
|
+
next?: string | null;
|
|
26
|
+
}): Canvas;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.simpleNextStep = simpleNextStep;
|
|
4
|
+
exports.simpleReplayStep = simpleReplayStep;
|
|
5
|
+
exports.simpleLines = simpleLines;
|
|
6
|
+
exports.renderSimple = renderSimple;
|
|
7
|
+
exports.renderSimpleReplay = renderSimpleReplay;
|
|
8
|
+
exports.renderSimplePanel = renderSimplePanel;
|
|
9
|
+
const canvas_1 = require("../canvas");
|
|
10
|
+
const i18n_1 = require("./i18n");
|
|
11
|
+
const pace_1 = require("./pace");
|
|
12
|
+
const render_1 = require("./render");
|
|
13
|
+
function duration(minutes) {
|
|
14
|
+
const n = Math.max(0, Math.ceil(minutes));
|
|
15
|
+
return (n >= 60 ? `${Math.floor(n / 60)}h ` : '') + `${n % 60}m`;
|
|
16
|
+
}
|
|
17
|
+
const planName = (window) => window.name === 'five_hour' || window.windowMinutes === 300 ? 'fiveHour'
|
|
18
|
+
: window.name === 'seven_day' || window.windowMinutes === 10080 ? 'weekly' : null;
|
|
19
|
+
/** One action, from the very same cause and thresholds as the detailed report. */
|
|
20
|
+
function simpleNextStep(transcript, rates = {}, lang = 'en') {
|
|
21
|
+
if (transcript.state.forkHistoryBoundaryUnknown)
|
|
22
|
+
return null;
|
|
23
|
+
const input = (0, render_1.whyTipInput)((0, render_1.sessionFigures)(transcript, rates), rates), cause = (0, render_1.whyTipCause)(input);
|
|
24
|
+
if (!cause)
|
|
25
|
+
return null;
|
|
26
|
+
const step = cause === 'reloads' && (input.reloads.cause === 'model_switch' || input.reloads.cause === 'idle_ttl_expired') ? input.reloads.cause : cause;
|
|
27
|
+
return i18n_1.SIMPLE_TEXT[lang].steps[step];
|
|
28
|
+
}
|
|
29
|
+
/** A replay saving describes recorded usage, never a change in plan-limit percentage. */
|
|
30
|
+
function simpleReplayStep(report, lang = 'en', minimumPercent = 0) {
|
|
31
|
+
if (!report.suggestion || report.backtest.unreliable || !report.backtest.complete)
|
|
32
|
+
return null;
|
|
33
|
+
const row = report.windows.find(row => row.window === report.suggestion.window);
|
|
34
|
+
const percent = -(row?.tokenChangePercent ?? 0);
|
|
35
|
+
if (percent <= 0 || percent < minimumPercent)
|
|
36
|
+
return null;
|
|
37
|
+
return i18n_1.SIMPLE_TEXT[lang].replay(report.suggestion.command, percent.toFixed(0), report.days);
|
|
38
|
+
}
|
|
39
|
+
function simpleLines(usage, options = {}) {
|
|
40
|
+
const words = i18n_1.SIMPLE_TEXT[options.lang ?? 'en'], lines = [];
|
|
41
|
+
if (usage.billing === 'metered') {
|
|
42
|
+
lines.push(`${words.today}: ${usage.spentTodayUsd === null ? words.dollarsUnavailable : '$' + usage.spentTodayUsd.toFixed(2)}`);
|
|
43
|
+
lines.push(`${words.pace}: ${usage.paceUsdPerHour === null ? words.dollarsUnavailable : '$' + usage.paceUsdPerHour.toFixed(2) + ' ' + words.perHour}`);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
for (const name of ['fiveHour', 'weekly']) {
|
|
47
|
+
const samples = usage.windows.filter(w => planName(w) === name && Number.isFinite(w.observedAt) && w.observedAt <= usage.now && w.observedAt >= usage.now - 600_000 && w.resetsAt > usage.now && w.usedPercent >= 0 && w.usedPercent <= 100);
|
|
48
|
+
const latest = samples.filter(w => w.observedAt >= usage.now - 60_000).sort((a, b) => b.observedAt - a.observedAt)[0];
|
|
49
|
+
if (!latest) {
|
|
50
|
+
lines.push(`${words[name]}: ${words.unavailable}`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const forecast = (0, pace_1.forecastLimit)(samples.filter(w => w.source === latest.source && w.pool === latest.pool && w.resetsAt === latest.resetsAt), usage.now);
|
|
54
|
+
lines.push(`${words[name]}: ${latest.usedPercent.toFixed(0)}% ${words.used}; ${words.reset} ${duration((latest.resetsAt - usage.now) / 60_000)}; `
|
|
55
|
+
+ (forecast.minutes === null ? words.paceUnavailable : `${duration(forecast.minutes)} ${words.left}`));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (options.next)
|
|
59
|
+
lines.push(`${words.next}: ${options.next}`);
|
|
60
|
+
return lines;
|
|
61
|
+
}
|
|
62
|
+
function renderSimple(usage, options = {}) {
|
|
63
|
+
const words = i18n_1.SIMPLE_TEXT[options.lang ?? 'en'];
|
|
64
|
+
const title = options.title ?? `AgentGuard | ${words[usage.billing === 'metered' ? 'metered' : usage.billing === 'subscription' ? 'subscription' : 'unknown']}`;
|
|
65
|
+
const lines = simpleLines(usage, options);
|
|
66
|
+
if (options.line)
|
|
67
|
+
return [title, ...lines].join(' | ');
|
|
68
|
+
return [title, ...lines, ...(usage.spentTodayUsd !== null && usage.billing === 'metered' ? [words.reported] : [])].join('\n');
|
|
69
|
+
}
|
|
70
|
+
function renderSimpleReplay(usage, report, lang = 'en', tips = true) {
|
|
71
|
+
const suggestion = simpleReplayStep(report, lang);
|
|
72
|
+
return renderSimple(usage, { lang, next: tips ? suggestion : null }) + '\n' + (suggestion ? i18n_1.SIMPLE_TEXT[lang].replayCaution : i18n_1.SIMPLE_TEXT[lang].replayUnavailable);
|
|
73
|
+
}
|
|
74
|
+
function renderSimplePanel(usage, options = {}) {
|
|
75
|
+
const words = i18n_1.SIMPLE_TEXT[options.lang ?? 'en'], canvas = new canvas_1.Canvas(options);
|
|
76
|
+
canvas.header('AGENTGUARD / BURN', options.recorded ? words.recorded : words.live);
|
|
77
|
+
const lines = renderSimple(usage, options).split('\n');
|
|
78
|
+
let y = 3;
|
|
79
|
+
for (const line of lines) {
|
|
80
|
+
let remaining = line;
|
|
81
|
+
while (remaining && y < canvas.height - 2) {
|
|
82
|
+
let end = canvas.width;
|
|
83
|
+
if (remaining.length > end && remaining.lastIndexOf(' ', end) > 0)
|
|
84
|
+
end = remaining.lastIndexOf(' ', end);
|
|
85
|
+
canvas.put(y++, 0, remaining.slice(0, end), 'white');
|
|
86
|
+
remaining = remaining.slice(end).trimStart();
|
|
87
|
+
}
|
|
88
|
+
y++;
|
|
89
|
+
}
|
|
90
|
+
canvas.footer('', words.controls);
|
|
91
|
+
return canvas;
|
|
92
|
+
}
|