@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/dist/index.js CHANGED
@@ -2,12 +2,12 @@
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';
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
  // --------------------------------------------------------------------------
@@ -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', 'out', 'o', 'stamp', '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'],
436
436
  'from-helicone': ['out', 'o'],
437
437
  'from-langsmith': ['out', 'o'],
438
438
  switch: ['to', 'migration-usd', 'cases'],
@@ -2687,6 +2687,9 @@ function printReceiptSummary(document, t) {
2687
2687
  console.error(t.receipt.unread(gap.count));
2688
2688
  if (gap.kind === 'no-clock')
2689
2689
  console.error(t.receipt.noClock());
2690
+ if (gap.kind === 'tier-ceiling') {
2691
+ console.error(t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)));
2692
+ }
2690
2693
  }
2691
2694
  }
2692
2695
  /**
@@ -2742,11 +2745,23 @@ function usageSourcesOf(text) {
2742
2745
  * a bill rather than usage, and pointed at `reconcile`.
2743
2746
  */
2744
2747
  async function commandBill(args, pricing, t) {
2745
- if (args.positional.length === 0)
2746
- throw new Error(t.bill.noPath());
2747
2748
  /* Refused before any file is read: a bad shape found after the receipt
2748
2749
  printed would end a run that looked finished with an error. */
2749
2750
  const csvShape = csvShapeOf(args, t);
2751
+ /*
2752
+ No path is the most common first run, and it used to be a refusal: the
2753
+ person had to know where Claude Code keeps its sessions before the one
2754
+ line on the README worked. Claude Code's own folders are searched
2755
+ instead, and the ones found are named, so nothing is read silently.
2756
+ */
2757
+ let targets = args.positional;
2758
+ if (targets.length === 0) {
2759
+ const { found, tried } = await claudeProjectFolders(process.env);
2760
+ if (found.length === 0)
2761
+ throw new Error(t.bill.noPath(tried.join(', ')));
2762
+ console.error(t.bill.defaultPath(found.join(', ')));
2763
+ targets = found;
2764
+ }
2750
2765
  /*
2751
2766
  Every path given, files and directories alike, because a shell glob hands
2752
2767
  over many and reading the first was a bill missing the rest. A file named
@@ -2755,14 +2770,18 @@ async function commandBill(args, pricing, t) {
2755
2770
  */
2756
2771
  const files = [];
2757
2772
  const seen = new Set();
2758
- const add = (file) => {
2773
+ /* Reached through a directory: where a project folder can name the work. */
2774
+ const walked = new Set();
2775
+ const add = (file, fromDirectory) => {
2759
2776
  const key = resolvePath(file);
2777
+ if (fromDirectory)
2778
+ walked.add(file);
2760
2779
  if (seen.has(key))
2761
2780
  return;
2762
2781
  seen.add(key);
2763
2782
  files.push(file);
2764
2783
  };
2765
- for (const target of args.positional) {
2784
+ for (const target of targets) {
2766
2785
  let info;
2767
2786
  try {
2768
2787
  info = await stat(target);
@@ -2779,16 +2798,33 @@ async function commandBill(args, pricing, t) {
2779
2798
  if (found.length === 0)
2780
2799
  throw new Error(t.bill.noFiles(target));
2781
2800
  for (const file of found)
2782
- add(file);
2801
+ add(file, true);
2783
2802
  }
2784
2803
  else {
2785
- add(target);
2804
+ add(target, false);
2786
2805
  }
2787
2806
  }
2788
2807
  const label = stringFlag(args, 'label');
2789
2808
  const withLabel = label === undefined ? {} : { label };
2809
+ /*
2810
+ Claude Code keeps one folder per project, and "per project" is the
2811
+ question this door is for. `from-claude-code` has labelled a directory by
2812
+ its project folders since 1.77; `bill` read the same transcripts with no
2813
+ label at all, so the bill it printed could not say which project spent
2814
+ the money. Same default, same function, same way to decline.
2815
+ */
2816
+ const labelFromProject = boolFlag(args, 'label-from-project', true);
2817
+ let labelledByProject = 0;
2790
2818
  const lines = [];
2791
2819
  let sources = 0;
2820
+ /*
2821
+ One line per file is right for a handful and noise for a Claude Code
2822
+ folder of hundreds. Past a handful, the lines are per shape, and the
2823
+ files no shape claims are named for the first few and counted after.
2824
+ */
2825
+ const perFile = files.length <= 8;
2826
+ const unclaimed = [];
2827
+ const byShape = new Map();
2792
2828
  for (const file of files) {
2793
2829
  const text = await readUsageLog(file, t);
2794
2830
  const claims = usageSourcesOf(text);
@@ -2797,7 +2833,7 @@ async function commandBill(args, pricing, t) {
2797
2833
  console.error(t.bill.costReport(file));
2798
2834
  }
2799
2835
  else {
2800
- console.error(t.bill.unknown(file));
2836
+ unclaimed.push(file);
2801
2837
  }
2802
2838
  continue;
2803
2839
  }
@@ -2812,7 +2848,10 @@ async function commandBill(args, pricing, t) {
2812
2848
  let leftOut = 0;
2813
2849
  switch (shape) {
2814
2850
  case 'claude-code': {
2815
- const c = claudeCodeRecords(text, withLabel);
2851
+ const project = label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
2852
+ if (project !== undefined && project !== '')
2853
+ labelledByProject += 1;
2854
+ const c = claudeCodeRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
2816
2855
  records = c.records;
2817
2856
  leftOut = c.assistantWithoutUsage + c.unparseable;
2818
2857
  break;
@@ -2871,23 +2910,55 @@ async function commandBill(args, pricing, t) {
2871
2910
  for (const record of records)
2872
2911
  lines.push(JSON.stringify(record));
2873
2912
  sources += 1;
2874
- console.error(t.bill.file(file, shape, shape === 'usage-log' ? null : records.length, leftOut));
2875
- }
2913
+ const count = shape === 'usage-log' ? null : records.length;
2914
+ if (perFile) {
2915
+ console.error(t.bill.file(file, shape, count, leftOut));
2916
+ }
2917
+ else {
2918
+ const sum = byShape.get(shape) ?? { files: 0, records: count === null ? null : 0, leftOut: 0 };
2919
+ sum.files += 1;
2920
+ if (sum.records !== null && count !== null)
2921
+ sum.records += count;
2922
+ sum.leftOut += leftOut;
2923
+ byShape.set(shape, sum);
2924
+ }
2925
+ }
2926
+ for (const [shape, sum] of byShape)
2927
+ console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut));
2928
+ const named = perFile ? unclaimed : unclaimed.slice(0, 3);
2929
+ for (const file of named)
2930
+ console.error(t.bill.unknown(file));
2931
+ if (unclaimed.length > named.length)
2932
+ console.error(t.bill.unknownMore(unclaimed.length - named.length));
2933
+ if (labelledByProject > 0)
2934
+ console.error(t.bill.labelledByProject(labelledByProject));
2876
2935
  if (sources === 0)
2877
2936
  throw new Error(t.bill.nothingRead());
2878
2937
  const report = profileUsage(lines.join('\n'), { catalogue: pricing });
2879
2938
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
2880
2939
  const json = JSON.stringify(document, null, 2);
2940
+ /*
2941
+ A terminal gets a statement a person can read; a pipe gets the receipt.
2942
+ The receipt on a terminal was 60 lines of JSON before the first figure a
2943
+ reader wanted, which is the screen a first run ends on. Scripts are
2944
+ untouched: they pipe, and a pipe is not a TTY. `--receipt` forces the
2945
+ receipt and `--table` forces the statement, either way round. Not
2946
+ `--json`: that flag means a documented contract in docs/format.md, and
2947
+ the receipt is `trazum receipt`'s document, emitted here unchanged.
2948
+ */
2881
2949
  const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
2950
+ const statement = !boolFlag(args, 'receipt') && boolFlag(args, 'table', process.stdout.isTTY === true);
2882
2951
  if (out !== undefined) {
2883
2952
  await writeFile(out, json + '\n', 'utf8');
2884
2953
  console.error(t.bill.written(out));
2885
2954
  }
2886
- else {
2955
+ else if (!statement) {
2887
2956
  console.log(json);
2888
2957
  }
2889
2958
  console.error(t.bill.sources(sources, files.length));
2890
2959
  printReceiptSummary(document, t);
2960
+ if (statement)
2961
+ printBillStatement(report, labelledByProject > 0, t);
2891
2962
  await writeBillSideFiles(args, report, pricing, csvShape, t);
2892
2963
  /*
2893
2964
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -2900,6 +2971,101 @@ async function commandBill(args, pricing, t) {
2900
2971
  console.error(t.bill.pricingLiveHint(slugged.length));
2901
2972
  }
2902
2973
  }
2974
+ /**
2975
+ * Where Claude Code keeps its sessions, in the order it looks itself.
2976
+ *
2977
+ * `CLAUDE_CONFIG_DIR` first, because a person who set it moved the folder on
2978
+ * purpose; then the two defaults Claude Code has used. Every folder that
2979
+ * exists is returned, deduplicated, so a machine with both is billed for
2980
+ * both, once each. `tried` is every candidate, for the refusal to name.
2981
+ */
2982
+ async function claudeProjectFolders(env) {
2983
+ const home = homedir();
2984
+ const tried = [
2985
+ ...(env.CLAUDE_CONFIG_DIR ? [join(env.CLAUDE_CONFIG_DIR, 'projects')] : []),
2986
+ join(home, '.claude', 'projects'),
2987
+ join(home, '.config', 'claude', 'projects'),
2988
+ ];
2989
+ const found = [];
2990
+ const seen = new Set();
2991
+ for (const candidate of tried) {
2992
+ const key = resolvePath(candidate);
2993
+ if (seen.has(key))
2994
+ continue;
2995
+ seen.add(key);
2996
+ try {
2997
+ if ((await stat(candidate)).isDirectory())
2998
+ found.push(candidate);
2999
+ }
3000
+ catch {
3001
+ // Not there, which is the ordinary case for two of the three.
3002
+ }
3003
+ }
3004
+ return { found, tried };
3005
+ }
3006
+ /**
3007
+ * The bill as a person reads it: the total, by project, by model, and what
3008
+ * is not in the total, on stdout. The receipt's figures, rendered: nothing
3009
+ * here is computed that the receipt does not carry.
3010
+ */
3011
+ function printBillStatement(report, byProject, t) {
3012
+ const n = (value) => value.toLocaleString(t.numberLocale);
3013
+ const pct = (share) => `${(share * 100).toFixed(1)}%`;
3014
+ const total = report.total.totalUsd;
3015
+ const LIMIT = 12;
3016
+ const rowsOf = (entries) => {
3017
+ const shown = entries.slice(0, LIMIT).map(({ name, calls, usd }) => {
3018
+ const share = total > 0 ? usd / total : 0;
3019
+ return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3020
+ });
3021
+ if (entries.length > LIMIT)
3022
+ shown.push([c.dim(t.bill.moreRows(entries.length - LIMIT)), '', '', '']);
3023
+ return shown;
3024
+ };
3025
+ const columns = (first) => [
3026
+ { header: first, align: 'left' },
3027
+ { header: t.bill.colCalls(), align: 'right' },
3028
+ { header: 'USD', align: 'right' },
3029
+ { header: t.bill.colShare(), align: 'left' },
3030
+ ];
3031
+ console.log();
3032
+ console.log(sectionHeading(t.bill.statementHeading()));
3033
+ console.log(` ${c.bold(t.bill.statementTotal(formatUsd(total), report.total.calls))}`);
3034
+ if (report.span !== null) {
3035
+ const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3036
+ console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3037
+ }
3038
+ const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3039
+ if (labelled.length > 0) {
3040
+ console.log();
3041
+ const entries = report.byLabel.map((row) => ({
3042
+ name: row.label === UNLABELLED ? t.profile.unlabelled() : row.label,
3043
+ calls: row.breakdown.calls,
3044
+ usd: row.breakdown.totalUsd,
3045
+ }));
3046
+ for (const line of table(columns(byProject ? t.bill.colProject() : t.bill.colWorkload()), rowsOf(entries))) {
3047
+ console.log(line);
3048
+ }
3049
+ }
3050
+ const priced = report.byModel.filter((row) => !report.unpricedModels.includes(row.model));
3051
+ if (priced.length > 0) {
3052
+ console.log();
3053
+ const entries = priced.map((row) => ({ name: row.model, calls: row.breakdown.calls, usd: row.breakdown.totalUsd }));
3054
+ for (const line of table(columns(t.bill.colModel()), rowsOf(entries)))
3055
+ console.log(line);
3056
+ }
3057
+ console.log();
3058
+ if (report.unpricedModels.length > 0) {
3059
+ console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
3060
+ }
3061
+ const ceiling = tierCeilingLine(report, t);
3062
+ if (ceiling !== null)
3063
+ console.log(` ${wrap(ceiling, 74, ' ')}`);
3064
+ if (report.skippedLines.length > 0)
3065
+ console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
3066
+ console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3067
+ console.log();
3068
+ }
2903
3069
  /**
2904
3070
  * The bill as a document for somebody else: PDF, HTML, Markdown, CSV.
2905
3071
  *
@@ -3463,6 +3629,8 @@ async function commandFromOpenai(args, t) {
3463
3629
  if (conversion.mixedRows > 0) {
3464
3630
  console.error(t.fromOpenai.mixed(conversion.mixedRows, conversion.nonTextTokens, conversion.cacheWriteUnplaced));
3465
3631
  }
3632
+ if (conversion.cacheWrite12hTokens > 0)
3633
+ console.error(t.fromOpenai.cacheWrite12h(conversion.cacheWrite12hTokens));
3466
3634
  if (conversion.unsplitRows > 0)
3467
3635
  console.error(t.fromOpenai.unsplit(conversion.unsplitRows));
3468
3636
  if (conversion.labelledByProject > 0)
@@ -5265,6 +5433,12 @@ async function readInput(source, t, limit = null) {
5265
5433
  * did not opt in, and turning it into a crash would make an optional dependency
5266
5434
  * a required one by accident.
5267
5435
  */
5436
+ /**
5437
+ * A counter, or why there is none: `null` when the package is not installed,
5438
+ * `{ refused }` when it is and holds no table for this model. Two refusals,
5439
+ * because they send a reader to different places: one to `npm install`, the
5440
+ * other nowhere, since installing what is already installed fixes nothing.
5441
+ */
5268
5442
  async function localCounterFor(model) {
5269
5443
  let loaded;
5270
5444
  try {
@@ -5287,7 +5461,7 @@ async function localCounterFor(model) {
5287
5461
  }
5288
5462
  const result = await loaded.openaiCounter(model);
5289
5463
  if (!result.ok)
5290
- return null;
5464
+ return { refused: result.refusal.known };
5291
5465
  return {
5292
5466
  count: result.count,
5293
5467
  counter: 'openai-tiktoken',
@@ -5562,7 +5736,9 @@ async function commandOptimize(args, config, pricing, t, locale) {
5562
5736
  * the network at all. A prompt counted here is read in this process and
5563
5737
  * goes nowhere, which is the distinction `TokenProvenance.where` carries.
5564
5738
  */
5565
- const local = await localCounterFor(result.usage.model);
5739
+ const found = await localCounterFor(result.usage.model);
5740
+ const local = found !== null && !('refused' in found) ? found : null;
5741
+ const refusedEncodings = found !== null && 'refused' in found ? found.refused : null;
5566
5742
  if (local !== null) {
5567
5743
  result = await withExactTokenCounts(result, async (text) => local.count(text), pricing, {
5568
5744
  counter: local.counter,
@@ -5596,7 +5772,9 @@ async function commandOptimize(args, config, pricing, t, locale) {
5596
5772
  const offered = OPTIONAL_COUNTERS[priced?.provider ?? ''];
5597
5773
  throw new Error(offered === undefined
5598
5774
  ? t.errors.exactTokensWrongFamily(result.usage.model, priced?.provider ?? null)
5599
- : t.errors.exactTokensNeedsPackage(result.usage.model, offered));
5775
+ : refusedEncodings !== null
5776
+ ? t.errors.exactTokensNoEncoding(result.usage.model, offered, refusedEncodings.join(', '))
5777
+ : t.errors.exactTokensNeedsPackage(result.usage.model, offered));
5600
5778
  }
5601
5779
  const apiKey = process.env.ANTHROPIC_API_KEY;
5602
5780
  if (!apiKey) {
@@ -6470,6 +6648,13 @@ async function commandConnect(args, pricing, t) {
6470
6648
  const line = t.connect.unpriced(model.model, n(model.inputTokens + model.outputTokens));
6471
6649
  out.push(md ? `- ${line}` : `! ${line}`);
6472
6650
  }
6651
+ /* A bucket sums requests, so a model priced by prompt length is a range. */
6652
+ const ceilinged = report.byModel.filter((slice) => slice.tierCeilingBuckets > 0);
6653
+ if (ceilinged.length > 0) {
6654
+ out.push('');
6655
+ 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)));
6656
+ out.push(md ? `- ${line}` : `! ${line}`);
6657
+ }
6473
6658
  if (report.gaps.length > 0)
6474
6659
  out.push('');
6475
6660
  for (const gap of report.gaps) {
@@ -8245,6 +8430,9 @@ function reportWhatIf(whatIf, report, t) {
8245
8430
  * adding two savings, and hedged the only honest way — whether these
8246
8431
  * calls can wait is not in the log.
8247
8432
  */
8433
+ if (whatIf.tierCeiling !== null) {
8434
+ console.log(` ${c.yellow('!')} ${wrap(t.profile.whatIfTierCeiling(whatIf.tierCeiling.slices, whatIf.target.displayName, formatUsd(whatIf.tierCeiling.targetFloorUsd)), 74, ' ')}`);
8435
+ }
8248
8436
  if (whatIf.batchOnTarget !== null) {
8249
8437
  console.log(` ${c.dim(wrap(t.profile.whatIfBatchOnTarget(formatUsd(whatIf.batchOnTarget.targetUsd), formatUsd(whatIf.targetUsd)), 74, ' '))}`);
8250
8438
  }
@@ -8485,9 +8673,12 @@ async function reportLabelsBudgetsAndCache(report, config, pricing, t) {
8485
8673
  const name = fit.label === UNLABELLED ? t.profile.unlabelled() : fit.label;
8486
8674
  const gap = formatGap(fit.medianGapMs);
8487
8675
  if (fit.verdict === 'expires-before-reuse') {
8488
- const line = fit.medianGapMs > TTL_1H_MS
8489
- ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
8490
- : t.profile.ttlFitExpires(name, fit.modelName, gap);
8676
+ // The model's own entries: one kind on OpenAI, two on Anthropic.
8677
+ const line = fit.longerTtlMs === null
8678
+ ? t.profile.ttlFitExpiresOnly(name, fit.modelName, gap, formatGap(fit.entryTtlMs))
8679
+ : fit.medianGapMs > fit.longerTtlMs
8680
+ ? t.profile.ttlFitExpiresBoth(name, fit.modelName, gap)
8681
+ : t.profile.ttlFitExpires(name, fit.modelName, gap);
8491
8682
  console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
8492
8683
  }
8493
8684
  else if (fit.verdict === 'overlong-ttl') {
@@ -8570,6 +8761,10 @@ async function reportLabelsBudgetsAndCache(report, config, pricing, t) {
8570
8761
  console.log(` ${c.dim(wrap(t.profile.assumedWriteTtl(report.total.assumedWriteTtlCalls), 74, ' '))}`);
8571
8762
  }
8572
8763
  }
8764
+ /** The ceiling caveat for a report, or `null` when nothing was billed at one. */
8765
+ function tierCeilingLine(report, t) {
8766
+ return report.total.tierCeilingCalls === 0 ? null : tierCeilingCaveat(report, t);
8767
+ }
8573
8768
  /**
8574
8769
  * What caching did to this bill, and what it is about to do.
8575
8770
  *
@@ -9414,6 +9609,15 @@ function reportProfileGaps(report, t, n, stalePricing = null) {
9414
9609
  console.log();
9415
9610
  console.log(` ${c.yellow('!')} ${c.dim(wrap(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' '))}`);
9416
9611
  }
9612
+ /*
9613
+ * A total that billed summed rows at the dearer rate is a ceiling, said with
9614
+ * the other end beside it: the range is the finding, not the doubt.
9615
+ */
9616
+ const ceiling = tierCeilingLine(report, t);
9617
+ if (ceiling !== null) {
9618
+ console.log();
9619
+ console.log(` ${c.yellow('!')} ${wrap(ceiling, 74, ' ')}`);
9620
+ }
9417
9621
  if (report.skippedLines.length > 0) {
9418
9622
  const shown = report.skippedLines.slice(0, 5).join(', ');
9419
9623
  console.log(` ${c.dim(t.profile.skipped(report.skippedLines.length, report.skippedLines.length > 5 ? `${shown}…` : shown))}`);