@trazum/cli 2.5.0 → 2.5.2

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 (64) 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 +151 -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 +25 -2
  16. package/dist/html.js.map +1 -1
  17. package/dist/i18n/en.d.ts.map +1 -1
  18. package/dist/i18n/en.js +50 -6
  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 +51 -6
  22. package/dist/i18n/es.js.map +1 -1
  23. package/dist/i18n/types.d.ts +28 -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 +225 -41
  27. package/dist/index.js.map +1 -1
  28. package/dist/markdown.d.ts +7 -0
  29. package/dist/markdown.d.ts.map +1 -1
  30. package/dist/markdown.js +24 -2
  31. package/dist/markdown.js.map +1 -1
  32. package/dist/pdf.d.ts.map +1 -1
  33. package/dist/pdf.js +41 -2
  34. package/dist/pdf.js.map +1 -1
  35. package/dist/serve-savings-schema.d.ts +65 -0
  36. package/dist/serve-savings-schema.d.ts.map +1 -0
  37. package/dist/serve-savings-schema.js +54 -0
  38. package/dist/serve-savings-schema.js.map +1 -0
  39. package/dist/serve-savings.d.ts +55 -0
  40. package/dist/serve-savings.d.ts.map +1 -0
  41. package/dist/serve-savings.js +144 -0
  42. package/dist/serve-savings.js.map +1 -0
  43. package/dist/serve-schema.d.ts +536 -0
  44. package/dist/serve-schema.d.ts.map +1 -0
  45. package/dist/serve-schema.js +143 -0
  46. package/dist/serve-schema.js.map +1 -0
  47. package/dist/serve.d.ts.map +1 -1
  48. package/dist/serve.js +30 -5
  49. package/dist/serve.js.map +1 -1
  50. package/package.json +2 -2
  51. package/src/filter.ts +114 -0
  52. package/src/gateway-server.ts +46 -10
  53. package/src/gateway-spend.ts +120 -0
  54. package/src/html.ts +27 -2
  55. package/src/i18n/en.ts +57 -7
  56. package/src/i18n/es.ts +58 -7
  57. package/src/i18n/types.ts +29 -1
  58. package/src/index.ts +227 -43
  59. package/src/markdown.ts +32 -2
  60. package/src/pdf.ts +38 -2
  61. package/src/serve-savings-schema.ts +53 -0
  62. package/src/serve-savings.ts +140 -0
  63. package/src/serve-schema.ts +147 -0
  64. package/src/serve.ts +31 -5
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,7 @@ interface Args {
321
324
  }
322
325
 
323
326
  const VALUE_FLAGS = new Set([
327
+ 'recovery-dir',
324
328
  'answers',
325
329
  'label-by-cwd',
326
330
  'label-by-workspace',
@@ -733,6 +737,7 @@ function disabledRules(args: Args, config: TrazumConfig): RuleId[] | undefined {
733
737
  */
734
738
  const GLOBAL_FLAGS = ['help', 'h', 'version', 'v', 'locale', 'json', 'config', 'pricing', 'pricing-live', 'max-input'];
735
739
  const COMMAND_FLAGS: Record<string, string[]> = {
740
+ filter: ['recovery-dir'],
736
741
  optimize: [
737
742
  'level', 'model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch',
738
743
  'disable', 'llm', 'exact-tokens', 'diff', 'reorder', 'out', 'o',
@@ -760,7 +765,8 @@ const COMMAND_FLAGS: Record<string, string[]> = {
760
765
  schema: [],
761
766
  rollup: ['json', 'html-out'],
762
767
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
763
- receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live'],
768
+ receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
769
+ 'from-codex': ['label', 'out', 'o'],
764
770
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
765
771
  'from-otel': ['label-from-service', 'out', 'o'],
766
772
  'from-litellm': ['out', 'o'],
@@ -768,7 +774,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
768
774
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
769
775
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
770
776
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
771
- bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape'],
777
+ bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'since', 'until'],
772
778
  'from-helicone': ['out', 'o'],
773
779
  'from-langsmith': ['out', 'o'],
774
780
  switch: ['to', 'migration-usd', 'cases'],
@@ -1340,6 +1346,11 @@ function printMoney(
1340
1346
  * a measurable one, and it is the honest answer to "what did I gain" on a plan
1341
1347
  * that costs the same either way.
1342
1348
  */
1349
+ /** A conservative display default, never evidence of a payment arrangement. */
1350
+ function prefersTokenReport(host: HostEnvironment): boolean {
1351
+ return ['claude-code', 'codex', 'cursor'].includes(host.id);
1352
+ }
1353
+
1343
1354
  function printTokensOnly(
1344
1355
  result: OptimizationResult,
1345
1356
  host: HostEnvironment,
@@ -1353,15 +1364,10 @@ function printTokensOnly(
1353
1364
 
1354
1365
  console.log();
1355
1366
  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
1367
  console.log(
1360
- ` ${
1361
- host.billing === 'subscription'
1362
- ? t.report.tokensOnlyWhy(host.displayName)
1363
- : t.report.tokensOnlyAsked()
1364
- }`,
1368
+ ` ${prefersTokenReport(host)
1369
+ ? t.report.tokensOnlyWhy(host.displayName)
1370
+ : t.report.tokensOnlyAsked()}`,
1365
1371
  );
1366
1372
  console.log();
1367
1373
  console.log(` ${c.green(t.report.tokensSaved(n(saved)))}`);
@@ -1671,12 +1677,7 @@ async function commandWhere(
1671
1677
  console.log(
1672
1678
  ` ${host.displayName}${host.evidence ? c.dim(` (${host.evidence})`) : ''}`,
1673
1679
  );
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
- }
1680
+ console.log(` ${c.dim(t.where.billingUnknown(host.displayName))}`);
1680
1681
 
1681
1682
  const target = args.positional[0];
1682
1683
  if (target === undefined) {
@@ -1856,9 +1857,7 @@ function renderInit(proposal: InitProposal, ctx: InitRenderContext): void {
1856
1857
 
1857
1858
  // 1. Where this is running.
1858
1859
  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
- }
1860
+ console.log(` ${c.dim(t.where.billingUnknown(ctx.host.displayName))}`);
1862
1861
 
1863
1862
  // 2. The prompts.
1864
1863
  console.log(
@@ -3316,6 +3315,57 @@ async function commandReconcile(args: Args, t: CliMessages): Promise<void> {
3316
3315
  if (billed.unreadableAmount > 0) console.error(t.reconcile.unreadableAmount(billed.unreadableAmount));
3317
3316
  }
3318
3317
 
3318
+ /**
3319
+ * The period a bill or a receipt covers, from `--since`/`--until`.
3320
+ *
3321
+ * `profile`'s window, read the same way: a UTC day, a timestamp, a relative
3322
+ * window or `now`; a bare day is the whole of it, and the window is half-open
3323
+ * underneath, so two adjacent periods share no call and add up to the whole.
3324
+ * Refused before any file is read: a bad date found after the receipt printed
3325
+ * would end a run that looked finished with an error. `words` is the window as
3326
+ * typed, for the documents to print, because rendering the internal exclusive
3327
+ * bound would name the day after the one asked for.
3328
+ */
3329
+ function billingPeriod(
3330
+ args: Args,
3331
+ t: CliMessages,
3332
+ ): { sinceMs?: number; untilMs?: number; relative: boolean; words?: { since: string; until: string } } {
3333
+ const now = Date.now();
3334
+ const since = parseWhen(args, 'since', false, t, now);
3335
+ const until = parseWhen(args, 'until', true, t, now);
3336
+ if (since.ms !== undefined && until.ms !== undefined && since.ms >= until.ms) {
3337
+ throw new Error(t.profile.sinceAfterUntil());
3338
+ }
3339
+ if (since.ms === undefined && until.ms === undefined) return { relative: false };
3340
+ return {
3341
+ ...(since.ms !== undefined ? { sinceMs: since.ms } : {}),
3342
+ ...(until.ms !== undefined ? { untilMs: until.ms } : {}),
3343
+ relative: since.relative || until.relative,
3344
+ words: { since: stringFlag(args, 'since') ?? '—', until: stringFlag(args, 'until') ?? '—' },
3345
+ };
3346
+ }
3347
+
3348
+ /**
3349
+ * A period with nothing in it is refused, never billed at $0: that reads as
3350
+ * "this month was free" when it means the dates missed the log. Said against
3351
+ * what was read, so the fix is in the message.
3352
+ */
3353
+ function refuseEmptyPeriod(
3354
+ text: string,
3355
+ report: UsageProfileReport,
3356
+ period: ReturnType<typeof billingPeriod>,
3357
+ pricing: PricingCatalogue,
3358
+ t: CliMessages,
3359
+ ): void {
3360
+ if (period.words === undefined || report.total.calls > 0 || report.unpriced.calls > 0) return;
3361
+ const whole = profileUsage(text, { catalogue: pricing });
3362
+ if (whole.total.calls === 0 && whole.unpriced.calls === 0) return;
3363
+ if (whole.span === null) throw new Error(t.profile.windowNeedsClock());
3364
+ throw new Error(
3365
+ `${t.bill.windowMatchesNothing(dayOf(whole.span.fromMs), dayOf(whole.span.toMs))}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`,
3366
+ );
3367
+ }
3368
+
3319
3369
  async function commandReceipt(
3320
3370
  args: Args,
3321
3371
  pricing: PricingCatalogue,
@@ -3323,9 +3373,15 @@ async function commandReceipt(
3323
3373
  ): Promise<void> {
3324
3374
  const file = args.positional[0];
3325
3375
  if (file === undefined) throw new Error(t.receipt.noLog());
3376
+ const period = billingPeriod(args, t);
3326
3377
 
3327
3378
  const text = await readUsageLog(file, t);
3328
- const report = profileUsage(text, { catalogue: pricing });
3379
+ const report = profileUsage(text, {
3380
+ catalogue: pricing,
3381
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3382
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3383
+ });
3384
+ refuseEmptyPeriod(text, report, period, pricing, t);
3329
3385
  const document = receiptFrom(
3330
3386
  report,
3331
3387
  pricing,
@@ -3362,6 +3418,7 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3362
3418
  if (gap.kind === 'unpriced') console.error(t.receipt.unpriced(gap.models.length, gap.calls));
3363
3419
  if (gap.kind === 'unread-lines') console.error(t.receipt.unread(gap.count));
3364
3420
  if (gap.kind === 'no-clock') console.error(t.receipt.noClock());
3421
+ if (gap.kind === 'undated-excluded') console.error(t.receipt.undatedExcluded(gap.calls));
3365
3422
  if (gap.kind === 'tier-ceiling') {
3366
3423
  console.error(
3367
3424
  t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)),
@@ -3373,6 +3430,7 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3373
3430
  /** The shapes `bill` can tell apart from a file's own text. */
3374
3431
  type UsageSource =
3375
3432
  | 'claude-code'
3433
+ | 'codex'
3376
3434
  | 'otel'
3377
3435
  | 'litellm'
3378
3436
  | 'helicone'
@@ -3389,6 +3447,7 @@ type UsageSource =
3389
3447
  */
3390
3448
  function usageSourcesOf(text: string): UsageSource[] {
3391
3449
  const claims: UsageSource[] = [];
3450
+ if (looksLikeCodexTranscript(text)) claims.push('codex');
3392
3451
  if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3393
3452
  if (looksLikeOtel(text)) claims.push('otel');
3394
3453
  if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
@@ -3429,6 +3488,9 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3429
3488
  /* Refused before any file is read: a bad shape found after the receipt
3430
3489
  printed would end a run that looked finished with an error. */
3431
3490
  const csvShape = csvShapeOf(args, t);
3491
+ /* "What did this month cost" is the question a Claude Code folder of a
3492
+ year's sessions answers worst without a period. */
3493
+ const period = billingPeriod(args, t);
3432
3494
 
3433
3495
  /*
3434
3496
  No path is the most common first run, and it used to be a refusal: the
@@ -3492,6 +3554,10 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3492
3554
  */
3493
3555
  const labelFromProject = boolFlag(args, 'label-from-project', true);
3494
3556
  let labelledByProject = 0;
3557
+ /* Claude Code transcripts read: their money is an API-rate equivalent. */
3558
+ let claudeCodeFiles = 0;
3559
+ let codexFiles = 0;
3560
+ const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
3495
3561
  const lines: string[] = [];
3496
3562
  let sources = 0;
3497
3563
  /*
@@ -3525,7 +3591,21 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3525
3591
  let records: unknown[] = [];
3526
3592
  let leftOut = 0;
3527
3593
  switch (shape) {
3594
+ case 'codex': {
3595
+ codexFiles += 1;
3596
+ const c = codexRecords(text, withLabel);
3597
+ codexEvidence.files += 1;
3598
+ codexEvidence.duplicates += c.duplicates;
3599
+ codexEvidence.missingModel += c.missingModel;
3600
+ codexEvidence.unsupported += c.unsupported;
3601
+ codexEvidence.unparseable += c.unparseable;
3602
+ records = c.records;
3603
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
3604
+ if (leftOut > 0) console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
3605
+ break;
3606
+ }
3528
3607
  case 'claude-code': {
3608
+ claudeCodeFiles += 1;
3529
3609
  const project =
3530
3610
  label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
3531
3611
  if (project !== undefined && project !== '') labelledByProject += 1;
@@ -3604,9 +3684,19 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3604
3684
 
3605
3685
  if (sources === 0) throw new Error(t.bill.nothingRead());
3606
3686
 
3607
- const report = profileUsage(lines.join('\n'), { catalogue: pricing });
3687
+ const text = lines.join('\n');
3688
+ const report = profileUsage(text, {
3689
+ catalogue: pricing,
3690
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3691
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3692
+ });
3693
+ refuseEmptyPeriod(text, report, period, pricing, t);
3608
3694
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3609
- const json = JSON.stringify(document, null, 2);
3695
+ const billDocument = codexFiles === 0 ? document : {
3696
+ ...document,
3697
+ importEvidence: [{ ...codexEvidence, complete: codexEvidence.missingModel + codexEvidence.unsupported + codexEvidence.unparseable === 0 }],
3698
+ };
3699
+ const json = JSON.stringify(billDocument, null, 2);
3610
3700
 
3611
3701
  /*
3612
3702
  A terminal gets a statement a person can read; a pipe gets the receipt.
@@ -3627,8 +3717,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3627
3717
  }
3628
3718
  console.error(t.bill.sources(sources, files.length));
3629
3719
  printReceiptSummary(document, t);
3630
- if (statement) printBillStatement(report, labelledByProject > 0, t);
3631
- await writeBillSideFiles(args, report, pricing, csvShape, t);
3720
+ if (statement) printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3721
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles + codexFiles > 0);
3632
3722
 
3633
3723
  /*
3634
3724
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3642,6 +3732,16 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3642
3732
  if (slugged.length > 0 && !boolFlag(args, 'pricing-live')) {
3643
3733
  console.error(t.bill.pricingLiveHint(slugged.length));
3644
3734
  }
3735
+ /*
3736
+ `xai/grok-4.3` is LiteLLM's way of saying "grok-4.3, called on xAI", and
3737
+ `anthropic/claude-sonnet-5-5` could be that or an OpenRouter route. The
3738
+ catalogue never strips a prefix by rule, because a router can bill the same
3739
+ model differently and an alias is a statement, never a derivation. What it
3740
+ can do is say which of these it prices under its own name, so the fix is
3741
+ one rename away rather than a guess made on the reader's behalf.
3742
+ */
3743
+ const priceableAfterSlash = slugged.filter((model) => pricing.byId.has(model.slice(model.lastIndexOf('/') + 1)));
3744
+ if (priceableAfterSlash.length > 0) console.error(t.bill.prefixedKnown(priceableAfterSlash.join(', ')));
3645
3745
  }
3646
3746
 
3647
3747
  /**
@@ -3679,7 +3779,13 @@ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: st
3679
3779
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3680
3780
  * here is computed that the receipt does not carry.
3681
3781
  */
3682
- function printBillStatement(report: UsageProfileReport, byProject: boolean, t: CliMessages): void {
3782
+ function printBillStatement(
3783
+ report: UsageProfileReport,
3784
+ byProject: boolean,
3785
+ t: CliMessages,
3786
+ window?: { since: string; until: string },
3787
+ apiEquivalent = false,
3788
+ ): void {
3683
3789
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
3684
3790
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
3685
3791
  const total = report.total.totalUsd;
@@ -3706,6 +3812,14 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3706
3812
  const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3707
3813
  console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3708
3814
  }
3815
+ // The period asked for, as typed: the span above is when the calls in it fell.
3816
+ if (window !== undefined) console.log(c.dim(` ${wrap(t.profile.windowLine(window.since, window.until), 74, ' ')}`));
3817
+ /*
3818
+ "Your bill" over Claude Code transcripts is the API's list price for the
3819
+ work. On a Pro or Max plan the plan is what was paid, and a statement that
3820
+ did not say so would hand somebody a figure they never owed.
3821
+ */
3822
+ if (apiEquivalent) console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3709
3823
 
3710
3824
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3711
3825
  if (labelled.length > 0) {
@@ -3727,6 +3841,28 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3727
3841
  for (const line of table(columns(t.bill.colModel()), rowsOf(entries))) console.log(line);
3728
3842
  }
3729
3843
 
3844
+ /*
3845
+ A year of Claude Code sessions billed in one total says what it all cost
3846
+ and not which month cost what, which is the next question. Summed from the
3847
+ report's own days, oldest first, newest kept when there are many; shown
3848
+ only once the bill spans two calendar months, since one month is the total.
3849
+ */
3850
+ const { months, undated } = spendByMonth(report);
3851
+ if (months.length >= 2) {
3852
+ const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
3853
+ const share = total > 0 ? usd / total : 0;
3854
+ return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3855
+ });
3856
+ if (months.length > LIMIT) shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
3857
+ console.log();
3858
+ for (const line of table(columns(t.bill.colMonth()), shown)) console.log(line);
3859
+ if (undated.calls > 0) {
3860
+ console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
3861
+ }
3862
+ const newest = months[months.length - 1]!;
3863
+ console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
3864
+ }
3865
+
3730
3866
  console.log();
3731
3867
  if (report.unpricedModels.length > 0) {
3732
3868
  console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
@@ -3734,6 +3870,9 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3734
3870
  const ceiling = tierCeilingLine(report, t);
3735
3871
  if (ceiling !== null) console.log(` ${wrap(ceiling, 74, ' ')}`);
3736
3872
  if (report.skippedLines.length > 0) console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
3873
+ if (report.timeWindow !== null && report.timeWindow.undatedExcluded > 0) {
3874
+ console.log(` ${c.yellow(wrap(t.receipt.undatedExcluded(report.timeWindow.undatedExcluded), 74, ' '))}`);
3875
+ }
3737
3876
  console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3738
3877
  console.log();
3739
3878
  }
@@ -3755,6 +3894,8 @@ async function writeBillSideFiles(
3755
3894
  pricing: PricingCatalogue,
3756
3895
  csvShape: ProfileCsvShape,
3757
3896
  t: CliMessages,
3897
+ window?: { since: string; until: string },
3898
+ apiEquivalent = false,
3758
3899
  ): Promise<void> {
3759
3900
  const markdownOut = stringFlag(args, 'markdown-out');
3760
3901
  const htmlOut = stringFlag(args, 'html-out');
@@ -3769,6 +3910,8 @@ async function writeBillSideFiles(
3769
3910
  levers: billLevers(report, { catalogue: pricing }),
3770
3911
  cache: cacheEconomics(report.total),
3771
3912
  t,
3913
+ ...(window !== undefined ? { window } : {}),
3914
+ ...(apiEquivalent ? { apiEquivalent } : {}),
3772
3915
  ...(ageDays !== null && ageDays > STALE_PRICING_DAYS ? { stalePricing: { date: reviewed, days: ageDays } } : {}),
3773
3916
  };
3774
3917
  if (markdownOut !== undefined) {
@@ -3944,6 +4087,48 @@ function commandOwnrate(args: Args, t: CliMessages): void {
3944
4087
  console.log(JSON.stringify(snippet, null, 2));
3945
4088
  }
3946
4089
 
4090
+ /** Explicit paths only: Codex histories are not discovered from the user's home. */
4091
+ async function commandFromCodex(args: Args, t: CliMessages): Promise<void> {
4092
+ const target = args.positional[0];
4093
+ if (target === undefined) throw new Error(t.fromCodex.noPath());
4094
+ let info;
4095
+ try { info = await stat(target); } catch { throw new Error(t.fromCodex.notFound(target)); }
4096
+ const files = info.isDirectory()
4097
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
4098
+ .filter((entry) => entry.isFile() && /\.(jsonl|ndjson)$/i.test(entry.name))
4099
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
4100
+ : [target];
4101
+ if (files.length === 0) throw new Error(t.fromCodex.noFiles(target));
4102
+ const label = stringFlag(args, 'label');
4103
+ const lines: string[] = [];
4104
+ let duplicates = 0;
4105
+ let missingModel = 0;
4106
+ let unsupported = 0;
4107
+ let unparseable = 0;
4108
+ for (const file of files) {
4109
+ const text = await readFile(file, 'utf8');
4110
+ if (!looksLikeCodexTranscript(text)) { unsupported++; continue; }
4111
+ const conversion = codexRecords(text, label === undefined ? {} : { label });
4112
+ for (const record of conversion.records) lines.push(JSON.stringify(record));
4113
+ duplicates += conversion.duplicates;
4114
+ missingModel += conversion.missingModel;
4115
+ unsupported += conversion.unsupported;
4116
+ unparseable += conversion.unparseable;
4117
+ }
4118
+ console.error(t.fromCodex.summary(files.length, lines.length, duplicates));
4119
+ if (missingModel + unsupported + unparseable > 0) {
4120
+ console.error(t.fromCodex.gaps(missingModel, unsupported, unparseable));
4121
+ }
4122
+ console.error(t.fromCodex.caveat());
4123
+ if (lines.length === 0) throw new Error(t.fromCodex.noUsage());
4124
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
4125
+ const text = lines.join('\n') + '\n';
4126
+ if (out !== undefined) {
4127
+ await writeFile(out, text, 'utf8');
4128
+ console.error(t.fromCodex.written(out));
4129
+ } else console.log(text.trimEnd());
4130
+ }
4131
+
3947
4132
  async function commandFromOtel(args: Args, t: CliMessages): Promise<void> {
3948
4133
  const target = args.positional[0];
3949
4134
  if (target === undefined) throw new Error(t.fromOtel.noPath());
@@ -5163,12 +5348,13 @@ async function commandGateway(
5163
5348
  const position = budget.positions[0] ?? null;
5164
5349
 
5165
5350
  /**
5166
- * Read once at start, like `serve`'s.
5351
+ * Read the baseline once at start. The gateway adds its own completed
5352
+ * usage and reserves in-flight estimates in memory via `liveBudget`.
5167
5353
  *
5168
5354
  * A file read in the request path would put Trazum's own latency between a
5169
5355
  * caller and their provider on every call, which is a cost this product
5170
- * would otherwise be reporting on somebody else. The staleness is real, so a
5171
- * refusal carries `asOfMs` and says what it rested on.
5356
+ * would otherwise be reporting on somebody else. External spend is still
5357
+ * stale, so a refusal carries the baseline's `asOfMs`.
5172
5358
  */
5173
5359
  const standing: GatewayStanding | null =
5174
5360
  position === null || position.coverage === 'none'
@@ -5193,6 +5379,7 @@ async function commandGateway(
5193
5379
  */
5194
5380
  let unmeasured = 0;
5195
5381
  const server = buildGateway({
5382
+ liveBudget: true,
5196
5383
  provider,
5197
5384
  catalogue: pricing,
5198
5385
  policy: {
@@ -6957,24 +7144,12 @@ async function commandOptimize(
6957
7144
  return;
6958
7145
  }
6959
7146
 
6960
- // Tokens-only when the host bills by subscription: there is no bill to
6961
- // reduce, so a monthly figure would be arithmetic about tokens dressed as
6962
- // money. Either flag overrides it, because the host says where *Trazum* runs
6963
- // and not where the prompt goes — somebody editing a production prompt inside
6964
- // Cursor wants the dollars, and they should not have to leave the editor to
6965
- // see them.
7147
+ // Agent harnesses default to token context; their identity does not establish
7148
+ // billing. Explicit API-cost requests and usage-log scenarios retain pricing.
6966
7149
  const host = detectHost();
6967
- /**
6968
- * `--from-log` implies `--cost`, and the reasoning is different from the
6969
- * `--calls` case documented below: `--calls` is a typed scenario parameter,
6970
- * but a usage log with billed token counts is *evidence* — proof this
6971
- * prompt's traffic goes to a metered API, whatever the terminal running
6972
- * the command bills like. Withholding the money there would suppress
6973
- * exactly the figures the person measured in order to see.
6974
- */
6975
7150
  const tokensOnly = boolFlag(args, 'cost') || measured !== null
6976
7151
  ? false
6977
- : boolFlag(args, 'tokens-only') || host.billing === 'subscription';
7152
+ : boolFlag(args, 'tokens-only') || prefersTokenReport(host);
6978
7153
  /**
6979
7154
  * Whether they named a scenario while the money was being withheld.
6980
7155
  *
@@ -13332,6 +13507,12 @@ function printRank(
13332
13507
 
13333
13508
  async function main(): Promise<void> {
13334
13509
  const argv = process.argv.slice(2);
13510
+ // The stdin display filter has its own small grammar and no project config.
13511
+ if (argv[0] === 'filter') {
13512
+ const { runFilter } = await import('./filter.js');
13513
+ await runFilter(argv.slice(1));
13514
+ return;
13515
+ }
13335
13516
  let locale = localeFromArgv(argv);
13336
13517
  let t = getCliMessages(locale);
13337
13518
  const args = parseArgs(argv, t);
@@ -13543,6 +13724,9 @@ async function main(): Promise<void> {
13543
13724
  case 'reconcile':
13544
13725
  await commandReconcile(args, t);
13545
13726
  break;
13727
+ case 'from-codex':
13728
+ await commandFromCodex(args, t);
13729
+ break;
13546
13730
  case 'from-otel':
13547
13731
  await commandFromOtel(args, t);
13548
13732
  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
 
@@ -771,6 +771,13 @@ export interface ProfileMarkdownInput {
771
771
  * does not name its own size the way a skipped line does.
772
772
  */
773
773
  stalePricing?: { date: string; days: number };
774
+ /**
775
+ * Set when any of the calls came from Claude Code transcripts. Those are
776
+ * priced at the API's list rates, and somebody on a Pro or Max plan paid
777
+ * the plan instead: a document headed "bill" that does not say so would
778
+ * hand them a figure they never owed. Said among the caveats, every time.
779
+ */
780
+ apiEquivalent?: boolean;
774
781
  /**
775
782
  * The comparison, when `--against` was given — the section the terminal
776
783
  * has had since 1.11 and the markdown did not, so a CI summary reporting
@@ -817,7 +824,7 @@ export interface ProfileMarkdownInput {
817
824
  * reading CI instead of machines.
818
825
  */
819
826
  export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
820
- const { report, levers, cache, t, window, stalePricing, against, whatIf, pressure = [], gates, summary = false } = input;
827
+ const { report, levers, cache, t, window, stalePricing, apiEquivalent, against, whatIf, pressure = [], gates, summary = false } = input;
821
828
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
822
829
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
823
830
  const shares = sharesOf(report.total);
@@ -974,6 +981,25 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
974
981
  lines.push('');
975
982
  }
976
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
+
977
1003
  // The most expensive day against the median day, loud past twice it — the
978
1004
  // same sentence and the same yardstick the terminal prints.
979
1005
  if (report.spendByDay.length >= 2) {
@@ -1332,6 +1358,10 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1332
1358
  lines.push(`> ⚠️ ${mdText(t.profile.pricesStale(stalePricing.date, stalePricing.days))}`);
1333
1359
  lines.push('');
1334
1360
  }
1361
+ if (apiEquivalent === true) {
1362
+ lines.push(`> ⚠️ ${mdText(t.bill.apiEquivalent())}`);
1363
+ lines.push('');
1364
+ }
1335
1365
  if (report.unpricedModels.length > 0) {
1336
1366
  lines.push(`> ⚠️ ${mdText(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls))}`);
1337
1367
  lines.push('');
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';
@@ -49,7 +49,7 @@ export interface ProfilePdfOptions {
49
49
 
50
50
  /** The profile as one PDF. Same input as the HTML and Markdown doors. */
51
51
  export function renderProfilePdf(input: ProfileMarkdownInput, options: ProfilePdfOptions = {}): Uint8Array {
52
- const { report, levers, cache, t, gates, window, stalePricing } = input;
52
+ const { report, levers, cache, t, gates, window, stalePricing, apiEquivalent } = input;
53
53
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
54
54
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
55
55
  const showLabel = (label: string): string => (label === UNLABELLED ? t.profile.unlabelled() : label);
@@ -238,6 +238,7 @@ export function renderProfilePdf(input: ProfileMarkdownInput, options: ProfilePd
238
238
  }
239
239
  if (report.total.tierCeilingCalls > 0) caveats.push(tierCeilingCaveat(report, t));
240
240
  if (stalePricing !== undefined) caveats.push(t.profile.pricesStale(stalePricing.date, stalePricing.days));
241
+ if (apiEquivalent === true) caveats.push(t.bill.apiEquivalent());
241
242
  if (caveats.length > 0) {
242
243
  box(t.html.caveatsHeading(), caveats, { edge: CAVEAT_EDGE, fill: CAVEAT_FILL, ink: CAVEAT_INK }, true);
243
244
  }
@@ -258,6 +259,41 @@ export function renderProfilePdf(input: ProfileMarkdownInput, options: ProfilePd
258
259
  t.html.colModel(),
259
260
  );
260
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
+
261
297
  // The findings, as the sentences the terminal says.
262
298
  const findings: string[] = [];
263
299
  for (const lever of levers.slices.slice(0, 5)) {