@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/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { createInterface } from 'node:readline/promises';
7
7
  import { dirname, join, resolve as resolvePath } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { gunzipSync } from 'node:zlib';
10
- import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, evaluateWatch, firedKey, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, bandGoverns, countTokensAnthropic, DEFAULT_USAGE, budgetPositions, conform, BREAK_EVEN_BAND, allocate, annualRecord, replayCommitment, coversTheTerm, runExperiment, qualityGate, semanticPassCost, verifySemanticProposals, SEMANTIC_SYSTEM_PROMPT, ladderPosition, validateLadder, outcomeReport, rankPerOutcome, FAILURE_POLICIES, detectFromSource, matchLocale, parsePlanDocument, waiverDay, waiverHistory, proposeInit, MIN_RATE_DAYS, parseConfig, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, rollUp, heartbeats, ruleYield, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, receiptFrom, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, matchGlob, MAX_INPUT_CHARS, moneyIsComparable, mostSpecificMatch, assemble, interview, nearestName, slot, SLOT_IDS, optimize, parseBaseline, PHRASE_LANGUAGES, detectTextLanguage, dictionaryStanding, languagesWithStanding, indexUsage, parseUsageLine, plannedCalls, claudeCodeRecords, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, looksLikeAnthropicUsage, looksLikeClaudeCodeTranscript, looksLikeHelicone, looksLikeLangsmith, looksLikeLiteLlm, looksLikeOpenaiUsage, looksLikeOpenrouterActivity, looksLikeOtel, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, TTL_1H_MS, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
10
+ import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, evaluateWatch, firedKey, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, bandGoverns, countTokensAnthropic, DEFAULT_USAGE, budgetPositions, conform, BREAK_EVEN_BAND, allocate, annualRecord, replayCommitment, coversTheTerm, runExperiment, qualityGate, semanticPassCost, verifySemanticProposals, SEMANTIC_SYSTEM_PROMPT, ladderPosition, validateLadder, outcomeReport, rankPerOutcome, FAILURE_POLICIES, detectFromSource, matchLocale, parsePlanDocument, waiverDay, waiverHistory, proposeInit, MIN_RATE_DAYS, parseConfig, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, rollUp, heartbeats, ruleYield, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, receiptFrom, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, matchGlob, MAX_INPUT_CHARS, moneyIsComparable, mostSpecificMatch, assemble, interview, nearestName, slot, SLOT_IDS, optimize, parseBaseline, PHRASE_LANGUAGES, detectTextLanguage, dictionaryStanding, languagesWithStanding, indexUsage, parseUsageLine, plannedCalls, claudeCodeRecords, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, looksLikeAnthropicUsage, looksLikeClaudeCodeTranscript, looksLikeHelicone, looksLikeLangsmith, looksLikeLiteLlm, looksLikeOpenaiUsage, looksLikeOpenrouterActivity, looksLikeOtel, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
11
11
  import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
12
12
  import { OPTIONAL_COUNTERS } from './optional-counters.js';
13
13
  import { dayOf, formatGap, median, spanDays } from './time.js';
@@ -22,7 +22,7 @@ import { DEFAULT_PORT, buildServer, listen } from './serve.js';
22
22
  import { DEFAULT_GATEWAY_PORT, UPSTREAMS, buildGateway, listenGateway, } from './gateway-server.js';
23
23
  import { WATCH_STATE_VERSION, checkWebhook, postWebhook, readWatchState, writeWatchState, } from './watch-run.js';
24
24
  import { LOCALE_ENV_VARS, detectLocale, getCliMessages } from './i18n/index.js';
25
- import { MAX_SUMMARY_CHARS, fitWithin, renderBlameMarkdown, renderCheckMarkdown, renderDiffMarkdown, renderRankMarkdown, renderProfileMarkdown, } from './markdown.js';
25
+ import { MAX_SUMMARY_CHARS, fitWithin, renderBlameMarkdown, renderCheckMarkdown, renderDiffMarkdown, renderRankMarkdown, renderProfileMarkdown, tierCeilingCaveat, } from './markdown.js';
26
26
  import { renderPositionHtml, renderProfileHtml, renderRollupHtml } from './html.js';
27
27
  import { renderProfilePdf } from './pdf.js';
28
28
  // --------------------------------------------------------------------------
@@ -424,7 +424,7 @@ const COMMAND_FLAGS = {
424
424
  schema: [],
425
425
  rollup: ['json', 'html-out'],
426
426
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
427
- receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live'],
427
+ receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
428
428
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
429
429
  'from-otel': ['label-from-service', 'out', 'o'],
430
430
  'from-litellm': ['out', 'o'],
@@ -432,7 +432,7 @@ const COMMAND_FLAGS = {
432
432
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
433
433
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
434
434
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
435
- bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape'],
435
+ 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'],
436
436
  'from-helicone': ['out', 'o'],
437
437
  'from-langsmith': ['out', 'o'],
438
438
  switch: ['to', 'migration-usd', 'cases'],
@@ -2648,12 +2648,60 @@ async function commandReconcile(args, t) {
2648
2648
  if (billed.unreadableAmount > 0)
2649
2649
  console.error(t.reconcile.unreadableAmount(billed.unreadableAmount));
2650
2650
  }
2651
+ /**
2652
+ * The period a bill or a receipt covers, from `--since`/`--until`.
2653
+ *
2654
+ * `profile`'s window, read the same way: a UTC day, a timestamp, a relative
2655
+ * window or `now`; a bare day is the whole of it, and the window is half-open
2656
+ * underneath, so two adjacent periods share no call and add up to the whole.
2657
+ * Refused before any file is read: a bad date found after the receipt printed
2658
+ * would end a run that looked finished with an error. `words` is the window as
2659
+ * typed, for the documents to print, because rendering the internal exclusive
2660
+ * bound would name the day after the one asked for.
2661
+ */
2662
+ function billingPeriod(args, t) {
2663
+ const now = Date.now();
2664
+ const since = parseWhen(args, 'since', false, t, now);
2665
+ const until = parseWhen(args, 'until', true, t, now);
2666
+ if (since.ms !== undefined && until.ms !== undefined && since.ms >= until.ms) {
2667
+ throw new Error(t.profile.sinceAfterUntil());
2668
+ }
2669
+ if (since.ms === undefined && until.ms === undefined)
2670
+ return { relative: false };
2671
+ return {
2672
+ ...(since.ms !== undefined ? { sinceMs: since.ms } : {}),
2673
+ ...(until.ms !== undefined ? { untilMs: until.ms } : {}),
2674
+ relative: since.relative || until.relative,
2675
+ words: { since: stringFlag(args, 'since') ?? '—', until: stringFlag(args, 'until') ?? '—' },
2676
+ };
2677
+ }
2678
+ /**
2679
+ * A period with nothing in it is refused, never billed at $0: that reads as
2680
+ * "this month was free" when it means the dates missed the log. Said against
2681
+ * what was read, so the fix is in the message.
2682
+ */
2683
+ function refuseEmptyPeriod(text, report, period, pricing, t) {
2684
+ if (period.words === undefined || report.total.calls > 0 || report.unpriced.calls > 0)
2685
+ return;
2686
+ const whole = profileUsage(text, { catalogue: pricing });
2687
+ if (whole.total.calls === 0 && whole.unpriced.calls === 0)
2688
+ return;
2689
+ if (whole.span === null)
2690
+ throw new Error(t.profile.windowNeedsClock());
2691
+ throw new Error(`${t.bill.windowMatchesNothing(dayOf(whole.span.fromMs), dayOf(whole.span.toMs))}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`);
2692
+ }
2651
2693
  async function commandReceipt(args, pricing, t) {
2652
2694
  const file = args.positional[0];
2653
2695
  if (file === undefined)
2654
2696
  throw new Error(t.receipt.noLog());
2697
+ const period = billingPeriod(args, t);
2655
2698
  const text = await readUsageLog(file, t);
2656
- const report = profileUsage(text, { catalogue: pricing });
2699
+ const report = profileUsage(text, {
2700
+ catalogue: pricing,
2701
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
2702
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
2703
+ });
2704
+ refuseEmptyPeriod(text, report, period, pricing, t);
2657
2705
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
2658
2706
  const json = JSON.stringify(document, null, 2);
2659
2707
  const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
@@ -2687,6 +2735,11 @@ function printReceiptSummary(document, t) {
2687
2735
  console.error(t.receipt.unread(gap.count));
2688
2736
  if (gap.kind === 'no-clock')
2689
2737
  console.error(t.receipt.noClock());
2738
+ if (gap.kind === 'undated-excluded')
2739
+ console.error(t.receipt.undatedExcluded(gap.calls));
2740
+ if (gap.kind === 'tier-ceiling') {
2741
+ console.error(t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)));
2742
+ }
2690
2743
  }
2691
2744
  }
2692
2745
  /**
@@ -2745,6 +2798,9 @@ async function commandBill(args, pricing, t) {
2745
2798
  /* Refused before any file is read: a bad shape found after the receipt
2746
2799
  printed would end a run that looked finished with an error. */
2747
2800
  const csvShape = csvShapeOf(args, t);
2801
+ /* "What did this month cost" is the question a Claude Code folder of a
2802
+ year's sessions answers worst without a period. */
2803
+ const period = billingPeriod(args, t);
2748
2804
  /*
2749
2805
  No path is the most common first run, and it used to be a refusal: the
2750
2806
  person had to know where Claude Code keeps its sessions before the one
@@ -2812,6 +2868,8 @@ async function commandBill(args, pricing, t) {
2812
2868
  */
2813
2869
  const labelFromProject = boolFlag(args, 'label-from-project', true);
2814
2870
  let labelledByProject = 0;
2871
+ /* Claude Code transcripts read: their money is an API-rate equivalent. */
2872
+ let claudeCodeFiles = 0;
2815
2873
  const lines = [];
2816
2874
  let sources = 0;
2817
2875
  /*
@@ -2845,6 +2903,7 @@ async function commandBill(args, pricing, t) {
2845
2903
  let leftOut = 0;
2846
2904
  switch (shape) {
2847
2905
  case 'claude-code': {
2906
+ claudeCodeFiles += 1;
2848
2907
  const project = label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
2849
2908
  if (project !== undefined && project !== '')
2850
2909
  labelledByProject += 1;
@@ -2931,7 +2990,13 @@ async function commandBill(args, pricing, t) {
2931
2990
  console.error(t.bill.labelledByProject(labelledByProject));
2932
2991
  if (sources === 0)
2933
2992
  throw new Error(t.bill.nothingRead());
2934
- const report = profileUsage(lines.join('\n'), { catalogue: pricing });
2993
+ const text = lines.join('\n');
2994
+ const report = profileUsage(text, {
2995
+ catalogue: pricing,
2996
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
2997
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
2998
+ });
2999
+ refuseEmptyPeriod(text, report, period, pricing, t);
2935
3000
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
2936
3001
  const json = JSON.stringify(document, null, 2);
2937
3002
  /*
@@ -2955,8 +3020,8 @@ async function commandBill(args, pricing, t) {
2955
3020
  console.error(t.bill.sources(sources, files.length));
2956
3021
  printReceiptSummary(document, t);
2957
3022
  if (statement)
2958
- printBillStatement(report, labelledByProject > 0, t);
2959
- await writeBillSideFiles(args, report, pricing, csvShape, t);
3023
+ printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles > 0);
3024
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles > 0);
2960
3025
  /*
2961
3026
  A slug with a slash in it is how OpenRouter names a model, and the bundled
2962
3027
  catalogue does not carry those: the live overlay does. Said only when the
@@ -2967,6 +3032,17 @@ async function commandBill(args, pricing, t) {
2967
3032
  if (slugged.length > 0 && !boolFlag(args, 'pricing-live')) {
2968
3033
  console.error(t.bill.pricingLiveHint(slugged.length));
2969
3034
  }
3035
+ /*
3036
+ `xai/grok-4.3` is LiteLLM's way of saying "grok-4.3, called on xAI", and
3037
+ `anthropic/claude-sonnet-5-5` could be that or an OpenRouter route. The
3038
+ catalogue never strips a prefix by rule, because a router can bill the same
3039
+ model differently and an alias is a statement, never a derivation. What it
3040
+ can do is say which of these it prices under its own name, so the fix is
3041
+ one rename away rather than a guess made on the reader's behalf.
3042
+ */
3043
+ const priceableAfterSlash = slugged.filter((model) => pricing.byId.has(model.slice(model.lastIndexOf('/') + 1)));
3044
+ if (priceableAfterSlash.length > 0)
3045
+ console.error(t.bill.prefixedKnown(priceableAfterSlash.join(', ')));
2970
3046
  }
2971
3047
  /**
2972
3048
  * Where Claude Code keeps its sessions, in the order it looks itself.
@@ -3005,7 +3081,7 @@ async function claudeProjectFolders(env) {
3005
3081
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3006
3082
  * here is computed that the receipt does not carry.
3007
3083
  */
3008
- function printBillStatement(report, byProject, t) {
3084
+ function printBillStatement(report, byProject, t, window, apiEquivalent = false) {
3009
3085
  const n = (value) => value.toLocaleString(t.numberLocale);
3010
3086
  const pct = (share) => `${(share * 100).toFixed(1)}%`;
3011
3087
  const total = report.total.totalUsd;
@@ -3032,6 +3108,16 @@ function printBillStatement(report, byProject, t) {
3032
3108
  const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3033
3109
  console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3034
3110
  }
3111
+ // The period asked for, as typed: the span above is when the calls in it fell.
3112
+ if (window !== undefined)
3113
+ console.log(c.dim(` ${wrap(t.profile.windowLine(window.since, window.until), 74, ' ')}`));
3114
+ /*
3115
+ "Your bill" over Claude Code transcripts is the API's list price for the
3116
+ work. On a Pro or Max plan the plan is what was paid, and a statement that
3117
+ did not say so would hand somebody a figure they never owed.
3118
+ */
3119
+ if (apiEquivalent)
3120
+ console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3035
3121
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3036
3122
  if (labelled.length > 0) {
3037
3123
  console.log();
@@ -3051,12 +3137,57 @@ function printBillStatement(report, byProject, t) {
3051
3137
  for (const line of table(columns(t.bill.colModel()), rowsOf(entries)))
3052
3138
  console.log(line);
3053
3139
  }
3140
+ /*
3141
+ A year of Claude Code sessions billed in one total says what it all cost
3142
+ and not which month cost what, which is the next question. Summed from the
3143
+ report's own days, oldest first, newest kept when there are many; shown
3144
+ only once the bill spans two calendar months, since one month is the total.
3145
+ */
3146
+ const months = new Map();
3147
+ for (const day of report.spendByDay) {
3148
+ const month = months.get(day.day.slice(0, 7)) ?? { calls: 0, usd: 0 };
3149
+ month.calls += day.calls;
3150
+ month.usd += day.usd;
3151
+ months.set(day.day.slice(0, 7), month);
3152
+ }
3153
+ if (months.size >= 2) {
3154
+ const ordered = [...months.entries()].sort(([a], [b]) => a.localeCompare(b));
3155
+ const shown = ordered.slice(-LIMIT).map(([name, { calls, usd }]) => {
3156
+ const share = total > 0 ? usd / total : 0;
3157
+ return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3158
+ });
3159
+ if (ordered.length > LIMIT)
3160
+ shown.unshift([c.dim(t.bill.earlierMonths(ordered.length - LIMIT)), '', '', '']);
3161
+ console.log();
3162
+ for (const line of table(columns(t.bill.colMonth()), shown))
3163
+ console.log(line);
3164
+ const dated = ordered.reduce((sum, [, month]) => ({ calls: sum.calls + month.calls, usd: sum.usd + month.usd }), {
3165
+ calls: 0,
3166
+ usd: 0,
3167
+ });
3168
+ const undatedCalls = report.total.calls - dated.calls;
3169
+ if (undatedCalls > 0) {
3170
+ console.log(c.dim(` ${wrap(t.bill.monthsUndated(undatedCalls, formatUsd(total - dated.usd)), 74, ' ')}`));
3171
+ }
3172
+ const newest = ordered[ordered.length - 1]?.[0];
3173
+ if (newest !== undefined) {
3174
+ const [year, month] = newest.split('-').map(Number);
3175
+ const lastDay = new Date(Date.UTC(year ?? 1970, month ?? 1, 0)).toISOString().slice(0, 10);
3176
+ console.log(c.dim(` ${t.bill.monthHint(`${newest}-01`, lastDay)}`));
3177
+ }
3178
+ }
3054
3179
  console.log();
3055
3180
  if (report.unpricedModels.length > 0) {
3056
3181
  console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
3057
3182
  }
3183
+ const ceiling = tierCeilingLine(report, t);
3184
+ if (ceiling !== null)
3185
+ console.log(` ${wrap(ceiling, 74, ' ')}`);
3058
3186
  if (report.skippedLines.length > 0)
3059
3187
  console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
3188
+ if (report.timeWindow !== null && report.timeWindow.undatedExcluded > 0) {
3189
+ console.log(` ${c.yellow(wrap(t.receipt.undatedExcluded(report.timeWindow.undatedExcluded), 74, ' '))}`);
3190
+ }
3060
3191
  console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3061
3192
  console.log();
3062
3193
  }
@@ -3071,7 +3202,7 @@ function printBillStatement(report, byProject, t) {
3071
3202
  * envelopes. The stale-price caveat travels with them, computed the way
3072
3203
  * `profile` computes it, for the providers this bill actually used.
3073
3204
  */
3074
- async function writeBillSideFiles(args, report, pricing, csvShape, t) {
3205
+ async function writeBillSideFiles(args, report, pricing, csvShape, t, window, apiEquivalent = false) {
3075
3206
  const markdownOut = stringFlag(args, 'markdown-out');
3076
3207
  const htmlOut = stringFlag(args, 'html-out');
3077
3208
  const pdfOut = stringFlag(args, 'pdf-out');
@@ -3085,6 +3216,8 @@ async function writeBillSideFiles(args, report, pricing, csvShape, t) {
3085
3216
  levers: billLevers(report, { catalogue: pricing }),
3086
3217
  cache: cacheEconomics(report.total),
3087
3218
  t,
3219
+ ...(window !== undefined ? { window } : {}),
3220
+ ...(apiEquivalent ? { apiEquivalent } : {}),
3088
3221
  ...(ageDays !== null && ageDays > STALE_PRICING_DAYS ? { stalePricing: { date: reviewed, days: ageDays } } : {}),
3089
3222
  };
3090
3223
  if (markdownOut !== undefined) {
@@ -3623,6 +3756,8 @@ async function commandFromOpenai(args, t) {
3623
3756
  if (conversion.mixedRows > 0) {
3624
3757
  console.error(t.fromOpenai.mixed(conversion.mixedRows, conversion.nonTextTokens, conversion.cacheWriteUnplaced));
3625
3758
  }
3759
+ if (conversion.cacheWrite12hTokens > 0)
3760
+ console.error(t.fromOpenai.cacheWrite12h(conversion.cacheWrite12hTokens));
3626
3761
  if (conversion.unsplitRows > 0)
3627
3762
  console.error(t.fromOpenai.unsplit(conversion.unsplitRows));
3628
3763
  if (conversion.labelledByProject > 0)
@@ -5425,6 +5560,12 @@ async function readInput(source, t, limit = null) {
5425
5560
  * did not opt in, and turning it into a crash would make an optional dependency
5426
5561
  * a required one by accident.
5427
5562
  */
5563
+ /**
5564
+ * A counter, or why there is none: `null` when the package is not installed,
5565
+ * `{ refused }` when it is and holds no table for this model. Two refusals,
5566
+ * because they send a reader to different places: one to `npm install`, the
5567
+ * other nowhere, since installing what is already installed fixes nothing.
5568
+ */
5428
5569
  async function localCounterFor(model) {
5429
5570
  let loaded;
5430
5571
  try {
@@ -5447,7 +5588,7 @@ async function localCounterFor(model) {
5447
5588
  }
5448
5589
  const result = await loaded.openaiCounter(model);
5449
5590
  if (!result.ok)
5450
- return null;
5591
+ return { refused: result.refusal.known };
5451
5592
  return {
5452
5593
  count: result.count,
5453
5594
  counter: 'openai-tiktoken',
@@ -5722,7 +5863,9 @@ async function commandOptimize(args, config, pricing, t, locale) {
5722
5863
  * the network at all. A prompt counted here is read in this process and
5723
5864
  * goes nowhere, which is the distinction `TokenProvenance.where` carries.
5724
5865
  */
5725
- const local = await localCounterFor(result.usage.model);
5866
+ const found = await localCounterFor(result.usage.model);
5867
+ const local = found !== null && !('refused' in found) ? found : null;
5868
+ const refusedEncodings = found !== null && 'refused' in found ? found.refused : null;
5726
5869
  if (local !== null) {
5727
5870
  result = await withExactTokenCounts(result, async (text) => local.count(text), pricing, {
5728
5871
  counter: local.counter,
@@ -5756,7 +5899,9 @@ async function commandOptimize(args, config, pricing, t, locale) {
5756
5899
  const offered = OPTIONAL_COUNTERS[priced?.provider ?? ''];
5757
5900
  throw new Error(offered === undefined
5758
5901
  ? t.errors.exactTokensWrongFamily(result.usage.model, priced?.provider ?? null)
5759
- : t.errors.exactTokensNeedsPackage(result.usage.model, offered));
5902
+ : refusedEncodings !== null
5903
+ ? t.errors.exactTokensNoEncoding(result.usage.model, offered, refusedEncodings.join(', '))
5904
+ : t.errors.exactTokensNeedsPackage(result.usage.model, offered));
5760
5905
  }
5761
5906
  const apiKey = process.env.ANTHROPIC_API_KEY;
5762
5907
  if (!apiKey) {
@@ -6630,6 +6775,13 @@ async function commandConnect(args, pricing, t) {
6630
6775
  const line = t.connect.unpriced(model.model, n(model.inputTokens + model.outputTokens));
6631
6776
  out.push(md ? `- ${line}` : `! ${line}`);
6632
6777
  }
6778
+ /* A bucket sums requests, so a model priced by prompt length is a range. */
6779
+ const ceilinged = report.byModel.filter((slice) => slice.tierCeilingBuckets > 0);
6780
+ if (ceilinged.length > 0) {
6781
+ out.push('');
6782
+ const line = t.profile.tierCeiling(ceilinged.reduce((sum, slice) => sum + slice.tierCeilingBuckets, 0), ceilinged.map((slice) => slice.model).join(', '), formatUsd(ceilinged.reduce((sum, slice) => sum + slice.tierCeilingUsd, 0)), formatUsd(ceilinged.reduce((sum, slice) => sum + slice.tierFloorUsd, 0)));
6783
+ out.push(md ? `- ${line}` : `! ${line}`);
6784
+ }
6633
6785
  if (report.gaps.length > 0)
6634
6786
  out.push('');
6635
6787
  for (const gap of report.gaps) {
@@ -8405,6 +8557,9 @@ function reportWhatIf(whatIf, report, t) {
8405
8557
  * adding two savings, and hedged the only honest way — whether these
8406
8558
  * calls can wait is not in the log.
8407
8559
  */
8560
+ if (whatIf.tierCeiling !== null) {
8561
+ console.log(` ${c.yellow('!')} ${wrap(t.profile.whatIfTierCeiling(whatIf.tierCeiling.slices, whatIf.target.displayName, formatUsd(whatIf.tierCeiling.targetFloorUsd)), 74, ' ')}`);
8562
+ }
8408
8563
  if (whatIf.batchOnTarget !== null) {
8409
8564
  console.log(` ${c.dim(wrap(t.profile.whatIfBatchOnTarget(formatUsd(whatIf.batchOnTarget.targetUsd), formatUsd(whatIf.targetUsd)), 74, ' '))}`);
8410
8565
  }
@@ -8645,9 +8800,12 @@ async function reportLabelsBudgetsAndCache(report, config, pricing, t) {
8645
8800
  const name = fit.label === UNLABELLED ? t.profile.unlabelled() : fit.label;
8646
8801
  const gap = formatGap(fit.medianGapMs);
8647
8802
  if (fit.verdict === 'expires-before-reuse') {
8648
- const line = fit.medianGapMs > TTL_1H_MS
8649
- ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
8650
- : t.profile.ttlFitExpires(name, fit.modelName, gap);
8803
+ // The model's own entries: one kind on OpenAI, two on Anthropic.
8804
+ const line = fit.longerTtlMs === null
8805
+ ? t.profile.ttlFitExpiresOnly(name, fit.modelName, gap, formatGap(fit.entryTtlMs))
8806
+ : fit.medianGapMs > fit.longerTtlMs
8807
+ ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
8808
+ : t.profile.ttlFitExpires(name, fit.modelName, gap);
8651
8809
  console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
8652
8810
  }
8653
8811
  else if (fit.verdict === 'overlong-ttl') {
@@ -8730,6 +8888,10 @@ async function reportLabelsBudgetsAndCache(report, config, pricing, t) {
8730
8888
  console.log(` ${c.dim(wrap(t.profile.assumedWriteTtl(report.total.assumedWriteTtlCalls), 74, ' '))}`);
8731
8889
  }
8732
8890
  }
8891
+ /** The ceiling caveat for a report, or `null` when nothing was billed at one. */
8892
+ function tierCeilingLine(report, t) {
8893
+ return report.total.tierCeilingCalls === 0 ? null : tierCeilingCaveat(report, t);
8894
+ }
8733
8895
  /**
8734
8896
  * What caching did to this bill, and what it is about to do.
8735
8897
  *
@@ -9574,6 +9736,15 @@ function reportProfileGaps(report, t, n, stalePricing = null) {
9574
9736
  console.log();
9575
9737
  console.log(` ${c.yellow('!')} ${c.dim(wrap(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' '))}`);
9576
9738
  }
9739
+ /*
9740
+ * A total that billed summed rows at the dearer rate is a ceiling, said with
9741
+ * the other end beside it: the range is the finding, not the doubt.
9742
+ */
9743
+ const ceiling = tierCeilingLine(report, t);
9744
+ if (ceiling !== null) {
9745
+ console.log();
9746
+ console.log(` ${c.yellow('!')} ${wrap(ceiling, 74, ' ')}`);
9747
+ }
9577
9748
  if (report.skippedLines.length > 0) {
9578
9749
  const shown = report.skippedLines.slice(0, 5).join(', ');
9579
9750
  console.log(` ${c.dim(t.profile.skipped(report.skippedLines.length, report.skippedLines.length > 5 ? `${shown}…` : shown))}`);