@trazum/cli 2.4.2 → 2.5.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.
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readdirSync, readFileSync } from 'node:fs';
4
4
  import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
- import { cpus, tmpdir } from 'node:os';
5
+ import { cpus, homedir, tmpdir } from 'node:os';
6
6
  import { createInterface } from 'node:readline/promises';
7
7
  import { dirname, join, resolve as resolvePath } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
@@ -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';
@@ -300,6 +300,7 @@ import type { CliMessages } from './i18n/index.js';
300
300
  // style.test.js holds the contract: stripped colour output is byte-identical
301
301
  // to plain output, and a pipe stays plain.
302
302
  import { bar, c, sectionHeading, table } from './style.js';
303
+ import type { TableColumn } from './style.js';
303
304
 
304
305
  // --------------------------------------------------------------------------
305
306
  // Argument parsing
@@ -767,7 +768,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
767
768
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
768
769
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
769
770
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
770
- bill: ['label', 'out', 'o', 'stamp', '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'],
771
772
  'from-helicone': ['out', 'o'],
772
773
  'from-langsmith': ['out', 'o'],
773
774
  switch: ['to', 'migration-usd', 'cases'],
@@ -3361,6 +3362,11 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3361
3362
  if (gap.kind === 'unpriced') console.error(t.receipt.unpriced(gap.models.length, gap.calls));
3362
3363
  if (gap.kind === 'unread-lines') console.error(t.receipt.unread(gap.count));
3363
3364
  if (gap.kind === 'no-clock') console.error(t.receipt.noClock());
3365
+ if (gap.kind === 'tier-ceiling') {
3366
+ console.error(
3367
+ t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)),
3368
+ );
3369
+ }
3364
3370
  }
3365
3371
  }
3366
3372
 
@@ -3420,11 +3426,24 @@ function usageSourcesOf(text: string): UsageSource[] {
3420
3426
  * a bill rather than usage, and pointed at `reconcile`.
3421
3427
  */
3422
3428
  async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
3423
- if (args.positional.length === 0) throw new Error(t.bill.noPath());
3424
3429
  /* Refused before any file is read: a bad shape found after the receipt
3425
3430
  printed would end a run that looked finished with an error. */
3426
3431
  const csvShape = csvShapeOf(args, t);
3427
3432
 
3433
+ /*
3434
+ No path is the most common first run, and it used to be a refusal: the
3435
+ person had to know where Claude Code keeps its sessions before the one
3436
+ line on the README worked. Claude Code's own folders are searched
3437
+ instead, and the ones found are named, so nothing is read silently.
3438
+ */
3439
+ let targets = args.positional;
3440
+ if (targets.length === 0) {
3441
+ const { found, tried } = await claudeProjectFolders(process.env);
3442
+ if (found.length === 0) throw new Error(t.bill.noPath(tried.join(', ')));
3443
+ console.error(t.bill.defaultPath(found.join(', ')));
3444
+ targets = found;
3445
+ }
3446
+
3428
3447
  /*
3429
3448
  Every path given, files and directories alike, because a shell glob hands
3430
3449
  over many and reading the first was a bill missing the rest. A file named
@@ -3433,13 +3452,16 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3433
3452
  */
3434
3453
  const files: string[] = [];
3435
3454
  const seen = new Set<string>();
3436
- const add = (file: string): void => {
3455
+ /* Reached through a directory: where a project folder can name the work. */
3456
+ const walked = new Set<string>();
3457
+ const add = (file: string, fromDirectory: boolean): void => {
3437
3458
  const key = resolvePath(file);
3459
+ if (fromDirectory) walked.add(file);
3438
3460
  if (seen.has(key)) return;
3439
3461
  seen.add(key);
3440
3462
  files.push(file);
3441
3463
  };
3442
- for (const target of args.positional) {
3464
+ for (const target of targets) {
3443
3465
  let info;
3444
3466
  try {
3445
3467
  info = await stat(target);
@@ -3453,16 +3475,33 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3453
3475
  .map((entry) => join(entry.parentPath, entry.name))
3454
3476
  .sort();
3455
3477
  if (found.length === 0) throw new Error(t.bill.noFiles(target));
3456
- for (const file of found) add(file);
3478
+ for (const file of found) add(file, true);
3457
3479
  } else {
3458
- add(target);
3480
+ add(target, false);
3459
3481
  }
3460
3482
  }
3461
3483
 
3462
3484
  const label = stringFlag(args, 'label');
3463
3485
  const withLabel = label === undefined ? {} : { label };
3486
+ /*
3487
+ Claude Code keeps one folder per project, and "per project" is the
3488
+ question this door is for. `from-claude-code` has labelled a directory by
3489
+ its project folders since 1.77; `bill` read the same transcripts with no
3490
+ label at all, so the bill it printed could not say which project spent
3491
+ the money. Same default, same function, same way to decline.
3492
+ */
3493
+ const labelFromProject = boolFlag(args, 'label-from-project', true);
3494
+ let labelledByProject = 0;
3464
3495
  const lines: string[] = [];
3465
3496
  let sources = 0;
3497
+ /*
3498
+ One line per file is right for a handful and noise for a Claude Code
3499
+ folder of hundreds. Past a handful, the lines are per shape, and the
3500
+ files no shape claims are named for the first few and counted after.
3501
+ */
3502
+ const perFile = files.length <= 8;
3503
+ const unclaimed: string[] = [];
3504
+ const byShape = new Map<string, { files: number; records: number | null; leftOut: number }>();
3466
3505
 
3467
3506
  for (const file of files) {
3468
3507
  const text = await readUsageLog(file, t);
@@ -3472,7 +3511,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3472
3511
  if (looksLikeAnthropicCost(text) || looksLikeOpenaiCost(text)) {
3473
3512
  console.error(t.bill.costReport(file));
3474
3513
  } else {
3475
- console.error(t.bill.unknown(file));
3514
+ unclaimed.push(file);
3476
3515
  }
3477
3516
  continue;
3478
3517
  }
@@ -3487,7 +3526,10 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3487
3526
  let leftOut = 0;
3488
3527
  switch (shape) {
3489
3528
  case 'claude-code': {
3490
- const c = claudeCodeRecords(text, withLabel);
3529
+ const project =
3530
+ label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
3531
+ if (project !== undefined && project !== '') labelledByProject += 1;
3532
+ const c = claudeCodeRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
3491
3533
  records = c.records;
3492
3534
  leftOut = c.assistantWithoutUsage + c.unparseable;
3493
3535
  break;
@@ -3543,8 +3585,22 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3543
3585
  }
3544
3586
  for (const record of records) lines.push(JSON.stringify(record));
3545
3587
  sources += 1;
3546
- console.error(t.bill.file(file, shape, shape === 'usage-log' ? null : records.length, leftOut));
3588
+ const count = shape === 'usage-log' ? null : records.length;
3589
+ if (perFile) {
3590
+ console.error(t.bill.file(file, shape, count, leftOut));
3591
+ } else {
3592
+ const sum = byShape.get(shape) ?? { files: 0, records: count === null ? null : 0, leftOut: 0 };
3593
+ sum.files += 1;
3594
+ if (sum.records !== null && count !== null) sum.records += count;
3595
+ sum.leftOut += leftOut;
3596
+ byShape.set(shape, sum);
3597
+ }
3547
3598
  }
3599
+ for (const [shape, sum] of byShape) console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut));
3600
+ const named = perFile ? unclaimed : unclaimed.slice(0, 3);
3601
+ for (const file of named) console.error(t.bill.unknown(file));
3602
+ if (unclaimed.length > named.length) console.error(t.bill.unknownMore(unclaimed.length - named.length));
3603
+ if (labelledByProject > 0) console.error(t.bill.labelledByProject(labelledByProject));
3548
3604
 
3549
3605
  if (sources === 0) throw new Error(t.bill.nothingRead());
3550
3606
 
@@ -3552,15 +3608,26 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3552
3608
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3553
3609
  const json = JSON.stringify(document, null, 2);
3554
3610
 
3611
+ /*
3612
+ A terminal gets a statement a person can read; a pipe gets the receipt.
3613
+ The receipt on a terminal was 60 lines of JSON before the first figure a
3614
+ reader wanted, which is the screen a first run ends on. Scripts are
3615
+ untouched: they pipe, and a pipe is not a TTY. `--receipt` forces the
3616
+ receipt and `--table` forces the statement, either way round. Not
3617
+ `--json`: that flag means a documented contract in docs/format.md, and
3618
+ the receipt is `trazum receipt`'s document, emitted here unchanged.
3619
+ */
3555
3620
  const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3621
+ const statement = !boolFlag(args, 'receipt') && boolFlag(args, 'table', process.stdout.isTTY === true);
3556
3622
  if (out !== undefined) {
3557
3623
  await writeFile(out, json + '\n', 'utf8');
3558
3624
  console.error(t.bill.written(out));
3559
- } else {
3625
+ } else if (!statement) {
3560
3626
  console.log(json);
3561
3627
  }
3562
3628
  console.error(t.bill.sources(sources, files.length));
3563
3629
  printReceiptSummary(document, t);
3630
+ if (statement) printBillStatement(report, labelledByProject > 0, t);
3564
3631
  await writeBillSideFiles(args, report, pricing, csvShape, t);
3565
3632
 
3566
3633
  /*
@@ -3577,6 +3644,100 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3577
3644
  }
3578
3645
  }
3579
3646
 
3647
+ /**
3648
+ * Where Claude Code keeps its sessions, in the order it looks itself.
3649
+ *
3650
+ * `CLAUDE_CONFIG_DIR` first, because a person who set it moved the folder on
3651
+ * purpose; then the two defaults Claude Code has used. Every folder that
3652
+ * exists is returned, deduplicated, so a machine with both is billed for
3653
+ * both, once each. `tried` is every candidate, for the refusal to name.
3654
+ */
3655
+ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: string[]; tried: string[] }> {
3656
+ const home = homedir();
3657
+ const tried = [
3658
+ ...(env.CLAUDE_CONFIG_DIR ? [join(env.CLAUDE_CONFIG_DIR, 'projects')] : []),
3659
+ join(home, '.claude', 'projects'),
3660
+ join(home, '.config', 'claude', 'projects'),
3661
+ ];
3662
+ const found: string[] = [];
3663
+ const seen = new Set<string>();
3664
+ for (const candidate of tried) {
3665
+ const key = resolvePath(candidate);
3666
+ if (seen.has(key)) continue;
3667
+ seen.add(key);
3668
+ try {
3669
+ if ((await stat(candidate)).isDirectory()) found.push(candidate);
3670
+ } catch {
3671
+ // Not there, which is the ordinary case for two of the three.
3672
+ }
3673
+ }
3674
+ return { found, tried };
3675
+ }
3676
+
3677
+ /**
3678
+ * The bill as a person reads it: the total, by project, by model, and what
3679
+ * is not in the total, on stdout. The receipt's figures, rendered: nothing
3680
+ * here is computed that the receipt does not carry.
3681
+ */
3682
+ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: CliMessages): void {
3683
+ const n = (value: number): string => value.toLocaleString(t.numberLocale);
3684
+ const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
3685
+ const total = report.total.totalUsd;
3686
+ const LIMIT = 12;
3687
+ const rowsOf = (entries: { name: string; calls: number; usd: number }[]): string[][] => {
3688
+ const shown = entries.slice(0, LIMIT).map(({ name, calls, usd }) => {
3689
+ const share = total > 0 ? usd / total : 0;
3690
+ return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3691
+ });
3692
+ if (entries.length > LIMIT) shown.push([c.dim(t.bill.moreRows(entries.length - LIMIT)), '', '', '']);
3693
+ return shown;
3694
+ };
3695
+ const columns = (first: string): TableColumn[] => [
3696
+ { header: first, align: 'left' },
3697
+ { header: t.bill.colCalls(), align: 'right' },
3698
+ { header: 'USD', align: 'right' },
3699
+ { header: t.bill.colShare(), align: 'left' },
3700
+ ];
3701
+
3702
+ console.log();
3703
+ console.log(sectionHeading(t.bill.statementHeading()));
3704
+ console.log(` ${c.bold(t.bill.statementTotal(formatUsd(total), report.total.calls))}`);
3705
+ if (report.span !== null) {
3706
+ const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3707
+ console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3708
+ }
3709
+
3710
+ const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3711
+ if (labelled.length > 0) {
3712
+ console.log();
3713
+ const entries = report.byLabel.map((row) => ({
3714
+ name: row.label === UNLABELLED ? t.profile.unlabelled() : row.label,
3715
+ calls: row.breakdown.calls,
3716
+ usd: row.breakdown.totalUsd,
3717
+ }));
3718
+ for (const line of table(columns(byProject ? t.bill.colProject() : t.bill.colWorkload()), rowsOf(entries))) {
3719
+ console.log(line);
3720
+ }
3721
+ }
3722
+
3723
+ const priced = report.byModel.filter((row) => !report.unpricedModels.includes(row.model));
3724
+ if (priced.length > 0) {
3725
+ console.log();
3726
+ const entries = priced.map((row) => ({ name: row.model, calls: row.breakdown.calls, usd: row.breakdown.totalUsd }));
3727
+ for (const line of table(columns(t.bill.colModel()), rowsOf(entries))) console.log(line);
3728
+ }
3729
+
3730
+ console.log();
3731
+ if (report.unpricedModels.length > 0) {
3732
+ console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
3733
+ }
3734
+ const ceiling = tierCeilingLine(report, t);
3735
+ if (ceiling !== null) console.log(` ${wrap(ceiling, 74, ' ')}`);
3736
+ if (report.skippedLines.length > 0) console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
3737
+ console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3738
+ console.log();
3739
+ }
3740
+
3580
3741
  /**
3581
3742
  * The bill as a document for somebody else: PDF, HTML, Markdown, CSV.
3582
3743
  *
@@ -4123,6 +4284,7 @@ async function commandFromOpenai(args: Args, t: CliMessages): Promise<void> {
4123
4284
  if (conversion.mixedRows > 0) {
4124
4285
  console.error(t.fromOpenai.mixed(conversion.mixedRows, conversion.nonTextTokens, conversion.cacheWriteUnplaced));
4125
4286
  }
4287
+ if (conversion.cacheWrite12hTokens > 0) console.error(t.fromOpenai.cacheWrite12h(conversion.cacheWrite12hTokens));
4126
4288
  if (conversion.unsplitRows > 0) console.error(t.fromOpenai.unsplit(conversion.unsplitRows));
4127
4289
  if (conversion.labelledByProject > 0) console.error(t.fromOpenai.labelledByProject(conversion.labelledByProject));
4128
4290
  if (conversion.unruledProject > 0) console.error(t.fromOpenai.unruledProject(conversion.unruledProject));
@@ -6339,7 +6501,13 @@ interface LocalCounter {
6339
6501
  * did not opt in, and turning it into a crash would make an optional dependency
6340
6502
  * a required one by accident.
6341
6503
  */
6342
- async function localCounterFor(model: string): Promise<LocalCounter | null> {
6504
+ /**
6505
+ * A counter, or why there is none: `null` when the package is not installed,
6506
+ * `{ refused }` when it is and holds no table for this model. Two refusals,
6507
+ * because they send a reader to different places: one to `npm install`, the
6508
+ * other nowhere, since installing what is already installed fixes nothing.
6509
+ */
6510
+ async function localCounterFor(model: string): Promise<LocalCounter | { refused: readonly string[] } | null> {
6343
6511
  let loaded: OptionalCounterModule;
6344
6512
  try {
6345
6513
  /*
@@ -6360,7 +6528,7 @@ async function localCounterFor(model: string): Promise<LocalCounter | null> {
6360
6528
  }
6361
6529
 
6362
6530
  const result = await loaded.openaiCounter(model);
6363
- if (!result.ok) return null;
6531
+ if (!result.ok) return { refused: result.refusal.known };
6364
6532
  return {
6365
6533
  count: result.count,
6366
6534
  counter: 'openai-tiktoken',
@@ -6677,7 +6845,9 @@ async function commandOptimize(
6677
6845
  * the network at all. A prompt counted here is read in this process and
6678
6846
  * goes nowhere, which is the distinction `TokenProvenance.where` carries.
6679
6847
  */
6680
- const local = await localCounterFor(result.usage.model);
6848
+ const found = await localCounterFor(result.usage.model);
6849
+ const local = found !== null && !('refused' in found) ? found : null;
6850
+ const refusedEncodings = found !== null && 'refused' in found ? found.refused : null;
6681
6851
  if (local !== null) {
6682
6852
  result = await withExactTokenCounts(
6683
6853
  result,
@@ -6716,7 +6886,9 @@ async function commandOptimize(
6716
6886
  throw new Error(
6717
6887
  offered === undefined
6718
6888
  ? t.errors.exactTokensWrongFamily(result.usage.model, priced?.provider ?? null)
6719
- : t.errors.exactTokensNeedsPackage(result.usage.model, offered),
6889
+ : refusedEncodings !== null
6890
+ ? t.errors.exactTokensNoEncoding(result.usage.model, offered, refusedEncodings.join(', '))
6891
+ : t.errors.exactTokensNeedsPackage(result.usage.model, offered),
6720
6892
  );
6721
6893
  }
6722
6894
  const apiKey = process.env.ANTHROPIC_API_KEY;
@@ -7927,6 +8099,19 @@ async function commandConnect(
7927
8099
  out.push(md ? `- ${line}` : `! ${line}`);
7928
8100
  }
7929
8101
 
8102
+ /* A bucket sums requests, so a model priced by prompt length is a range. */
8103
+ const ceilinged = report.byModel.filter((slice) => slice.tierCeilingBuckets > 0);
8104
+ if (ceilinged.length > 0) {
8105
+ out.push('');
8106
+ const line = t.profile.tierCeiling(
8107
+ ceilinged.reduce((sum, slice) => sum + slice.tierCeilingBuckets, 0),
8108
+ ceilinged.map((slice) => slice.model).join(', '),
8109
+ formatUsd(ceilinged.reduce((sum, slice) => sum + slice.tierCeilingUsd, 0)),
8110
+ formatUsd(ceilinged.reduce((sum, slice) => sum + slice.tierFloorUsd, 0)),
8111
+ );
8112
+ out.push(md ? `- ${line}` : `! ${line}`);
8113
+ }
8114
+
7930
8115
  if (report.gaps.length > 0) out.push('');
7931
8116
  for (const gap of report.gaps) {
7932
8117
  const line = t.connect.gap(gap.detail);
@@ -9996,6 +10181,11 @@ function reportWhatIf(
9996
10181
  * adding two savings, and hedged the only honest way — whether these
9997
10182
  * calls can wait is not in the log.
9998
10183
  */
10184
+ if (whatIf.tierCeiling !== null) {
10185
+ console.log(
10186
+ ` ${c.yellow('!')} ${wrap(t.profile.whatIfTierCeiling(whatIf.tierCeiling.slices, whatIf.target.displayName, formatUsd(whatIf.tierCeiling.targetFloorUsd)), 74, ' ')}`,
10187
+ );
10188
+ }
9999
10189
  if (whatIf.batchOnTarget !== null) {
10000
10190
  console.log(
10001
10191
  ` ${c.dim(wrap(t.profile.whatIfBatchOnTarget(formatUsd(whatIf.batchOnTarget.targetUsd), formatUsd(whatIf.targetUsd)), 74, ' '))}`,
@@ -10271,10 +10461,13 @@ async function reportLabelsBudgetsAndCache(
10271
10461
  const name = fit.label === UNLABELLED ? t.profile.unlabelled() : fit.label;
10272
10462
  const gap = formatGap(fit.medianGapMs);
10273
10463
  if (fit.verdict === 'expires-before-reuse') {
10464
+ // The model's own entries: one kind on OpenAI, two on Anthropic.
10274
10465
  const line =
10275
- fit.medianGapMs > TTL_1H_MS
10276
- ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
10277
- : t.profile.ttlFitExpires(name, fit.modelName, gap);
10466
+ fit.longerTtlMs === null
10467
+ ? t.profile.ttlFitExpiresOnly(name, fit.modelName, gap, formatGap(fit.entryTtlMs))
10468
+ : fit.medianGapMs > fit.longerTtlMs
10469
+ ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
10470
+ : t.profile.ttlFitExpires(name, fit.modelName, gap);
10278
10471
  console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
10279
10472
  } else if (fit.verdict === 'overlong-ttl') {
10280
10473
  console.log(
@@ -10375,6 +10568,11 @@ async function reportLabelsBudgetsAndCache(
10375
10568
  }
10376
10569
  }
10377
10570
 
10571
+ /** The ceiling caveat for a report, or `null` when nothing was billed at one. */
10572
+ function tierCeilingLine(report: UsageProfileReport, t: CliMessages): string | null {
10573
+ return report.total.tierCeilingCalls === 0 ? null : tierCeilingCaveat(report, t);
10574
+ }
10575
+
10378
10576
  /**
10379
10577
  * What caching did to this bill, and what it is about to do.
10380
10578
  *
@@ -11331,6 +11529,15 @@ function reportProfileGaps(
11331
11529
  ` ${c.yellow('!')} ${c.dim(wrap(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' '))}`,
11332
11530
  );
11333
11531
  }
11532
+ /*
11533
+ * A total that billed summed rows at the dearer rate is a ceiling, said with
11534
+ * the other end beside it: the range is the finding, not the doubt.
11535
+ */
11536
+ const ceiling = tierCeilingLine(report, t);
11537
+ if (ceiling !== null) {
11538
+ console.log();
11539
+ console.log(` ${c.yellow('!')} ${wrap(ceiling, 74, ' ')}`);
11540
+ }
11334
11541
  if (report.skippedLines.length > 0) {
11335
11542
  const shown = report.skippedLines.slice(0, 5).join(', ');
11336
11543
  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
 
@@ -1161,6 +1161,10 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1161
1161
  );
1162
1162
  lines.push('');
1163
1163
  // The decision's other half, on the target's rates, never summed.
1164
+ if (whatIf.tierCeiling !== null) {
1165
+ lines.push(`> ⚠️ ${mdText(t.profile.whatIfTierCeiling(whatIf.tierCeiling.slices, whatIf.target.displayName, formatUsd(whatIf.tierCeiling.targetFloorUsd)))}`);
1166
+ lines.push('');
1167
+ }
1164
1168
  if (whatIf.batchOnTarget !== null) {
1165
1169
  lines.push(`_${mdText(t.profile.whatIfBatchOnTarget(formatUsd(whatIf.batchOnTarget.targetUsd), formatUsd(whatIf.targetUsd)))}_`);
1166
1170
  lines.push('');
@@ -1212,9 +1216,11 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1212
1216
  const gap = formatGap(fit.medianGapMs);
1213
1217
  const sentence =
1214
1218
  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)
1219
+ ? fit.longerTtlMs === null
1220
+ ? t.profile.ttlFitExpiresOnly(who, fit.modelName, gap, formatGap(fit.entryTtlMs))
1221
+ : fit.medianGapMs > fit.longerTtlMs
1222
+ ? t.profile.ttlFitExpiresBoth(who, fit.modelName, gap)
1223
+ : t.profile.ttlFitExpires(who, fit.modelName, gap)
1218
1224
  : fit.verdict === 'overlong-ttl'
1219
1225
  ? t.profile.ttlFitOverlong(who, fit.modelName, gap, formatUsd(fit.overpayUsd))
1220
1226
  : fit.verdict === 'unsettled'
@@ -1330,6 +1336,10 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1330
1336
  lines.push(`> ⚠️ ${mdText(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls))}`);
1331
1337
  lines.push('');
1332
1338
  }
1339
+ if (report.total.tierCeilingCalls > 0) {
1340
+ lines.push(`> ⚠️ ${mdText(tierCeilingCaveat(report, t))}`);
1341
+ lines.push('');
1342
+ }
1333
1343
  if (report.skippedLines.length > 0) {
1334
1344
  const shown = report.skippedLines.slice(0, 5).join(', ');
1335
1345
  lines.push(`_${mdText(t.profile.skipped(report.skippedLines.length, report.skippedLines.length > 5 ? `${shown}…` : shown))}_`);
@@ -1338,3 +1348,19 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1338
1348
 
1339
1349
  return `${lines.join('\n').trimEnd()}\n`;
1340
1350
  }
1351
+
1352
+ /**
1353
+ * The ceiling caveat in words: rows billed at the dearer of two rates because
1354
+ * they sum requests on a model priced by prompt length. One sentence for every
1355
+ * surface that prints a report, so the terminal, the receipt summary and the
1356
+ * exported documents cannot word the range differently.
1357
+ */
1358
+ export function tierCeilingCaveat(report: UsageProfileReport, t: CliMessages): string {
1359
+ const models = report.byModel.filter((row) => row.breakdown.tierCeilingCalls > 0).map((row) => row.model);
1360
+ return t.profile.tierCeiling(
1361
+ report.total.tierCeilingCalls,
1362
+ models.join(', '),
1363
+ formatUsd(report.total.tierCeilingUsd),
1364
+ formatUsd(report.total.tierFloorUsd),
1365
+ );
1366
+ }
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
 
@@ -235,6 +236,7 @@ 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));
239
241
  if (caveats.length > 0) {
240
242
  box(t.html.caveatsHeading(), caveats, { edge: CAVEAT_EDGE, fill: CAVEAT_FILL, ink: CAVEAT_INK }, true);