@trazum/cli 2.4.3 → 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/i18n/types.ts CHANGED
@@ -137,6 +137,8 @@ export interface CliMessages {
137
137
  * tool when the answer ships under the same scope is a worse refusal than
138
138
  * the one it replaced.
139
139
  */
140
+ /** The optional counter is installed and has no rank table for this model. */
141
+ exactTokensNoEncoding(model: string, packageName: string, known: string): string;
140
142
  exactTokensNeedsPackage(model: string, packageName: string): string;
141
143
  checkNeedsMaxTokens(): string;
142
144
  evalNeedsCases(): string;
@@ -618,6 +620,8 @@ export interface CliMessages {
618
620
  unpriced(models: number, calls: number): string;
619
621
  unread(count: number): string;
620
622
  noClock(): string;
623
+ /** Calls a --since/--until window left out because they carry no timestamp. */
624
+ undatedExcluded(calls: number): string;
621
625
  nothingToBill(): string;
622
626
  };
623
627
 
@@ -710,6 +714,8 @@ export interface CliMessages {
710
714
  tierUnknown(): string;
711
715
  /** Rows reduced to their text part; audio and image tokens set aside. */
712
716
  mixed(rows: number, tokens: number, cacheWrites: number): string;
717
+ /** 12-hour cache writes: in the prompt total at the plain input rate, a floor. */
718
+ cacheWrite12h(tokens: number): string;
713
719
  /** Mixed rows the report gave no text split for, refused whole. */
714
720
  unsplit(count: number): string;
715
721
  truncated(): string;
@@ -743,6 +749,13 @@ export interface CliMessages {
743
749
  colCalls(): string;
744
750
  colShare(): string;
745
751
  moreRows(count: number): string;
752
+ /** The by-month table, shown when a bill spans two calendar months or more. */
753
+ colMonth(): string;
754
+ earlierMonths(count: number): string;
755
+ /** Priced calls with no timestamp: in the total, in no month. */
756
+ monthsUndated(calls: number, usd: string): string;
757
+ /** How to bill the newest month on its own. */
758
+ monthHint(since: string, until: string): string;
746
759
  statementUnpriced(models: string, calls: number): string;
747
760
  statementUnread(lines: number): string;
748
761
  statementNext(): string;
@@ -760,6 +773,12 @@ export interface CliMessages {
760
773
  sources(read: number, seen: number): string;
761
774
  /** An unpriced slug with a slash is OpenRouter's, and --pricing-live prices it. */
762
775
  pricingLiveHint(count: number): string;
776
+ /** Prefixed ids whose part after the slash the catalogue prices under its own name. */
777
+ prefixedKnown(ids: string): string;
778
+ /** Claude Code transcripts are priced at API list rates; on a plan, that is not what was paid. */
779
+ apiEquivalent(): string;
780
+ /** A --since/--until window no record falls in: refused, never a $0 bill. */
781
+ windowMatchesNothing(from: string, to: string): string;
763
782
  written(file: string): string;
764
783
  };
765
784
 
@@ -1498,6 +1517,12 @@ export interface CliMessages {
1498
1517
  truncationRetryNote(): string;
1499
1518
  inputFullRate(): string;
1500
1519
  assumedWriteTtl(calls: number): string;
1520
+ /**
1521
+ * Rows billed at the dearer of two rates: a model priced by prompt length,
1522
+ * and rows that sum requests without giving one prompt's length. The total
1523
+ * is a ceiling on them, and the cheaper figure is printed beside it.
1524
+ */
1525
+ tierCeiling(rows: number, models: string, ceiling: string, floor: string): string;
1501
1526
  /**
1502
1527
  * The period the log covers, when its records carry a clock. Stated and
1503
1528
  * never extrapolated: naming the span makes the reader's own monthly
@@ -1516,6 +1541,8 @@ export interface CliMessages {
1516
1541
  */
1517
1542
  ttlFitExpires(label: string, model: string, gap: string): string;
1518
1543
  ttlFitExpiresBoth(label: string, model: string, gap: string): string;
1544
+ /** A provider that sells one kind of entry: there is no longer TTL to suggest. */
1545
+ ttlFitExpiresOnly(label: string, model: string, gap: string, ttl: string): string;
1519
1546
  ttlFitOverlong(label: string, model: string, gap: string, usd: string): string;
1520
1547
  ttlFitUnsettledGap(label: string, model: string, gap: string): string;
1521
1548
  ttlFitFits(label: string, model: string, gap: string): string;
@@ -1747,6 +1774,8 @@ export interface CliMessages {
1747
1774
  * summed with the move.
1748
1775
  */
1749
1776
  whatIfBatchOnTarget(batched: string, moved: string): string;
1777
+ /** The target is priced by prompt length and some slices could not be placed in a band. */
1778
+ whatIfTierCeiling(slices: number, target: string, floor: string): string;
1750
1779
  whatIfCacheBeyond(largest: string, min: string, noCache: string): string;
1751
1780
  whatIfSlice(label: string, model: string, current: string, target: string): string;
1752
1781
  /** A call the target's context window could not have accepted. */
package/src/index.ts CHANGED
@@ -170,7 +170,6 @@ import {
170
170
  suggestRewrites,
171
171
  toOtlpMetrics,
172
172
  toPromptfoo,
173
- TTL_1H_MS,
174
173
  UNLABELLED,
175
174
  withExactTokenCounts,
176
175
  } from '@trazum/core';
@@ -285,6 +284,7 @@ import {
285
284
  renderDiffMarkdown,
286
285
  renderRankMarkdown,
287
286
  renderProfileMarkdown,
287
+ tierCeilingCaveat,
288
288
  } from './markdown.js';
289
289
  import type { ProfileMarkdownInput } from './markdown.js';
290
290
  import { renderPositionHtml, renderProfileHtml, renderRollupHtml } from './html.js';
@@ -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,12 @@ 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));
3423
+ if (gap.kind === 'tier-ceiling') {
3424
+ console.error(
3425
+ t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)),
3426
+ );
3427
+ }
3365
3428
  }
3366
3429
  }
3367
3430
 
@@ -3424,6 +3487,9 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3424
3487
  /* Refused before any file is read: a bad shape found after the receipt
3425
3488
  printed would end a run that looked finished with an error. */
3426
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);
3427
3493
 
3428
3494
  /*
3429
3495
  No path is the most common first run, and it used to be a refusal: the
@@ -3487,6 +3553,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3487
3553
  */
3488
3554
  const labelFromProject = boolFlag(args, 'label-from-project', true);
3489
3555
  let labelledByProject = 0;
3556
+ /* Claude Code transcripts read: their money is an API-rate equivalent. */
3557
+ let claudeCodeFiles = 0;
3490
3558
  const lines: string[] = [];
3491
3559
  let sources = 0;
3492
3560
  /*
@@ -3521,6 +3589,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3521
3589
  let leftOut = 0;
3522
3590
  switch (shape) {
3523
3591
  case 'claude-code': {
3592
+ claudeCodeFiles += 1;
3524
3593
  const project =
3525
3594
  label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
3526
3595
  if (project !== undefined && project !== '') labelledByProject += 1;
@@ -3599,7 +3668,13 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3599
3668
 
3600
3669
  if (sources === 0) throw new Error(t.bill.nothingRead());
3601
3670
 
3602
- 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);
3603
3678
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3604
3679
  const json = JSON.stringify(document, null, 2);
3605
3680
 
@@ -3622,8 +3697,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3622
3697
  }
3623
3698
  console.error(t.bill.sources(sources, files.length));
3624
3699
  printReceiptSummary(document, t);
3625
- if (statement) printBillStatement(report, labelledByProject > 0, t);
3626
- 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);
3627
3702
 
3628
3703
  /*
3629
3704
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3637,6 +3712,16 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3637
3712
  if (slugged.length > 0 && !boolFlag(args, 'pricing-live')) {
3638
3713
  console.error(t.bill.pricingLiveHint(slugged.length));
3639
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(', ')));
3640
3725
  }
3641
3726
 
3642
3727
  /**
@@ -3674,7 +3759,13 @@ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: st
3674
3759
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3675
3760
  * here is computed that the receipt does not carry.
3676
3761
  */
3677
- 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 {
3678
3769
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
3679
3770
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
3680
3771
  const total = report.total.totalUsd;
@@ -3701,6 +3792,14 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3701
3792
  const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3702
3793
  console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3703
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, ' '))}`);
3704
3803
 
3705
3804
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3706
3805
  if (labelled.length > 0) {
@@ -3722,11 +3821,54 @@ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: C
3722
3821
  for (const line of table(columns(t.bill.colModel()), rowsOf(entries))) console.log(line);
3723
3822
  }
3724
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
+
3725
3862
  console.log();
3726
3863
  if (report.unpricedModels.length > 0) {
3727
3864
  console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
3728
3865
  }
3866
+ const ceiling = tierCeilingLine(report, t);
3867
+ if (ceiling !== null) console.log(` ${wrap(ceiling, 74, ' ')}`);
3729
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
+ }
3730
3872
  console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3731
3873
  console.log();
3732
3874
  }
@@ -3748,6 +3890,8 @@ async function writeBillSideFiles(
3748
3890
  pricing: PricingCatalogue,
3749
3891
  csvShape: ProfileCsvShape,
3750
3892
  t: CliMessages,
3893
+ window?: { since: string; until: string },
3894
+ apiEquivalent = false,
3751
3895
  ): Promise<void> {
3752
3896
  const markdownOut = stringFlag(args, 'markdown-out');
3753
3897
  const htmlOut = stringFlag(args, 'html-out');
@@ -3762,6 +3906,8 @@ async function writeBillSideFiles(
3762
3906
  levers: billLevers(report, { catalogue: pricing }),
3763
3907
  cache: cacheEconomics(report.total),
3764
3908
  t,
3909
+ ...(window !== undefined ? { window } : {}),
3910
+ ...(apiEquivalent ? { apiEquivalent } : {}),
3765
3911
  ...(ageDays !== null && ageDays > STALE_PRICING_DAYS ? { stalePricing: { date: reviewed, days: ageDays } } : {}),
3766
3912
  };
3767
3913
  if (markdownOut !== undefined) {
@@ -4277,6 +4423,7 @@ async function commandFromOpenai(args: Args, t: CliMessages): Promise<void> {
4277
4423
  if (conversion.mixedRows > 0) {
4278
4424
  console.error(t.fromOpenai.mixed(conversion.mixedRows, conversion.nonTextTokens, conversion.cacheWriteUnplaced));
4279
4425
  }
4426
+ if (conversion.cacheWrite12hTokens > 0) console.error(t.fromOpenai.cacheWrite12h(conversion.cacheWrite12hTokens));
4280
4427
  if (conversion.unsplitRows > 0) console.error(t.fromOpenai.unsplit(conversion.unsplitRows));
4281
4428
  if (conversion.labelledByProject > 0) console.error(t.fromOpenai.labelledByProject(conversion.labelledByProject));
4282
4429
  if (conversion.unruledProject > 0) console.error(t.fromOpenai.unruledProject(conversion.unruledProject));
@@ -6493,7 +6640,13 @@ interface LocalCounter {
6493
6640
  * did not opt in, and turning it into a crash would make an optional dependency
6494
6641
  * a required one by accident.
6495
6642
  */
6496
- async function localCounterFor(model: string): Promise<LocalCounter | null> {
6643
+ /**
6644
+ * A counter, or why there is none: `null` when the package is not installed,
6645
+ * `{ refused }` when it is and holds no table for this model. Two refusals,
6646
+ * because they send a reader to different places: one to `npm install`, the
6647
+ * other nowhere, since installing what is already installed fixes nothing.
6648
+ */
6649
+ async function localCounterFor(model: string): Promise<LocalCounter | { refused: readonly string[] } | null> {
6497
6650
  let loaded: OptionalCounterModule;
6498
6651
  try {
6499
6652
  /*
@@ -6514,7 +6667,7 @@ async function localCounterFor(model: string): Promise<LocalCounter | null> {
6514
6667
  }
6515
6668
 
6516
6669
  const result = await loaded.openaiCounter(model);
6517
- if (!result.ok) return null;
6670
+ if (!result.ok) return { refused: result.refusal.known };
6518
6671
  return {
6519
6672
  count: result.count,
6520
6673
  counter: 'openai-tiktoken',
@@ -6831,7 +6984,9 @@ async function commandOptimize(
6831
6984
  * the network at all. A prompt counted here is read in this process and
6832
6985
  * goes nowhere, which is the distinction `TokenProvenance.where` carries.
6833
6986
  */
6834
- const local = await localCounterFor(result.usage.model);
6987
+ const found = await localCounterFor(result.usage.model);
6988
+ const local = found !== null && !('refused' in found) ? found : null;
6989
+ const refusedEncodings = found !== null && 'refused' in found ? found.refused : null;
6835
6990
  if (local !== null) {
6836
6991
  result = await withExactTokenCounts(
6837
6992
  result,
@@ -6870,7 +7025,9 @@ async function commandOptimize(
6870
7025
  throw new Error(
6871
7026
  offered === undefined
6872
7027
  ? t.errors.exactTokensWrongFamily(result.usage.model, priced?.provider ?? null)
6873
- : t.errors.exactTokensNeedsPackage(result.usage.model, offered),
7028
+ : refusedEncodings !== null
7029
+ ? t.errors.exactTokensNoEncoding(result.usage.model, offered, refusedEncodings.join(', '))
7030
+ : t.errors.exactTokensNeedsPackage(result.usage.model, offered),
6874
7031
  );
6875
7032
  }
6876
7033
  const apiKey = process.env.ANTHROPIC_API_KEY;
@@ -8081,6 +8238,19 @@ async function commandConnect(
8081
8238
  out.push(md ? `- ${line}` : `! ${line}`);
8082
8239
  }
8083
8240
 
8241
+ /* A bucket sums requests, so a model priced by prompt length is a range. */
8242
+ const ceilinged = report.byModel.filter((slice) => slice.tierCeilingBuckets > 0);
8243
+ if (ceilinged.length > 0) {
8244
+ out.push('');
8245
+ const line = t.profile.tierCeiling(
8246
+ ceilinged.reduce((sum, slice) => sum + slice.tierCeilingBuckets, 0),
8247
+ ceilinged.map((slice) => slice.model).join(', '),
8248
+ formatUsd(ceilinged.reduce((sum, slice) => sum + slice.tierCeilingUsd, 0)),
8249
+ formatUsd(ceilinged.reduce((sum, slice) => sum + slice.tierFloorUsd, 0)),
8250
+ );
8251
+ out.push(md ? `- ${line}` : `! ${line}`);
8252
+ }
8253
+
8084
8254
  if (report.gaps.length > 0) out.push('');
8085
8255
  for (const gap of report.gaps) {
8086
8256
  const line = t.connect.gap(gap.detail);
@@ -10150,6 +10320,11 @@ function reportWhatIf(
10150
10320
  * adding two savings, and hedged the only honest way — whether these
10151
10321
  * calls can wait is not in the log.
10152
10322
  */
10323
+ if (whatIf.tierCeiling !== null) {
10324
+ console.log(
10325
+ ` ${c.yellow('!')} ${wrap(t.profile.whatIfTierCeiling(whatIf.tierCeiling.slices, whatIf.target.displayName, formatUsd(whatIf.tierCeiling.targetFloorUsd)), 74, ' ')}`,
10326
+ );
10327
+ }
10153
10328
  if (whatIf.batchOnTarget !== null) {
10154
10329
  console.log(
10155
10330
  ` ${c.dim(wrap(t.profile.whatIfBatchOnTarget(formatUsd(whatIf.batchOnTarget.targetUsd), formatUsd(whatIf.targetUsd)), 74, ' '))}`,
@@ -10425,10 +10600,13 @@ async function reportLabelsBudgetsAndCache(
10425
10600
  const name = fit.label === UNLABELLED ? t.profile.unlabelled() : fit.label;
10426
10601
  const gap = formatGap(fit.medianGapMs);
10427
10602
  if (fit.verdict === 'expires-before-reuse') {
10603
+ // The model's own entries: one kind on OpenAI, two on Anthropic.
10428
10604
  const line =
10429
- fit.medianGapMs > TTL_1H_MS
10430
- ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
10431
- : t.profile.ttlFitExpires(name, fit.modelName, gap);
10605
+ fit.longerTtlMs === null
10606
+ ? t.profile.ttlFitExpiresOnly(name, fit.modelName, gap, formatGap(fit.entryTtlMs))
10607
+ : fit.medianGapMs > fit.longerTtlMs
10608
+ ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
10609
+ : t.profile.ttlFitExpires(name, fit.modelName, gap);
10432
10610
  console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
10433
10611
  } else if (fit.verdict === 'overlong-ttl') {
10434
10612
  console.log(
@@ -10529,6 +10707,11 @@ async function reportLabelsBudgetsAndCache(
10529
10707
  }
10530
10708
  }
10531
10709
 
10710
+ /** The ceiling caveat for a report, or `null` when nothing was billed at one. */
10711
+ function tierCeilingLine(report: UsageProfileReport, t: CliMessages): string | null {
10712
+ return report.total.tierCeilingCalls === 0 ? null : tierCeilingCaveat(report, t);
10713
+ }
10714
+
10532
10715
  /**
10533
10716
  * What caching did to this bill, and what it is about to do.
10534
10717
  *
@@ -11485,6 +11668,15 @@ function reportProfileGaps(
11485
11668
  ` ${c.yellow('!')} ${c.dim(wrap(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' '))}`,
11486
11669
  );
11487
11670
  }
11671
+ /*
11672
+ * A total that billed summed rows at the dearer rate is a ceiling, said with
11673
+ * the other end beside it: the range is the finding, not the doubt.
11674
+ */
11675
+ const ceiling = tierCeilingLine(report, t);
11676
+ if (ceiling !== null) {
11677
+ console.log();
11678
+ console.log(` ${c.yellow('!')} ${wrap(ceiling, 74, ' ')}`);
11679
+ }
11488
11680
  if (report.skippedLines.length > 0) {
11489
11681
  const shown = report.skippedLines.slice(0, 5).join(', ');
11490
11682
  console.log(
package/src/markdown.ts CHANGED
@@ -8,7 +8,7 @@ import type {
8
8
  PromptProfile,
9
9
  RuleLevel,
10
10
  } from '@trazum/core';
11
- import { TTL_1H_MS, UNLABELLED, formatSignedUsd, formatUsd, getMessages, getModel, sharesOf } from '@trazum/core';
11
+ import { UNLABELLED, formatSignedUsd, formatUsd, getMessages, getModel, sharesOf } 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);
@@ -1161,6 +1168,10 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1161
1168
  );
1162
1169
  lines.push('');
1163
1170
  // The decision's other half, on the target's rates, never summed.
1171
+ if (whatIf.tierCeiling !== null) {
1172
+ lines.push(`> ⚠️ ${mdText(t.profile.whatIfTierCeiling(whatIf.tierCeiling.slices, whatIf.target.displayName, formatUsd(whatIf.tierCeiling.targetFloorUsd)))}`);
1173
+ lines.push('');
1174
+ }
1164
1175
  if (whatIf.batchOnTarget !== null) {
1165
1176
  lines.push(`_${mdText(t.profile.whatIfBatchOnTarget(formatUsd(whatIf.batchOnTarget.targetUsd), formatUsd(whatIf.targetUsd)))}_`);
1166
1177
  lines.push('');
@@ -1212,9 +1223,11 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1212
1223
  const gap = formatGap(fit.medianGapMs);
1213
1224
  const sentence =
1214
1225
  fit.verdict === 'expires-before-reuse'
1215
- ? fit.medianGapMs > TTL_1H_MS
1216
- ? t.profile.ttlFitExpiresBoth(who, fit.modelName, gap)
1217
- : t.profile.ttlFitExpires(who, fit.modelName, gap)
1226
+ ? fit.longerTtlMs === null
1227
+ ? t.profile.ttlFitExpiresOnly(who, fit.modelName, gap, formatGap(fit.entryTtlMs))
1228
+ : fit.medianGapMs > fit.longerTtlMs
1229
+ ? t.profile.ttlFitExpiresBoth(who, fit.modelName, gap)
1230
+ : t.profile.ttlFitExpires(who, fit.modelName, gap)
1218
1231
  : fit.verdict === 'overlong-ttl'
1219
1232
  ? t.profile.ttlFitOverlong(who, fit.modelName, gap, formatUsd(fit.overpayUsd))
1220
1233
  : fit.verdict === 'unsettled'
@@ -1326,10 +1339,18 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1326
1339
  lines.push(`> ⚠️ ${mdText(t.profile.pricesStale(stalePricing.date, stalePricing.days))}`);
1327
1340
  lines.push('');
1328
1341
  }
1342
+ if (apiEquivalent === true) {
1343
+ lines.push(`> ⚠️ ${mdText(t.bill.apiEquivalent())}`);
1344
+ lines.push('');
1345
+ }
1329
1346
  if (report.unpricedModels.length > 0) {
1330
1347
  lines.push(`> ⚠️ ${mdText(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls))}`);
1331
1348
  lines.push('');
1332
1349
  }
1350
+ if (report.total.tierCeilingCalls > 0) {
1351
+ lines.push(`> ⚠️ ${mdText(tierCeilingCaveat(report, t))}`);
1352
+ lines.push('');
1353
+ }
1333
1354
  if (report.skippedLines.length > 0) {
1334
1355
  const shown = report.skippedLines.slice(0, 5).join(', ');
1335
1356
  lines.push(`_${mdText(t.profile.skipped(report.skippedLines.length, report.skippedLines.length > 5 ? `${shown}…` : shown))}_`);
@@ -1338,3 +1359,19 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1338
1359
 
1339
1360
  return `${lines.join('\n').trimEnd()}\n`;
1340
1361
  }
1362
+
1363
+ /**
1364
+ * The ceiling caveat in words: rows billed at the dearer of two rates because
1365
+ * they sum requests on a model priced by prompt length. One sentence for every
1366
+ * surface that prints a report, so the terminal, the receipt summary and the
1367
+ * exported documents cannot word the range differently.
1368
+ */
1369
+ export function tierCeilingCaveat(report: UsageProfileReport, t: CliMessages): string {
1370
+ const models = report.byModel.filter((row) => row.breakdown.tierCeilingCalls > 0).map((row) => row.model);
1371
+ return t.profile.tierCeiling(
1372
+ report.total.tierCeilingCalls,
1373
+ models.join(', '),
1374
+ formatUsd(report.total.tierCeilingUsd),
1375
+ formatUsd(report.total.tierFloorUsd),
1376
+ );
1377
+ }
package/src/pdf.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { PdfDocument, UNLABELLED, formatUsd, pdfFit, pdfWrap, sharesOf } from '@trazum/core';
2
2
  import type { PdfColor, PdfFont, UsageBreakdown } from '@trazum/core';
3
+ import { tierCeilingCaveat } from './markdown.js';
3
4
  import type { ProfileMarkdownInput } from './markdown.js';
4
5
  import { dayOf, spanDays } from './time.js';
5
6
 
@@ -48,7 +49,7 @@ export interface ProfilePdfOptions {
48
49
 
49
50
  /** The profile as one PDF. Same input as the HTML and Markdown doors. */
50
51
  export function renderProfilePdf(input: ProfileMarkdownInput, options: ProfilePdfOptions = {}): Uint8Array {
51
- const { report, levers, cache, t, gates, window, stalePricing } = input;
52
+ const { report, levers, cache, t, gates, window, stalePricing, apiEquivalent } = input;
52
53
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
53
54
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
54
55
  const showLabel = (label: string): string => (label === UNLABELLED ? t.profile.unlabelled() : label);
@@ -235,7 +236,9 @@ export function renderProfilePdf(input: ProfileMarkdownInput, options: ProfilePd
235
236
  ),
236
237
  );
237
238
  }
239
+ if (report.total.tierCeilingCalls > 0) caveats.push(tierCeilingCaveat(report, t));
238
240
  if (stalePricing !== undefined) caveats.push(t.profile.pricesStale(stalePricing.date, stalePricing.days));
241
+ if (apiEquivalent === true) caveats.push(t.bill.apiEquivalent());
239
242
  if (caveats.length > 0) {
240
243
  box(t.html.caveatsHeading(), caveats, { edge: CAVEAT_EDGE, fill: CAVEAT_FILL, ink: CAVEAT_INK }, true);
241
244
  }