@trazum/cli 2.5.1 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +75 -6
  2. package/dist/filter.d.ts +2 -0
  3. package/dist/filter.d.ts.map +1 -0
  4. package/dist/filter.js +187 -0
  5. package/dist/filter.js.map +1 -0
  6. package/dist/gateway-server.d.ts +2 -0
  7. package/dist/gateway-server.d.ts.map +1 -1
  8. package/dist/gateway-server.js +49 -9
  9. package/dist/gateway-server.js.map +1 -1
  10. package/dist/gateway-spend.d.ts +32 -0
  11. package/dist/gateway-spend.d.ts.map +1 -0
  12. package/dist/gateway-spend.js +116 -0
  13. package/dist/gateway-spend.js.map +1 -0
  14. package/dist/html.d.ts.map +1 -1
  15. package/dist/html.js +22 -1
  16. package/dist/html.js.map +1 -1
  17. package/dist/i18n/en.d.ts.map +1 -1
  18. package/dist/i18n/en.js +45 -3
  19. package/dist/i18n/en.js.map +1 -1
  20. package/dist/i18n/es.d.ts.map +1 -1
  21. package/dist/i18n/es.js +45 -3
  22. package/dist/i18n/es.js.map +1 -1
  23. package/dist/i18n/types.d.ts +13 -1
  24. package/dist/i18n/types.d.ts.map +1 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +125 -61
  27. package/dist/index.js.map +1 -1
  28. package/dist/markdown.d.ts.map +1 -1
  29. package/dist/markdown.js +19 -1
  30. package/dist/markdown.js.map +1 -1
  31. package/dist/pdf.d.ts.map +1 -1
  32. package/dist/pdf.js +38 -1
  33. package/dist/pdf.js.map +1 -1
  34. package/dist/serve-import-schema.d.ts +34 -0
  35. package/dist/serve-import-schema.d.ts.map +1 -0
  36. package/dist/serve-import-schema.js +31 -0
  37. package/dist/serve-import-schema.js.map +1 -0
  38. package/dist/serve-import.d.ts +43 -0
  39. package/dist/serve-import.d.ts.map +1 -0
  40. package/dist/serve-import.js +49 -0
  41. package/dist/serve-import.js.map +1 -0
  42. package/dist/serve-savings-schema.d.ts +65 -0
  43. package/dist/serve-savings-schema.d.ts.map +1 -0
  44. package/dist/serve-savings-schema.js +54 -0
  45. package/dist/serve-savings-schema.js.map +1 -0
  46. package/dist/serve-savings.d.ts +55 -0
  47. package/dist/serve-savings.d.ts.map +1 -0
  48. package/dist/serve-savings.js +144 -0
  49. package/dist/serve-savings.js.map +1 -0
  50. package/dist/serve-schema.d.ts +606 -0
  51. package/dist/serve-schema.d.ts.map +1 -0
  52. package/dist/serve-schema.js +151 -0
  53. package/dist/serve-schema.js.map +1 -0
  54. package/dist/serve.d.ts.map +1 -1
  55. package/dist/serve.js +37 -5
  56. package/dist/serve.js.map +1 -1
  57. package/dist/task-files.d.ts +9 -0
  58. package/dist/task-files.d.ts.map +1 -0
  59. package/dist/task-files.js +136 -0
  60. package/dist/task-files.js.map +1 -0
  61. package/dist/task.d.ts +2 -0
  62. package/dist/task.d.ts.map +1 -0
  63. package/dist/task.js +137 -0
  64. package/dist/task.js.map +1 -0
  65. package/package.json +2 -2
  66. package/src/filter.ts +150 -0
  67. package/src/gateway-server.ts +46 -10
  68. package/src/gateway-spend.ts +120 -0
  69. package/src/html.ts +25 -1
  70. package/src/i18n/en.ts +47 -4
  71. package/src/i18n/es.ts +47 -4
  72. package/src/i18n/types.ts +14 -1
  73. package/src/index.ts +115 -63
  74. package/src/markdown.ts +20 -1
  75. package/src/pdf.ts +36 -1
  76. package/src/serve-import-schema.ts +31 -0
  77. package/src/serve-import.ts +57 -0
  78. package/src/serve-savings-schema.ts +53 -0
  79. package/src/serve-savings.ts +140 -0
  80. package/src/serve-schema.ts +155 -0
  81. package/src/serve.ts +38 -5
  82. package/src/task-files.ts +114 -0
  83. package/src/task.ts +119 -0
package/src/i18n/es.ts CHANGED
@@ -50,6 +50,7 @@ ${bold('USO')}
50
50
  trazum bill [<fichero|dir>...] [--label <nombre>] [--no-label-from-project] [--receipt|--table] [--stamp] [-o <fichero>]
51
51
  [--since <cuándo>] [--until <cuándo>] [--pdf-out|--html-out|--markdown-out|--csv-out <fichero>]
52
52
  trazum from-claude-code <fichero|dir> [--label <nombre>] [-o <fichero>]
53
+ trazum from-codex <fichero|dir> [--label <nombre>] [-o <fichero>]
53
54
  trazum from-otel <fichero|dir> [--label-from-service] [-o <fichero>]
54
55
  trazum from-litellm <fichero|dir> [-o <fichero>]
55
56
  trazum from-anthropic <usage.json> [--label <name>] [--label-by-workspace <file>] [-o <file>]
@@ -74,6 +75,8 @@ ${bold('USO')}
74
75
  trazum owners <log>
75
76
  trazum ladder <log>
76
77
  trazum feedback
78
+ trazum filter compact|restore|instructions [--recovery-dir <directory>]
79
+ trazum task analyze|policy|apply|revert|compare [--help]
77
80
  trazum --version
78
81
 
79
82
  ${bold('OPCIONES DE init')}
@@ -344,6 +347,15 @@ ${bold('OPCIONES DE from-otel')}
344
347
  puede saber" en vez de uno inventado. Los spans que no son de LLM se cuentan
345
348
  y se omiten, dicho en stderr.
346
349
 
350
+ ${bold('OPCIONES DE from-codex')}
351
+ --label <nombre> Marca cada registro con una etiqueta.
352
+ -o, --out <fichero> Escribe el uso normalizado en vez de stdout.
353
+
354
+ Lee un archivo o directorio de Codex indicado explícitamente, en local.
355
+ Solo contadores corroborados: colapsa duplicados y excluye uso ambiguo.
356
+ Los huecos se indican en stderr. Los precios son equivalentes API,
357
+ nunca tu factura de suscripción. El contenido de prompts se descarta.
358
+
347
359
  ${bold('OPCIONES DE from-claude-code')}
348
360
  --label <nombre> Marca cada registro con una etiqueta.
349
361
  --label-from-project Etiqueta cada registro con el nombre del
@@ -421,6 +433,25 @@ ${bold('OPCIONES DE rules')}
421
433
  "Inerte" se dice siempre sobre el corpus. Una regla que no encuentra nada en
422
434
  estos ficheros no ha demostrado no encontrar nada en ninguna parte.
423
435
 
436
+ ${bold('OPCIONES DE task')}
437
+ --id <id> --type <tipo> Identifica una tarea y su tipo comparable.
438
+ --criterion <texto> Declara el criterio de aceptación antes del cambio.
439
+ --claude-code <archivo> Añade una sesión explícita de Claude Code; repetible.
440
+ --codex <archivo> Añade una sesión explícita de Codex; repetible.
441
+ --outcome <valor> accepted, rejected o unknown (por defecto unknown).
442
+ --assessor <etiqueta> Obligatorio para un resultado accepted o rejected.
443
+ --policy <id> baseline (por defecto) o repeat-review-v1.
444
+ --instructions <archivo> Archivo local existente para apply o revert.
445
+ -o, --out <archivo-nuevo> Crea un informe o política privados; no sobrescribe.
446
+ --json Los informes y comparaciones ya usan JSON por defecto.
447
+ Consulta task --help para analyze, policy, apply, revert y compare.
448
+ Máximo 400.000 caracteres entre fuentes. Nunca se infiere el éxito de la tarea.
449
+
450
+ ${bold('OPCIONES DE filter')}
451
+ --recovery-dir <directorio> Directorio privado; obligatorio para compact/restore.
452
+ --stats Solo compact: emite ahorro neto estimado en JSON por stderr.
453
+ trazum filter --help explica el filtro opcional (ayuda en inglés).
454
+
424
455
  ${bold('OPCIONES DE feedback')}
425
456
  (ninguna)
426
457
 
@@ -1353,7 +1384,7 @@ ${bold('EJEMPLOS')}
1353
1384
  diff: () => 'Diff',
1354
1385
  tokensOnlyHeading: (host) => `Qué ganas con esto en ${host}`,
1355
1386
  tokensOnlyWhy: (host) =>
1356
- `${host} cobra por suscripción, así que no hay factura que reducir ni cifra mensual que imprimir.`,
1387
+ `${host} identifica la herramienta, no tu forma de pago. Se muestran tokens por defecto; el ahorro en factura es desconocido.`,
1357
1388
  tokensOnlyAsked: () => 'Costes ocultos porque has pedido solo tokens.',
1358
1389
  tokensSaved: (tokens) =>
1359
1390
  `${tokens} token${tokens === '1' ? '' : 's'} de vuelta, en cada llamada.`,
@@ -1921,6 +1952,17 @@ ${bold('EJEMPLOS')}
1921
1952
  nothingToBill: () => 'Nada de este log se pudo precificar, así que el recibo no tiene líneas.',
1922
1953
  },
1923
1954
 
1955
+ fromCodex: {
1956
+ noPath: () => 'from-codex necesita una ruta explícita: trazum from-codex ./sesiones',
1957
+ notFound: (path) => `No se puede leer ${path}`,
1958
+ noFiles: (path) => `No hay archivos JSONL en ${path}`,
1959
+ noUsage: () => 'No hay uso de Codex atribuible. Revisa los huecos indicados; no se escribió un registro de coste cero.',
1960
+ summary: (files, records, duplicates) => `${files} archivo(s) Codex, ${records} registro(s) corroborados, ${duplicates} instantáneas repetidas descartadas.`,
1961
+ gaps: (missingModel, unsupported, unparseable) => `Huecos Codex: ${missingModel} sin contexto de modelo, ${unsupported} instantáneas no admitidas o sin corroborar, ${unparseable} líneas ilegibles. No son llamadas de coste cero.`,
1962
+ caveat: () => 'La telemetría Codex se valora a tarifas API del catálogo, no como factura de suscripción. Totales restaurados, reinicios y deltas ambiguos quedan excluidos.',
1963
+ written: (file) => `Registro normalizado escrito en ${file}`,
1964
+ },
1965
+
1924
1966
  fromOtel: {
1925
1967
  noPath: () => 'from-otel necesita un archivo o directorio OTLP: trazum from-otel spans.json',
1926
1968
  notFound: (path) => `${path}: no existe`,
@@ -2085,7 +2127,7 @@ ${bold('EJEMPLOS')}
2085
2127
  pricingLiveHint: (count) =>
2086
2128
  `${count} id(s) de modelo sin precio llevan prefijo de proveedor, como nombran los modelos OpenRouter y LiteLLM, y el catálogo incluido no los trae. Vuelve a ejecutar con --pricing-live para cobrar los slugs de OpenRouter desde su propia lista.`,
2087
2129
  apiEquivalent: () =>
2088
- 'Las transcripciones de Claude Code se cobran a las tarifas de la API de Anthropic. Con un plan Pro o Max pagaste el plan, no esto: léelo como lo que costaría el mismo trabajo a través de la API.',
2130
+ 'Las sesiones de Claude Code y Codex se valoran a tarifas API del catálogo. Si pagas una suscripción, pagaste el plan, no esta estimación equivalente; los datos ausentes y las tarifas propias pueden cambiar el resultado.',
2089
2131
  prefixedKnown: (ids) =>
2090
2132
  `${ids}: el modelo tras la barra tiene precio aquí con su propio nombre. El prefijo no se quita por ti, porque el mismo modelo a través de un router puede facturarse distinto. Si esas llamadas fueron directas al proveedor, registra el modelo sin el prefijo.`,
2091
2133
  windowMatchesNothing: (from, to) =>
@@ -2279,6 +2321,7 @@ ${bold('EJEMPLOS')}
2279
2321
  noSessions: () => 'Ningún registro traía sesión, así que el crecimiento de conversación y los costes por conversación no están en este informe.',
2280
2322
  byLabelHeading: () => 'Por carga de trabajo',
2281
2323
  byModelHeading: () => 'Por modelo',
2324
+ byMonthHeading: () => 'Por mes',
2282
2325
  findingsHeading: () => 'Qué movería esta factura',
2283
2326
  colLabel: () => 'carga',
2284
2327
  colModel: () => 'modelo',
@@ -2338,8 +2381,8 @@ ${bold('EJEMPLOS')}
2338
2381
 
2339
2382
  where: {
2340
2383
  hostHeading: () => 'Ejecutándose dentro de',
2341
- subscription: (host) =>
2342
- `${host} cobra por suscripción, no por token. Un ahorro mensual de los de abajo es aritmética sobre tokens, no dinero que recuperes: lo que ganas es margen de ventana de contexto y de rate limit.`,
2384
+ billingUnknown: (host) =>
2385
+ `${host} solo identifica el entorno de ejecución. La forma de pago es desconocida; los precios por token no demuestran ahorro en factura.`,
2343
2386
  noTarget: () => 'Pasa un fichero fuente para ver a qué proveedor van sus prompts.',
2344
2387
  sourceHeading: (path) => `Los prompts de ${path} van a`,
2345
2388
  conflict: () => 'No se puede saber: el fichero nombra más de un proveedor.',
package/src/i18n/types.ts CHANGED
@@ -625,6 +625,17 @@ export interface CliMessages {
625
625
  nothingToBill(): string;
626
626
  };
627
627
 
628
+ fromCodex: {
629
+ noPath(): string;
630
+ notFound(path: string): string;
631
+ noFiles(path: string): string;
632
+ noUsage(): string;
633
+ summary(files: number, records: number, duplicates: number): string;
634
+ gaps(missingModel: number, unsupported: number, unparseable: number): string;
635
+ caveat(): string;
636
+ written(file: string): string;
637
+ };
638
+
628
639
  fromOtel: {
629
640
  noPath(): string;
630
641
  notFound(path: string): string;
@@ -926,6 +937,8 @@ export interface CliMessages {
926
937
  noSessions(): string;
927
938
  byLabelHeading(): string;
928
939
  byModelHeading(): string;
940
+ /** Shown once a report spans two calendar months; the column is `bill.colMonth`. */
941
+ byMonthHeading(): string;
929
942
  findingsHeading(): string;
930
943
  colLabel(): string;
931
944
  colModel(): string;
@@ -977,7 +990,7 @@ export interface CliMessages {
977
990
 
978
991
  where: {
979
992
  hostHeading(): string;
980
- subscription(host: string): string;
993
+ billingUnknown(host: string): string;
981
994
  noTarget(): string;
982
995
  sourceHeading(path: string): string;
983
996
  conflict(): string;
package/src/index.ts CHANGED
@@ -114,6 +114,8 @@ import {
114
114
  parseUsageLine,
115
115
  plannedCalls,
116
116
  claudeCodeRecords,
117
+ codexRecords,
118
+ looksLikeCodexTranscript,
117
119
  type CwdLabel,
118
120
  type WorkspaceLabel,
119
121
  type ProjectLabel,
@@ -165,6 +167,7 @@ import {
165
167
  RULES,
166
168
  sharedPrefixes,
167
169
  sharesOf,
170
+ spendByMonth,
168
171
  isOffered,
169
172
  SOURCE_EXTENSIONS,
170
173
  suggestRewrites,
@@ -321,6 +324,8 @@ interface Args {
321
324
  }
322
325
 
323
326
  const VALUE_FLAGS = new Set([
327
+ 'id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions',
328
+ 'recovery-dir',
324
329
  'answers',
325
330
  'label-by-cwd',
326
331
  'label-by-workspace',
@@ -733,6 +738,8 @@ function disabledRules(args: Args, config: TrazumConfig): RuleId[] | undefined {
733
738
  */
734
739
  const GLOBAL_FLAGS = ['help', 'h', 'version', 'v', 'locale', 'json', 'config', 'pricing', 'pricing-live', 'max-input'];
735
740
  const COMMAND_FLAGS: Record<string, string[]> = {
741
+ task: ['id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions', 'out', 'o', 'json'],
742
+ filter: ['recovery-dir', 'stats'],
736
743
  optimize: [
737
744
  'level', 'model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch',
738
745
  'disable', 'llm', 'exact-tokens', 'diff', 'reorder', 'out', 'o',
@@ -761,6 +768,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
761
768
  rollup: ['json', 'html-out'],
762
769
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
763
770
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
771
+ 'from-codex': ['label', 'out', 'o'],
764
772
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
765
773
  'from-otel': ['label-from-service', 'out', 'o'],
766
774
  'from-litellm': ['out', 'o'],
@@ -1340,6 +1348,11 @@ function printMoney(
1340
1348
  * a measurable one, and it is the honest answer to "what did I gain" on a plan
1341
1349
  * that costs the same either way.
1342
1350
  */
1351
+ /** A conservative display default, never evidence of a payment arrangement. */
1352
+ function prefersTokenReport(host: HostEnvironment): boolean {
1353
+ return ['claude-code', 'codex', 'cursor'].includes(host.id);
1354
+ }
1355
+
1343
1356
  function printTokensOnly(
1344
1357
  result: OptimizationResult,
1345
1358
  host: HostEnvironment,
@@ -1353,15 +1366,10 @@ function printTokensOnly(
1353
1366
 
1354
1367
  console.log();
1355
1368
  console.log(sectionHeading(t.report.tokensOnlyHeading(host.displayName)));
1356
- // Only claim the host bills by subscription when it does. Forced with the
1357
- // flag on GitHub Actions, the first version said "GitHub Actions bills by
1358
- // subscription", which is simply false.
1359
1369
  console.log(
1360
- ` ${
1361
- host.billing === 'subscription'
1362
- ? t.report.tokensOnlyWhy(host.displayName)
1363
- : t.report.tokensOnlyAsked()
1364
- }`,
1370
+ ` ${prefersTokenReport(host)
1371
+ ? t.report.tokensOnlyWhy(host.displayName)
1372
+ : t.report.tokensOnlyAsked()}`,
1365
1373
  );
1366
1374
  console.log();
1367
1375
  console.log(` ${c.green(t.report.tokensSaved(n(saved)))}`);
@@ -1671,12 +1679,7 @@ async function commandWhere(
1671
1679
  console.log(
1672
1680
  ` ${host.displayName}${host.evidence ? c.dim(` (${host.evidence})`) : ''}`,
1673
1681
  );
1674
- // The reason this is worth printing at all. Inside a flat plan the monthly
1675
- // figure Trazum computes is arithmetic about tokens, not money anybody gets
1676
- // back, and saying so is more useful than saying nothing.
1677
- if (host.billing === 'subscription') {
1678
- console.log(` ${c.yellow(t.where.subscription(host.displayName))}`);
1679
- }
1682
+ console.log(` ${c.dim(t.where.billingUnknown(host.displayName))}`);
1680
1683
 
1681
1684
  const target = args.positional[0];
1682
1685
  if (target === undefined) {
@@ -1856,9 +1859,7 @@ function renderInit(proposal: InitProposal, ctx: InitRenderContext): void {
1856
1859
 
1857
1860
  // 1. Where this is running.
1858
1861
  console.log(` ${t.init.host(ctx.host.displayName)}`);
1859
- if (ctx.host.billing === 'subscription') {
1860
- console.log(` ${c.yellow(t.where.subscription(ctx.host.displayName))}`);
1861
- }
1862
+ console.log(` ${c.dim(t.where.billingUnknown(ctx.host.displayName))}`);
1862
1863
 
1863
1864
  // 2. The prompts.
1864
1865
  console.log(
@@ -3431,6 +3432,7 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3431
3432
  /** The shapes `bill` can tell apart from a file's own text. */
3432
3433
  type UsageSource =
3433
3434
  | 'claude-code'
3435
+ | 'codex'
3434
3436
  | 'otel'
3435
3437
  | 'litellm'
3436
3438
  | 'helicone'
@@ -3447,6 +3449,7 @@ type UsageSource =
3447
3449
  */
3448
3450
  function usageSourcesOf(text: string): UsageSource[] {
3449
3451
  const claims: UsageSource[] = [];
3452
+ if (looksLikeCodexTranscript(text)) claims.push('codex');
3450
3453
  if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3451
3454
  if (looksLikeOtel(text)) claims.push('otel');
3452
3455
  if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
@@ -3555,6 +3558,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3555
3558
  let labelledByProject = 0;
3556
3559
  /* Claude Code transcripts read: their money is an API-rate equivalent. */
3557
3560
  let claudeCodeFiles = 0;
3561
+ let codexFiles = 0;
3562
+ const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
3558
3563
  const lines: string[] = [];
3559
3564
  let sources = 0;
3560
3565
  /*
@@ -3588,6 +3593,19 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3588
3593
  let records: unknown[] = [];
3589
3594
  let leftOut = 0;
3590
3595
  switch (shape) {
3596
+ case 'codex': {
3597
+ codexFiles += 1;
3598
+ const c = codexRecords(text, withLabel);
3599
+ codexEvidence.files += 1;
3600
+ codexEvidence.duplicates += c.duplicates;
3601
+ codexEvidence.missingModel += c.missingModel;
3602
+ codexEvidence.unsupported += c.unsupported;
3603
+ codexEvidence.unparseable += c.unparseable;
3604
+ records = c.records;
3605
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
3606
+ if (leftOut > 0) console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
3607
+ break;
3608
+ }
3591
3609
  case 'claude-code': {
3592
3610
  claudeCodeFiles += 1;
3593
3611
  const project =
@@ -3676,7 +3694,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3676
3694
  });
3677
3695
  refuseEmptyPeriod(text, report, period, pricing, t);
3678
3696
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3679
- const json = JSON.stringify(document, null, 2);
3697
+ const billDocument = codexFiles === 0 ? document : {
3698
+ ...document,
3699
+ importEvidence: [{ ...codexEvidence, complete: codexEvidence.missingModel + codexEvidence.unsupported + codexEvidence.unparseable === 0 }],
3700
+ };
3701
+ const json = JSON.stringify(billDocument, null, 2);
3680
3702
 
3681
3703
  /*
3682
3704
  A terminal gets a statement a person can read; a pipe gets the receipt.
@@ -3697,8 +3719,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3697
3719
  }
3698
3720
  console.error(t.bill.sources(sources, files.length));
3699
3721
  printReceiptSummary(document, t);
3700
- if (statement) printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles > 0);
3701
- await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles > 0);
3722
+ if (statement) printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3723
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles + codexFiles > 0);
3702
3724
 
3703
3725
  /*
3704
3726
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3827,36 +3849,20 @@ function printBillStatement(
3827
3849
  report's own days, oldest first, newest kept when there are many; shown
3828
3850
  only once the bill spans two calendar months, since one month is the total.
3829
3851
  */
3830
- const months = new Map<string, { calls: number; usd: number }>();
3831
- for (const day of report.spendByDay) {
3832
- const month = months.get(day.day.slice(0, 7)) ?? { calls: 0, usd: 0 };
3833
- month.calls += day.calls;
3834
- month.usd += day.usd;
3835
- months.set(day.day.slice(0, 7), month);
3836
- }
3837
- if (months.size >= 2) {
3838
- const ordered = [...months.entries()].sort(([a], [b]) => a.localeCompare(b));
3839
- const shown = ordered.slice(-LIMIT).map(([name, { calls, usd }]) => {
3852
+ const { months, undated } = spendByMonth(report);
3853
+ if (months.length >= 2) {
3854
+ const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
3840
3855
  const share = total > 0 ? usd / total : 0;
3841
- return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3856
+ return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3842
3857
  });
3843
- if (ordered.length > LIMIT) shown.unshift([c.dim(t.bill.earlierMonths(ordered.length - LIMIT)), '', '', '']);
3858
+ if (months.length > LIMIT) shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
3844
3859
  console.log();
3845
3860
  for (const line of table(columns(t.bill.colMonth()), shown)) console.log(line);
3846
- const dated = ordered.reduce((sum, [, month]) => ({ calls: sum.calls + month.calls, usd: sum.usd + month.usd }), {
3847
- calls: 0,
3848
- usd: 0,
3849
- });
3850
- const undatedCalls = report.total.calls - dated.calls;
3851
- if (undatedCalls > 0) {
3852
- console.log(c.dim(` ${wrap(t.bill.monthsUndated(undatedCalls, formatUsd(total - dated.usd)), 74, ' ')}`));
3853
- }
3854
- const newest = ordered[ordered.length - 1]?.[0];
3855
- if (newest !== undefined) {
3856
- const [year, month] = newest.split('-').map(Number);
3857
- const lastDay = new Date(Date.UTC(year ?? 1970, month ?? 1, 0)).toISOString().slice(0, 10);
3858
- console.log(c.dim(` ${t.bill.monthHint(`${newest}-01`, lastDay)}`));
3861
+ if (undated.calls > 0) {
3862
+ console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
3859
3863
  }
3864
+ const newest = months[months.length - 1]!;
3865
+ console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
3860
3866
  }
3861
3867
 
3862
3868
  console.log();
@@ -4083,6 +4089,48 @@ function commandOwnrate(args: Args, t: CliMessages): void {
4083
4089
  console.log(JSON.stringify(snippet, null, 2));
4084
4090
  }
4085
4091
 
4092
+ /** Explicit paths only: Codex histories are not discovered from the user's home. */
4093
+ async function commandFromCodex(args: Args, t: CliMessages): Promise<void> {
4094
+ const target = args.positional[0];
4095
+ if (target === undefined) throw new Error(t.fromCodex.noPath());
4096
+ let info;
4097
+ try { info = await stat(target); } catch { throw new Error(t.fromCodex.notFound(target)); }
4098
+ const files = info.isDirectory()
4099
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
4100
+ .filter((entry) => entry.isFile() && /\.(jsonl|ndjson)$/i.test(entry.name))
4101
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
4102
+ : [target];
4103
+ if (files.length === 0) throw new Error(t.fromCodex.noFiles(target));
4104
+ const label = stringFlag(args, 'label');
4105
+ const lines: string[] = [];
4106
+ let duplicates = 0;
4107
+ let missingModel = 0;
4108
+ let unsupported = 0;
4109
+ let unparseable = 0;
4110
+ for (const file of files) {
4111
+ const text = await readFile(file, 'utf8');
4112
+ if (!looksLikeCodexTranscript(text)) { unsupported++; continue; }
4113
+ const conversion = codexRecords(text, label === undefined ? {} : { label });
4114
+ for (const record of conversion.records) lines.push(JSON.stringify(record));
4115
+ duplicates += conversion.duplicates;
4116
+ missingModel += conversion.missingModel;
4117
+ unsupported += conversion.unsupported;
4118
+ unparseable += conversion.unparseable;
4119
+ }
4120
+ console.error(t.fromCodex.summary(files.length, lines.length, duplicates));
4121
+ if (missingModel + unsupported + unparseable > 0) {
4122
+ console.error(t.fromCodex.gaps(missingModel, unsupported, unparseable));
4123
+ }
4124
+ console.error(t.fromCodex.caveat());
4125
+ if (lines.length === 0) throw new Error(t.fromCodex.noUsage());
4126
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
4127
+ const text = lines.join('\n') + '\n';
4128
+ if (out !== undefined) {
4129
+ await writeFile(out, text, 'utf8');
4130
+ console.error(t.fromCodex.written(out));
4131
+ } else console.log(text.trimEnd());
4132
+ }
4133
+
4086
4134
  async function commandFromOtel(args: Args, t: CliMessages): Promise<void> {
4087
4135
  const target = args.positional[0];
4088
4136
  if (target === undefined) throw new Error(t.fromOtel.noPath());
@@ -5302,12 +5350,13 @@ async function commandGateway(
5302
5350
  const position = budget.positions[0] ?? null;
5303
5351
 
5304
5352
  /**
5305
- * Read once at start, like `serve`'s.
5353
+ * Read the baseline once at start. The gateway adds its own completed
5354
+ * usage and reserves in-flight estimates in memory via `liveBudget`.
5306
5355
  *
5307
5356
  * A file read in the request path would put Trazum's own latency between a
5308
5357
  * caller and their provider on every call, which is a cost this product
5309
- * would otherwise be reporting on somebody else. The staleness is real, so a
5310
- * refusal carries `asOfMs` and says what it rested on.
5358
+ * would otherwise be reporting on somebody else. External spend is still
5359
+ * stale, so a refusal carries the baseline's `asOfMs`.
5311
5360
  */
5312
5361
  const standing: GatewayStanding | null =
5313
5362
  position === null || position.coverage === 'none'
@@ -5332,6 +5381,7 @@ async function commandGateway(
5332
5381
  */
5333
5382
  let unmeasured = 0;
5334
5383
  const server = buildGateway({
5384
+ liveBudget: true,
5335
5385
  provider,
5336
5386
  catalogue: pricing,
5337
5387
  policy: {
@@ -7096,24 +7146,12 @@ async function commandOptimize(
7096
7146
  return;
7097
7147
  }
7098
7148
 
7099
- // Tokens-only when the host bills by subscription: there is no bill to
7100
- // reduce, so a monthly figure would be arithmetic about tokens dressed as
7101
- // money. Either flag overrides it, because the host says where *Trazum* runs
7102
- // and not where the prompt goes — somebody editing a production prompt inside
7103
- // Cursor wants the dollars, and they should not have to leave the editor to
7104
- // see them.
7149
+ // Agent harnesses default to token context; their identity does not establish
7150
+ // billing. Explicit API-cost requests and usage-log scenarios retain pricing.
7105
7151
  const host = detectHost();
7106
- /**
7107
- * `--from-log` implies `--cost`, and the reasoning is different from the
7108
- * `--calls` case documented below: `--calls` is a typed scenario parameter,
7109
- * but a usage log with billed token counts is *evidence* — proof this
7110
- * prompt's traffic goes to a metered API, whatever the terminal running
7111
- * the command bills like. Withholding the money there would suppress
7112
- * exactly the figures the person measured in order to see.
7113
- */
7114
7152
  const tokensOnly = boolFlag(args, 'cost') || measured !== null
7115
7153
  ? false
7116
- : boolFlag(args, 'tokens-only') || host.billing === 'subscription';
7154
+ : boolFlag(args, 'tokens-only') || prefersTokenReport(host);
7117
7155
  /**
7118
7156
  * Whether they named a scenario while the money was being withheld.
7119
7157
  *
@@ -13471,6 +13509,17 @@ function printRank(
13471
13509
 
13472
13510
  async function main(): Promise<void> {
13473
13511
  const argv = process.argv.slice(2);
13512
+ if (argv[0] === 'task') {
13513
+ const { runTask } = await import('./task.js');
13514
+ await runTask(argv.slice(1));
13515
+ return;
13516
+ }
13517
+ // The stdin display filter has its own small grammar and no project config.
13518
+ if (argv[0] === 'filter') {
13519
+ const { runFilter } = await import('./filter.js');
13520
+ await runFilter(argv.slice(1));
13521
+ return;
13522
+ }
13474
13523
  let locale = localeFromArgv(argv);
13475
13524
  let t = getCliMessages(locale);
13476
13525
  const args = parseArgs(argv, t);
@@ -13682,6 +13731,9 @@ async function main(): Promise<void> {
13682
13731
  case 'reconcile':
13683
13732
  await commandReconcile(args, t);
13684
13733
  break;
13734
+ case 'from-codex':
13735
+ await commandFromCodex(args, t);
13736
+ break;
13685
13737
  case 'from-otel':
13686
13738
  await commandFromOtel(args, t);
13687
13739
  break;
package/src/markdown.ts CHANGED
@@ -8,7 +8,7 @@ import type {
8
8
  PromptProfile,
9
9
  RuleLevel,
10
10
  } from '@trazum/core';
11
- import { UNLABELLED, formatSignedUsd, formatUsd, getMessages, getModel, sharesOf } from '@trazum/core';
11
+ import { UNLABELLED, formatSignedUsd, formatUsd, getMessages, getModel, sharesOf, spendByMonth } from '@trazum/core';
12
12
  import { dayOf, formatGap, median, spanDays } from './time.js';
13
13
  import type { AgainstDriver, BillLevers, CacheEconomics, ContextPressure, RepriceReport, UsageProfileReport } from '@trazum/core';
14
14
 
@@ -981,6 +981,25 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
981
981
  lines.push('');
982
982
  }
983
983
 
984
+ // By month, once the report spans two, every month and the undated part
985
+ // said under it — the same rows as the HTML and PDF doors.
986
+ const { months, undated } = spendByMonth(report);
987
+ if (months.length >= 2) {
988
+ lines.push(`#### ${t.html.byMonthHeading()}`);
989
+ lines.push('');
990
+ lines.push(`| ${t.bill.colMonth()} | ${t.html.colCalls()} | USD | % |`);
991
+ lines.push('|---|---:|---:|---:|');
992
+ for (const { month, calls, usd } of months) {
993
+ const share = report.total.totalUsd > 0 ? pct(usd / report.total.totalUsd) : '—';
994
+ lines.push(`| ${month} | ${n(calls)} | ${formatUsd(usd)} | ${share} |`);
995
+ }
996
+ lines.push('');
997
+ if (undated.calls > 0) {
998
+ lines.push(`_${mdText(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)))}_`);
999
+ lines.push('');
1000
+ }
1001
+ }
1002
+
984
1003
  // The most expensive day against the median day, loud past twice it — the
985
1004
  // same sentence and the same yardstick the terminal prints.
986
1005
  if (report.spendByDay.length >= 2) {
package/src/pdf.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PdfDocument, UNLABELLED, formatUsd, pdfFit, pdfWrap, sharesOf } from '@trazum/core';
1
+ import { PdfDocument, UNLABELLED, formatUsd, pdfFit, pdfWrap, sharesOf, spendByMonth } from '@trazum/core';
2
2
  import type { PdfColor, PdfFont, UsageBreakdown } from '@trazum/core';
3
3
  import { tierCeilingCaveat } from './markdown.js';
4
4
  import type { ProfileMarkdownInput } from './markdown.js';
@@ -259,6 +259,41 @@ export function renderProfilePdf(input: ProfileMarkdownInput, options: ProfilePd
259
259
  t.html.colModel(),
260
260
  );
261
261
 
262
+ // By month, every month, as in the HTML door: a page has the room.
263
+ const { months, undated } = spendByMonth(report);
264
+ if (months.length >= 2) {
265
+ heading(t.html.byMonthHeading());
266
+ const size = 7.5;
267
+ const rowHeight = 13;
268
+ const figureWidth = 70;
269
+ const columns = [t.html.colCalls(), 'USD', '%'];
270
+ const nameWidth = width - figureWidth * columns.length;
271
+ const right = (column: number): number => MARGIN + nameWidth + figureWidth * (column + 1) - 4;
272
+ const header = (): void => {
273
+ doc.text(MARGIN + 4, y + 9, pdfFit(t.bill.colMonth(), 'bold', size, nameWidth - 8), { font: 'bold', size, color: INK });
274
+ columns.forEach((column, i) => {
275
+ doc.textRight(right(i), y + 9, pdfFit(column, 'bold', size, figureWidth - 6), { font: 'bold', size, color: INK });
276
+ });
277
+ y += rowHeight;
278
+ doc.line(MARGIN, y, MARGIN + width, y, { color: RULE, width: 1.25 });
279
+ y += 2;
280
+ };
281
+ need(rowHeight * 3);
282
+ header();
283
+ months.forEach(({ month, calls, usd }, index) => {
284
+ if (need(rowHeight)) header();
285
+ if (index % 2 === 1) doc.rect(MARGIN, y, width, rowHeight, { fill: ZEBRA });
286
+ const share = report.total.totalUsd > 0 ? pct(usd / report.total.totalUsd) : '—';
287
+ doc.text(MARGIN + 4, y + 9, month, { size, color: INK });
288
+ [n(calls), formatUsd(usd), share].forEach((cell, i) => {
289
+ doc.textRight(right(i), y + 9, pdfFit(cell, 'regular', size, figureWidth - 6), { size, color: INK });
290
+ });
291
+ y += rowHeight;
292
+ });
293
+ y += 6;
294
+ if (undated.calls > 0) paragraph(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 'regular', 9, MUTED);
295
+ }
296
+
262
297
  // The findings, as the sentences the terminal says.
263
298
  const findings: string[] = [];
264
299
  for (const lever of levers.slices.slice(0, 5)) {
@@ -0,0 +1,31 @@
1
+ const object = (properties: Record<string, unknown>) => ({
2
+ type: 'object', properties, required: Object.keys(properties), additionalProperties: false,
3
+ });
4
+ const count = { type: 'integer', minimum: 0 };
5
+ const counters = (names: string[]) => Object.fromEntries(names.map((name) => [name, count]));
6
+ const common = {
7
+ schemaVersion: { const: 1 }, log: { type: 'string' }, records: count,
8
+ evidence: object({ billingMode: { const: 'unknown' }, valuation: { const: 'api-equivalent' }, completeness: { const: 'not-established' } }),
9
+ limitations: { type: 'array', items: { type: 'string' } },
10
+ };
11
+
12
+ export const IMPORT_SCHEMAS = {
13
+ UsageImportRequest: {
14
+ type: 'object', required: ['format', 'text'], additionalProperties: false,
15
+ properties: {
16
+ format: { type: 'string', enum: ['claude-code', 'codex'] },
17
+ text: { type: 'string', minLength: 1, description: 'Non-blank transcript JSONL contents, never a path. No automatic format detection or shared deduplication state.' },
18
+ label: { type: 'string', minLength: 1, maxLength: 200, description: 'Optional explicit, non-blank workload label; limited to 200 UTF-16 code units. Never inferred from source metadata.' },
19
+ },
20
+ },
21
+ UsageImportAnswer: {
22
+ description: 'Complete JSON response is limited to 1,000,000 UTF-8 bytes. Empty output does not establish zero usage. Preserve diagnostics alongside downstream reports.',
23
+ oneOf: [
24
+ object({ ...common, format: { const: 'codex' }, diagnostics: object(counters(['duplicates', 'unparseable', 'missingModel', 'unsupported', 'otherLines'])) }),
25
+ object({ ...common, format: { const: 'claude-code' }, diagnostics: object({
26
+ ...counters(['collapsed', 'noRequestId', 'otherLines', 'unparseable', 'assistantWithoutUsage', 'streamed', 'disagreements', 'synthetic']),
27
+ resume: object({ line: count, records: count }),
28
+ }) }),
29
+ ],
30
+ },
31
+ };
@@ -0,0 +1,57 @@
1
+ import { claudeCodeRecords, codexRecords } from '@trazum/core';
2
+
3
+ /** Bound the complete serialized answer, including JSON escaping and repeated labels. */
4
+ export const MAX_IMPORT_RESPONSE_BYTES = 1_000_000;
5
+
6
+ interface ImportPayload {
7
+ format: 'claude-code' | 'codex';
8
+ text: string;
9
+ label?: string;
10
+ }
11
+
12
+ export function validateImportPayload(value: unknown): asserts value is ImportPayload {
13
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
14
+ throw new Error('The body must be a JSON object.');
15
+ }
16
+ const payload = value as Record<string, unknown>;
17
+ if (Object.keys(payload).some((key) => !['format', 'text', 'label'].includes(key))) {
18
+ throw new Error('Unknown properties are not accepted for usage imports.');
19
+ }
20
+ if (payload.format !== 'claude-code' && payload.format !== 'codex') {
21
+ throw new Error('format must be claude-code or codex.');
22
+ }
23
+ if (typeof payload.text !== 'string' || payload.text.trim() === '') {
24
+ throw new Error('text must be non-empty transcript contents, not a file path.');
25
+ }
26
+ if (payload.label !== undefined && (typeof payload.label !== 'string' ||
27
+ payload.label.trim() === '' || payload.label.length > 200)) {
28
+ throw new Error('label must be non-empty text of at most 200 characters.');
29
+ }
30
+ }
31
+
32
+ /** Explicit text only: no filesystem, measurement lookup or provider access. */
33
+ export function importUsage(payload: ImportPayload) {
34
+ const options = payload.label === undefined ? {} : { label: payload.label };
35
+ const conversion = payload.format === 'codex'
36
+ ? codexRecords(payload.text, options) : claudeCodeRecords(payload.text, options);
37
+ const { records, ...diagnostics } = conversion;
38
+ const result = {
39
+ schemaVersion: 1 as const,
40
+ format: payload.format,
41
+ log: records.map((record) => JSON.stringify(record)).join('\n'),
42
+ records: records.length,
43
+ diagnostics,
44
+ evidence: { billingMode: 'unknown', valuation: 'api-equivalent', completeness: 'not-established' },
45
+ limitations: [
46
+ 'Conversion diagnostics describe the supplied text only; missing source events and missing files cannot be detected.',
47
+ 'Usage priced downstream is API-equivalent, not a subscription invoice or proof of realized savings.',
48
+ 'No deduplication state is shared between calls. Do not concatenate overlapping imports.',
49
+ 'Session identifiers are retained. Prompt, tool, cwd and path content is not copied; labels are caller supplied.',
50
+ 'Empty output means no convertible records, not zero usage or zero cost. Preserve these diagnostics alongside downstream reports.',
51
+ ],
52
+ };
53
+ if (Buffer.byteLength(JSON.stringify(result), 'utf8') > MAX_IMPORT_RESPONSE_BYTES) {
54
+ throw new Error(`Normalized import response exceeds ${MAX_IMPORT_RESPONSE_BYTES} UTF-8 bytes; use a smaller complete source or a shorter label.`);
55
+ }
56
+ return result;
57
+ }