@agentguard-run/burn 0.3.19 → 0.3.20
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 +22 -0
- package/README.md +61 -2
- package/dist/src/canvas.d.ts +7 -1
- package/dist/src/canvas.js +10 -1
- package/dist/src/cli.js +64 -4
- package/dist/src/frames.d.ts +10 -0
- package/dist/src/frames.js +5 -0
- package/dist/src/history/claude-transcript.d.ts +26 -1
- package/dist/src/history/claude-transcript.js +58 -2
- package/dist/src/hook/pre-tool-use.d.ts +5 -1
- package/dist/src/hook/pre-tool-use.js +35 -8
- package/dist/src/insights/calendar-render.d.ts +48 -0
- package/dist/src/insights/calendar-render.js +196 -0
- package/dist/src/insights/calendar.d.ts +138 -0
- package/dist/src/insights/calendar.js +431 -0
- package/dist/src/insights/i18n.d.ts +101 -6
- package/dist/src/insights/i18n.js +120 -7
- package/dist/src/insights/render.d.ts +70 -12
- package/dist/src/insights/render.js +190 -15
- package/dist/src/insights/transcript.d.ts +13 -2
- package/dist/src/insights/transcript.js +61 -6
- package/dist/src/insights/types.d.ts +14 -0
- package/dist/src/recording.js +5 -1
- package/dist/src/replay/render.d.ts +2 -0
- package/dist/src/replay/render.js +4 -0
- package/dist/src/stop-text.d.ts +11 -2
- package/dist/src/stop-text.js +23 -3
- package/dist/src/subagent-cost.d.ts +38 -0
- package/dist/src/subagent-cost.js +65 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.COMPARE_TEXT = exports.WHY_TEXT = void 0;
|
|
3
|
+
exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = void 0;
|
|
4
4
|
exports.whyLangOf = whyLangOf;
|
|
5
5
|
exports.detectWhyLang = detectWhyLang;
|
|
6
6
|
/**
|
|
@@ -30,6 +30,9 @@ function detectWhyLang(sources = {}) {
|
|
|
30
30
|
}
|
|
31
31
|
/** Spanish and Portuguese nouns agree with their count: 1 is singular, 0 and everything else plural. */
|
|
32
32
|
const plural = (n, one, other) => `${n} ${n === 1 ? one : other}`;
|
|
33
|
+
const times = (n) => n === 1 ? 'once' : `${n} times`;
|
|
34
|
+
const veces = (n) => n === 1 ? 'una vez' : `${n} veces`;
|
|
35
|
+
const vezes = (n) => n === 1 ? 'uma vez' : `${n} vezes`;
|
|
33
36
|
const en = {
|
|
34
37
|
labels: {
|
|
35
38
|
instruction_stack: 'Instruction stack + system', history_resent: 'History re-sent', reread_files: 'Re-read files',
|
|
@@ -64,9 +67,18 @@ const en = {
|
|
|
64
67
|
missingTtl: 'Cache TTL is missing for some writes; their dollars span the verified five-minute and one-hour rates.',
|
|
65
68
|
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.',
|
|
66
69
|
diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
|
|
67
|
-
tipFanout: share => `Next: sub-
|
|
70
|
+
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/try`,
|
|
68
71
|
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`,
|
|
69
|
-
|
|
72
|
+
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.`,
|
|
73
|
+
tipIdleReloads: (count, longest) => `Next: Claude had to reload the whole conversation ${times(count)} after a pause longer than its cache lasts (longest pause: ${longest}). Run /compact before a break, so the reload after it is smaller.`,
|
|
74
|
+
tipModelSwitch: count => `Next: switching models made Claude reload the whole conversation ${times(count)}. Pick your model when you start, or switch at a break, right after /compact.`,
|
|
75
|
+
tipConversation: tokens => `Next: Claude re-reads the conversation on every message, a median of ${tokens} tokens each time. Run /compact at a natural break, or /clear between unrelated tasks.`,
|
|
76
|
+
tipSetup: tokens => `Next: Claude reads ${tokens} tokens of setup before every message (CLAUDE.md, tools, MCP servers and your first message). Keep CLAUDE.md short and turn off MCP servers you are not using (/mcp).`,
|
|
77
|
+
proof: (event, when, after, before, messages, direction) => {
|
|
78
|
+
const what = event.kind === 'model' ? `the switch to ${event.model}` : { compact: '/compact', auto: 'automatic compaction', compaction: 'compaction', clear: '/clear' }[event.kind];
|
|
79
|
+
const change = direction === 'same' ? `the same as in the ${messages} messages before` : `${direction} from ${before} in the ${messages} messages before`;
|
|
80
|
+
return `Measured change: after ${what} on ${when.date} at ${when.time} UTC, Claude read a median of ${after} tokens per message, ${change}.`;
|
|
81
|
+
},
|
|
70
82
|
hide: 'Hide tips like this: npx agentguard-burn quiet on',
|
|
71
83
|
};
|
|
72
84
|
/** Latin American Spanish: tú forms and vocabulary that reads the same from Mexico and Panama to Argentina. */
|
|
@@ -104,9 +116,18 @@ const es = {
|
|
|
104
116
|
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.',
|
|
105
117
|
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.',
|
|
106
118
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
|
|
107
|
-
tipFanout: share => `Próximo paso:
|
|
119
|
+
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/try`,
|
|
108
120
|
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`,
|
|
109
|
-
|
|
121
|
+
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.`,
|
|
122
|
+
tipIdleReloads: (count, longest) => `Próximo paso: Claude tuvo que recargar toda la conversación ${veces(count)} después de una pausa más larga de lo que dura su caché (pausa más larga: ${longest}). Usa /compact antes de un descanso, así la recarga que viene después es más pequeña.`,
|
|
123
|
+
tipModelSwitch: count => `Próximo paso: cambiar de modelo hizo que Claude recargara toda la conversación ${veces(count)}. Elige tu modelo al empezar, o cambia en una pausa, justo después de /compact.`,
|
|
124
|
+
tipConversation: tokens => `Próximo paso: Claude vuelve a leer la conversación en cada mensaje, una mediana de ${tokens} tokens cada vez. Usa /compact en una pausa natural, o /clear entre tareas que no tienen relación.`,
|
|
125
|
+
tipSetup: tokens => `Próximo paso: Claude lee ${tokens} tokens de configuración antes de cada mensaje (CLAUDE.md, herramientas, servidores MCP y tu primer mensaje). Mantén CLAUDE.md corto y desactiva los servidores MCP que no uses (/mcp).`,
|
|
126
|
+
proof: (event, when, after, before, messages, direction) => {
|
|
127
|
+
const what = event.kind === 'model' ? `del cambio a ${event.model}` : { compact: 'de /compact', auto: 'de la compactación automática', compaction: 'de la compactación', clear: 'de /clear' }[event.kind];
|
|
128
|
+
const change = direction === 'same' ? `igual que en los ${messages} mensajes anteriores` : `${direction === 'down' ? 'por debajo' : 'por encima'} de los ${before} de los ${messages} mensajes anteriores`;
|
|
129
|
+
return `Cambio medido: después ${what} el ${when.date} a las ${when.time} UTC, Claude leyó una mediana de ${after} tokens por mensaje, ${change}.`;
|
|
130
|
+
},
|
|
110
131
|
hide: 'Para ocultar consejos como este: npx agentguard-burn quiet on',
|
|
111
132
|
};
|
|
112
133
|
/** Brazilian Portuguese: você forms. */
|
|
@@ -144,12 +165,26 @@ const pt = {
|
|
|
144
165
|
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.',
|
|
145
166
|
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.',
|
|
146
167
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
|
|
147
|
-
tipFanout: share => `Próximo passo:
|
|
168
|
+
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/try`,
|
|
148
169
|
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`,
|
|
149
|
-
|
|
170
|
+
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.`,
|
|
171
|
+
tipIdleReloads: (count, longest) => `Próximo passo: o Claude teve que recarregar a conversa inteira ${vezes(count)} depois de uma pausa mais longa que a duração do cache (pausa mais longa: ${longest}). Use /compact antes de um intervalo, assim a recarga depois dele fica menor.`,
|
|
172
|
+
tipModelSwitch: count => `Próximo passo: trocar de modelo fez o Claude recarregar a conversa inteira ${vezes(count)}. Escolha o modelo ao começar, ou troque em uma pausa, logo depois do /compact.`,
|
|
173
|
+
tipConversation: tokens => `Próximo passo: o Claude relê a conversa a cada mensagem, uma mediana de ${tokens} tokens por vez. Use /compact em uma pausa natural, ou /clear entre tarefas sem relação.`,
|
|
174
|
+
tipSetup: tokens => `Próximo passo: o Claude lê ${tokens} tokens de configuração antes de cada mensagem (CLAUDE.md, ferramentas, servidores MCP e sua primeira mensagem). Mantenha o CLAUDE.md curto e desative os servidores MCP que você não usa (/mcp).`,
|
|
175
|
+
proof: (event, when, after, before, messages, direction) => {
|
|
176
|
+
const what = event.kind === 'model' ? `da troca para o ${event.model}` : { compact: 'do /compact', auto: 'da compactação automática', compaction: 'da compactação', clear: 'do /clear' }[event.kind];
|
|
177
|
+
const change = direction === 'same' ? `a mesma das ${messages} mensagens anteriores` : `${direction === 'down' ? 'abaixo' : 'acima'} dos ${before} das ${messages} mensagens anteriores`;
|
|
178
|
+
return `Mudança medida: depois ${what} em ${when.date} às ${when.time} UTC, o Claude leu uma mediana de ${after} tokens por mensagem, ${change}.`;
|
|
179
|
+
},
|
|
150
180
|
hide: 'Para ocultar dicas como esta: npx agentguard-burn quiet on',
|
|
151
181
|
};
|
|
152
182
|
exports.WHY_TEXT = { en, es, pt };
|
|
183
|
+
exports.DECISION_TEXT = {
|
|
184
|
+
en: { finished: (count, tokens, usd) => `The ${count} sub-agents that finished in this session averaged ${tokens} tokens each${usd ? ` (${usd} at API prices, not a bill)` : ''}. This one could differ.` },
|
|
185
|
+
es: { finished: (count, tokens, usd) => `Los ${count} subagentes que terminaron en esta sesión promediaron ${tokens} tokens cada uno${usd ? ` (${usd} a precios de la API, no una factura)` : ''}. Este podría ser distinto.` },
|
|
186
|
+
pt: { finished: (count, tokens, usd) => `Os ${count} subagentes que terminaram nesta sessão usaram em média ${tokens} tokens cada${usd ? ` (${usd} a preços da API, não uma fatura)` : ''}. Este pode ser diferente.` },
|
|
187
|
+
};
|
|
153
188
|
const TWO_IDS = 'agentguard-burn compare SESSION_A SESSION_B';
|
|
154
189
|
const compareEn = {
|
|
155
190
|
title: 'AgentGuard compare: B against A',
|
|
@@ -224,3 +259,81 @@ const comparePt = {
|
|
|
224
259
|
: `Só uma sessão principal foi encontrada${project ? ` em ${project}` : ''}, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`,
|
|
225
260
|
};
|
|
226
261
|
exports.COMPARE_TEXT = { en: compareEn, es: compareEs, pt: comparePt };
|
|
262
|
+
const hostList = (claude, codex, and, of = '') => [claude ? `${of}Claude Code` : '', codex ? `${of}Codex` : ''].filter(Boolean).join(` ${and} `);
|
|
263
|
+
const calendarEn = {
|
|
264
|
+
weekdays: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
|
|
265
|
+
months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
|
|
266
|
+
date: (date, withYear) => `${date.month} ${date.day}${withYear ? `, ${date.year}` : ''}`,
|
|
267
|
+
span: (from, to) => from.year === to.year ? `${from.month} ${from.day} to ${to.month} ${to.day}, ${to.year}`
|
|
268
|
+
: `${from.month} ${from.day}, ${from.year} to ${to.month} ${to.day}, ${to.year}`,
|
|
269
|
+
title: span => `AgentGuard calendar: tokens per day, ${span}`,
|
|
270
|
+
tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
|
|
271
|
+
dollars: usd => usd === null ? 'no dollar total: no known API price for these models' : `${usd} at API prices, not a bill`,
|
|
272
|
+
busiest: (date, count) => `busiest day: ${date} (${count} ${count === '1' ? 'token' : 'tokens'})`,
|
|
273
|
+
subagents: share => `sub-agents used ${share} of tokens`,
|
|
274
|
+
held: launches => `AgentGuard held ${launches} ${launches === 1 ? 'launch' : 'launches'}`,
|
|
275
|
+
less: 'Less',
|
|
276
|
+
more: 'More',
|
|
277
|
+
subagentDays: { colour: 'Days in amber: sub-agents used more than half of that day\'s tokens.', plain: letter => `Days marked ${letter}: sub-agents used more than half of that day's tokens.` },
|
|
278
|
+
heldDays: { colour: 'Red mark: AgentGuard held a launch that day.', plain: letter => `Days marked ${letter}: AgentGuard held a launch that day.` },
|
|
279
|
+
sources: (claude, codex) => `From ${hostList(claude, codex, 'and')} sessions on this machine, sub-agents included.`,
|
|
280
|
+
unpriced: (tokens, models) => `Unknown API price for ${models}: ${tokens} tokens not in the dollar total.`,
|
|
281
|
+
forkUnknown: forks => forks === 1 ? 'Not counted: 1 forked Codex session; its copied history cannot be split off.'
|
|
282
|
+
: `Not counted: ${forks} forked Codex sessions; their copied history cannot be split off.`,
|
|
283
|
+
unreadable: files => files === 1 ? 'Could not read 1 session file this time; its days show only what Burn counted before.'
|
|
284
|
+
: `Could not read ${files} session files this time; their days show only what Burn counted before.`,
|
|
285
|
+
noData: 'No Claude Code or Codex sessions found on this machine yet.',
|
|
286
|
+
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.'],
|
|
287
|
+
saveFailed: 'Burn could not store the counts from this run.',
|
|
288
|
+
};
|
|
289
|
+
const calendarEs = {
|
|
290
|
+
weekdays: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
|
|
291
|
+
months: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'],
|
|
292
|
+
date: (date, withYear) => `${date.day} ${date.month}${withYear ? ` de ${date.year}` : ''}`,
|
|
293
|
+
span: (from, to) => from.year === to.year ? `del ${from.day} ${from.month} al ${to.day} ${to.month} de ${to.year}`
|
|
294
|
+
: `del ${from.day} ${from.month} de ${from.year} al ${to.day} ${to.month} de ${to.year}`,
|
|
295
|
+
title: span => `AgentGuard calendar: tokens por día, ${span}`,
|
|
296
|
+
tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
|
|
297
|
+
dollars: usd => usd === null ? 'sin total en dólares: no se conoce el precio de la API de estos modelos' : `${usd} a precios de la API, no es una factura`,
|
|
298
|
+
busiest: (date, count) => `día con más tokens: ${date} (${count})`,
|
|
299
|
+
subagents: share => `los subagentes usaron el ${share} de los tokens`,
|
|
300
|
+
held: launches => launches === 1 ? 'AgentGuard retuvo 1 lanzamiento' : `AgentGuard retuvo ${launches} lanzamientos`,
|
|
301
|
+
less: 'Menos',
|
|
302
|
+
more: 'Más',
|
|
303
|
+
subagentDays: { colour: 'Días en ámbar: los subagentes usaron más de la mitad de los tokens de ese día.', plain: letter => `Días con ${letter}: los subagentes usaron más de la mitad de los tokens de ese día.` },
|
|
304
|
+
heldDays: { colour: 'Marca roja: AgentGuard retuvo un lanzamiento ese día.', plain: letter => `Días con ${letter}: AgentGuard retuvo un lanzamiento ese día.` },
|
|
305
|
+
sources: (claude, codex) => `De las sesiones de ${hostList(claude, codex, 'y')} en esta máquina, subagentes incluidos.`,
|
|
306
|
+
unpriced: (tokens, models) => `Precio de la API desconocido para ${models}: ${tokens} tokens fuera del total en dólares.`,
|
|
307
|
+
forkUnknown: forks => `Sin contar: ${plural(forks, 'sesión bifurcada', 'sesiones bifurcadas')} de Codex; el historial copiado no se puede separar.`,
|
|
308
|
+
unreadable: files => files === 1 ? 'No se pudo leer 1 archivo de sesión esta vez; sus días muestran solo lo que Burn guardó antes.'
|
|
309
|
+
: `No se pudieron leer ${files} archivos de sesión esta vez; sus días muestran solo lo que Burn guardó antes.`,
|
|
310
|
+
noData: 'Todavía no hay sesiones de Claude Code ni de Codex en esta máquina.',
|
|
311
|
+
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.'],
|
|
312
|
+
saveFailed: 'Burn no pudo guardar los conteos de esta ejecución.',
|
|
313
|
+
};
|
|
314
|
+
const calendarPt = {
|
|
315
|
+
weekdays: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
|
|
316
|
+
months: ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
|
|
317
|
+
date: (date, withYear) => `${date.day} ${date.month}${withYear ? ` de ${date.year}` : ''}`,
|
|
318
|
+
span: (from, to) => from.year === to.year ? `de ${from.day} ${from.month} a ${to.day} ${to.month} de ${to.year}`
|
|
319
|
+
: `de ${from.day} ${from.month} de ${from.year} a ${to.day} ${to.month} de ${to.year}`,
|
|
320
|
+
title: span => `AgentGuard calendar: tokens por dia, ${span}`,
|
|
321
|
+
tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
|
|
322
|
+
dollars: usd => usd === null ? 'sem total em dólares: o preço da API destes modelos não é conhecido' : `${usd} a preços da API, não é uma fatura`,
|
|
323
|
+
busiest: (date, count) => `dia com mais tokens: ${date} (${count})`,
|
|
324
|
+
subagents: share => `os subagentes usaram ${share} dos tokens`,
|
|
325
|
+
held: launches => launches === 1 ? 'o AgentGuard reteve 1 lançamento' : `o AgentGuard reteve ${launches} lançamentos`,
|
|
326
|
+
less: 'Menos',
|
|
327
|
+
more: 'Mais',
|
|
328
|
+
subagentDays: { colour: 'Dias em âmbar: os subagentes usaram mais da metade dos tokens daquele dia.', plain: letter => `Dias com ${letter}: os subagentes usaram mais da metade dos tokens daquele dia.` },
|
|
329
|
+
heldDays: { colour: 'Marca vermelha: o AgentGuard reteve um lançamento naquele dia.', plain: letter => `Dias com ${letter}: o AgentGuard reteve um lançamento naquele dia.` },
|
|
330
|
+
sources: (claude, codex) => `Das sessões ${hostList(claude, codex, 'e', 'do ')} nesta máquina, subagentes incluídos.`,
|
|
331
|
+
unpriced: (tokens, models) => `Preço da API desconhecido para ${models}: ${tokens} tokens fora do total em dólares.`,
|
|
332
|
+
forkUnknown: forks => `Fora da conta: ${plural(forks, 'sessão bifurcada', 'sessões bifurcadas')} do Codex; o histórico copiado não pode ser separado.`,
|
|
333
|
+
unreadable: files => files === 1 ? 'Não foi possível ler 1 arquivo de sessão desta vez; os dias dele mostram só o que o Burn salvou antes.'
|
|
334
|
+
: `Não foi possível ler ${files} arquivos de sessão desta vez; os dias deles mostram só o que o Burn salvou antes.`,
|
|
335
|
+
noData: 'Ainda não há sessões do Claude Code nem do Codex nesta máquina.',
|
|
336
|
+
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.'],
|
|
337
|
+
saveFailed: 'O Burn não conseguiu salvar as contagens desta execução.',
|
|
338
|
+
};
|
|
339
|
+
exports.CALENDAR_TEXT = { en: calendarEn, es: calendarEs, pt: calendarPt };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DollarRange, type PricingTable, type TurnPrice } from './pricing';
|
|
2
|
-
import { type AttributionSummary, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
|
|
2
|
+
import { type AttributionSummary, type InsightBucket, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } 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;
|
|
@@ -26,19 +26,77 @@ export declare const count: (n: number) => string;
|
|
|
26
26
|
/** The table's share column; the tip prints the same figure. */
|
|
27
27
|
export declare const share: (tokens: number, total: number) => string;
|
|
28
28
|
export declare const WHY_TIP_HIDE_LINE: string;
|
|
29
|
-
/**
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
*/
|
|
35
|
-
export declare function whyTip(input: {
|
|
29
|
+
/** 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
|
+
export declare function modelLabel(model: string): string;
|
|
31
|
+
/** What the coach tip is chosen from: each cause's measured size in this session, and the facts its action line quotes. */
|
|
32
|
+
export interface WhyTipInput {
|
|
33
|
+
/** The table's session total, children included. */
|
|
36
34
|
totalTokens: number;
|
|
37
|
-
|
|
38
|
-
historyTokens: number;
|
|
39
|
-
rewriteUsd: DollarRange | null;
|
|
35
|
+
/** The session's API list equivalent; null when a model is unpriced, and causes then compare by tokens. */
|
|
40
36
|
totalUsd: DollarRange | null;
|
|
41
|
-
|
|
37
|
+
/** The table's sub-agent row, the main conversation's model, and the sub-agents that ran on it with their share of all sub-agent tokens. */
|
|
38
|
+
subagents: {
|
|
39
|
+
tokens: number;
|
|
40
|
+
usd: DollarRange | null;
|
|
41
|
+
mainModel?: string | null;
|
|
42
|
+
onMainModel?: number;
|
|
43
|
+
onMainModelShare?: number;
|
|
44
|
+
};
|
|
45
|
+
/** The table's full-prefix rewrite row, and its largest cause at list price with that cause's count and longest idle gap. */
|
|
46
|
+
reloads: {
|
|
47
|
+
tokens: number;
|
|
48
|
+
usd: DollarRange | null;
|
|
49
|
+
cause?: RewriteCause | null;
|
|
50
|
+
count?: number;
|
|
51
|
+
longestIdleMs?: number | null;
|
|
52
|
+
};
|
|
53
|
+
/** Main-conversation cached reads past the first call's context: the conversation Claude re-reads on every message. */
|
|
54
|
+
conversation: {
|
|
55
|
+
tokens: number;
|
|
56
|
+
usd: DollarRange | null;
|
|
57
|
+
medianPerCall: number;
|
|
58
|
+
};
|
|
59
|
+
/** The first call's context, and each later call's cached reads up to that size: the setup Claude reads before every message. */
|
|
60
|
+
setup: {
|
|
61
|
+
tokens: number;
|
|
62
|
+
usd: DollarRange | null;
|
|
63
|
+
medianPerCall: number;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The coach: one next step, for the largest cause that stands out in this
|
|
68
|
+
* session; null when none does, never a generic line. A cause stands out at the
|
|
69
|
+
* 0.3.16 thresholds: sub-agents at 20% of session tokens, full-prefix rewrites at
|
|
70
|
+
* 15% of the list total (priced sessions only), and the re-read conversation and
|
|
71
|
+
* the setup at 30% of session tokens each. Among those the largest at list price
|
|
72
|
+
* wins (a dollar range at its midpoint), or the largest in tokens when a model is
|
|
73
|
+
* unpriced; a tie keeps that order. Each action is Anthropic's published advice
|
|
74
|
+
* for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
|
|
75
|
+
* and every figure is this session's own. Where the cause has no sharper action,
|
|
76
|
+
* the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
|
|
77
|
+
*/
|
|
78
|
+
export declare function whyTip(input: WhyTipInput, lang?: WhyLang): string | null;
|
|
79
|
+
/**
|
|
80
|
+
* What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
|
|
81
|
+
* rows are the table's own. The setup and the re-read conversation split each
|
|
82
|
+
* main-conversation call's cached reads at the size of the session's first call,
|
|
83
|
+
* so a rewrite that resets the table's fixed-prefix baseline never turns re-read
|
|
84
|
+
* conversation into setup; they are measured, like every row, from recorded usage.
|
|
85
|
+
*/
|
|
86
|
+
export declare function whyTipInput(figures: Pick<SessionFigures, 'turns' | 'attribution' | 'totalUsd'>, rates?: PricingTable, bucketUsd?: (bucket: InsightBucket) => DollarRange | null): WhyTipInput;
|
|
87
|
+
/** Messages on each side of an event the measured change compares, at most and at least. */
|
|
88
|
+
export declare const PROOF_WINDOW = 20;
|
|
89
|
+
export declare const PROOF_MINIMUM = 5;
|
|
90
|
+
/**
|
|
91
|
+
* One measured change, around the latest compaction, /clear or model switch the
|
|
92
|
+
* main conversation's transcript records: the median tokens Claude read per
|
|
93
|
+
* message in the N messages after it against the N before it. N is 20, or fewer
|
|
94
|
+
* when the session, or the previous or next such event, leaves fewer on a side;
|
|
95
|
+
* below 5 on either side that event says nothing and an earlier one is tried.
|
|
96
|
+
* It states what was measured next to the event, never a saving and never that
|
|
97
|
+
* the event caused it.
|
|
98
|
+
*/
|
|
99
|
+
export declare function proofLine(turns: InsightTurn[], lang?: WhyLang): string | null;
|
|
42
100
|
/** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
|
|
43
101
|
export declare function renderWhy(transcript: InsightTranscript, rates?: PricingTable, options?: {
|
|
44
102
|
tips?: boolean;
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WHY_TIP_HIDE_LINE = exports.share = exports.count = void 0;
|
|
3
|
+
exports.PROOF_MINIMUM = exports.PROOF_WINDOW = 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
7
|
exports.table = table;
|
|
8
|
+
exports.modelLabel = modelLabel;
|
|
8
9
|
exports.whyTip = whyTip;
|
|
10
|
+
exports.whyTipInput = whyTipInput;
|
|
11
|
+
exports.proofLine = proofLine;
|
|
9
12
|
exports.renderWhy = renderWhy;
|
|
10
13
|
exports.rewriteReport = rewriteReport;
|
|
11
14
|
exports.rewriteReportJson = rewriteReportJson;
|
|
@@ -17,6 +20,7 @@ const live_1 = require("./live");
|
|
|
17
20
|
const transcript_1 = require("./transcript");
|
|
18
21
|
const types_1 = require("./types");
|
|
19
22
|
const i18n_1 = require("./i18n");
|
|
23
|
+
const stop_text_1 = require("../stop-text");
|
|
20
24
|
function sumPrices(values) {
|
|
21
25
|
return values.some(value => value === null) ? null : values.reduce((sum, value) => ({ min: sum.min + value.min, max: sum.max + value.max }), { min: 0, max: 0 });
|
|
22
26
|
}
|
|
@@ -53,21 +57,190 @@ const share = (tokens, total) => `${(total ? tokens / total * 100 : 0).toFixed(1
|
|
|
53
57
|
exports.share = share;
|
|
54
58
|
const midpoint = (value) => (value.min + value.max) / 2;
|
|
55
59
|
exports.WHY_TIP_HIDE_LINE = i18n_1.WHY_TEXT.en.hide;
|
|
60
|
+
const median = (values) => {
|
|
61
|
+
if (!values.length)
|
|
62
|
+
return 0;
|
|
63
|
+
const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2);
|
|
64
|
+
return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
|
|
65
|
+
};
|
|
66
|
+
/** 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. */
|
|
67
|
+
function modelLabel(model) {
|
|
68
|
+
const match = /^claude-(opus|sonnet|haiku|fable)-(\d{1,2})(?:-(\d{1,2}))?(?:-\d{8})?$/.exec(model);
|
|
69
|
+
return match ? `${match[1][0].toUpperCase()}${match[1].slice(1)} ${match[2]}${match[3] ? `.${match[3]}` : ''}` : model;
|
|
70
|
+
}
|
|
71
|
+
/** The model with the most output tokens, then the most responses; null when no response names one. */
|
|
72
|
+
function dominantModel(turns) {
|
|
73
|
+
const byModel = new Map();
|
|
74
|
+
for (const turn of turns) {
|
|
75
|
+
if (!turn.model)
|
|
76
|
+
continue;
|
|
77
|
+
const row = byModel.get(turn.model) ?? { output: 0, responses: 0 };
|
|
78
|
+
row.output += turn.outputTokens;
|
|
79
|
+
row.responses++;
|
|
80
|
+
byModel.set(turn.model, row);
|
|
81
|
+
}
|
|
82
|
+
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;
|
|
83
|
+
}
|
|
84
|
+
/** A main model with a smaller Claude model below it, the one CLAUDE_CODE_SUBAGENT_MODEL=haiku names. */
|
|
85
|
+
const HAS_SMALLER_MODEL = /^claude-(?:opus|fable|sonnet)-/;
|
|
56
86
|
/**
|
|
57
|
-
*
|
|
58
|
-
* when
|
|
59
|
-
*
|
|
60
|
-
*
|
|
87
|
+
* The coach: one next step, for the largest cause that stands out in this
|
|
88
|
+
* session; null when none does, never a generic line. A cause stands out at the
|
|
89
|
+
* 0.3.16 thresholds: sub-agents at 20% of session tokens, full-prefix rewrites at
|
|
90
|
+
* 15% of the list total (priced sessions only), and the re-read conversation and
|
|
91
|
+
* the setup at 30% of session tokens each. Among those the largest at list price
|
|
92
|
+
* wins (a dollar range at its midpoint), or the largest in tokens when a model is
|
|
93
|
+
* unpriced; a tie keeps that order. Each action is Anthropic's published advice
|
|
94
|
+
* for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
|
|
95
|
+
* and every figure is this session's own. Where the cause has no sharper action,
|
|
96
|
+
* the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
|
|
61
97
|
*/
|
|
62
98
|
function whyTip(input, lang = 'en') {
|
|
63
|
-
const { totalTokens,
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
99
|
+
const { totalTokens, totalUsd } = input, text = i18n_1.WHY_TEXT[lang];
|
|
100
|
+
const priced = totalUsd !== null && midpoint(totalUsd) > 0;
|
|
101
|
+
const tokenShare = (tokens) => totalTokens > 0 ? tokens / totalTokens : 0;
|
|
102
|
+
const { subagents, reloads, conversation, setup } = input;
|
|
103
|
+
const causes = [
|
|
104
|
+
['subagents', tokenShare(subagents.tokens) >= 0.2, subagents],
|
|
105
|
+
['reloads', priced && reloads.usd !== null && midpoint(reloads.usd) / midpoint(totalUsd) >= 0.15, reloads],
|
|
106
|
+
['conversation', tokenShare(conversation.tokens) >= 0.3 && conversation.medianPerCall > 0, conversation],
|
|
107
|
+
['setup', tokenShare(setup.tokens) >= 0.3 && setup.medianPerCall > 0, setup],
|
|
108
|
+
];
|
|
109
|
+
let largest = null;
|
|
110
|
+
for (const [cause, standsOut, { tokens, usd }] of causes) {
|
|
111
|
+
const size = !standsOut ? null : priced ? (usd === null ? null : midpoint(usd)) : tokens;
|
|
112
|
+
if (size !== null && (largest === null || size > largest.size))
|
|
113
|
+
largest = { cause, size };
|
|
114
|
+
}
|
|
115
|
+
switch (largest?.cause) {
|
|
116
|
+
case 'subagents': {
|
|
117
|
+
const { mainModel, onMainModel = 0, onMainModelShare = 0 } = input.subagents;
|
|
118
|
+
return mainModel && onMainModel > 0 && onMainModelShare >= 0.5 && HAS_SMALLER_MODEL.test(mainModel)
|
|
119
|
+
? text.tipSubagentModel(onMainModel, modelLabel(mainModel))
|
|
120
|
+
: text.tipFanout((0, exports.share)(input.subagents.tokens, totalTokens));
|
|
121
|
+
}
|
|
122
|
+
case 'reloads': {
|
|
123
|
+
const { cause, count = 0, longestIdleMs = null } = input.reloads;
|
|
124
|
+
if (cause === 'idle_ttl_expired' && count > 0 && longestIdleMs !== null)
|
|
125
|
+
return text.tipIdleReloads(count, (0, attribution_1.idleLabel)(longestIdleMs));
|
|
126
|
+
if (cause === 'model_switch' && count > 0)
|
|
127
|
+
return text.tipModelSwitch(count);
|
|
128
|
+
return text.tipRewrites((0, live_1.dollars)(input.reloads.usd, text), (0, live_1.dollars)(totalUsd, text));
|
|
129
|
+
}
|
|
130
|
+
case 'conversation': return text.tipConversation((0, stop_text_1.shortTokens)(input.conversation.medianPerCall));
|
|
131
|
+
case 'setup': return text.tipSetup((0, stop_text_1.shortTokens)(input.setup.medianPerCall));
|
|
132
|
+
default: return null;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
|
|
137
|
+
* rows are the table's own. The setup and the re-read conversation split each
|
|
138
|
+
* main-conversation call's cached reads at the size of the session's first call,
|
|
139
|
+
* so a rewrite that resets the table's fixed-prefix baseline never turns re-read
|
|
140
|
+
* conversation into setup; they are measured, like every row, from recorded usage.
|
|
141
|
+
*/
|
|
142
|
+
function whyTipInput(figures, rates = {}, bucketUsd) {
|
|
143
|
+
const { turns, attribution, totalUsd } = figures;
|
|
144
|
+
const byTurn = new Map(attribution.turnAttributions.map(turn => [turn.turnId, turn]));
|
|
145
|
+
const usdOf = bucketUsd ?? ((bucket) => sumPrices(turns.map(turn => bucketPrice(turn, byTurn.get(turn.id).buckets.find(item => item.bucket === bucket), rates))));
|
|
146
|
+
const tokensOf = (bucket) => attribution.buckets.find(item => item.bucket === bucket).tokens;
|
|
147
|
+
const main = turns.filter(turn => !turn.subagent);
|
|
148
|
+
// Sub-agents on the main conversation's model, and their share of all sub-agent tokens.
|
|
149
|
+
const mainModel = dominantModel(main);
|
|
150
|
+
const children = new Map();
|
|
151
|
+
for (const turn of turns) {
|
|
152
|
+
if (!turn.subagent)
|
|
153
|
+
continue;
|
|
154
|
+
const own = children.get(turn.sessionId);
|
|
155
|
+
if (own)
|
|
156
|
+
own.push(turn);
|
|
157
|
+
else
|
|
158
|
+
children.set(turn.sessionId, [turn]);
|
|
159
|
+
}
|
|
160
|
+
let childTokens = 0, onMainTokens = 0, onMainModel = 0;
|
|
161
|
+
for (const own of children.values()) {
|
|
162
|
+
const tokens = own.reduce((sum, turn) => sum + totalTokens(turn), 0);
|
|
163
|
+
childTokens += tokens;
|
|
164
|
+
if (mainModel !== null && dominantModel(own) === mainModel) {
|
|
165
|
+
onMainModel++;
|
|
166
|
+
onMainTokens += tokens;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
// The rewrite cause with the largest cache-write list price, then the most rewrites, then precedence.
|
|
170
|
+
const byId = new Map(turns.map(turn => [turn.id, turn]));
|
|
171
|
+
const causes = new Map();
|
|
172
|
+
for (const rewrite of attribution.rewrites) {
|
|
173
|
+
const turn = byId.get(rewrite.turnId);
|
|
174
|
+
const price = turn ? (0, pricing_1.priceTurn)({ ...turn, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 }, rates).usd : null;
|
|
175
|
+
const row = causes.get(rewrite.cause) ?? { usd: 0, count: 0, longestIdleMs: null };
|
|
176
|
+
row.usd += price ? midpoint(price) : 0;
|
|
177
|
+
row.count++;
|
|
178
|
+
if (rewrite.idleMs !== undefined)
|
|
179
|
+
row.longestIdleMs = Math.max(row.longestIdleMs ?? 0, rewrite.idleMs);
|
|
180
|
+
causes.set(rewrite.cause, row);
|
|
181
|
+
}
|
|
182
|
+
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];
|
|
183
|
+
// Setup and re-read conversation, split at the first call's context.
|
|
184
|
+
const rewritten = new Set(attribution.rewrites.map(rewrite => rewrite.turnId));
|
|
185
|
+
const baseline = main[0]?.contextTokens ?? 0;
|
|
186
|
+
const setup = { tokens: 0, usd: { min: 0, max: 0 }, perCall: [] };
|
|
187
|
+
const conversation = { tokens: 0, usd: { min: 0, max: 0 }, perCall: [] };
|
|
188
|
+
main.forEach((turn, index) => {
|
|
189
|
+
// The first call's whole context sets the baseline, as the table's first row does.
|
|
190
|
+
const opening = index === 0 && !rewritten.has(turn.id) && !turn.explicitAttribution.length;
|
|
191
|
+
const setupTokens = opening ? turn.inputTokens + turn.cacheWriteTokens + turn.cacheReadTokens : Math.min(turn.cacheReadTokens, baseline);
|
|
192
|
+
const conversationTokens = opening ? 0 : turn.cacheReadTokens - setupTokens;
|
|
193
|
+
const reads = (tokens) => (0, pricing_1.priceTurn)({ ...turn, inputTokens: 0, cacheWriteTokens: 0, cacheWrite5mTokens: undefined, cacheWrite1hTokens: undefined, outputTokens: 0, cacheReadTokens: tokens }, rates).usd;
|
|
194
|
+
setup.tokens += setupTokens;
|
|
195
|
+
setup.perCall.push(setupTokens);
|
|
196
|
+
setup.usd = sumPrices([setup.usd, opening ? (0, pricing_1.priceTurn)({ ...turn, outputTokens: 0 }, rates).usd : reads(setupTokens)]);
|
|
197
|
+
conversation.tokens += conversationTokens;
|
|
198
|
+
conversation.perCall.push(conversationTokens);
|
|
199
|
+
conversation.usd = sumPrices([conversation.usd, reads(conversationTokens)]);
|
|
200
|
+
});
|
|
201
|
+
return { totalTokens: attribution.totalTokens, totalUsd,
|
|
202
|
+
subagents: { tokens: tokensOf('subagent_fanout'), usd: usdOf('subagent_fanout'), mainModel, onMainModel, onMainModelShare: childTokens ? onMainTokens / childTokens : 0 },
|
|
203
|
+
reloads: { tokens: tokensOf('full_prefix_rewrites'), usd: usdOf('full_prefix_rewrites'), cause, count: top?.count ?? 0, longestIdleMs: top?.longestIdleMs ?? null },
|
|
204
|
+
conversation: { tokens: conversation.tokens, usd: conversation.usd, medianPerCall: median(conversation.perCall) },
|
|
205
|
+
setup: { tokens: setup.tokens, usd: setup.usd, medianPerCall: median(setup.perCall) } };
|
|
206
|
+
}
|
|
207
|
+
/** Messages on each side of an event the measured change compares, at most and at least. */
|
|
208
|
+
exports.PROOF_WINDOW = 20;
|
|
209
|
+
exports.PROOF_MINIMUM = 5;
|
|
210
|
+
/**
|
|
211
|
+
* One measured change, around the latest compaction, /clear or model switch the
|
|
212
|
+
* main conversation's transcript records: the median tokens Claude read per
|
|
213
|
+
* message in the N messages after it against the N before it. N is 20, or fewer
|
|
214
|
+
* when the session, or the previous or next such event, leaves fewer on a side;
|
|
215
|
+
* below 5 on either side that event says nothing and an earlier one is tried.
|
|
216
|
+
* It states what was measured next to the event, never a saving and never that
|
|
217
|
+
* the event caused it.
|
|
218
|
+
*/
|
|
219
|
+
function proofLine(turns, lang = 'en') {
|
|
220
|
+
const main = turns.filter(turn => !turn.subagent);
|
|
221
|
+
const events = [];
|
|
222
|
+
main.forEach((turn, index) => {
|
|
223
|
+
if (index === 0)
|
|
224
|
+
return;
|
|
225
|
+
const reset = turn.signals.reset;
|
|
226
|
+
if (reset)
|
|
227
|
+
events.push({ index, at: reset.at ?? turn.at,
|
|
228
|
+
event: { kind: reset.kind === 'clear' ? 'clear' : reset.trigger === 'manual' ? 'compact' : reset.trigger === 'auto' ? 'auto' : 'compaction' } });
|
|
229
|
+
else if (turn.signals.modelChanged && turn.model)
|
|
230
|
+
events.push({ index, at: turn.at, event: { kind: 'model', model: modelLabel(turn.model) } });
|
|
231
|
+
});
|
|
232
|
+
for (let e = events.length - 1; e >= 0; e--) {
|
|
233
|
+
const { index, at, event } = events[e];
|
|
234
|
+
const from = e > 0 ? events[e - 1].index : 0, to = e + 1 < events.length ? events[e + 1].index : main.length;
|
|
235
|
+
const messages = Math.min(exports.PROOF_WINDOW, index - from, to - index);
|
|
236
|
+
if (at === undefined || messages < exports.PROOF_MINIMUM)
|
|
237
|
+
continue;
|
|
238
|
+
const before = median(main.slice(index - messages, index).map(turn => turn.contextTokens));
|
|
239
|
+
const after = median(main.slice(index, index + messages).map(turn => turn.contextTokens));
|
|
240
|
+
const [printedAfter, printedBefore] = [(0, stop_text_1.shortTokens)(after), (0, stop_text_1.shortTokens)(before)];
|
|
241
|
+
const stamp = new Date(at).toISOString();
|
|
242
|
+
return i18n_1.WHY_TEXT[lang].proof(event, { date: stamp.slice(0, 10), time: stamp.slice(11, 16) }, printedAfter, printedBefore, messages, printedAfter === printedBefore ? 'same' : after < before ? 'down' : 'up');
|
|
243
|
+
}
|
|
71
244
|
return null;
|
|
72
245
|
}
|
|
73
246
|
/** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
|
|
@@ -92,8 +265,9 @@ function renderWhy(transcript, rates = {}, options = {}) {
|
|
|
92
265
|
return [text.labels[bucket], (0, exports.count)(tokens), money(bucketUsd(bucket)), (0, exports.share)(tokens, attribution.totalTokens), (0, exports.share)(lastTokens, lastAttribution?.totalTokens ?? 0)];
|
|
93
266
|
});
|
|
94
267
|
const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
|
|
95
|
-
const tip = options.tips ? whyTip({
|
|
96
|
-
|
|
268
|
+
const tip = options.tips ? whyTip(whyTipInput({ turns, attribution, totalUsd }, rates, bucketUsd), lang) : null;
|
|
269
|
+
// A measurement, not a tip: it prints whether or not tips are on.
|
|
270
|
+
const proof = proofLine(turns, lang);
|
|
97
271
|
return [
|
|
98
272
|
`AgentGuard why: ${transcript.sessionId}`,
|
|
99
273
|
text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
|
|
@@ -109,6 +283,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
|
|
|
109
283
|
...(prices.some(price => price.unknownCacheWriteTokens > 0) ? [text.missingTtl] : []),
|
|
110
284
|
...(mixedWriteAllocation ? [text.mixedRanges] : []),
|
|
111
285
|
text.diagnostics(transcript.diagnostics.duplicateUsageRecords, transcript.diagnostics.malformedLines),
|
|
286
|
+
...(proof ? ['', proof] : []),
|
|
112
287
|
...(tip ? ['', tip, text.hide] : []),
|
|
113
288
|
].join('\n');
|
|
114
289
|
}
|
|
@@ -7,8 +7,19 @@ export declare const providerResponseIdentity: (host: InsightHost, id: unknown)
|
|
|
7
7
|
* to previous totals because an assistant message can gain output usage later.
|
|
8
8
|
*/
|
|
9
9
|
export declare function parseInsightTranscript(text: string, options?: InsightParseOptions): InsightTranscript;
|
|
10
|
-
|
|
10
|
+
/** How a transcript file is read, never how it is parsed. */
|
|
11
|
+
export interface InsightReadOptions {
|
|
12
|
+
/**
|
|
13
|
+
* A file larger than this many bytes is read in pieces cut at line ends, each
|
|
14
|
+
* parsed with the parser state the previous piece returned, so no single string
|
|
15
|
+
* holds the whole file (V8 cannot hold a string past about 512 MB). The turns,
|
|
16
|
+
* observations and summed diagnostics equal a whole-file parse. Unset reads the
|
|
17
|
+
* whole file at once, as `why` does.
|
|
18
|
+
*/
|
|
19
|
+
chunkBytes?: number;
|
|
20
|
+
}
|
|
21
|
+
export declare function readInsightTranscript(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
|
|
11
22
|
/** Read one Claude session plus its explicitly stored child transcripts. */
|
|
12
|
-
export declare function readInsightSession(filename: string, options?: InsightParseOptions): InsightTranscript;
|
|
23
|
+
export declare function readInsightSession(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
|
|
13
24
|
/** Forked transcript copies can repeat provider response ids across files. */
|
|
14
25
|
export declare function deduplicateTurns(turns: InsightTurn[]): InsightTurn[];
|