@agentguard-run/burn 0.3.19 → 0.3.21

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +63 -2
  3. package/dist/src/canvas.d.ts +7 -1
  4. package/dist/src/canvas.js +10 -1
  5. package/dist/src/cli.js +70 -6
  6. package/dist/src/frames.d.ts +10 -0
  7. package/dist/src/frames.js +5 -0
  8. package/dist/src/gateway.js +11 -7
  9. package/dist/src/history/claude-transcript.d.ts +63 -1
  10. package/dist/src/history/claude-transcript.js +105 -2
  11. package/dist/src/hook/pre-tool-use.d.ts +2 -10
  12. package/dist/src/hook/pre-tool-use.js +9 -18
  13. package/dist/src/index.d.ts +4 -1
  14. package/dist/src/index.js +18 -2
  15. package/dist/src/insights/calendar-render.d.ts +71 -0
  16. package/dist/src/insights/calendar-render.js +251 -0
  17. package/dist/src/insights/calendar.d.ts +138 -0
  18. package/dist/src/insights/calendar.js +431 -0
  19. package/dist/src/insights/i18n.d.ts +103 -6
  20. package/dist/src/insights/i18n.js +123 -7
  21. package/dist/src/insights/render.d.ts +85 -12
  22. package/dist/src/insights/render.js +207 -17
  23. package/dist/src/insights/session-tip.d.ts +33 -0
  24. package/dist/src/insights/session-tip.js +32 -0
  25. package/dist/src/insights/sessions.d.ts +6 -0
  26. package/dist/src/insights/sessions.js +15 -4
  27. package/dist/src/insights/transcript.d.ts +13 -2
  28. package/dist/src/insights/transcript.js +61 -6
  29. package/dist/src/insights/types.d.ts +14 -0
  30. package/dist/src/policy.d.ts +25 -0
  31. package/dist/src/policy.js +82 -9
  32. package/dist/src/recording.js +5 -1
  33. package/dist/src/replay/render.d.ts +2 -0
  34. package/dist/src/replay/render.js +4 -0
  35. package/dist/src/stop-text.d.ts +11 -2
  36. package/dist/src/stop-text.js +23 -3
  37. package/dist/src/subagent-cost.d.ts +49 -0
  38. package/dist/src/subagent-cost.js +90 -0
  39. package/package.json +5 -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,19 @@ 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-agent fan-out is ${share} of this session's tokens. Spawn limits refuse the next sub-agent launch past your limit, free on one machine: agentguard.run/try`,
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`,
71
+ tipFanoutPlugin: share => `Next: sub-agents used ${share} of this session's tokens. Give related work to one sub-agent instead of several.`,
68
72
  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
- tipHistory: share => `Next: history re-sent is ${share} of this session's tokens. A fresh session, or /compact, starts that history over.`,
73
+ 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.`,
74
+ 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.`,
75
+ 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.`,
76
+ 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.`,
77
+ 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).`,
78
+ proof: (event, when, after, before, messages, direction) => {
79
+ const what = event.kind === 'model' ? `the switch to ${event.model}` : { compact: '/compact', auto: 'automatic compaction', compaction: 'compaction', clear: '/clear' }[event.kind];
80
+ const change = direction === 'same' ? `the same as in the ${messages} messages before` : `${direction} from ${before} in the ${messages} messages before`;
81
+ return `Measured change: after ${what} on ${when.date} at ${when.time} UTC, Claude read a median of ${after} tokens per message, ${change}.`;
82
+ },
70
83
  hide: 'Hide tips like this: npx agentguard-burn quiet on',
71
84
  };
72
85
  /** Latin American Spanish: tú forms and vocabulary that reads the same from Mexico and Panama to Argentina. */
@@ -104,9 +117,19 @@ const es = {
104
117
  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
118
  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
119
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
107
- tipFanout: share => `Próximo paso: el fan-out de subagentes representa el ${share} de los tokens de esta sesión. Los límites de subagentes rechazan nuevos subagentes cuando llegas a tu límite, gratis en una máquina: agentguard.run/try`,
120
+ 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`,
121
+ tipFanoutPlugin: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. Da el trabajo relacionado a un solo subagente en lugar de a varios.`,
108
122
  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
- tipHistory: share => `Próximo paso: el historial reenviado representa el ${share} de los tokens de esta sesión. Una sesión nueva, o /compact, reinicia ese historial.`,
123
+ 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.`,
124
+ 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.`,
125
+ 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.`,
126
+ 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.`,
127
+ 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).`,
128
+ proof: (event, when, after, before, messages, direction) => {
129
+ 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];
130
+ 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`;
131
+ return `Cambio medido: después ${what} el ${when.date} a las ${when.time} UTC, Claude leyó una mediana de ${after} tokens por mensaje, ${change}.`;
132
+ },
110
133
  hide: 'Para ocultar consejos como este: npx agentguard-burn quiet on',
111
134
  };
112
135
  /** Brazilian Portuguese: você forms. */
@@ -144,12 +167,27 @@ const pt = {
144
167
  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
168
  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
169
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
147
- tipFanout: share => `Próximo passo: o fan-out de subagentes representa ${share} dos tokens desta sessão. Os limites de subagentes recusam novos subagentes quando você chega ao seu limite, grátis em uma máquina: agentguard.run/try`,
170
+ 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`,
171
+ tipFanoutPlugin: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. Dê o trabalho relacionado a um único subagente em vez de vários.`,
148
172
  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
- tipHistory: share => `Próximo passo: o histórico reenviado representa ${share} dos tokens desta sessão. Uma sessão nova, ou /compact, reinicia esse histórico.`,
173
+ 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.`,
174
+ 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.`,
175
+ 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.`,
176
+ 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.`,
177
+ 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).`,
178
+ proof: (event, when, after, before, messages, direction) => {
179
+ 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];
180
+ const change = direction === 'same' ? `a mesma das ${messages} mensagens anteriores` : `${direction === 'down' ? 'abaixo' : 'acima'} dos ${before} das ${messages} mensagens anteriores`;
181
+ return `Mudança medida: depois ${what} em ${when.date} às ${when.time} UTC, o Claude leu uma mediana de ${after} tokens por mensagem, ${change}.`;
182
+ },
150
183
  hide: 'Para ocultar dicas como esta: npx agentguard-burn quiet on',
151
184
  };
152
185
  exports.WHY_TEXT = { en, es, pt };
186
+ exports.DECISION_TEXT = {
187
+ 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.` },
188
+ 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.` },
189
+ 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.` },
190
+ };
153
191
  const TWO_IDS = 'agentguard-burn compare SESSION_A SESSION_B';
154
192
  const compareEn = {
155
193
  title: 'AgentGuard compare: B against A',
@@ -224,3 +262,81 @@ const comparePt = {
224
262
  : `Só uma sessão principal foi encontrada${project ? ` em ${project}` : ''}, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`,
225
263
  };
226
264
  exports.COMPARE_TEXT = { en: compareEn, es: compareEs, pt: comparePt };
265
+ const hostList = (claude, codex, and, of = '') => [claude ? `${of}Claude Code` : '', codex ? `${of}Codex` : ''].filter(Boolean).join(` ${and} `);
266
+ const calendarEn = {
267
+ weekdays: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
268
+ months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
269
+ date: (date, withYear) => `${date.month} ${date.day}${withYear ? `, ${date.year}` : ''}`,
270
+ span: (from, to) => from.year === to.year ? `${from.month} ${from.day} to ${to.month} ${to.day}, ${to.year}`
271
+ : `${from.month} ${from.day}, ${from.year} to ${to.month} ${to.day}, ${to.year}`,
272
+ title: span => `AgentGuard calendar: tokens per day, ${span}`,
273
+ tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
274
+ dollars: usd => usd === null ? 'no dollar total: no known API price for these models' : `${usd} at API prices, not a bill`,
275
+ busiest: (date, count) => `busiest day: ${date} (${count} ${count === '1' ? 'token' : 'tokens'})`,
276
+ subagents: share => `sub-agents used ${share} of tokens`,
277
+ held: launches => `AgentGuard held ${launches} ${launches === 1 ? 'launch' : 'launches'}`,
278
+ less: 'Less',
279
+ more: 'More',
280
+ 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.` },
281
+ heldDays: { colour: 'Red mark: AgentGuard held a launch that day.', plain: letter => `Days marked ${letter}: AgentGuard held a launch that day.` },
282
+ sources: (claude, codex) => `From ${hostList(claude, codex, 'and')} sessions on this machine, sub-agents included.`,
283
+ unpriced: (tokens, models) => `Unknown API price for ${models}: ${tokens} tokens not in the dollar total.`,
284
+ forkUnknown: forks => forks === 1 ? 'Not counted: 1 forked Codex session; its copied history cannot be split off.'
285
+ : `Not counted: ${forks} forked Codex sessions; their copied history cannot be split off.`,
286
+ unreadable: files => files === 1 ? 'Could not read 1 session file this time; its days show only what Burn counted before.'
287
+ : `Could not read ${files} session files this time; their days show only what Burn counted before.`,
288
+ noData: 'No Claude Code or Codex sessions found on this machine yet.',
289
+ 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.'],
290
+ saveFailed: 'Burn could not store the counts from this run.',
291
+ };
292
+ const calendarEs = {
293
+ weekdays: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
294
+ months: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'],
295
+ date: (date, withYear) => `${date.day} ${date.month}${withYear ? ` de ${date.year}` : ''}`,
296
+ span: (from, to) => from.year === to.year ? `del ${from.day} ${from.month} al ${to.day} ${to.month} de ${to.year}`
297
+ : `del ${from.day} ${from.month} de ${from.year} al ${to.day} ${to.month} de ${to.year}`,
298
+ title: span => `AgentGuard calendar: tokens por día, ${span}`,
299
+ tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
300
+ 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`,
301
+ busiest: (date, count) => `día con más tokens: ${date} (${count})`,
302
+ subagents: share => `los subagentes usaron el ${share} de los tokens`,
303
+ held: launches => launches === 1 ? 'AgentGuard retuvo 1 lanzamiento' : `AgentGuard retuvo ${launches} lanzamientos`,
304
+ less: 'Menos',
305
+ more: 'Más',
306
+ 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.` },
307
+ heldDays: { colour: 'Marca roja: AgentGuard retuvo un lanzamiento ese día.', plain: letter => `Días con ${letter}: AgentGuard retuvo un lanzamiento ese día.` },
308
+ sources: (claude, codex) => `De las sesiones de ${hostList(claude, codex, 'y')} en esta máquina, subagentes incluidos.`,
309
+ unpriced: (tokens, models) => `Precio de la API desconocido para ${models}: ${tokens} tokens fuera del total en dólares.`,
310
+ forkUnknown: forks => `Sin contar: ${plural(forks, 'sesión bifurcada', 'sesiones bifurcadas')} de Codex; el historial copiado no se puede separar.`,
311
+ 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.'
312
+ : `No se pudieron leer ${files} archivos de sesión esta vez; sus días muestran solo lo que Burn guardó antes.`,
313
+ noData: 'Todavía no hay sesiones de Claude Code ni de Codex en esta máquina.',
314
+ 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.'],
315
+ saveFailed: 'Burn no pudo guardar los conteos de esta ejecución.',
316
+ };
317
+ const calendarPt = {
318
+ weekdays: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
319
+ months: ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
320
+ date: (date, withYear) => `${date.day} ${date.month}${withYear ? ` de ${date.year}` : ''}`,
321
+ span: (from, to) => from.year === to.year ? `de ${from.day} ${from.month} a ${to.day} ${to.month} de ${to.year}`
322
+ : `de ${from.day} ${from.month} de ${from.year} a ${to.day} ${to.month} de ${to.year}`,
323
+ title: span => `AgentGuard calendar: tokens por dia, ${span}`,
324
+ tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
325
+ 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`,
326
+ busiest: (date, count) => `dia com mais tokens: ${date} (${count})`,
327
+ subagents: share => `os subagentes usaram ${share} dos tokens`,
328
+ held: launches => launches === 1 ? 'o AgentGuard reteve 1 lançamento' : `o AgentGuard reteve ${launches} lançamentos`,
329
+ less: 'Menos',
330
+ more: 'Mais',
331
+ 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.` },
332
+ 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.` },
333
+ sources: (claude, codex) => `Das sessões ${hostList(claude, codex, 'e', 'do ')} nesta máquina, subagentes incluídos.`,
334
+ unpriced: (tokens, models) => `Preço da API desconhecido para ${models}: ${tokens} tokens fora do total em dólares.`,
335
+ forkUnknown: forks => `Fora da conta: ${plural(forks, 'sessão bifurcada', 'sessões bifurcadas')} do Codex; o histórico copiado não pode ser separado.`,
336
+ 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.'
337
+ : `Não foi possível ler ${files} arquivos de sessão desta vez; os dias deles mostram só o que o Burn salvou antes.`,
338
+ noData: 'Ainda não há sessões do Claude Code nem do Codex nesta máquina.',
339
+ 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.'],
340
+ saveFailed: 'O Burn não conseguiu salvar as contagens desta execução.',
341
+ };
342
+ 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,92 @@ 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
- * One next step from the session's own measured shares, first match wins; null
31
- * when nothing stands out, never a generic line. Fan-out and history compare
32
- * session tokens; rewrites compare list USD and are skipped when either figure
33
- * is unpriced. A dollar range compares midpoints, as the `rewrites` share does.
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
- fanoutTokens: number;
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
- }, lang?: WhyLang): string | null;
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
+ * Where the tip is shown: `why` itself, or the AgentGuard plugin. The fan-out
68
+ * tip points `why` readers to the plugin; someone the plugin shows it to already
69
+ * runs it, so there it ends with the STOP box's action for too many sub-agents.
70
+ */
71
+ export type TipContext = 'why' | 'plugin';
72
+ /**
73
+ * The coach: one next step, for the largest cause that stands out in this
74
+ * session; null when none does, never a generic line. A cause stands out at the
75
+ * 0.3.16 thresholds: sub-agents at 20% of session tokens, full-prefix rewrites at
76
+ * 15% of the list total (priced sessions only), and the re-read conversation and
77
+ * the setup at 30% of session tokens each. Among those the largest at list price
78
+ * wins (a dollar range at its midpoint), or the largest in tokens when a model is
79
+ * unpriced; a tie keeps that order. Each action is Anthropic's published advice
80
+ * for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
81
+ * and every figure is this session's own. Where the cause has no sharper action,
82
+ * the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
83
+ * In the plugin context only the share tip's second sentence changes.
84
+ */
85
+ export declare function whyTip(input: WhyTipInput, lang?: WhyLang, context?: TipContext): string | null;
86
+ /**
87
+ * What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
88
+ * rows are the table's own. The setup and the re-read conversation split each
89
+ * main-conversation call's cached reads at the size of the session's first call,
90
+ * so a rewrite that resets the table's fixed-prefix baseline never turns re-read
91
+ * conversation into setup; they are measured, like every row, from recorded usage.
92
+ */
93
+ export declare function whyTipInput(figures: Pick<SessionFigures, 'turns' | 'attribution' | 'totalUsd'>, rates?: PricingTable, bucketUsd?: (bucket: InsightBucket) => DollarRange | null): WhyTipInput;
94
+ /**
95
+ * The tip line `why` ends with for this transcript, in the same words and with
96
+ * the same figures: null when nothing stands out, and for the unknown
97
+ * fork-history report, which prints no tip. The plugin context changes only
98
+ * the fan-out tip's second sentence. It does not read the quiet flag; the
99
+ * caller decides whether to show it.
100
+ */
101
+ export declare function whyTipLine(transcript: InsightTranscript, rates?: PricingTable, lang?: WhyLang, context?: TipContext): string | null;
102
+ /** Messages on each side of an event the measured change compares, at most and at least. */
103
+ export declare const PROOF_WINDOW = 20;
104
+ export declare const PROOF_MINIMUM = 5;
105
+ /**
106
+ * One measured change, around the latest compaction, /clear or model switch the
107
+ * main conversation's transcript records: the median tokens Claude read per
108
+ * message in the N messages after it against the N before it. N is 20, or fewer
109
+ * when the session, or the previous or next such event, leaves fewer on a side;
110
+ * below 5 on either side that event says nothing and an earlier one is tried.
111
+ * It states what was measured next to the event, never a saving and never that
112
+ * the event caused it.
113
+ */
114
+ export declare function proofLine(turns: InsightTurn[], lang?: WhyLang): string | null;
42
115
  /** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
43
116
  export declare function renderWhy(transcript: InsightTranscript, rates?: PricingTable, options?: {
44
117
  tips?: boolean;
@@ -1,11 +1,15 @@
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.whyTipLine = whyTipLine;
12
+ exports.proofLine = proofLine;
9
13
  exports.renderWhy = renderWhy;
10
14
  exports.rewriteReport = rewriteReport;
11
15
  exports.rewriteReportJson = rewriteReportJson;
@@ -17,6 +21,7 @@ const live_1 = require("./live");
17
21
  const transcript_1 = require("./transcript");
18
22
  const types_1 = require("./types");
19
23
  const i18n_1 = require("./i18n");
24
+ const stop_text_1 = require("../stop-text");
20
25
  function sumPrices(values) {
21
26
  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
27
  }
@@ -53,21 +58,203 @@ const share = (tokens, total) => `${(total ? tokens / total * 100 : 0).toFixed(1
53
58
  exports.share = share;
54
59
  const midpoint = (value) => (value.min + value.max) / 2;
55
60
  exports.WHY_TIP_HIDE_LINE = i18n_1.WHY_TEXT.en.hide;
61
+ const median = (values) => {
62
+ if (!values.length)
63
+ return 0;
64
+ const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2);
65
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
66
+ };
67
+ /** 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. */
68
+ function modelLabel(model) {
69
+ const match = /^claude-(opus|sonnet|haiku|fable)-(\d{1,2})(?:-(\d{1,2}))?(?:-\d{8})?$/.exec(model);
70
+ return match ? `${match[1][0].toUpperCase()}${match[1].slice(1)} ${match[2]}${match[3] ? `.${match[3]}` : ''}` : model;
71
+ }
72
+ /** The model with the most output tokens, then the most responses; null when no response names one. */
73
+ function dominantModel(turns) {
74
+ const byModel = new Map();
75
+ for (const turn of turns) {
76
+ if (!turn.model)
77
+ continue;
78
+ const row = byModel.get(turn.model) ?? { output: 0, responses: 0 };
79
+ row.output += turn.outputTokens;
80
+ row.responses++;
81
+ byModel.set(turn.model, row);
82
+ }
83
+ 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;
84
+ }
85
+ /** A main model with a smaller Claude model below it, the one CLAUDE_CODE_SUBAGENT_MODEL=haiku names. */
86
+ const HAS_SMALLER_MODEL = /^claude-(?:opus|fable|sonnet)-/;
56
87
  /**
57
- * One next step from the session's own measured shares, first match wins; null
58
- * when nothing stands out, never a generic line. Fan-out and history compare
59
- * session tokens; rewrites compare list USD and are skipped when either figure
60
- * is unpriced. A dollar range compares midpoints, as the `rewrites` share does.
88
+ * The coach: one next step, for the largest cause that stands out in this
89
+ * session; null when none does, never a generic line. A cause stands out at the
90
+ * 0.3.16 thresholds: sub-agents at 20% of session tokens, full-prefix rewrites at
91
+ * 15% of the list total (priced sessions only), and the re-read conversation and
92
+ * the setup at 30% of session tokens each. Among those the largest at list price
93
+ * wins (a dollar range at its midpoint), or the largest in tokens when a model is
94
+ * unpriced; a tie keeps that order. Each action is Anthropic's published advice
95
+ * for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
96
+ * and every figure is this session's own. Where the cause has no sharper action,
97
+ * the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
98
+ * In the plugin context only the share tip's second sentence changes.
61
99
  */
62
- function whyTip(input, lang = 'en') {
63
- const { totalTokens, fanoutTokens, historyTokens, rewriteUsd, totalUsd } = input;
64
- const text = i18n_1.WHY_TEXT[lang];
65
- if (totalTokens > 0 && fanoutTokens / totalTokens >= 0.2)
66
- return text.tipFanout((0, exports.share)(fanoutTokens, totalTokens));
67
- if (rewriteUsd && totalUsd && midpoint(totalUsd) > 0 && midpoint(rewriteUsd) / midpoint(totalUsd) >= 0.15)
68
- return text.tipRewrites((0, live_1.dollars)(rewriteUsd, text), (0, live_1.dollars)(totalUsd, text));
69
- if (totalTokens > 0 && historyTokens / totalTokens >= 0.3)
70
- return text.tipHistory((0, exports.share)(historyTokens, totalTokens));
100
+ function whyTip(input, lang = 'en', context = 'why') {
101
+ const { totalTokens, totalUsd } = input, text = i18n_1.WHY_TEXT[lang];
102
+ const priced = totalUsd !== null && midpoint(totalUsd) > 0;
103
+ const tokenShare = (tokens) => totalTokens > 0 ? tokens / totalTokens : 0;
104
+ const { subagents, reloads, conversation, setup } = input;
105
+ const causes = [
106
+ ['subagents', tokenShare(subagents.tokens) >= 0.2, subagents],
107
+ ['reloads', priced && reloads.usd !== null && midpoint(reloads.usd) / midpoint(totalUsd) >= 0.15, reloads],
108
+ ['conversation', tokenShare(conversation.tokens) >= 0.3 && conversation.medianPerCall > 0, conversation],
109
+ ['setup', tokenShare(setup.tokens) >= 0.3 && setup.medianPerCall > 0, setup],
110
+ ];
111
+ let largest = null;
112
+ for (const [cause, standsOut, { tokens, usd }] of causes) {
113
+ const size = !standsOut ? null : priced ? (usd === null ? null : midpoint(usd)) : tokens;
114
+ if (size !== null && (largest === null || size > largest.size))
115
+ largest = { cause, size };
116
+ }
117
+ switch (largest?.cause) {
118
+ case 'subagents': {
119
+ const { mainModel, onMainModel = 0, onMainModelShare = 0 } = input.subagents;
120
+ return mainModel && onMainModel > 0 && onMainModelShare >= 0.5 && HAS_SMALLER_MODEL.test(mainModel)
121
+ ? text.tipSubagentModel(onMainModel, modelLabel(mainModel))
122
+ : (context === 'plugin' ? text.tipFanoutPlugin : text.tipFanout)((0, exports.share)(input.subagents.tokens, totalTokens));
123
+ }
124
+ case 'reloads': {
125
+ const { cause, count = 0, longestIdleMs = null } = input.reloads;
126
+ if (cause === 'idle_ttl_expired' && count > 0 && longestIdleMs !== null)
127
+ return text.tipIdleReloads(count, (0, attribution_1.idleLabel)(longestIdleMs));
128
+ if (cause === 'model_switch' && count > 0)
129
+ return text.tipModelSwitch(count);
130
+ return text.tipRewrites((0, live_1.dollars)(input.reloads.usd, text), (0, live_1.dollars)(totalUsd, text));
131
+ }
132
+ case 'conversation': return text.tipConversation((0, stop_text_1.shortTokens)(input.conversation.medianPerCall));
133
+ case 'setup': return text.tipSetup((0, stop_text_1.shortTokens)(input.setup.medianPerCall));
134
+ default: return null;
135
+ }
136
+ }
137
+ /**
138
+ * What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
139
+ * rows are the table's own. The setup and the re-read conversation split each
140
+ * main-conversation call's cached reads at the size of the session's first call,
141
+ * so a rewrite that resets the table's fixed-prefix baseline never turns re-read
142
+ * conversation into setup; they are measured, like every row, from recorded usage.
143
+ */
144
+ function whyTipInput(figures, rates = {}, bucketUsd) {
145
+ const { turns, attribution, totalUsd } = figures;
146
+ const byTurn = new Map(attribution.turnAttributions.map(turn => [turn.turnId, turn]));
147
+ const usdOf = bucketUsd ?? ((bucket) => sumPrices(turns.map(turn => bucketPrice(turn, byTurn.get(turn.id).buckets.find(item => item.bucket === bucket), rates))));
148
+ const tokensOf = (bucket) => attribution.buckets.find(item => item.bucket === bucket).tokens;
149
+ const main = turns.filter(turn => !turn.subagent);
150
+ // Sub-agents on the main conversation's model, and their share of all sub-agent tokens.
151
+ const mainModel = dominantModel(main);
152
+ const children = new Map();
153
+ for (const turn of turns) {
154
+ if (!turn.subagent)
155
+ continue;
156
+ const own = children.get(turn.sessionId);
157
+ if (own)
158
+ own.push(turn);
159
+ else
160
+ children.set(turn.sessionId, [turn]);
161
+ }
162
+ let childTokens = 0, onMainTokens = 0, onMainModel = 0;
163
+ for (const own of children.values()) {
164
+ const tokens = own.reduce((sum, turn) => sum + totalTokens(turn), 0);
165
+ childTokens += tokens;
166
+ if (mainModel !== null && dominantModel(own) === mainModel) {
167
+ onMainModel++;
168
+ onMainTokens += tokens;
169
+ }
170
+ }
171
+ // The rewrite cause with the largest cache-write list price, then the most rewrites, then precedence.
172
+ const byId = new Map(turns.map(turn => [turn.id, turn]));
173
+ const causes = new Map();
174
+ for (const rewrite of attribution.rewrites) {
175
+ const turn = byId.get(rewrite.turnId);
176
+ const price = turn ? (0, pricing_1.priceTurn)({ ...turn, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 }, rates).usd : null;
177
+ const row = causes.get(rewrite.cause) ?? { usd: 0, count: 0, longestIdleMs: null };
178
+ row.usd += price ? midpoint(price) : 0;
179
+ row.count++;
180
+ if (rewrite.idleMs !== undefined)
181
+ row.longestIdleMs = Math.max(row.longestIdleMs ?? 0, rewrite.idleMs);
182
+ causes.set(rewrite.cause, row);
183
+ }
184
+ 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];
185
+ // Setup and re-read conversation, split at the first call's context.
186
+ const rewritten = new Set(attribution.rewrites.map(rewrite => rewrite.turnId));
187
+ const baseline = main[0]?.contextTokens ?? 0;
188
+ const setup = { tokens: 0, usd: { min: 0, max: 0 }, perCall: [] };
189
+ const conversation = { tokens: 0, usd: { min: 0, max: 0 }, perCall: [] };
190
+ main.forEach((turn, index) => {
191
+ // The first call's whole context sets the baseline, as the table's first row does.
192
+ const opening = index === 0 && !rewritten.has(turn.id) && !turn.explicitAttribution.length;
193
+ const setupTokens = opening ? turn.inputTokens + turn.cacheWriteTokens + turn.cacheReadTokens : Math.min(turn.cacheReadTokens, baseline);
194
+ const conversationTokens = opening ? 0 : turn.cacheReadTokens - setupTokens;
195
+ const reads = (tokens) => (0, pricing_1.priceTurn)({ ...turn, inputTokens: 0, cacheWriteTokens: 0, cacheWrite5mTokens: undefined, cacheWrite1hTokens: undefined, outputTokens: 0, cacheReadTokens: tokens }, rates).usd;
196
+ setup.tokens += setupTokens;
197
+ setup.perCall.push(setupTokens);
198
+ setup.usd = sumPrices([setup.usd, opening ? (0, pricing_1.priceTurn)({ ...turn, outputTokens: 0 }, rates).usd : reads(setupTokens)]);
199
+ conversation.tokens += conversationTokens;
200
+ conversation.perCall.push(conversationTokens);
201
+ conversation.usd = sumPrices([conversation.usd, reads(conversationTokens)]);
202
+ });
203
+ return { totalTokens: attribution.totalTokens, totalUsd,
204
+ subagents: { tokens: tokensOf('subagent_fanout'), usd: usdOf('subagent_fanout'), mainModel, onMainModel, onMainModelShare: childTokens ? onMainTokens / childTokens : 0 },
205
+ reloads: { tokens: tokensOf('full_prefix_rewrites'), usd: usdOf('full_prefix_rewrites'), cause, count: top?.count ?? 0, longestIdleMs: top?.longestIdleMs ?? null },
206
+ conversation: { tokens: conversation.tokens, usd: conversation.usd, medianPerCall: median(conversation.perCall) },
207
+ setup: { tokens: setup.tokens, usd: setup.usd, medianPerCall: median(setup.perCall) } };
208
+ }
209
+ /** The one path from a session's figures to its tip: `renderWhy` prints this line and `whyTipLine` returns it. */
210
+ const figuresTip = (figures, rates, lang, context = 'why') => whyTip(whyTipInput(figures, rates), lang, context);
211
+ /**
212
+ * The tip line `why` ends with for this transcript, in the same words and with
213
+ * the same figures: null when nothing stands out, and for the unknown
214
+ * fork-history report, which prints no tip. The plugin context changes only
215
+ * the fan-out tip's second sentence. It does not read the quiet flag; the
216
+ * caller decides whether to show it.
217
+ */
218
+ function whyTipLine(transcript, rates = {}, lang = 'en', context = 'why') {
219
+ return transcript.state.forkHistoryBoundaryUnknown ? null : figuresTip(sessionFigures(transcript, rates), rates, lang, context);
220
+ }
221
+ /** Messages on each side of an event the measured change compares, at most and at least. */
222
+ exports.PROOF_WINDOW = 20;
223
+ exports.PROOF_MINIMUM = 5;
224
+ /**
225
+ * One measured change, around the latest compaction, /clear or model switch the
226
+ * main conversation's transcript records: the median tokens Claude read per
227
+ * message in the N messages after it against the N before it. N is 20, or fewer
228
+ * when the session, or the previous or next such event, leaves fewer on a side;
229
+ * below 5 on either side that event says nothing and an earlier one is tried.
230
+ * It states what was measured next to the event, never a saving and never that
231
+ * the event caused it.
232
+ */
233
+ function proofLine(turns, lang = 'en') {
234
+ const main = turns.filter(turn => !turn.subagent);
235
+ const events = [];
236
+ main.forEach((turn, index) => {
237
+ if (index === 0)
238
+ return;
239
+ const reset = turn.signals.reset;
240
+ if (reset)
241
+ events.push({ index, at: reset.at ?? turn.at,
242
+ event: { kind: reset.kind === 'clear' ? 'clear' : reset.trigger === 'manual' ? 'compact' : reset.trigger === 'auto' ? 'auto' : 'compaction' } });
243
+ else if (turn.signals.modelChanged && turn.model)
244
+ events.push({ index, at: turn.at, event: { kind: 'model', model: modelLabel(turn.model) } });
245
+ });
246
+ for (let e = events.length - 1; e >= 0; e--) {
247
+ const { index, at, event } = events[e];
248
+ const from = e > 0 ? events[e - 1].index : 0, to = e + 1 < events.length ? events[e + 1].index : main.length;
249
+ const messages = Math.min(exports.PROOF_WINDOW, index - from, to - index);
250
+ if (at === undefined || messages < exports.PROOF_MINIMUM)
251
+ continue;
252
+ const before = median(main.slice(index - messages, index).map(turn => turn.contextTokens));
253
+ const after = median(main.slice(index, index + messages).map(turn => turn.contextTokens));
254
+ const [printedAfter, printedBefore] = [(0, stop_text_1.shortTokens)(after), (0, stop_text_1.shortTokens)(before)];
255
+ const stamp = new Date(at).toISOString();
256
+ 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');
257
+ }
71
258
  return null;
72
259
  }
73
260
  /** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
@@ -80,7 +267,8 @@ function renderWhy(transcript, rates = {}, options = {}) {
80
267
  text.forkUnavailable,
81
268
  table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
82
269
  ].join('\n');
83
- const { turns, attribution, prices, totals, totalUsd } = sessionFigures(transcript, rates);
270
+ const figures = sessionFigures(transcript, rates);
271
+ const { turns, attribution, prices, totals, totalUsd } = figures;
84
272
  const lastAttribution = attribution.turnAttributions.at(-1);
85
273
  const byTurn = new Map(attribution.turnAttributions.map(turn => [turn.turnId, turn]));
86
274
  const mixedWriteAllocation = turns.some(turn => (turn.cacheWrite5mTokens ?? 0) > 0 && (turn.cacheWrite1hTokens ?? 0) > 0
@@ -92,8 +280,9 @@ function renderWhy(transcript, rates = {}, options = {}) {
92
280
  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
281
  });
94
282
  const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
95
- const tip = options.tips ? whyTip({ totalTokens: attribution.totalTokens, fanoutTokens: bucketTokens('subagent_fanout'),
96
- historyTokens: bucketTokens('history_resent'), rewriteUsd: bucketUsd('full_prefix_rewrites'), totalUsd }, lang) : null;
283
+ const tip = options.tips ? figuresTip(figures, rates, lang) : null;
284
+ // A measurement, not a tip: it prints whether or not tips are on.
285
+ const proof = proofLine(turns, lang);
97
286
  return [
98
287
  `AgentGuard why: ${transcript.sessionId}`,
99
288
  text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
@@ -109,6 +298,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
109
298
  ...(prices.some(price => price.unknownCacheWriteTokens > 0) ? [text.missingTtl] : []),
110
299
  ...(mixedWriteAllocation ? [text.mixedRanges] : []),
111
300
  text.diagnostics(transcript.diagnostics.duplicateUsageRecords, transcript.diagnostics.malformedLines),
301
+ ...(proof ? ['', proof] : []),
112
302
  ...(tip ? ['', tip, text.hide] : []),
113
303
  ].join('\n');
114
304
  }
@@ -0,0 +1,33 @@
1
+ import type { WhyLang } from './i18n';
2
+ import type { PricingTable } from './pricing';
3
+ import { type TipContext } from './render';
4
+ export type { TipContext };
5
+ export interface SessionTipOptions {
6
+ /** The AgentGuard home whose pricing overrides `why` uses: AGENTGUARD_HOME, else ~/.agentguard. */
7
+ home?: string;
8
+ /** Rates to price with instead of the home's. */
9
+ rates?: PricingTable;
10
+ /** The language, as `why --lang` takes it. English when not given. */
11
+ lang?: WhyLang;
12
+ /** Read files larger than this many bytes in pieces of this size (16 MB). The tip is the same; only memory changes. */
13
+ chunkBytes?: number;
14
+ /**
15
+ * Where the line is shown. 'why' (the default) is `why`'s own line. 'plugin'
16
+ * is for the AgentGuard plugin, whose users already run it: the fan-out tip
17
+ * ends with "Give related work to one sub-agent instead of several." instead
18
+ * of pointing to the plugin. Every other tip is the same in both.
19
+ */
20
+ context?: TipContext;
21
+ }
22
+ /**
23
+ * The "Next: ..." line `why <transcriptPath>` ends with, or null when nothing
24
+ * stands out. The transcript is read as `why` reads it: Codex when the path is
25
+ * a rollout, Claude Code otherwise, with every sub-agent transcript in the
26
+ * session's `subagents` folder, priced with the home's overrides. The words and
27
+ * figures come from the function `why` prints the tip with, so the two cannot
28
+ * differ. A long transcript is read in pieces cut at line ends, which gives the
29
+ * same turns as reading it whole and keeps it out of memory as one string. It
30
+ * ignores the quiet flag (the caller decides whether to show the line), writes
31
+ * nothing, and throws when the path is not a transcript file.
32
+ */
33
+ export declare function sessionTip(transcriptPath: string, options?: SessionTipOptions): string | null;