@trazum/cli 2.5.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -760,7 +760,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
760
760
  schema: [],
761
761
  rollup: ['json', 'html-out'],
762
762
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
763
- receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live'],
763
+ receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
764
764
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
765
765
  'from-otel': ['label-from-service', 'out', 'o'],
766
766
  'from-litellm': ['out', 'o'],
@@ -768,7 +768,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
768
768
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
769
769
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
770
770
  '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'],
771
+ 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
772
  'from-helicone': ['out', 'o'],
773
773
  'from-langsmith': ['out', 'o'],
774
774
  switch: ['to', 'migration-usd', 'cases'],
@@ -3316,6 +3316,57 @@ async function commandReconcile(args: Args, t: CliMessages): Promise<void> {
3316
3316
  if (billed.unreadableAmount > 0) console.error(t.reconcile.unreadableAmount(billed.unreadableAmount));
3317
3317
  }
3318
3318
 
3319
+ /**
3320
+ * The period a bill or a receipt covers, from `--since`/`--until`.
3321
+ *
3322
+ * `profile`'s window, read the same way: a UTC day, a timestamp, a relative
3323
+ * window or `now`; a bare day is the whole of it, and the window is half-open
3324
+ * underneath, so two adjacent periods share no call and add up to the whole.
3325
+ * Refused before any file is read: a bad date found after the receipt printed
3326
+ * would end a run that looked finished with an error. `words` is the window as
3327
+ * typed, for the documents to print, because rendering the internal exclusive
3328
+ * bound would name the day after the one asked for.
3329
+ */
3330
+ function billingPeriod(
3331
+ args: Args,
3332
+ t: CliMessages,
3333
+ ): { sinceMs?: number; untilMs?: number; relative: boolean; words?: { since: string; until: string } } {
3334
+ const now = Date.now();
3335
+ const since = parseWhen(args, 'since', false, t, now);
3336
+ const until = parseWhen(args, 'until', true, t, now);
3337
+ if (since.ms !== undefined && until.ms !== undefined && since.ms >= until.ms) {
3338
+ throw new Error(t.profile.sinceAfterUntil());
3339
+ }
3340
+ if (since.ms === undefined && until.ms === undefined) return { relative: false };
3341
+ return {
3342
+ ...(since.ms !== undefined ? { sinceMs: since.ms } : {}),
3343
+ ...(until.ms !== undefined ? { untilMs: until.ms } : {}),
3344
+ relative: since.relative || until.relative,
3345
+ words: { since: stringFlag(args, 'since') ?? '—', until: stringFlag(args, 'until') ?? '—' },
3346
+ };
3347
+ }
3348
+
3349
+ /**
3350
+ * A period with nothing in it is refused, never billed at $0: that reads as
3351
+ * "this month was free" when it means the dates missed the log. Said against
3352
+ * what was read, so the fix is in the message.
3353
+ */
3354
+ function refuseEmptyPeriod(
3355
+ text: string,
3356
+ report: UsageProfileReport,
3357
+ period: ReturnType<typeof billingPeriod>,
3358
+ pricing: PricingCatalogue,
3359
+ t: CliMessages,
3360
+ ): void {
3361
+ if (period.words === undefined || report.total.calls > 0 || report.unpriced.calls > 0) return;
3362
+ const whole = profileUsage(text, { catalogue: pricing });
3363
+ if (whole.total.calls === 0 && whole.unpriced.calls === 0) return;
3364
+ if (whole.span === null) throw new Error(t.profile.windowNeedsClock());
3365
+ throw new Error(
3366
+ `${t.bill.windowMatchesNothing(dayOf(whole.span.fromMs), dayOf(whole.span.toMs))}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`,
3367
+ );
3368
+ }
3369
+
3319
3370
  async function commandReceipt(
3320
3371
  args: Args,
3321
3372
  pricing: PricingCatalogue,
@@ -3323,9 +3374,15 @@ async function commandReceipt(
3323
3374
  ): Promise<void> {
3324
3375
  const file = args.positional[0];
3325
3376
  if (file === undefined) throw new Error(t.receipt.noLog());
3377
+ const period = billingPeriod(args, t);
3326
3378
 
3327
3379
  const text = await readUsageLog(file, t);
3328
- const report = profileUsage(text, { catalogue: pricing });
3380
+ const report = profileUsage(text, {
3381
+ catalogue: pricing,
3382
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3383
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3384
+ });
3385
+ refuseEmptyPeriod(text, report, period, pricing, t);
3329
3386
  const document = receiptFrom(
3330
3387
  report,
3331
3388
  pricing,
@@ -3362,6 +3419,7 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3362
3419
  if (gap.kind === 'unpriced') console.error(t.receipt.unpriced(gap.models.length, gap.calls));
3363
3420
  if (gap.kind === 'unread-lines') console.error(t.receipt.unread(gap.count));
3364
3421
  if (gap.kind === 'no-clock') console.error(t.receipt.noClock());
3422
+ if (gap.kind === 'undated-excluded') console.error(t.receipt.undatedExcluded(gap.calls));
3365
3423
  if (gap.kind === 'tier-ceiling') {
3366
3424
  console.error(
3367
3425
  t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)),
@@ -3429,6 +3487,9 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3429
3487
  /* Refused before any file is read: a bad shape found after the receipt
3430
3488
  printed would end a run that looked finished with an error. */
3431
3489
  const csvShape = csvShapeOf(args, t);
3490
+ /* "What did this month cost" is the question a Claude Code folder of a
3491
+ year's sessions answers worst without a period. */
3492
+ const period = billingPeriod(args, t);
3432
3493
 
3433
3494
  /*
3434
3495
  No path is the most common first run, and it used to be a refusal: the
@@ -3492,6 +3553,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3492
3553
  */
3493
3554
  const labelFromProject = boolFlag(args, 'label-from-project', true);
3494
3555
  let labelledByProject = 0;
3556
+ /* Claude Code transcripts read: their money is an API-rate equivalent. */
3557
+ let claudeCodeFiles = 0;
3495
3558
  const lines: string[] = [];
3496
3559
  let sources = 0;
3497
3560
  /*
@@ -3526,6 +3589,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3526
3589
  let leftOut = 0;
3527
3590
  switch (shape) {
3528
3591
  case 'claude-code': {
3592
+ claudeCodeFiles += 1;
3529
3593
  const project =
3530
3594
  label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
3531
3595
  if (project !== undefined && project !== '') labelledByProject += 1;
@@ -3604,7 +3668,13 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3604
3668
 
3605
3669
  if (sources === 0) throw new Error(t.bill.nothingRead());
3606
3670
 
3607
- const report = profileUsage(lines.join('\n'), { catalogue: pricing });
3671
+ const text = lines.join('\n');
3672
+ const report = profileUsage(text, {
3673
+ catalogue: pricing,
3674
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3675
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3676
+ });
3677
+ refuseEmptyPeriod(text, report, period, pricing, t);
3608
3678
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3609
3679
  const json = JSON.stringify(document, null, 2);
3610
3680
 
@@ -3627,8 +3697,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3627
3697
  }
3628
3698
  console.error(t.bill.sources(sources, files.length));
3629
3699
  printReceiptSummary(document, t);
3630
- if (statement) printBillStatement(report, labelledByProject > 0, t);
3631
- await writeBillSideFiles(args, report, pricing, csvShape, 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);
3632
3702
 
3633
3703
  /*
3634
3704
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3642,6 +3712,16 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3642
3712
  if (slugged.length > 0 && !boolFlag(args, 'pricing-live')) {
3643
3713
  console.error(t.bill.pricingLiveHint(slugged.length));
3644
3714
  }
3715
+ /*
3716
+ `xai/grok-4.3` is LiteLLM's way of saying "grok-4.3, called on xAI", and
3717
+ `anthropic/claude-sonnet-5-5` could be that or an OpenRouter route. The
3718
+ catalogue never strips a prefix by rule, because a router can bill the same
3719
+ model differently and an alias is a statement, never a derivation. What it
3720
+ can do is say which of these it prices under its own name, so the fix is
3721
+ one rename away rather than a guess made on the reader's behalf.
3722
+ */
3723
+ const priceableAfterSlash = slugged.filter((model) => pricing.byId.has(model.slice(model.lastIndexOf('/') + 1)));
3724
+ if (priceableAfterSlash.length > 0) console.error(t.bill.prefixedKnown(priceableAfterSlash.join(', ')));
3645
3725
  }
3646
3726
 
3647
3727
  /**
@@ -3679,7 +3759,13 @@ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: st
3679
3759
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3680
3760
  * here is computed that the receipt does not carry.
3681
3761
  */
3682
- function printBillStatement(report: UsageProfileReport, byProject: boolean, t: CliMessages): void {
3762
+ function printBillStatement(
3763
+ report: UsageProfileReport,
3764
+ byProject: boolean,
3765
+ t: CliMessages,
3766
+ window?: { since: string; until: string },
3767
+ apiEquivalent = false,
3768
+ ): void {
3683
3769
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
3684
3770
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
3685
3771
  const total = report.total.totalUsd;
@@ -3706,6 +3792,14 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3706
3792
  const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3707
3793
  console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3708
3794
  }
3795
+ // The period asked for, as typed: the span above is when the calls in it fell.
3796
+ if (window !== undefined) console.log(c.dim(` ${wrap(t.profile.windowLine(window.since, window.until), 74, ' ')}`));
3797
+ /*
3798
+ "Your bill" over Claude Code transcripts is the API's list price for the
3799
+ work. On a Pro or Max plan the plan is what was paid, and a statement that
3800
+ did not say so would hand somebody a figure they never owed.
3801
+ */
3802
+ if (apiEquivalent) console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3709
3803
 
3710
3804
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3711
3805
  if (labelled.length > 0) {
@@ -3727,6 +3821,44 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3727
3821
  for (const line of table(columns(t.bill.colModel()), rowsOf(entries))) console.log(line);
3728
3822
  }
3729
3823
 
3824
+ /*
3825
+ A year of Claude Code sessions billed in one total says what it all cost
3826
+ and not which month cost what, which is the next question. Summed from the
3827
+ report's own days, oldest first, newest kept when there are many; shown
3828
+ only once the bill spans two calendar months, since one month is the total.
3829
+ */
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 }]) => {
3840
+ const share = total > 0 ? usd / total : 0;
3841
+ return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3842
+ });
3843
+ if (ordered.length > LIMIT) shown.unshift([c.dim(t.bill.earlierMonths(ordered.length - LIMIT)), '', '', '']);
3844
+ console.log();
3845
+ 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)}`));
3859
+ }
3860
+ }
3861
+
3730
3862
  console.log();
3731
3863
  if (report.unpricedModels.length > 0) {
3732
3864
  console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
@@ -3734,6 +3866,9 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3734
3866
  const ceiling = tierCeilingLine(report, t);
3735
3867
  if (ceiling !== null) console.log(` ${wrap(ceiling, 74, ' ')}`);
3736
3868
  if (report.skippedLines.length > 0) console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
3869
+ if (report.timeWindow !== null && report.timeWindow.undatedExcluded > 0) {
3870
+ console.log(` ${c.yellow(wrap(t.receipt.undatedExcluded(report.timeWindow.undatedExcluded), 74, ' '))}`);
3871
+ }
3737
3872
  console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3738
3873
  console.log();
3739
3874
  }
@@ -3755,6 +3890,8 @@ async function writeBillSideFiles(
3755
3890
  pricing: PricingCatalogue,
3756
3891
  csvShape: ProfileCsvShape,
3757
3892
  t: CliMessages,
3893
+ window?: { since: string; until: string },
3894
+ apiEquivalent = false,
3758
3895
  ): Promise<void> {
3759
3896
  const markdownOut = stringFlag(args, 'markdown-out');
3760
3897
  const htmlOut = stringFlag(args, 'html-out');
@@ -3769,6 +3906,8 @@ async function writeBillSideFiles(
3769
3906
  levers: billLevers(report, { catalogue: pricing }),
3770
3907
  cache: cacheEconomics(report.total),
3771
3908
  t,
3909
+ ...(window !== undefined ? { window } : {}),
3910
+ ...(apiEquivalent ? { apiEquivalent } : {}),
3772
3911
  ...(ageDays !== null && ageDays > STALE_PRICING_DAYS ? { stalePricing: { date: reviewed, days: ageDays } } : {}),
3773
3912
  };
3774
3913
  if (markdownOut !== undefined) {
package/src/markdown.ts CHANGED
@@ -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);
@@ -1332,6 +1339,10 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1332
1339
  lines.push(`> ⚠️ ${mdText(t.profile.pricesStale(stalePricing.date, stalePricing.days))}`);
1333
1340
  lines.push('');
1334
1341
  }
1342
+ if (apiEquivalent === true) {
1343
+ lines.push(`> ⚠️ ${mdText(t.bill.apiEquivalent())}`);
1344
+ lines.push('');
1345
+ }
1335
1346
  if (report.unpricedModels.length > 0) {
1336
1347
  lines.push(`> ⚠️ ${mdText(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls))}`);
1337
1348
  lines.push('');
package/src/pdf.ts CHANGED
@@ -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
  }