@trazum/cli 2.5.0 → 2.5.2

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.
Files changed (64) hide show
  1. package/README.md +75 -6
  2. package/dist/filter.d.ts +2 -0
  3. package/dist/filter.d.ts.map +1 -0
  4. package/dist/filter.js +151 -0
  5. package/dist/filter.js.map +1 -0
  6. package/dist/gateway-server.d.ts +2 -0
  7. package/dist/gateway-server.d.ts.map +1 -1
  8. package/dist/gateway-server.js +49 -9
  9. package/dist/gateway-server.js.map +1 -1
  10. package/dist/gateway-spend.d.ts +32 -0
  11. package/dist/gateway-spend.d.ts.map +1 -0
  12. package/dist/gateway-spend.js +116 -0
  13. package/dist/gateway-spend.js.map +1 -0
  14. package/dist/html.d.ts.map +1 -1
  15. package/dist/html.js +25 -2
  16. package/dist/html.js.map +1 -1
  17. package/dist/i18n/en.d.ts.map +1 -1
  18. package/dist/i18n/en.js +50 -6
  19. package/dist/i18n/en.js.map +1 -1
  20. package/dist/i18n/es.d.ts.map +1 -1
  21. package/dist/i18n/es.js +51 -6
  22. package/dist/i18n/es.js.map +1 -1
  23. package/dist/i18n/types.d.ts +28 -1
  24. package/dist/i18n/types.d.ts.map +1 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +225 -41
  27. package/dist/index.js.map +1 -1
  28. package/dist/markdown.d.ts +7 -0
  29. package/dist/markdown.d.ts.map +1 -1
  30. package/dist/markdown.js +24 -2
  31. package/dist/markdown.js.map +1 -1
  32. package/dist/pdf.d.ts.map +1 -1
  33. package/dist/pdf.js +41 -2
  34. package/dist/pdf.js.map +1 -1
  35. package/dist/serve-savings-schema.d.ts +65 -0
  36. package/dist/serve-savings-schema.d.ts.map +1 -0
  37. package/dist/serve-savings-schema.js +54 -0
  38. package/dist/serve-savings-schema.js.map +1 -0
  39. package/dist/serve-savings.d.ts +55 -0
  40. package/dist/serve-savings.d.ts.map +1 -0
  41. package/dist/serve-savings.js +144 -0
  42. package/dist/serve-savings.js.map +1 -0
  43. package/dist/serve-schema.d.ts +536 -0
  44. package/dist/serve-schema.d.ts.map +1 -0
  45. package/dist/serve-schema.js +143 -0
  46. package/dist/serve-schema.js.map +1 -0
  47. package/dist/serve.d.ts.map +1 -1
  48. package/dist/serve.js +30 -5
  49. package/dist/serve.js.map +1 -1
  50. package/package.json +2 -2
  51. package/src/filter.ts +114 -0
  52. package/src/gateway-server.ts +46 -10
  53. package/src/gateway-spend.ts +120 -0
  54. package/src/html.ts +27 -2
  55. package/src/i18n/en.ts +57 -7
  56. package/src/i18n/es.ts +58 -7
  57. package/src/i18n/types.ts +29 -1
  58. package/src/index.ts +227 -43
  59. package/src/markdown.ts +32 -2
  60. package/src/pdf.ts +38 -2
  61. package/src/serve-savings-schema.ts +53 -0
  62. package/src/serve-savings.ts +140 -0
  63. package/src/serve-schema.ts +147 -0
  64. package/src/serve.ts +31 -5
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, 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, codexRecords, looksLikeCodexTranscript, 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, spendByMonth, 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';
@@ -34,6 +34,7 @@ import { renderProfilePdf } from './pdf.js';
34
34
  // to plain output, and a pipe stays plain.
35
35
  import { bar, c, sectionHeading, table } from './style.js';
36
36
  const VALUE_FLAGS = new Set([
37
+ 'recovery-dir',
37
38
  'answers',
38
39
  'label-by-cwd',
39
40
  'label-by-workspace',
@@ -397,6 +398,7 @@ function disabledRules(args, config) {
397
398
  */
398
399
  const GLOBAL_FLAGS = ['help', 'h', 'version', 'v', 'locale', 'json', 'config', 'pricing', 'pricing-live', 'max-input'];
399
400
  const COMMAND_FLAGS = {
401
+ filter: ['recovery-dir'],
400
402
  optimize: [
401
403
  'level', 'model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch',
402
404
  'disable', 'llm', 'exact-tokens', 'diff', 'reorder', 'out', 'o',
@@ -424,7 +426,8 @@ const COMMAND_FLAGS = {
424
426
  schema: [],
425
427
  rollup: ['json', 'html-out'],
426
428
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
427
- receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live'],
429
+ receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
430
+ 'from-codex': ['label', 'out', 'o'],
428
431
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
429
432
  'from-otel': ['label-from-service', 'out', 'o'],
430
433
  'from-litellm': ['out', 'o'],
@@ -432,7 +435,7 @@ const COMMAND_FLAGS = {
432
435
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
433
436
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
434
437
  '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'],
438
+ 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
439
  'from-helicone': ['out', 'o'],
437
440
  'from-langsmith': ['out', 'o'],
438
441
  switch: ['to', 'migration-usd', 'cases'],
@@ -890,6 +893,10 @@ measured = null) {
890
893
  * a measurable one, and it is the honest answer to "what did I gain" on a plan
891
894
  * that costs the same either way.
892
895
  */
896
+ /** A conservative display default, never evidence of a payment arrangement. */
897
+ function prefersTokenReport(host) {
898
+ return ['claude-code', 'codex', 'cursor'].includes(host.id);
899
+ }
893
900
  function printTokensOnly(result, host, t, n,
894
901
  /** Whether they named a scenario while the money was being withheld. */
895
902
  namedScenario = false) {
@@ -897,10 +904,7 @@ namedScenario = false) {
897
904
  const saved = result.tokensBefore - result.tokensAfter;
898
905
  console.log();
899
906
  console.log(sectionHeading(t.report.tokensOnlyHeading(host.displayName)));
900
- // Only claim the host bills by subscription when it does. Forced with the
901
- // flag on GitHub Actions, the first version said "GitHub Actions bills by
902
- // subscription", which is simply false.
903
- console.log(` ${host.billing === 'subscription'
907
+ console.log(` ${prefersTokenReport(host)
904
908
  ? t.report.tokensOnlyWhy(host.displayName)
905
909
  : t.report.tokensOnlyAsked()}`);
906
910
  console.log();
@@ -1142,12 +1146,7 @@ async function commandWhere(args, config, pricing, t) {
1142
1146
  console.log();
1143
1147
  console.log(c.bold(t.where.hostHeading()));
1144
1148
  console.log(` ${host.displayName}${host.evidence ? c.dim(` (${host.evidence})`) : ''}`);
1145
- // The reason this is worth printing at all. Inside a flat plan the monthly
1146
- // figure Trazum computes is arithmetic about tokens, not money anybody gets
1147
- // back, and saying so is more useful than saying nothing.
1148
- if (host.billing === 'subscription') {
1149
- console.log(` ${c.yellow(t.where.subscription(host.displayName))}`);
1150
- }
1149
+ console.log(` ${c.dim(t.where.billingUnknown(host.displayName))}`);
1151
1150
  const target = args.positional[0];
1152
1151
  if (target === undefined) {
1153
1152
  console.log();
@@ -1300,9 +1299,7 @@ function renderInit(proposal, ctx) {
1300
1299
  console.log();
1301
1300
  // 1. Where this is running.
1302
1301
  console.log(` ${t.init.host(ctx.host.displayName)}`);
1303
- if (ctx.host.billing === 'subscription') {
1304
- console.log(` ${c.yellow(t.where.subscription(ctx.host.displayName))}`);
1305
- }
1302
+ console.log(` ${c.dim(t.where.billingUnknown(ctx.host.displayName))}`);
1306
1303
  // 2. The prompts.
1307
1304
  console.log(` ${ctx.prompts.files.length === 0 ? c.dim(t.init.noPrompts()) : t.init.prompts(ctx.prompts.files.length)}`);
1308
1305
  if (ctx.truncated)
@@ -2648,12 +2645,60 @@ async function commandReconcile(args, t) {
2648
2645
  if (billed.unreadableAmount > 0)
2649
2646
  console.error(t.reconcile.unreadableAmount(billed.unreadableAmount));
2650
2647
  }
2648
+ /**
2649
+ * The period a bill or a receipt covers, from `--since`/`--until`.
2650
+ *
2651
+ * `profile`'s window, read the same way: a UTC day, a timestamp, a relative
2652
+ * window or `now`; a bare day is the whole of it, and the window is half-open
2653
+ * underneath, so two adjacent periods share no call and add up to the whole.
2654
+ * Refused before any file is read: a bad date found after the receipt printed
2655
+ * would end a run that looked finished with an error. `words` is the window as
2656
+ * typed, for the documents to print, because rendering the internal exclusive
2657
+ * bound would name the day after the one asked for.
2658
+ */
2659
+ function billingPeriod(args, t) {
2660
+ const now = Date.now();
2661
+ const since = parseWhen(args, 'since', false, t, now);
2662
+ const until = parseWhen(args, 'until', true, t, now);
2663
+ if (since.ms !== undefined && until.ms !== undefined && since.ms >= until.ms) {
2664
+ throw new Error(t.profile.sinceAfterUntil());
2665
+ }
2666
+ if (since.ms === undefined && until.ms === undefined)
2667
+ return { relative: false };
2668
+ return {
2669
+ ...(since.ms !== undefined ? { sinceMs: since.ms } : {}),
2670
+ ...(until.ms !== undefined ? { untilMs: until.ms } : {}),
2671
+ relative: since.relative || until.relative,
2672
+ words: { since: stringFlag(args, 'since') ?? '—', until: stringFlag(args, 'until') ?? '—' },
2673
+ };
2674
+ }
2675
+ /**
2676
+ * A period with nothing in it is refused, never billed at $0: that reads as
2677
+ * "this month was free" when it means the dates missed the log. Said against
2678
+ * what was read, so the fix is in the message.
2679
+ */
2680
+ function refuseEmptyPeriod(text, report, period, pricing, t) {
2681
+ if (period.words === undefined || report.total.calls > 0 || report.unpriced.calls > 0)
2682
+ return;
2683
+ const whole = profileUsage(text, { catalogue: pricing });
2684
+ if (whole.total.calls === 0 && whole.unpriced.calls === 0)
2685
+ return;
2686
+ if (whole.span === null)
2687
+ throw new Error(t.profile.windowNeedsClock());
2688
+ throw new Error(`${t.bill.windowMatchesNothing(dayOf(whole.span.fromMs), dayOf(whole.span.toMs))}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`);
2689
+ }
2651
2690
  async function commandReceipt(args, pricing, t) {
2652
2691
  const file = args.positional[0];
2653
2692
  if (file === undefined)
2654
2693
  throw new Error(t.receipt.noLog());
2694
+ const period = billingPeriod(args, t);
2655
2695
  const text = await readUsageLog(file, t);
2656
- const report = profileUsage(text, { catalogue: pricing });
2696
+ const report = profileUsage(text, {
2697
+ catalogue: pricing,
2698
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
2699
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
2700
+ });
2701
+ refuseEmptyPeriod(text, report, period, pricing, t);
2657
2702
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
2658
2703
  const json = JSON.stringify(document, null, 2);
2659
2704
  const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
@@ -2687,6 +2732,8 @@ function printReceiptSummary(document, t) {
2687
2732
  console.error(t.receipt.unread(gap.count));
2688
2733
  if (gap.kind === 'no-clock')
2689
2734
  console.error(t.receipt.noClock());
2735
+ if (gap.kind === 'undated-excluded')
2736
+ console.error(t.receipt.undatedExcluded(gap.calls));
2690
2737
  if (gap.kind === 'tier-ceiling') {
2691
2738
  console.error(t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)));
2692
2739
  }
@@ -2699,6 +2746,8 @@ function printReceiptSummary(document, t) {
2699
2746
  */
2700
2747
  function usageSourcesOf(text) {
2701
2748
  const claims = [];
2749
+ if (looksLikeCodexTranscript(text))
2750
+ claims.push('codex');
2702
2751
  if (looksLikeClaudeCodeTranscript(text))
2703
2752
  claims.push('claude-code');
2704
2753
  if (looksLikeOtel(text))
@@ -2748,6 +2797,9 @@ async function commandBill(args, pricing, t) {
2748
2797
  /* Refused before any file is read: a bad shape found after the receipt
2749
2798
  printed would end a run that looked finished with an error. */
2750
2799
  const csvShape = csvShapeOf(args, t);
2800
+ /* "What did this month cost" is the question a Claude Code folder of a
2801
+ year's sessions answers worst without a period. */
2802
+ const period = billingPeriod(args, t);
2751
2803
  /*
2752
2804
  No path is the most common first run, and it used to be a refusal: the
2753
2805
  person had to know where Claude Code keeps its sessions before the one
@@ -2815,6 +2867,10 @@ async function commandBill(args, pricing, t) {
2815
2867
  */
2816
2868
  const labelFromProject = boolFlag(args, 'label-from-project', true);
2817
2869
  let labelledByProject = 0;
2870
+ /* Claude Code transcripts read: their money is an API-rate equivalent. */
2871
+ let claudeCodeFiles = 0;
2872
+ let codexFiles = 0;
2873
+ const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
2818
2874
  const lines = [];
2819
2875
  let sources = 0;
2820
2876
  /*
@@ -2847,7 +2903,22 @@ async function commandBill(args, pricing, t) {
2847
2903
  let records = [];
2848
2904
  let leftOut = 0;
2849
2905
  switch (shape) {
2906
+ case 'codex': {
2907
+ codexFiles += 1;
2908
+ const c = codexRecords(text, withLabel);
2909
+ codexEvidence.files += 1;
2910
+ codexEvidence.duplicates += c.duplicates;
2911
+ codexEvidence.missingModel += c.missingModel;
2912
+ codexEvidence.unsupported += c.unsupported;
2913
+ codexEvidence.unparseable += c.unparseable;
2914
+ records = c.records;
2915
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
2916
+ if (leftOut > 0)
2917
+ console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
2918
+ break;
2919
+ }
2850
2920
  case 'claude-code': {
2921
+ claudeCodeFiles += 1;
2851
2922
  const project = label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
2852
2923
  if (project !== undefined && project !== '')
2853
2924
  labelledByProject += 1;
@@ -2934,9 +3005,19 @@ async function commandBill(args, pricing, t) {
2934
3005
  console.error(t.bill.labelledByProject(labelledByProject));
2935
3006
  if (sources === 0)
2936
3007
  throw new Error(t.bill.nothingRead());
2937
- const report = profileUsage(lines.join('\n'), { catalogue: pricing });
3008
+ const text = lines.join('\n');
3009
+ const report = profileUsage(text, {
3010
+ catalogue: pricing,
3011
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3012
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3013
+ });
3014
+ refuseEmptyPeriod(text, report, period, pricing, t);
2938
3015
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
2939
- const json = JSON.stringify(document, null, 2);
3016
+ const billDocument = codexFiles === 0 ? document : {
3017
+ ...document,
3018
+ importEvidence: [{ ...codexEvidence, complete: codexEvidence.missingModel + codexEvidence.unsupported + codexEvidence.unparseable === 0 }],
3019
+ };
3020
+ const json = JSON.stringify(billDocument, null, 2);
2940
3021
  /*
2941
3022
  A terminal gets a statement a person can read; a pipe gets the receipt.
2942
3023
  The receipt on a terminal was 60 lines of JSON before the first figure a
@@ -2958,8 +3039,8 @@ async function commandBill(args, pricing, t) {
2958
3039
  console.error(t.bill.sources(sources, files.length));
2959
3040
  printReceiptSummary(document, t);
2960
3041
  if (statement)
2961
- printBillStatement(report, labelledByProject > 0, t);
2962
- await writeBillSideFiles(args, report, pricing, csvShape, t);
3042
+ printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3043
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles + codexFiles > 0);
2963
3044
  /*
2964
3045
  A slug with a slash in it is how OpenRouter names a model, and the bundled
2965
3046
  catalogue does not carry those: the live overlay does. Said only when the
@@ -2970,6 +3051,17 @@ async function commandBill(args, pricing, t) {
2970
3051
  if (slugged.length > 0 && !boolFlag(args, 'pricing-live')) {
2971
3052
  console.error(t.bill.pricingLiveHint(slugged.length));
2972
3053
  }
3054
+ /*
3055
+ `xai/grok-4.3` is LiteLLM's way of saying "grok-4.3, called on xAI", and
3056
+ `anthropic/claude-sonnet-5-5` could be that or an OpenRouter route. The
3057
+ catalogue never strips a prefix by rule, because a router can bill the same
3058
+ model differently and an alias is a statement, never a derivation. What it
3059
+ can do is say which of these it prices under its own name, so the fix is
3060
+ one rename away rather than a guess made on the reader's behalf.
3061
+ */
3062
+ const priceableAfterSlash = slugged.filter((model) => pricing.byId.has(model.slice(model.lastIndexOf('/') + 1)));
3063
+ if (priceableAfterSlash.length > 0)
3064
+ console.error(t.bill.prefixedKnown(priceableAfterSlash.join(', ')));
2973
3065
  }
2974
3066
  /**
2975
3067
  * Where Claude Code keeps its sessions, in the order it looks itself.
@@ -3008,7 +3100,7 @@ async function claudeProjectFolders(env) {
3008
3100
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3009
3101
  * here is computed that the receipt does not carry.
3010
3102
  */
3011
- function printBillStatement(report, byProject, t) {
3103
+ function printBillStatement(report, byProject, t, window, apiEquivalent = false) {
3012
3104
  const n = (value) => value.toLocaleString(t.numberLocale);
3013
3105
  const pct = (share) => `${(share * 100).toFixed(1)}%`;
3014
3106
  const total = report.total.totalUsd;
@@ -3035,6 +3127,16 @@ function printBillStatement(report, byProject, t) {
3035
3127
  const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3036
3128
  console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3037
3129
  }
3130
+ // The period asked for, as typed: the span above is when the calls in it fell.
3131
+ if (window !== undefined)
3132
+ console.log(c.dim(` ${wrap(t.profile.windowLine(window.since, window.until), 74, ' ')}`));
3133
+ /*
3134
+ "Your bill" over Claude Code transcripts is the API's list price for the
3135
+ work. On a Pro or Max plan the plan is what was paid, and a statement that
3136
+ did not say so would hand somebody a figure they never owed.
3137
+ */
3138
+ if (apiEquivalent)
3139
+ console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3038
3140
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3039
3141
  if (labelled.length > 0) {
3040
3142
  console.log();
@@ -3054,6 +3156,29 @@ function printBillStatement(report, byProject, t) {
3054
3156
  for (const line of table(columns(t.bill.colModel()), rowsOf(entries)))
3055
3157
  console.log(line);
3056
3158
  }
3159
+ /*
3160
+ A year of Claude Code sessions billed in one total says what it all cost
3161
+ and not which month cost what, which is the next question. Summed from the
3162
+ report's own days, oldest first, newest kept when there are many; shown
3163
+ only once the bill spans two calendar months, since one month is the total.
3164
+ */
3165
+ const { months, undated } = spendByMonth(report);
3166
+ if (months.length >= 2) {
3167
+ const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
3168
+ const share = total > 0 ? usd / total : 0;
3169
+ return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3170
+ });
3171
+ if (months.length > LIMIT)
3172
+ shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
3173
+ console.log();
3174
+ for (const line of table(columns(t.bill.colMonth()), shown))
3175
+ console.log(line);
3176
+ if (undated.calls > 0) {
3177
+ console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
3178
+ }
3179
+ const newest = months[months.length - 1];
3180
+ console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
3181
+ }
3057
3182
  console.log();
3058
3183
  if (report.unpricedModels.length > 0) {
3059
3184
  console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
@@ -3063,6 +3188,9 @@ function printBillStatement(report, byProject, t) {
3063
3188
  console.log(` ${wrap(ceiling, 74, ' ')}`);
3064
3189
  if (report.skippedLines.length > 0)
3065
3190
  console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
3191
+ if (report.timeWindow !== null && report.timeWindow.undatedExcluded > 0) {
3192
+ console.log(` ${c.yellow(wrap(t.receipt.undatedExcluded(report.timeWindow.undatedExcluded), 74, ' '))}`);
3193
+ }
3066
3194
  console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3067
3195
  console.log();
3068
3196
  }
@@ -3077,7 +3205,7 @@ function printBillStatement(report, byProject, t) {
3077
3205
  * envelopes. The stale-price caveat travels with them, computed the way
3078
3206
  * `profile` computes it, for the providers this bill actually used.
3079
3207
  */
3080
- async function writeBillSideFiles(args, report, pricing, csvShape, t) {
3208
+ async function writeBillSideFiles(args, report, pricing, csvShape, t, window, apiEquivalent = false) {
3081
3209
  const markdownOut = stringFlag(args, 'markdown-out');
3082
3210
  const htmlOut = stringFlag(args, 'html-out');
3083
3211
  const pdfOut = stringFlag(args, 'pdf-out');
@@ -3091,6 +3219,8 @@ async function writeBillSideFiles(args, report, pricing, csvShape, t) {
3091
3219
  levers: billLevers(report, { catalogue: pricing }),
3092
3220
  cache: cacheEconomics(report.total),
3093
3221
  t,
3222
+ ...(window !== undefined ? { window } : {}),
3223
+ ...(apiEquivalent ? { apiEquivalent } : {}),
3094
3224
  ...(ageDays !== null && ageDays > STALE_PRICING_DAYS ? { stalePricing: { date: reviewed, days: ageDays } } : {}),
3095
3225
  };
3096
3226
  if (markdownOut !== undefined) {
@@ -3263,6 +3393,61 @@ function commandOwnrate(args, t) {
3263
3393
  };
3264
3394
  console.log(JSON.stringify(snippet, null, 2));
3265
3395
  }
3396
+ /** Explicit paths only: Codex histories are not discovered from the user's home. */
3397
+ async function commandFromCodex(args, t) {
3398
+ const target = args.positional[0];
3399
+ if (target === undefined)
3400
+ throw new Error(t.fromCodex.noPath());
3401
+ let info;
3402
+ try {
3403
+ info = await stat(target);
3404
+ }
3405
+ catch {
3406
+ throw new Error(t.fromCodex.notFound(target));
3407
+ }
3408
+ const files = info.isDirectory()
3409
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
3410
+ .filter((entry) => entry.isFile() && /\.(jsonl|ndjson)$/i.test(entry.name))
3411
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
3412
+ : [target];
3413
+ if (files.length === 0)
3414
+ throw new Error(t.fromCodex.noFiles(target));
3415
+ const label = stringFlag(args, 'label');
3416
+ const lines = [];
3417
+ let duplicates = 0;
3418
+ let missingModel = 0;
3419
+ let unsupported = 0;
3420
+ let unparseable = 0;
3421
+ for (const file of files) {
3422
+ const text = await readFile(file, 'utf8');
3423
+ if (!looksLikeCodexTranscript(text)) {
3424
+ unsupported++;
3425
+ continue;
3426
+ }
3427
+ const conversion = codexRecords(text, label === undefined ? {} : { label });
3428
+ for (const record of conversion.records)
3429
+ lines.push(JSON.stringify(record));
3430
+ duplicates += conversion.duplicates;
3431
+ missingModel += conversion.missingModel;
3432
+ unsupported += conversion.unsupported;
3433
+ unparseable += conversion.unparseable;
3434
+ }
3435
+ console.error(t.fromCodex.summary(files.length, lines.length, duplicates));
3436
+ if (missingModel + unsupported + unparseable > 0) {
3437
+ console.error(t.fromCodex.gaps(missingModel, unsupported, unparseable));
3438
+ }
3439
+ console.error(t.fromCodex.caveat());
3440
+ if (lines.length === 0)
3441
+ throw new Error(t.fromCodex.noUsage());
3442
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3443
+ const text = lines.join('\n') + '\n';
3444
+ if (out !== undefined) {
3445
+ await writeFile(out, text, 'utf8');
3446
+ console.error(t.fromCodex.written(out));
3447
+ }
3448
+ else
3449
+ console.log(text.trimEnd());
3450
+ }
3266
3451
  async function commandFromOtel(args, t) {
3267
3452
  const target = args.positional[0];
3268
3453
  if (target === undefined)
@@ -4413,12 +4598,13 @@ async function commandGateway(args, config, configDir, pricing, t) {
4413
4598
  const budget = budgetPositions(resolved.records, config.spend, { catalogue: pricing });
4414
4599
  const position = budget.positions[0] ?? null;
4415
4600
  /**
4416
- * Read once at start, like `serve`'s.
4601
+ * Read the baseline once at start. The gateway adds its own completed
4602
+ * usage and reserves in-flight estimates in memory via `liveBudget`.
4417
4603
  *
4418
4604
  * A file read in the request path would put Trazum's own latency between a
4419
4605
  * caller and their provider on every call, which is a cost this product
4420
- * would otherwise be reporting on somebody else. The staleness is real, so a
4421
- * refusal carries `asOfMs` and says what it rested on.
4606
+ * would otherwise be reporting on somebody else. External spend is still
4607
+ * stale, so a refusal carries the baseline's `asOfMs`.
4422
4608
  */
4423
4609
  const standing = position === null || position.coverage === 'none'
4424
4610
  ? null
@@ -4440,6 +4626,7 @@ async function commandGateway(args, config, configDir, pricing, t) {
4440
4626
  */
4441
4627
  let unmeasured = 0;
4442
4628
  const server = buildGateway({
4629
+ liveBudget: true,
4443
4630
  provider,
4444
4631
  catalogue: pricing,
4445
4632
  policy: {
@@ -5821,24 +6008,12 @@ async function commandOptimize(args, config, pricing, t, locale) {
5821
6008
  }
5822
6009
  return;
5823
6010
  }
5824
- // Tokens-only when the host bills by subscription: there is no bill to
5825
- // reduce, so a monthly figure would be arithmetic about tokens dressed as
5826
- // money. Either flag overrides it, because the host says where *Trazum* runs
5827
- // and not where the prompt goes — somebody editing a production prompt inside
5828
- // Cursor wants the dollars, and they should not have to leave the editor to
5829
- // see them.
6011
+ // Agent harnesses default to token context; their identity does not establish
6012
+ // billing. Explicit API-cost requests and usage-log scenarios retain pricing.
5830
6013
  const host = detectHost();
5831
- /**
5832
- * `--from-log` implies `--cost`, and the reasoning is different from the
5833
- * `--calls` case documented below: `--calls` is a typed scenario parameter,
5834
- * but a usage log with billed token counts is *evidence* — proof this
5835
- * prompt's traffic goes to a metered API, whatever the terminal running
5836
- * the command bills like. Withholding the money there would suppress
5837
- * exactly the figures the person measured in order to see.
5838
- */
5839
6014
  const tokensOnly = boolFlag(args, 'cost') || measured !== null
5840
6015
  ? false
5841
- : boolFlag(args, 'tokens-only') || host.billing === 'subscription';
6016
+ : boolFlag(args, 'tokens-only') || prefersTokenReport(host);
5842
6017
  /**
5843
6018
  * Whether they named a scenario while the money was being withheld.
5844
6019
  *
@@ -10988,6 +11163,12 @@ function printRank(ranked, context) {
10988
11163
  }
10989
11164
  async function main() {
10990
11165
  const argv = process.argv.slice(2);
11166
+ // The stdin display filter has its own small grammar and no project config.
11167
+ if (argv[0] === 'filter') {
11168
+ const { runFilter } = await import('./filter.js');
11169
+ await runFilter(argv.slice(1));
11170
+ return;
11171
+ }
10991
11172
  let locale = localeFromArgv(argv);
10992
11173
  let t = getCliMessages(locale);
10993
11174
  const args = parseArgs(argv, t);
@@ -11189,6 +11370,9 @@ async function main() {
11189
11370
  case 'reconcile':
11190
11371
  await commandReconcile(args, t);
11191
11372
  break;
11373
+ case 'from-codex':
11374
+ await commandFromCodex(args, t);
11375
+ break;
11192
11376
  case 'from-otel':
11193
11377
  await commandFromOtel(args, t);
11194
11378
  break;