@trazum/cli 3.0.0 → 3.0.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 (109) hide show
  1. package/README.md +4 -1
  2. package/assets/trazum-statusline.sh +45 -0
  3. package/dist/base-cost.d.ts +173 -0
  4. package/dist/base-cost.d.ts.map +1 -0
  5. package/dist/base-cost.js +244 -0
  6. package/dist/base-cost.js.map +1 -0
  7. package/dist/bill-range.d.ts +118 -0
  8. package/dist/bill-range.d.ts.map +1 -0
  9. package/dist/bill-range.js +122 -0
  10. package/dist/bill-range.js.map +1 -0
  11. package/dist/command-help.d.ts +17 -0
  12. package/dist/command-help.d.ts.map +1 -0
  13. package/dist/command-help.js +69 -0
  14. package/dist/command-help.js.map +1 -0
  15. package/dist/filter.d.ts +7 -1
  16. package/dist/filter.d.ts.map +1 -1
  17. package/dist/filter.js +10 -18
  18. package/dist/filter.js.map +1 -1
  19. package/dist/gateway-metrics.d.ts +83 -0
  20. package/dist/gateway-metrics.d.ts.map +1 -0
  21. package/dist/gateway-metrics.js +181 -0
  22. package/dist/gateway-metrics.js.map +1 -0
  23. package/dist/gateway-server.d.ts +23 -5
  24. package/dist/gateway-server.d.ts.map +1 -1
  25. package/dist/gateway-server.js +26 -1
  26. package/dist/gateway-server.js.map +1 -1
  27. package/dist/gateway-spend.d.ts +11 -1
  28. package/dist/gateway-spend.d.ts.map +1 -1
  29. package/dist/gateway-spend.js +44 -32
  30. package/dist/gateway-spend.js.map +1 -1
  31. package/dist/git.d.ts +70 -0
  32. package/dist/git.d.ts.map +1 -1
  33. package/dist/git.js +145 -0
  34. package/dist/git.js.map +1 -1
  35. package/dist/i18n/en.d.ts.map +1 -1
  36. package/dist/i18n/en.js +358 -6
  37. package/dist/i18n/en.js.map +1 -1
  38. package/dist/i18n/es.d.ts +0 -1
  39. package/dist/i18n/es.d.ts.map +1 -1
  40. package/dist/i18n/es.js +456 -35
  41. package/dist/i18n/es.js.map +1 -1
  42. package/dist/i18n/types.d.ts +205 -0
  43. package/dist/i18n/types.d.ts.map +1 -1
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +942 -59
  46. package/dist/index.js.map +1 -1
  47. package/dist/loopback-guard.d.ts +37 -0
  48. package/dist/loopback-guard.d.ts.map +1 -0
  49. package/dist/loopback-guard.js +65 -0
  50. package/dist/loopback-guard.js.map +1 -0
  51. package/dist/markdown.d.ts +23 -0
  52. package/dist/markdown.d.ts.map +1 -1
  53. package/dist/markdown.js +105 -0
  54. package/dist/markdown.js.map +1 -1
  55. package/dist/plan-edits.d.ts +63 -0
  56. package/dist/plan-edits.d.ts.map +1 -0
  57. package/dist/plan-edits.js +96 -0
  58. package/dist/plan-edits.js.map +1 -0
  59. package/dist/proactive.d.ts +17 -2
  60. package/dist/proactive.d.ts.map +1 -1
  61. package/dist/proactive.js +16 -9
  62. package/dist/proactive.js.map +1 -1
  63. package/dist/receipt-send.d.ts +44 -0
  64. package/dist/receipt-send.d.ts.map +1 -0
  65. package/dist/receipt-send.js +71 -0
  66. package/dist/receipt-send.js.map +1 -0
  67. package/dist/serve.d.ts +7 -0
  68. package/dist/serve.d.ts.map +1 -1
  69. package/dist/serve.js +22 -1
  70. package/dist/serve.js.map +1 -1
  71. package/dist/session-guard.d.ts +210 -0
  72. package/dist/session-guard.d.ts.map +1 -0
  73. package/dist/session-guard.js +463 -0
  74. package/dist/session-guard.js.map +1 -0
  75. package/dist/task.d.ts +7 -1
  76. package/dist/task.d.ts.map +1 -1
  77. package/dist/task.js +7 -26
  78. package/dist/task.js.map +1 -1
  79. package/dist/waste.d.ts +25 -0
  80. package/dist/waste.d.ts.map +1 -0
  81. package/dist/waste.js +39 -0
  82. package/dist/waste.js.map +1 -0
  83. package/dist/zone.d.ts +27 -0
  84. package/dist/zone.d.ts.map +1 -0
  85. package/dist/zone.js +96 -0
  86. package/dist/zone.js.map +1 -0
  87. package/package.json +2 -2
  88. package/src/base-cost.ts +384 -0
  89. package/src/bill-range.ts +206 -0
  90. package/src/command-help.ts +65 -0
  91. package/src/filter.ts +11 -18
  92. package/src/gateway-metrics.ts +209 -0
  93. package/src/gateway-server.ts +43 -6
  94. package/src/gateway-spend.ts +45 -33
  95. package/src/git.ts +158 -0
  96. package/src/i18n/en.ts +424 -6
  97. package/src/i18n/es.ts +542 -35
  98. package/src/i18n/types.ts +208 -0
  99. package/src/index.ts +952 -58
  100. package/src/loopback-guard.ts +74 -0
  101. package/src/markdown.ts +117 -0
  102. package/src/plan-edits.ts +120 -0
  103. package/src/proactive.ts +22 -13
  104. package/src/receipt-send.ts +89 -0
  105. package/src/serve.ts +23 -1
  106. package/src/session-guard.ts +541 -0
  107. package/src/task.ts +8 -26
  108. package/src/waste.ts +42 -0
  109. package/src/zone.ts +95 -0
package/dist/index.js CHANGED
@@ -4,27 +4,34 @@ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
4
4
  import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
5
  import { cpus, homedir, tmpdir } from 'node:os';
6
6
  import { createInterface } from 'node:readline/promises';
7
- import { dirname, join, resolve as resolvePath } from 'node:path';
7
+ import { basename, dirname, join, resolve as resolvePath } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { createGunzip, gunzipSync } from 'node:zlib';
10
10
  import { Readable } from 'node:stream';
11
- import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billFigures, billLevers, buildWeeklySummary, 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, SHAPE_COMMAND, notAUsageLog, usageShapesOf, plannedCalls, claudeCodeRecords, codexRecords, looksLikeCodexTranscript, geminiCliRecords, looksLikeGeminiCliSession, slimUsageLine, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, batchResultRecords, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, weekWindows, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, spendByPeriod, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
11
+ import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, analyzeSessionWaste, sessionCwd, billFigures, billLevers, buildWeeklySummary, 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, SHAPE_COMMAND, notAUsageLog, usageShapesOf, plannedCalls, claudeCodeRecords, codexRecords, looksLikeCodexTranscript, geminiCliRecords, looksLikeGeminiCliSession, slimUsageLine, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, batchResultRecords, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, modelFrom, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, weekWindows, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, spendByPeriod, isOffered, SOURCE_EXTENSIONS, suggestRewrites, billOtlpInput, toBillOtlpMetrics, toPrometheusText, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, overlayFromClaudeModelPricing, partnerModelId, } from '@trazum/core';
12
12
  import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
13
13
  import { OPTIONAL_COUNTERS } from './optional-counters.js';
14
14
  import { dayOf, formatGap, median, spanDays } from './time.js';
15
15
  // Everything that reads the filesystem, on its own entry point so the web
16
16
  // bundle cannot reach it. See packages/core/src/node.ts.
17
- import { CONFIG_FILENAME, DEFAULT_EXTENSIONS, budgetFor, BUNDLED_CATALOGUE, SAFE_FETCH_INIT, applyPricingOverlay, catalogueFromOverlay, checkedEndpoint, openrouterOverlay, detectHost, loadConfig, walkPrompts, } from '@trazum/core/node';
18
- import { contentAt, gitAvailable, namesByRevision, pathInRepository, repositoryRoot, revisionsFor, runSelf, } from './git.js';
17
+ import { CONFIG_FILENAME, DEFAULT_EXTENSIONS, budgetFor, BUNDLED_CATALOGUE, SAFE_FETCH_INIT, applyPricingOverlay, catalogueFromOverlay, MAX_PRICING_BYTES, checkedEndpoint, openrouterOverlay, detectHost, loadConfig, walkPrompts, } from '@trazum/core/node';
18
+ import { GitUnavailableError, commitTimes, rangeDelivery, contentAt, gitAvailable, namesByRevision, pathInRepository, repositoryRoot, revisionsFor, runSelf, } from './git.js';
19
+ import { billRange, perDelivery, projectLabelOfRoot, windowOf } from './bill-range.js';
20
+ import { canonicalZone, dayInZone, groupByDayInZone, nextDay, startOfDayInZone } from './zone.js';
21
+ import { currentFileDigests, planEditsFor } from './plan-edits.js';
22
+ import { baseGateFails, priceAgainstBase, readBothSides, volumeFor } from './base-cost.js';
19
23
  import { fetchProviderUsage, findCredential } from './connect.js';
20
24
  import { STORE_DIR, appendRecords, readStore, rewriteStore } from './store-fs.js';
21
25
  import { WAIVER_LOG, appendWaiverUse, readWaiverLog } from './waiver-log.js';
22
26
  import { DEFAULT_PORT, buildServer, listen } from './serve.js';
23
27
  import { DEFAULT_GATEWAY_PORT, UPSTREAMS, buildGateway, listenGateway, } from './gateway-server.js';
28
+ import { GatewayMetrics, buildMetricsServer } from './gateway-metrics.js';
29
+ import { priceGatewayUsage } from './gateway-spend.js';
24
30
  import { WATCH_STATE_VERSION, checkWebhook, postWebhook, readWatchState, writeWatchState, } from './watch-run.js';
25
31
  import { notificationFor, sendNotification } from './watch-notify.js';
32
+ import { RECEIPT_KEY_ENV, checkReceiptTarget, sendReceipt } from './receipt-send.js';
26
33
  import { LOCALE_ENV_VARS, detectLocale, getCliMessages } from './i18n/index.js';
27
- import { MAX_SUMMARY_CHARS, fitWithin, renderBlameMarkdown, renderCheckMarkdown, renderDiffMarkdown, renderRankMarkdown, renderProfileMarkdown, tierCeilingCaveat, } from './markdown.js';
34
+ import { MAX_SUMMARY_CHARS, baseChangeText, basePriceText, baseSideText, fitWithin, renderBlameMarkdown, renderCheckMarkdown, renderDiffMarkdown, renderRankMarkdown, renderProfileMarkdown, tierCeilingCaveat, } from './markdown.js';
28
35
  import { renderPositionHtml, renderProfileHtml, renderRollupHtml } from './html.js';
29
36
  import { renderProfilePdf } from './pdf.js';
30
37
  // --------------------------------------------------------------------------
@@ -36,7 +43,10 @@ import { renderProfilePdf } from './pdf.js';
36
43
  // to plain output, and a pipe stays plain.
37
44
  import { runCrontab } from './git.js';
38
45
  import { checkedWeekly } from './weekly.js';
39
- import { ITEMS as PROACTIVE_ITEMS, BACKUP_SUFFIX, CRONTAB, inspectAll as inspectProactive, run as runProactive, shown as shownPath, systemCrontab, } from './proactive.js';
46
+ import { ITEMS as PROACTIVE_ITEMS, BACKUP_SUFFIX, CRONTAB, inspectAll as inspectProactive, run as runProactive, pathsFor, readJsonObject, shown as shownPath, systemCrontab, } from './proactive.js';
47
+ import { GuardWriteFailed, applyGuardPlan, check as checkSessionGuard, guardState, parseThresholds as parseGuardThresholds, planGuard, viewGuard, } from './session-guard.js';
48
+ import { readSession, sizeOf } from './waste.js';
49
+ import { commandHelp } from './command-help.js';
40
50
  import { MAX_COLUMNS, Report, WINDOW, c, cErr, fitPath, sectionHeading, table, wrap } from './style.js';
41
51
  const VALUE_FLAGS = new Set([
42
52
  'only',
@@ -62,14 +72,25 @@ const VALUE_FLAGS = new Set([
62
72
  'against',
63
73
  'contract',
64
74
  'on-cannot-tell',
75
+ // `session-guard check|install`: the two dollar thresholds, which have no default.
76
+ 'warn',
77
+ 'stop',
78
+ // `waste`: a CLAUDE.md to size, the MCP servers the person says are loaded, and the fewest reads worth listing.
79
+ 'claude-md',
80
+ 'mcp-servers',
81
+ 'min-reads',
65
82
  'from-log',
66
83
  'min-usd',
67
84
  'payload',
68
85
  'keep',
69
86
  'interval',
70
87
  'webhook',
88
+ // `bill --receipt --send`: where the receipt is posted. The key is never a flag.
89
+ 'send',
71
90
  'port',
72
91
  'socket',
92
+ // `gateway`: the loopback port its counts are scraped from, off unless given.
93
+ 'metrics-port',
73
94
  // `route` takes a path here, and the flag is deliberately not `--prompt`:
74
95
  // everywhere else in this tool `--prompt` names a marked prompt *inside* a
75
96
  // source file, and reusing it for a path would be a trap laid for the reader.
@@ -88,6 +109,9 @@ const VALUE_FLAGS = new Set([
88
109
  'max-usd',
89
110
  'max-growth-usd',
90
111
  'max-cache-loss-usd',
112
+ // `check --base <ref>` and its gate (#785).
113
+ 'base',
114
+ 'max-monthly-increase-usd',
91
115
  'max-stale-hours',
92
116
  'measure',
93
117
  'workload',
@@ -103,6 +127,9 @@ const VALUE_FLAGS = new Set([
103
127
  'until',
104
128
  // `bill --by day|week|month`: the calendar unit the statement is split by.
105
129
  'by',
130
+ // `bill --agent <name>`: keep one coding agent. `bill --timezone <zone>`: cut days there (#826).
131
+ 'agent',
132
+ 'timezone',
106
133
  'export',
107
134
  'limit',
108
135
  'locale',
@@ -111,6 +138,10 @@ const VALUE_FLAGS = new Set([
111
138
  'html-out',
112
139
  'pdf-out',
113
140
  'otlp-out',
141
+ // `bill --prom-out <file>`: the bill in the Prometheus text format (#844).
142
+ 'prom-out',
143
+ // `bill --git-range <range>`: the commits whose span the statement sums.
144
+ 'git-range',
114
145
  'pricing',
115
146
  'prompt',
116
147
  'out',
@@ -121,6 +152,8 @@ const VALUE_FLAGS = new Set([
121
152
  'gpu-usd-hour',
122
153
  'tokens-per-second',
123
154
  'utilization',
155
+ // `model-pricing --reviewed <date>`: when the contracted rates were last checked (#856).
156
+ 'reviewed',
124
157
  'state',
125
158
  ]);
126
159
  function parseArgs(argv, t) {
@@ -193,6 +226,11 @@ function localeFromArgv(argv) {
193
226
  const flag = index >= 0 ? argv[index + 1] : undefined;
194
227
  return detectLocale(flag);
195
228
  }
229
+ /** The arguments without `--locale <value>`, for a command whose own parser does not know it. */
230
+ function withoutLocale(args) {
231
+ const index = args.indexOf('--locale');
232
+ return index === -1 ? args : [...args.slice(0, index), ...args.slice(index + 2)];
233
+ }
196
234
  function stringFlag(args, name) {
197
235
  const raw = args.flags.get(name);
198
236
  return typeof raw === 'string' ? raw : undefined;
@@ -498,10 +536,10 @@ const COMMAND_FLAGS = {
498
536
  'tokens-only', 'cost', 'prompt', 'suggest', 'apply-suggestions',
499
537
  'cache-suggestions', 'from-log', 'label', 'all-labels',
500
538
  ],
501
- check: ['max-tokens', 'level', 'exact-tokens', 'markdown-out', 'baseline', 'files-from'],
539
+ check: ['max-tokens', 'level', 'exact-tokens', 'markdown-out', 'baseline', 'files-from', 'base', 'max-monthly-increase-usd'],
502
540
  baseline: ['model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch', 'exact-tokens', 'out', 'o'],
503
541
  profile: ['json', 'pricing', 'pricing-live', 'against', 'what-if', 'markdown-out', 'html-out', 'pdf-out', 'csv-out', 'csv-shape', 'max-usd', 'max-growth-usd', 'max-cache-loss-usd', 'max-day-usd', 'max-session-usd', 'label', 'since', 'until', 'dry-run', 'markdown-summary', 'by-source', 'allow-empty'],
504
- plan: ['json', 'out', 'markdown-out', 'min-usd', 'pricing', 'pricing-live'],
542
+ plan: ['json', 'out', 'markdown-out', 'min-usd', 'pricing', 'pricing-live', 'edits', 'reorder'],
505
543
  verify: ['against', 'gate', 'json', 'markdown-out', 'pricing', 'pricing-live'],
506
544
  history: ['store', 'json', 'markdown-out'],
507
545
  connect: ['since', 'until', 'payload', 'store', 'json', 'out', 'markdown-out', 'pricing', 'pricing-live', 'dry-run'],
@@ -529,17 +567,18 @@ const COMMAND_FLAGS = {
529
567
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
530
568
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
531
569
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
532
- 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', 'by'],
570
+ bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'send', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'otlp-out', 'prom-out', 'git-range', 'delivery', 'since', 'until', 'by', 'agent', 'timezone'],
533
571
  weekly: ['label', 'label-from-project', 'out', 'o', 'until', 'notify', 'pricing', 'pricing-live'],
534
572
  'from-helicone': ['out', 'o'],
535
573
  'from-langsmith': ['out', 'o'],
536
574
  switch: ['to', 'migration-usd', 'cases'],
537
575
  ownrate: ['gpu-usd-hour', 'tokens-per-second', 'utilization'],
576
+ 'model-pricing': ['reviewed', 'out', 'o'],
538
577
  pulse: ['json', 'max-stale-hours'],
539
578
  bench: ['workload', 'json', 'record', 'against', 'max-ratio'],
540
579
  write: ['answers', 'json', 'out', 'o', 'calls', 'avg-output'],
541
580
  feedback: [],
542
- gateway: ['on-cannot-tell', 'port', 'socket', 'log', 'pricing', 'pricing-live'],
581
+ gateway: ['on-cannot-tell', 'port', 'socket', 'metrics-port', 'log', 'pricing', 'pricing-live'],
543
582
  ladder: ['pricing', 'pricing-live', 'since', 'until', 'label'],
544
583
  experiment: ['a', 'b', 'min-outcomes', 'pricing', 'pricing-live'],
545
584
  quality: ['label', 'at', 'gate', 'pricing', 'pricing-live'],
@@ -552,6 +591,8 @@ const COMMAND_FLAGS = {
552
591
  blame: ['limit', 'model', 'calls', 'output-tokens', 'batch', 'prompt', 'markdown-out'],
553
592
  doctor: ['level', 'model', 'calls', 'output-tokens', 'batch', 'disable', 'prompt', 'otlp-out'],
554
593
  proactive: ['only', 'dry-run', 'yes', 'json'],
594
+ 'session-guard': ['warn', 'stop', 'on-cannot-tell', 'dry-run', 'yes'],
595
+ waste: ['claude-md', 'mcp-servers', 'min-reads', 'json'],
555
596
  };
556
597
  function rejectUnknownFlags(args, t) {
557
598
  const known = COMMAND_FLAGS[args.command];
@@ -2783,10 +2824,10 @@ async function commandReconcile(args, t) {
2783
2824
  * typed, for the documents to print, because rendering the internal exclusive
2784
2825
  * bound would name the day after the one asked for.
2785
2826
  */
2786
- function billingPeriod(args, t) {
2827
+ function billingPeriod(args, t, zone) {
2787
2828
  const now = Date.now();
2788
- const since = parseWhen(args, 'since', false, t, now);
2789
- const until = parseWhen(args, 'until', true, t, now);
2829
+ const since = parseWhen(args, 'since', false, t, now, zone);
2830
+ const until = parseWhen(args, 'until', true, t, now, zone);
2790
2831
  if (since.ms !== undefined && until.ms !== undefined && since.ms >= until.ms) {
2791
2832
  throw new Error(t.profile.sinceAfterUntil());
2792
2833
  }
@@ -2804,7 +2845,7 @@ function billingPeriod(args, t) {
2804
2845
  * "this month was free" when it means the dates missed the log. Said against
2805
2846
  * what was read, so the fix is in the message.
2806
2847
  */
2807
- function refuseEmptyPeriod(text, report, period, pricing, t) {
2848
+ function refuseEmptyPeriod(text, report, period, pricing, t, zone) {
2808
2849
  if (period.words === undefined || report.total.calls > 0 || report.unpriced.calls > 0)
2809
2850
  return;
2810
2851
  const whole = profileUsage(text, { catalogue: pricing });
@@ -2812,7 +2853,7 @@ function refuseEmptyPeriod(text, report, period, pricing, t) {
2812
2853
  return;
2813
2854
  if (whole.span === null)
2814
2855
  throw new Error(t.profile.windowNeedsClock());
2815
- throw new Error(`${t.bill.windowMatchesNothing(dayOf(whole.span.fromMs), dayOf(whole.span.toMs))}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`);
2856
+ throw new Error(`${t.bill.windowMatchesNothing(zone === undefined ? dayOf(whole.span.fromMs) : dayInZone(whole.span.fromMs, zone), zone === undefined ? dayOf(whole.span.toMs) : dayInZone(whole.span.toMs, zone))}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`);
2816
2857
  }
2817
2858
  async function commandReceipt(args, pricing, t) {
2818
2859
  const file = args.positional[0];
@@ -2936,6 +2977,12 @@ async function readUsageLogOnly(file, t, billPath = file) {
2936
2977
  * a bill rather than usage, and pointed at `reconcile`.
2937
2978
  */
2938
2979
  async function commandBill(args, pricing, t) {
2980
+ /* A range of commits asks a different question and prints its own statement (#777). */
2981
+ const gitRange = stringFlag(args, 'git-range');
2982
+ if (gitRange !== undefined)
2983
+ return billGitRange(args, gitRange, pricing, t);
2984
+ if (args.flags.has('delivery'))
2985
+ throw new Error(t.bill.deliveryNeedsRange());
2939
2986
  /*
2940
2987
  The statement answers first (#758). What was read, file by file, is a
2941
2988
  note on the answer, and on a terminal it printed above it: five lines of
@@ -3101,6 +3148,7 @@ async function gatherUsageLines(args, t) {
3101
3148
  let geminiRemainder = 0;
3102
3149
  /* Each agent's own records, so a bill that read more than one can say which spent what. */
3103
3150
  const agentLines = new Map();
3151
+ const otherLines = [];
3104
3152
  const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
3105
3153
  const lines = [];
3106
3154
  let sources = 0;
@@ -3227,9 +3275,12 @@ async function gatherUsageLines(args, t) {
3227
3275
  case 'usage-log': {
3228
3276
  /* Already the shape every door reads: passed through line by line,
3229
3277
  and what does not parse is the receipt's own unread-lines gap. */
3230
- for (const line of text.split('\n'))
3231
- if (line.trim() !== '')
3232
- lines.push(line);
3278
+ for (const line of text.split('\n')) {
3279
+ if (line.trim() === '')
3280
+ continue;
3281
+ lines.push(line);
3282
+ otherLines.push(line);
3283
+ }
3233
3284
  break;
3234
3285
  }
3235
3286
  }
@@ -3241,6 +3292,10 @@ async function gatherUsageLines(args, t) {
3241
3292
  own.push(JSON.stringify(record));
3242
3293
  agentLines.set(shape, own);
3243
3294
  }
3295
+ else {
3296
+ for (const record of records)
3297
+ otherLines.push(JSON.stringify(record));
3298
+ }
3244
3299
  sources += 1;
3245
3300
  const count = shape === 'usage-log' ? null : records.length;
3246
3301
  if (perFile) {
@@ -3293,34 +3348,248 @@ async function gatherUsageLines(args, t) {
3293
3348
  console.error(t.fromGeminiCli.remainder(geminiRemainder));
3294
3349
  if (sources === 0)
3295
3350
  throw new Error(t.bill.nothingRead());
3296
- return { lines, sources, fileCount: files.length, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject };
3351
+ return { lines, sources, fileCount: files.length, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, otherLines, labelledByProject };
3352
+ }
3353
+ /**
3354
+ * `trazum bill --git-range <range>` (#777): what was recorded in this
3355
+ * repository's Claude Code sessions between the first and the last commit of
3356
+ * the range. The reasoning, and what the figure is not, is in `bill-range.ts`.
3357
+ *
3358
+ * Every flag that would set the period, the project or a file to write is
3359
+ * refused rather than ignored: a `--since` quietly overridden by the commits
3360
+ * would put a different period on the page than the one asked for.
3361
+ */
3362
+ async function billGitRange(args, range, pricing, t) {
3363
+ for (const flag of ['since', 'until', 'label', 'by', 'agent', 'timezone', 'out', 'receipt', 'send', 'table', 'stamp', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'otlp-out', 'prom-out']) {
3364
+ if (args.flags.has(flag))
3365
+ throw new Error(t.bill.rangeConflict(`--${flag}`));
3366
+ }
3367
+ if (!boolFlag(args, 'label-from-project', true))
3368
+ throw new Error(t.bill.rangeConflict('--no-label-from-project'));
3369
+ const cwd = process.cwd();
3370
+ if (!gitAvailable(cwd))
3371
+ throw new Error(t.bill.rangeNoGit());
3372
+ const root = repositoryRoot(cwd);
3373
+ if (root === null)
3374
+ throw new Error(t.bill.rangeNoRepository());
3375
+ let times;
3376
+ try {
3377
+ times = commitTimes(range, { cwd: root });
3378
+ }
3379
+ catch (error) {
3380
+ if (error instanceof GitUnavailableError)
3381
+ throw new Error(t.bill.rangeNoGit());
3382
+ throw error;
3383
+ }
3384
+ if (times === null)
3385
+ throw new Error(t.bill.rangeBad(range));
3386
+ const window = windowOf(times);
3387
+ if (window === null)
3388
+ throw new Error(t.bill.rangeEmpty(range));
3389
+ const gathered = await gatherUsageLines(args, t);
3390
+ const claudeCodeLines = gathered.agentLines.get('claude-code') ?? [];
3391
+ const otherSources = (gathered.agentLines.get('codex')?.length ?? 0) + (gathered.agentLines.get('gemini-cli')?.length ?? 0) + gathered.otherLines.length;
3392
+ const project = projectLabelOfRoot(root);
3393
+ const answer = billRange({ claudeCodeLines, otherSources, project, window, catalogue: pricing });
3394
+ if (answer.projectRecords === 0)
3395
+ throw new Error(t.bill.rangeNoProject());
3396
+ /* `--delivery`: what git shows landed in the same range, as counts (#825). */
3397
+ let delivery = null;
3398
+ if (boolFlag(args, 'delivery')) {
3399
+ try {
3400
+ delivery = rangeDelivery(range, { cwd: root });
3401
+ }
3402
+ catch (error) {
3403
+ if (error instanceof GitUnavailableError)
3404
+ throw new Error(t.bill.rangeNoGit());
3405
+ throw error;
3406
+ }
3407
+ }
3408
+ const at = (ms) => new Date(ms).toISOString().replace('.000Z', 'Z');
3409
+ const out = [
3410
+ '',
3411
+ t.bill.rangeHeading(range),
3412
+ '',
3413
+ t.bill.rangeWindow(at(window.fromMs), at(window.toMs), window.commits),
3414
+ answer.inside.sessions > 0
3415
+ ? t.bill.rangeInside(formatUsd(answer.inside.usd), answer.inside.calls, answer.inside.sessions)
3416
+ : t.bill.rangeNothingInside(),
3417
+ ];
3418
+ if (answer.straddling.length > 0) {
3419
+ out.push('', t.bill.rangeStraddleHeading(answer.straddling.length));
3420
+ for (const s of answer.straddling) {
3421
+ out.push(t.bill.rangeStraddleRow(s.session, at(s.firstMs), at(s.lastMs), formatUsd(s.insideUsd), s.insideCalls, formatUsd(s.outsideUsd), s.outsideCalls));
3422
+ }
3423
+ }
3424
+ else {
3425
+ out.push('', t.bill.rangeNoStraddle());
3426
+ }
3427
+ out.push('', t.bill.rangeMeaning());
3428
+ const left = answer.leftOut;
3429
+ out.push(t.bill.rangeLeftOut(answer.outsideCalls, left.otherProjects, left.otherSources, left.undated));
3430
+ if (answer.inside.unpricedCalls > 0)
3431
+ out.push(t.bill.rangeUnpriced(answer.inside.unpricedCalls));
3432
+ /* After everything the plain view prints, so the flag only adds lines at the end (#825). */
3433
+ if (delivery !== null) {
3434
+ out.push('', t.bill.rangeDelivered(delivery.commits, delivery.merges, delivery.pullRequests, delivery.days));
3435
+ if (answer.inside.sessions > 0) {
3436
+ const per = perDelivery(answer.inside.usd, delivery);
3437
+ const fmt = (usd) => (usd === null ? null : formatUsd(usd));
3438
+ out.push(t.bill.rangeDividedBy(fmt(per.perCommit), fmt(per.perPullRequest), fmt(per.perDay)));
3439
+ }
3440
+ else {
3441
+ out.push(t.bill.rangeDividedNothing());
3442
+ }
3443
+ }
3444
+ out.push('');
3445
+ console.log(out.join('\n'));
3446
+ if (gathered.claudeCodeFiles > 0)
3447
+ console.error(t.bill.apiEquivalent());
3448
+ }
3449
+ /** The ids `--agent` takes: the ones `bill` names each agent's records by. */
3450
+ const agentIds = () => Object.keys(AGENT_NAMES);
3451
+ /**
3452
+ * `bill --agent <name>`, checked: an id (`claude-code`) or the name the bill
3453
+ * prints (`Claude Code`), in any case. An agent it does not know is refused by
3454
+ * name, with the ones it does, never read as "no records".
3455
+ */
3456
+ function agentFlagOf(args, t) {
3457
+ const raw = stringFlag(args, 'agent');
3458
+ if (raw === undefined)
3459
+ return undefined;
3460
+ const wanted = raw.trim().toLowerCase();
3461
+ const found = agentIds().find((id) => id === wanted || AGENT_NAMES[id].toLowerCase() === wanted);
3462
+ if (found === undefined)
3463
+ throw new Error(t.bill.badAgent(raw, agentIds().join(', ')));
3464
+ return found;
3465
+ }
3466
+ /**
3467
+ * `bill --timezone <zone>`, checked, and refused beside the outputs that cut
3468
+ * their days in UTC: those would print days that are not the ones the flag
3469
+ * asked for. The receipt and the statement are not among them. The receipt
3470
+ * holds instants and no day; the statement is the one that is cut.
3471
+ */
3472
+ function zoneFlagOf(args, t, csvShape) {
3473
+ const raw = stringFlag(args, 'timezone');
3474
+ if (raw === undefined)
3475
+ return undefined;
3476
+ const zone = canonicalZone(raw);
3477
+ if (zone === null)
3478
+ throw new Error(t.bill.badTimezone(raw));
3479
+ for (const flag of ['otlp-out', 'prom-out', 'markdown-out', 'html-out', 'pdf-out']) {
3480
+ if (args.flags.has(flag))
3481
+ throw new Error(t.bill.timezoneConflict(`--${flag}`));
3482
+ }
3483
+ if (args.flags.has('csv-out') && csvShape !== 'slice')
3484
+ throw new Error(t.bill.timezoneConflict(`--csv-out --csv-shape ${csvShape}`));
3485
+ return zone;
3486
+ }
3487
+ /**
3488
+ * The priced, dated calls of a bill by day in `zone`: each day's records priced
3489
+ * through the same profile, window and catalogue as the whole, so the days add
3490
+ * up to what the UTC days would have.
3491
+ */
3492
+ function zonedSpendByDay(lines, zone, pricing, period) {
3493
+ const rows = [];
3494
+ for (const [day, own] of [...groupByDayInZone(lines, zone)].sort(([a], [b]) => (a < b ? -1 : 1))) {
3495
+ const part = profileUsage(own.join('\n'), {
3496
+ catalogue: pricing,
3497
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3498
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3499
+ });
3500
+ const calls = part.spendByDay.reduce((sum, d) => sum + d.calls, 0);
3501
+ const usd = part.spendByDay.reduce((sum, d) => sum + d.usd, 0);
3502
+ if (calls > 0)
3503
+ rows.push({ day, calls, usd, topLabel: null, topLabelUsd: 0, byModel: [] });
3504
+ }
3505
+ return rows;
3297
3506
  }
3507
+ /** `bill --send` could not deliver the receipt. 1 stays what every other failure exits with. */
3508
+ const BILL_SEND_FAILED = 3;
3298
3509
  async function billBody(args, pricing, t) {
3510
+ /* `--send` posts the receipt, so it is refused without the flag that asks
3511
+ for the receipt, and its URL and key are judged before any file is read:
3512
+ a send that would be refused must not follow a bill that took a minute. */
3513
+ const sendRaw = stringFlag(args, 'send');
3514
+ let sendTarget = null;
3515
+ if (sendRaw !== undefined) {
3516
+ if (!boolFlag(args, 'receipt'))
3517
+ throw new Error(t.bill.sendNeedsReceipt());
3518
+ const checked = checkReceiptTarget(sendRaw);
3519
+ if (!checked.ok)
3520
+ throw new Error(t.bill.badSendTarget(checked.reason, RECEIPT_KEY_ENV));
3521
+ sendTarget = { url: checked.url, key: checked.key };
3522
+ }
3299
3523
  /* Refused before any file is read: a bad shape found after the receipt
3300
3524
  printed would end a run that looked finished with an error. */
3301
3525
  const csvShape = csvShapeOf(args, t);
3526
+ /* `--agent` and `--timezone` are judged here too, for the same reason (#826). */
3527
+ const agent = agentFlagOf(args, t);
3528
+ const zone = zoneFlagOf(args, t, csvShape);
3302
3529
  /* "What did this month cost" is the question a Claude Code folder of a
3303
3530
  year's sessions answers worst without a period. */
3304
- const period = billingPeriod(args, t);
3531
+ const period = billingPeriod(args, t, zone);
3305
3532
  const byFlag = stringFlag(args, 'by');
3306
3533
  if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
3307
3534
  throw new Error(t.bill.badBy(byFlag));
3308
3535
  }
3309
3536
  const by = byFlag;
3310
- const { lines, sources, fileCount, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject } = await gatherUsageLines(args, t);
3537
+ const gathered = await gatherUsageLines(args, t);
3538
+ const { sources, fileCount, claudeCodeFiles, geminiCliFiles, codexEvidence, labelledByProject } = gathered;
3539
+ /*
3540
+ `--agent` keeps one coding agent's records, the ones `bill` already tells
3541
+ apart by the folder or shape they were read from, and nothing else: a plain
3542
+ log or a provider export belongs to no agent and is left out, counted. What
3543
+ is left out is said on stderr, so a narrower bill never passes for a whole one.
3544
+ */
3545
+ const only = agent === undefined ? null : (gathered.agentLines.get(agent) ?? []);
3546
+ if (agent !== undefined && only !== null) {
3547
+ if (only.length === 0)
3548
+ throw new Error(t.bill.agentNoRecords(AGENT_NAMES[agent], agentIds().join(', ')));
3549
+ console.error(t.bill.agentOnly(AGENT_NAMES[agent], only.length, gathered.lines.length - only.length));
3550
+ }
3551
+ const lines = only ?? gathered.lines;
3552
+ const agentLines = agent === undefined || only === null ? gathered.agentLines : new Map([[agent, only]]);
3553
+ const otherLines = only === null ? gathered.otherLines : [];
3554
+ const codexFiles = agent === undefined || agent === 'codex' ? gathered.codexFiles : 0;
3311
3555
  const text = lines.join('\n');
3312
3556
  const report = profileUsage(text, {
3313
3557
  catalogue: pricing,
3314
3558
  ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3315
3559
  ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3316
3560
  });
3317
- refuseEmptyPeriod(text, report, period, pricing, t);
3561
+ refuseEmptyPeriod(text, report, period, pricing, t, zone);
3318
3562
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3319
3563
  const billDocument = codexFiles === 0 ? document : {
3320
3564
  ...document,
3321
3565
  importEvidence: [{ ...codexEvidence, complete: codexEvidence.missingModel + codexEvidence.unsupported + codexEvidence.unparseable === 0 }],
3322
3566
  };
3323
3567
  const json = JSON.stringify(billDocument, null, 2);
3568
+ /*
3569
+ The bill as OTLP metrics, when asked for: a file and nothing sent, the way
3570
+ `doctor --otlp-out` does it. Priced here from the same records through the
3571
+ same `profileUsage`, split by day, project, model and agent; a day still
3572
+ being measured is counted in the payload's resource and not drawn as a
3573
+ point. See `toBillOtlpMetrics`.
3574
+ */
3575
+ const otlpPath = stringFlag(args, 'otlp-out');
3576
+ const promPath = stringFlag(args, 'prom-out');
3577
+ if (otlpPath !== undefined || promPath !== undefined) {
3578
+ // Built once for both: the Prometheus text is written from the OTLP payload, so the two cannot disagree.
3579
+ const payload = toBillOtlpMetrics(billOtlpInput([
3580
+ { agent: null, lines: otherLines },
3581
+ ...[...agentLines.entries()].map(([agent, own]) => ({ agent: AGENT_NAMES[agent], lines: own })),
3582
+ ], {
3583
+ catalogue: pricing,
3584
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3585
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3586
+ nowMs: Date.now(),
3587
+ }));
3588
+ if (otlpPath !== undefined && (await writeOtlp(args, () => payload)))
3589
+ console.error(t.report.reportWritten(otlpPath));
3590
+ if (promPath !== undefined && (await writeText(promPath, toPrometheusText(payload))))
3591
+ console.error(t.report.reportWritten(promPath));
3592
+ }
3324
3593
  /*
3325
3594
  A terminal gets a statement a person can read; a pipe gets the receipt.
3326
3595
  The receipt on a terminal was 60 lines of JSON before the first figure a
@@ -3339,6 +3608,25 @@ async function billBody(args, pricing, t) {
3339
3608
  else if (!statement) {
3340
3609
  console.log(json);
3341
3610
  }
3611
+ /*
3612
+ The send comes after the receipt is written, so a refusal or an error
3613
+ leaves the file (or stdout) as it was, and the same `json` is what goes:
3614
+ the bytes of this run's receipt with the newline `--out` ends on, and no
3615
+ log line, path or prompt, which `sendReceipt` is not given.
3616
+ */
3617
+ if (sendTarget !== null) {
3618
+ const sent = await sendReceipt(sendTarget.url, sendTarget.key, `${json}\n`);
3619
+ const where = sendTarget.url.host;
3620
+ if (sent.ok) {
3621
+ console.error(t.bill.sendDelivered(where, String(sent.status)));
3622
+ }
3623
+ else {
3624
+ console.error(c.yellow(t.bill.sendFailed(where, sent.status === null ? null : String(sent.status))));
3625
+ if (sent.detail !== '')
3626
+ console.error(sent.detail);
3627
+ process.exitCode = BILL_SEND_FAILED;
3628
+ }
3629
+ }
3342
3630
  console.error(t.bill.sources(sources, fileCount));
3343
3631
  printReceiptSummary(document, t);
3344
3632
  const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
@@ -3360,7 +3648,11 @@ async function billBody(args, pricing, t) {
3360
3648
  .filter((row) => row.calls > 0)
3361
3649
  .sort((a, b) => b.usd - a.usd);
3362
3650
  if (statement) {
3363
- printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by);
3651
+ const zoned = zone === undefined ? undefined : zonedSpendByDay(lines, zone, pricing, period);
3652
+ printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by, zone, zoned);
3653
+ }
3654
+ else if (zone !== undefined) {
3655
+ console.error(t.bill.zoneReceiptNote(zone));
3364
3656
  }
3365
3657
  await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, agentSessions);
3366
3658
  /*
@@ -3384,6 +3676,22 @@ async function billBody(args, pricing, t) {
3384
3676
  const priceableAfterSlash = slugged.filter((model) => pricing.byId.has(model.slice(model.lastIndexOf('/') + 1)));
3385
3677
  if (priceableAfterSlash.length > 0)
3386
3678
  console.error(t.bill.prefixedKnown(priceableAfterSlash.join(', ')));
3679
+ /*
3680
+ A Claude model as Bedrock or Vertex names it (#858). The platform sets its
3681
+ own price, so the call stays unpriced; what changes is that the reader is
3682
+ told what the id is, and the model inside when the catalogue knows it.
3683
+ */
3684
+ const partners = document.gaps.flatMap((gap) => gap.kind === 'unpriced'
3685
+ ? gap.models.flatMap((id) => {
3686
+ const read = partnerModelId(id);
3687
+ if (read === undefined)
3688
+ return [];
3689
+ const known = pricing.byId.get(read.model);
3690
+ return [`${id} (${t.bill.partnerModel(read.platform, known?.id)})`];
3691
+ })
3692
+ : []);
3693
+ if (partners.length > 0)
3694
+ console.error(t.bill.partnerUnpriced(partners.join('; ')));
3387
3695
  }
3388
3696
  /**
3389
3697
  * Where Claude Code keeps its sessions, in the order it looks itself.
@@ -3515,8 +3823,10 @@ async function geminiProjectLabelFor(file) {
3515
3823
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3516
3824
  * here is computed that the receipt does not carry.
3517
3825
  */
3518
- function printBillStatement(report, byProject, t, window, apiEquivalent = false, byAgent = [], by) {
3826
+ function printBillStatement(report, byProject, t, window, apiEquivalent = false, byAgent = [], by, zone, zoned) {
3519
3827
  const n = (value) => value.toLocaleString(t.numberLocale);
3828
+ /* The day an instant falls on: UTC, or the zone `--timezone` named (#826). */
3829
+ const dayAt = (ms) => (zone === undefined ? dayOf(ms) : dayInZone(ms, zone));
3520
3830
  const pct = (share) => `${(share * 100).toFixed(1)}%`;
3521
3831
  const total = report.total.totalUsd;
3522
3832
  const LIMIT = 12;
@@ -3574,7 +3884,7 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false,
3574
3884
  there are more than a screen holds: a month of days, twelve weeks.
3575
3885
  */
3576
3886
  const unit = by ?? 'month';
3577
- const { periods, undated } = spendByPeriod(report, unit);
3887
+ const { periods, undated } = spendByPeriod(zoned === undefined ? report : { spendByDay: zoned, total: report.total }, unit);
3578
3888
  if (periods.length >= (by === undefined ? 2 : 1)) {
3579
3889
  const keep = unit === 'day' ? 31 : LIMIT;
3580
3890
  const shown = periods.slice(-keep).map(({ period, calls, usd }) => [period, n(calls), formatUsd(usd), ...shareCells(usd)]);
@@ -3591,12 +3901,17 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false,
3591
3901
  }
3592
3902
  const newest = periods[periods.length - 1];
3593
3903
  draw.text(unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit), { tone: 'dim' });
3904
+ if (zone !== undefined)
3905
+ draw.text(t.bill.periodHintZone(zone), { tone: 'dim' });
3594
3906
  }
3595
3907
  // What qualifies the total: when the calls fell, and what it is not.
3596
3908
  draw.blank();
3597
3909
  if (report.span !== null) {
3598
- draw.text(t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs)), { tone: 'dim' });
3910
+ draw.text(t.profile.spanLine(dayAt(report.span.fromMs), dayAt(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs)), { tone: 'dim' });
3599
3911
  }
3912
+ // Which calendar the days above are on, said whenever it is not UTC.
3913
+ if (zone !== undefined)
3914
+ draw.text(t.bill.zoneLine(zone), { tone: 'dim' });
3600
3915
  // The period asked for, as typed: the span above is when the calls in it fell.
3601
3916
  if (window !== undefined)
3602
3917
  draw.text(t.profile.windowLine(window.since, window.until), { tone: 'dim' });
@@ -3763,6 +4078,72 @@ async function commandSwitch(args, pricing, t) {
3763
4078
  console.log();
3764
4079
  console.log(` ${wrap(t.switchCmd.quality(`trazum route ${file} --prompt-file <prompt> --cases <cases> --yes`), 74, ' ')}`);
3765
4080
  }
4081
+ /**
4082
+ * `trazum model-pricing` — the contracted rates an organisation already gave
4083
+ * Claude Code in its `modelPricing` managed setting, as a pricing overlay for
4084
+ * `--pricing` (#856). The conversion is `overlayFromClaudeModelPricing` in the
4085
+ * core; this reads the file, writes the overlay, and says on stderr what the
4086
+ * table could not say, model by model.
4087
+ */
4088
+ async function commandModelPricing(args, t) {
4089
+ const file = args.positional[0];
4090
+ if (file === undefined)
4091
+ throw new Error(t.modelPricing.noFile());
4092
+ const reviewed = stringFlag(args, 'reviewed');
4093
+ if (reviewed === undefined)
4094
+ throw new Error(t.modelPricing.noReviewed());
4095
+ /*
4096
+ One open file, measured and read through the same handle, as
4097
+ `readUsageLog` does: a stat by name and a read by name could see two
4098
+ different files. At most one byte past the ceiling is read, so a file
4099
+ that grew after the stat is refused rather than read whole.
4100
+ */
4101
+ const handle = await open(file, 'r').catch(() => undefined);
4102
+ if (handle === undefined)
4103
+ throw new Error(t.modelPricing.notFound(file));
4104
+ let raw;
4105
+ try {
4106
+ if (!(await handle.stat()).isFile())
4107
+ throw new Error(t.modelPricing.notFound(file));
4108
+ // A settings file, not a dataset: the same ceiling as an overlay.
4109
+ const buffer = Buffer.alloc(MAX_PRICING_BYTES + 1);
4110
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
4111
+ if (bytesRead > MAX_PRICING_BYTES)
4112
+ throw new Error(t.modelPricing.tooLarge(file, MAX_PRICING_BYTES));
4113
+ raw = buffer.subarray(0, bytesRead).toString('utf8');
4114
+ }
4115
+ finally {
4116
+ await handle.close();
4117
+ }
4118
+ let document;
4119
+ try {
4120
+ document = JSON.parse(raw);
4121
+ }
4122
+ catch (error) {
4123
+ throw new Error(t.modelPricing.notJson(file, error instanceof Error ? error.message : String(error)));
4124
+ }
4125
+ const result = overlayFromClaudeModelPricing(document, { reviewed, source: basename(file) });
4126
+ for (const skipped of result.skipped)
4127
+ console.error(` ${t.modelPricing.skipped(skipped.key, skipped.reason, skipped.detail)}`);
4128
+ const priced = Object.keys(result.overlay.models).length;
4129
+ if (priced === 0)
4130
+ throw new Error(t.modelPricing.empty());
4131
+ const text = `${JSON.stringify(result.overlay, null, 2)}\n`;
4132
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
4133
+ if (out !== undefined)
4134
+ await writeFile(out, text, 'utf8');
4135
+ else
4136
+ process.stdout.write(text);
4137
+ console.error(t.modelPricing.summary(result.fromRows.length, result.fromMultiplier.length, result.multiplier));
4138
+ if (result.batchFromRatio.length > 0)
4139
+ console.error(` ${t.modelPricing.batch(result.batchFromRatio.length)}`);
4140
+ if (result.fastKept.length > 0)
4141
+ console.error(` ${t.modelPricing.fastKept(result.fastKept.join(', '))}`);
4142
+ if (result.usOnlyDropped.length > 0)
4143
+ console.error(` ${t.modelPricing.usOnly(result.usOnlyDropped.join(', '))}`);
4144
+ if (out !== undefined)
4145
+ console.error(t.modelPricing.written(out, priced));
4146
+ }
3766
4147
  /**
3767
4148
  * `trazum ownrate` — the forty-second: a self-hosted model's $/MTok, derived
3768
4149
  * from the operator's own declared numbers, with the overlay snippet ready to
@@ -5144,6 +5525,16 @@ async function commandGateway(args, config, configDir, pricing, t) {
5144
5525
  * would be the flattering direction.
5145
5526
  */
5146
5527
  let unmeasured = 0;
5528
+ /**
5529
+ * The scrape port, checked before anything listens: a typo here should not
5530
+ * leave a gateway running with no counts behind it.
5531
+ */
5532
+ const metricsRaw = stringFlag(args, 'metrics-port');
5533
+ const metricsPort = metricsRaw === undefined ? null : Number(metricsRaw);
5534
+ if (metricsPort !== null && (!Number.isInteger(metricsPort) || metricsPort < 0 || metricsPort > 65_535)) {
5535
+ throw new Error(t.gateway.badMetricsPort(String(metricsRaw)));
5536
+ }
5537
+ const metrics = metricsPort === null ? null : new GatewayMetrics(provider, Date.now());
5147
5538
  const server = buildGateway({
5148
5539
  liveBudget: true,
5149
5540
  provider,
@@ -5158,15 +5549,18 @@ async function commandGateway(args, config, configDir, pricing, t) {
5158
5549
  standing: () => standing,
5159
5550
  record: (call) => {
5160
5551
  measured.calls += 1;
5552
+ metrics?.measured(call, priceGatewayUsage(pricing, call.model, call, Date.now()));
5161
5553
  console.error(c.dim(t.gateway.measured(call.model, call.label, call.inputTokens, call.outputTokens, call.substituted)));
5162
5554
  },
5163
5555
  unmeasured: (cause) => {
5164
5556
  unmeasured += 1;
5557
+ metrics?.unmeasured(cause);
5165
5558
  console.error(c.yellow(` ${t.gateway.unmeasured(cause, unmeasured)}`));
5166
5559
  },
5167
5560
  note: (line) => {
5168
5561
  console.error(c.yellow(` ${line}`));
5169
5562
  },
5563
+ ...(metrics === null ? {} : { count: (event) => metrics.count(event) }),
5170
5564
  });
5171
5565
  const socket = stringFlag(args, 'socket');
5172
5566
  const portRaw = stringFlag(args, 'port');
@@ -5177,6 +5571,10 @@ async function commandGateway(args, config, configDir, pricing, t) {
5177
5571
  const where = await listenGateway(server, socket !== undefined ? { socket } : { port });
5178
5572
  console.log(c.bold(t.gateway.listening(where, provider)));
5179
5573
  console.log(` ${c.dim(wrap(t.gateway.pointYourSdk(where), 74, ' '))}`);
5574
+ if (metrics !== null && metricsPort !== null) {
5575
+ const scrape = await listenGateway(buildMetricsServer(metrics), { port: metricsPort });
5576
+ console.log(` ${c.dim(wrap(t.gateway.metrics(scrape), 74, ' '))}`);
5577
+ }
5180
5578
  console.log(` ${c.dim(wrap(t.gateway.credential(), 74, ' '))}`);
5181
5579
  console.log(` ${c.dim(wrap(t.gateway.neverSubstitutes(), 74, ' '))}`);
5182
5580
  console.log(` ${c.dim(wrap(standing === null ? t.gateway.noStanding() : t.gateway.standing(formatUsd(standing.consumedUsd), formatUsd(standing.limitUsd)), 74, ' '))}`);
@@ -6593,6 +6991,20 @@ async function commandCheck(args, config, pricing, t, locale) {
6593
6991
  const counter = counterFor(args, t);
6594
6992
  // A flag beats the config, as everywhere else. -1 means "not given".
6595
6993
  const flagBudget = numberFlag(args, 'max-tokens', -1, t);
6994
+ /*
6995
+ `--base <ref>` (#785): each changed prompt's cost on that commit and
6996
+ here. Its gate needs it, and standard input has no base side; both are
6997
+ refused before anything is read.
6998
+ */
6999
+ const baseRef = stringFlag(args, 'base');
7000
+ const maxIncrease = args.flags.has('max-monthly-increase-usd')
7001
+ ? numberFlag(args, 'max-monthly-increase-usd', 0, t)
7002
+ : null;
7003
+ if (maxIncrease !== null && baseRef === undefined)
7004
+ throw new Error(t.againstBase.gateNeedsBase());
7005
+ const compare = async (kind, on, listed) => baseRef === undefined
7006
+ ? null
7007
+ : againstBase(baseRef, kind, on, listed, maxIncrease, config, counter, pricing);
6596
7008
  /**
6597
7009
  * `--files-from -` reads a file list from stdin — the shape
6598
7010
  * `git diff --name-only` already produces — so a pre-commit hook is one
@@ -6608,15 +7020,20 @@ async function commandCheck(args, config, pricing, t, locale) {
6608
7020
  .split('\n')
6609
7021
  .map((line) => line.trim())
6610
7022
  .filter((line) => line !== '');
6611
- await checkDirectory('.', args, flagBudget, config, counter, level, t, locale, pricing, listed);
7023
+ const base = await compare('list', '.', listed);
7024
+ await checkDirectory('.', args, flagBudget, config, counter, level, t, locale, pricing, listed, base);
6612
7025
  return;
6613
7026
  }
6614
7027
  const asDirectory = target !== undefined && target !== '-' ? await isDirectory(target) : false;
6615
7028
  if (asDirectory) {
6616
- await checkDirectory(target, args, flagBudget, config, counter, level, t, locale, pricing);
7029
+ const base = await compare('directory', target);
7030
+ await checkDirectory(target, args, flagBudget, config, counter, level, t, locale, pricing, undefined, base);
6617
7031
  return;
6618
7032
  }
7033
+ if (baseRef !== undefined && (target === undefined || target === '-'))
7034
+ throw new Error(t.againstBase.noStdin());
6619
7035
  const prompt = await readInput(target, t, maxInputFlag(args, t));
7036
+ const base = target === undefined ? null : await compare('file', target);
6620
7037
  const n = (value) => value.toLocaleString(t.numberLocale);
6621
7038
  // A single file falls back to the config budget for its own path, so
6622
7039
  // `trazum check prompts/system.txt` works with no flag once budgets exist.
@@ -6629,7 +7046,7 @@ async function commandCheck(args, config, pricing, t, locale) {
6629
7046
  // author asked to govern.
6630
7047
  const embedded = target && target !== '-' && hasMarker(prompt) ? extractPrompts(prompt) : null;
6631
7048
  if (embedded !== null && (embedded.prompts.length > 0 || embedded.declined.length > 0)) {
6632
- await checkEmbedded(target, embedded, { maxTokens, pattern: flagBudget >= 0 ? null : (configBudget?.pattern ?? null) }, args, counter, level, t, locale, pricing);
7049
+ await checkEmbedded(target, embedded, { maxTokens, pattern: flagBudget >= 0 ? null : (configBudget?.pattern ?? null) }, args, counter, level, t, locale, pricing, base);
6633
7050
  return;
6634
7051
  }
6635
7052
  const verdict = await judgeFile(target ?? '-', prompt, { maxTokens, pattern: flagBudget >= 0 ? null : (configBudget?.pattern ?? null) }, counter, level, locale, pricing);
@@ -6643,6 +7060,7 @@ async function commandCheck(args, config, pricing, t, locale) {
6643
7060
  tokenSource: counter.source,
6644
7061
  band: bandFor(prompt),
6645
7062
  truncated: false,
7063
+ ...(base === null ? {} : { againstBase: base }),
6646
7064
  t,
6647
7065
  }));
6648
7066
  if (boolFlag(args, 'json')) {
@@ -6654,6 +7072,7 @@ async function commandCheck(args, config, pricing, t, locale) {
6654
7072
  tokenSource: counter.source,
6655
7073
  optimizedTokens: verdict.optimizedTokens,
6656
7074
  wouldFitOptimized: verdict.optimizedTokens !== null ? verdict.optimizedTokens <= maxTokens : null,
7075
+ ...(base === null ? {} : { againstBase: base }),
6657
7076
  }));
6658
7077
  }
6659
7078
  else if (ok) {
@@ -6670,8 +7089,95 @@ async function commandCheck(args, config, pricing, t, locale) {
6670
7089
  }
6671
7090
  draw.print((line) => console.error(line));
6672
7091
  }
7092
+ if (base !== null && !boolFlag(args, 'json'))
7093
+ printAgainstBase(base, t);
6673
7094
  if (!ok)
6674
7095
  process.exitCode = 1;
7096
+ if (base !== null && baseGateFails(base))
7097
+ process.exitCode = 1;
7098
+ }
7099
+ /**
7100
+ * Reads both sides and prices them: the CLI's half of `check --base` (#785).
7101
+ *
7102
+ * The model is the one `usage.model` names, or Trazum's default, and the
7103
+ * report says which. The volume comes from `volumes` through `labels`, and
7104
+ * from nowhere else.
7105
+ */
7106
+ async function againstBase(ref, kind, target, listed, maxIncreaseUsd, config, counter, pricing) {
7107
+ const read = await readBothSides({
7108
+ ref,
7109
+ target,
7110
+ kind,
7111
+ ...(listed === undefined ? {} : { listed }),
7112
+ extensions: config.extensions ?? [...DEFAULT_EXTENSIONS, ...SOURCE_EXTENSIONS],
7113
+ ignore: config.ignore ?? [],
7114
+ });
7115
+ if (read.status === 'unavailable') {
7116
+ return {
7117
+ status: 'unavailable',
7118
+ ref,
7119
+ why: read.why,
7120
+ gate: maxIncreaseUsd === null ? null : { maxIncreaseUsd },
7121
+ };
7122
+ }
7123
+ const configured = config.usage?.model;
7124
+ return priceAgainstBase({
7125
+ ref,
7126
+ sha: read.sha,
7127
+ pairs: read.pairs,
7128
+ count: (text) => counter.count(text),
7129
+ model: modelFrom(pricing, configured ?? DEFAULT_USAGE.model),
7130
+ modelFrom: configured === undefined ? 'default' : 'config',
7131
+ pricing,
7132
+ volumeOf: (pair) => volumeFor(pair, config.labels ?? {}, config.volumes ?? {}),
7133
+ maxIncreaseUsd,
7134
+ });
7135
+ }
7136
+ /** The base comparison in the terminal: the same figures as the Markdown, one prompt a row. */
7137
+ function printAgainstBase(report, t) {
7138
+ const ab = t.againstBase;
7139
+ const n = (value) => value.toLocaleString(t.numberLocale);
7140
+ const draw = new Report();
7141
+ draw.blank();
7142
+ if (report.status === 'unavailable') {
7143
+ draw.note('caution', ab.unavailable(report.why, report.ref));
7144
+ if (report.gate !== null)
7145
+ draw.text(ab.gateUnavailable(formatUsd(report.gate.maxIncreaseUsd)), { tone: 'error' });
7146
+ draw.print();
7147
+ return;
7148
+ }
7149
+ draw.heading(ab.heading(report.ref, report.sha.slice(0, 7)));
7150
+ if (report.gate !== null) {
7151
+ const change = formatSignedUsd(report.totals?.changeUsd ?? 0);
7152
+ const limit = formatUsd(report.gate.maxIncreaseUsd);
7153
+ draw.text(report.gate.breached ? ab.gateBreached(change, limit) : ab.gateWithin(change, limit), {
7154
+ tone: report.gate.breached ? 'error' : 'good',
7155
+ });
7156
+ }
7157
+ if (report.rows.length === 0)
7158
+ draw.text(ab.nothingChanged());
7159
+ for (const row of report.rows) {
7160
+ const tokens = `${row.base === null ? '–' : n(row.base.tokens)} → ${row.head === null ? '–' : n(row.head.tokens)}`;
7161
+ draw.blank();
7162
+ draw.text(row.id, { tone: 'bold' });
7163
+ draw.text(`${ab.columnTokens()}: ${tokens} · ${ab.columnCalls()}: ${row.callsPerMonth === null ? ab.notStated() : n(row.callsPerMonth)}`, { indent: ' ' });
7164
+ draw.text(`${ab.columnBase()}: ${baseSideText(row.base, t)} · ${ab.columnHead()}: ${baseSideText(row.head, t)} · ${t.markdown.columnChange()}: ${baseChangeText(row, t)}`, { indent: ' ' });
7165
+ draw.text(basePriceText(row, report.price, t), { indent: ' ', tone: 'dim' });
7166
+ }
7167
+ if (report.totals !== null) {
7168
+ draw.blank().text(ab.totals(formatUsd(report.totals.baseUsd), formatUsd(report.totals.headUsd), formatSignedUsd(report.totals.changeUsd)));
7169
+ }
7170
+ draw.blank();
7171
+ if (report.gate !== null && report.perCallOnly > 0)
7172
+ draw.text(ab.gateNotJudged(report.perCallOnly), { tone: 'dim' });
7173
+ if (report.perCallOnly > 0)
7174
+ draw.text(ab.perCallNote(report.perCallOnly), { tone: 'dim' });
7175
+ if (report.unchanged > 0)
7176
+ draw.text(ab.unchanged(report.unchanged), { tone: 'dim' });
7177
+ if (report.modelFrom === 'default')
7178
+ draw.text(ab.modelDefault(report.price.displayName), { tone: 'dim' });
7179
+ draw.text(ab.inputOnly(), { tone: 'dim' });
7180
+ draw.print();
6675
7181
  }
6676
7182
  async function isDirectory(path) {
6677
7183
  return stat(path)
@@ -6711,16 +7217,30 @@ async function writeMarkdown(args, render) {
6711
7217
  * full disk on a metrics runner must not turn a survey into a failure — the
6712
7218
  * survey is the thing somebody asked for, and the metrics are a copy of it.
6713
7219
  */
7220
+ /** Writes a text file, reporting and swallowing a failure, as `writeOtlp` does: the bill is what was asked for. */
7221
+ async function writeText(path, text) {
7222
+ try {
7223
+ await writeFile(path, text, 'utf8');
7224
+ return true;
7225
+ }
7226
+ catch (error) {
7227
+ const message = error instanceof Error ? error.message : String(error);
7228
+ console.error(c.yellow(`Could not write ${path}: ${message}`));
7229
+ return false;
7230
+ }
7231
+ }
6714
7232
  async function writeOtlp(args, build) {
6715
7233
  const path = stringFlag(args, 'otlp-out');
6716
7234
  if (!path)
6717
- return;
7235
+ return false;
6718
7236
  try {
6719
7237
  await writeFile(path, `${JSON.stringify(build(), null, 2)}\n`, 'utf8');
7238
+ return true;
6720
7239
  }
6721
7240
  catch (error) {
6722
7241
  const message = error instanceof Error ? error.message : String(error);
6723
7242
  console.error(c.yellow(`Could not write ${path}: ${message}`));
7243
+ return false;
6724
7244
  }
6725
7245
  }
6726
7246
  /**
@@ -6744,7 +7264,7 @@ async function writeOtlp(args, build) {
6744
7264
  * then it is not governed, and a green build saying otherwise is the same lie as
6745
7265
  * "0 failures" from a run that measured nothing.
6746
7266
  */
6747
- async function checkEmbedded(path, extraction, budget, args, counter, level, t, locale, pricing) {
7267
+ async function checkEmbedded(path, extraction, budget, args, counter, level, t, locale, pricing, base = null) {
6748
7268
  const n = (value) => value.toLocaleString(t.numberLocale);
6749
7269
  const verdicts = [];
6750
7270
  for (const prompt of extraction.prompts) {
@@ -6763,6 +7283,7 @@ async function checkEmbedded(path, extraction, budget, args, counter, level, t,
6763
7283
  tokenSource: counter.source,
6764
7284
  band,
6765
7285
  truncated: false,
7286
+ ...(base === null ? {} : { againstBase: base }),
6766
7287
  t,
6767
7288
  }));
6768
7289
  if (boolFlag(args, 'json')) {
@@ -6777,8 +7298,9 @@ async function checkEmbedded(path, extraction, budget, args, counter, level, t,
6777
7298
  ok: !isOverBudget(v),
6778
7299
  })),
6779
7300
  declined: extraction.declined,
7301
+ ...(base === null ? {} : { againstBase: base }),
6780
7302
  }, null, 2));
6781
- if (!ok)
7303
+ if (!ok || (base !== null && baseGateFails(base)))
6782
7304
  process.exitCode = 1;
6783
7305
  return;
6784
7306
  }
@@ -6798,7 +7320,9 @@ async function checkEmbedded(path, extraction, budget, args, counter, level, t,
6798
7320
  }
6799
7321
  }
6800
7322
  console.log();
6801
- if (!ok)
7323
+ if (base !== null)
7324
+ printAgainstBase(base, t);
7325
+ if (!ok || (base !== null && baseGateFails(base)))
6802
7326
  process.exitCode = 1;
6803
7327
  }
6804
7328
  /**
@@ -6843,7 +7367,7 @@ function isoDate() {
6843
7367
  * is measured against **the machine's clock, not the data's**, and a log
6844
7368
  * exported last month answers `--since 7d` with nothing.
6845
7369
  */
6846
- function parseWhen(args, flag, endOfDay, t, now) {
7370
+ function parseWhen(args, flag, endOfDay, t, now, zone) {
6847
7371
  const value = stringFlag(args, flag);
6848
7372
  if (value === undefined)
6849
7373
  return { ms: undefined, relative: false };
@@ -6858,6 +7382,10 @@ function parseWhen(args, flag, endOfDay, t, now) {
6858
7382
  if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
6859
7383
  const midnight = Date.parse(`${value}T00:00:00Z`);
6860
7384
  if (Number.isFinite(midnight)) {
7385
+ /* A bare day is a day of the zone asked for, `--timezone`, and of UTC otherwise (#826). */
7386
+ if (zone !== undefined) {
7387
+ return { ms: startOfDayInZone(endOfDay ? nextDay(value) : value, zone), relative: false };
7388
+ }
6861
7389
  return { ms: endOfDay ? midnight + 86_400_000 : midnight, relative: false };
6862
7390
  }
6863
7391
  }
@@ -7999,7 +8527,12 @@ async function commandVerify(args, pricing, t) {
7999
8527
  const texts = await Promise.all(files.map((file) => readUsageLogOnly(file, t, againstPath)));
8000
8528
  const raw = texts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
8001
8529
  const report = profileUsage(raw, { catalogue: pricing });
8002
- const verification = verifyPlan(plan, report, { currentPricingLastReviewed: pricing.lastReviewed });
8530
+ // An edit is checked in the tree as well as in the log: the files it names
8531
+ // are hashed where they are now, and a file that is not there says so.
8532
+ const verification = verifyPlan(plan, report, {
8533
+ currentPricingLastReviewed: pricing.lastReviewed,
8534
+ files: await currentFileDigests(plan),
8535
+ });
8003
8536
  const gate = boolFlag(args, 'gate');
8004
8537
  const n = (value) => value.toLocaleString(t.numberLocale);
8005
8538
  const lines = (md) => {
@@ -8023,6 +8556,12 @@ async function commandVerify(args, pricing, t) {
8023
8556
  if (v.action.kind === 'fix-caching' && v.outcome !== 'cannot-tell') {
8024
8557
  rows.push(t.verify.cacheObserved(formatUsd(Number(v.observed.deltaUsd ?? 0)), v.outcome));
8025
8558
  }
8559
+ if (v.action.kind === 'edit-file' && v.observed.file === 'as-planned-from') {
8560
+ rows.push(t.verify.editNotMade(v.action.detail.edit?.path ?? ''));
8561
+ }
8562
+ if (v.action.kind === 'edit-file' && v.observed.file === 'edited' && v.outcome !== 'cannot-tell') {
8563
+ rows.push(t.verify.editObserved(n(Math.round(Number(v.observed.inputPerCallTokensBefore ?? 0))), n(Math.round(Number(v.observed.inputPerCallTokens ?? 0)))));
8564
+ }
8026
8565
  if (v.attribution?.calls !== undefined) {
8027
8566
  rows.push(t.verify.attribution(n(Math.round(v.attribution.calls.before)), n(Math.round(v.attribution.calls.after)), n(Math.round(v.attribution.outputPerCallTokens?.before ?? 0)), n(Math.round(v.attribution.outputPerCallTokens?.after ?? 0))));
8028
8567
  }
@@ -9900,10 +10439,21 @@ function reportCacheVerdict(report, t) {
9900
10439
  * against a later log possible at all — a prediction nobody wrote down is a
9901
10440
  * prediction nobody can be held to.
9902
10441
  */
9903
- async function commandPlan(args, pricing, t) {
10442
+ async function commandPlan(args, config, pricing, t) {
9904
10443
  const path = args.positional[0];
9905
10444
  if (path === undefined)
9906
10445
  throw new Error(t.plan.noTarget());
10446
+ /*
10447
+ `--edits` (#796): an edit to each prompt file the configuration maps a
10448
+ label to, made by the deterministic steps and recorded by hash. Refused
10449
+ before the log is read when it cannot do anything, rather than after.
10450
+ */
10451
+ const withEdits = boolFlag(args, 'edits');
10452
+ if (boolFlag(args, 'reorder') && !withEdits)
10453
+ throw new Error(t.plan.reorderNeedsEdits());
10454
+ const labelMap = config.labels ?? {};
10455
+ if (withEdits && Object.keys(labelMap).length === 0)
10456
+ throw new Error(t.plan.editsNeedLabels());
9907
10457
  const GZ = LOG_EXTENSIONS.map((ext) => `${ext}.gz`);
9908
10458
  const READABLE = [...LOG_EXTENSIONS, ...GZ];
9909
10459
  const target = await stat(path).catch(() => null);
@@ -9926,12 +10476,47 @@ async function commandPlan(args, pricing, t) {
9926
10476
  throw new Error(t.plan.nothingPriced());
9927
10477
  const levers = billLevers(report, { catalogue: pricing });
9928
10478
  const plan = buildPlan(report, levers, pricing.lastReviewed);
10479
+ let editSkips = [];
10480
+ if (withEdits) {
10481
+ const planned = await planEditsFor({
10482
+ report,
10483
+ labels: labelMap,
10484
+ steps: boolFlag(args, 'reorder') ? ['reorder', 'trim'] : ['trim'],
10485
+ disabledRules: config.disable ?? [],
10486
+ pricing,
10487
+ });
10488
+ // Last, because they carry no money to rank by: the edit's figure is the
10489
+ // workload's measured bill, not a saving, and ranking it among savings
10490
+ // would be ranking it by a number it does not have.
10491
+ plan.actions.push(...planned.actions);
10492
+ editSkips = planned.skipped;
10493
+ }
10494
+ /*
10495
+ `--min-usd` is a floor on money, and an edit carries none, so it keeps
10496
+ every edit: one dropped for having no projected saving would have been
10497
+ dropped for being honest about it.
10498
+ */
9929
10499
  const minUsd = typeof args.flags.get('min-usd') === 'string' ? numberFlag(args, 'min-usd', 0, t) : 0;
9930
- const actions = plan.actions.filter((a) => (a.savingUsd ?? a.stakeUsd ?? 0) >= minUsd);
10500
+ const kept = (a) => a.kind === 'edit-file' || (a.savingUsd ?? a.stakeUsd ?? 0) >= minUsd;
10501
+ const actions = plan.actions.filter(kept);
9931
10502
  const filtered = plan.actions.length - actions.length;
9932
10503
  const droppedUsd = plan.actions
9933
- .filter((a) => (a.savingUsd ?? a.stakeUsd ?? 0) < minUsd)
10504
+ .filter((a) => !kept(a))
9934
10505
  .reduce((sum, a) => sum + (a.savingUsd ?? a.stakeUsd ?? 0), 0);
10506
+ /** An edit's figure and change, in the order the reader needs them. */
10507
+ const editLines = (action) => {
10508
+ const edit = action.detail.edit;
10509
+ const base = action.detail.baseline;
10510
+ if (action.kind !== 'edit-file' || edit === undefined || base === undefined)
10511
+ return null;
10512
+ return {
10513
+ money: t.plan.editMeasured(formatUsd(base.usd), n(base.calls), n(Math.round(base.inputPerCallTokens))),
10514
+ rows: [
10515
+ t.plan.editChange(edit.path, edit.steps.includes('reorder'), n(edit.beforeTokens), n(edit.afterTokens)),
10516
+ t.plan.editCheck(),
10517
+ ],
10518
+ };
10519
+ };
9935
10520
  const n = (value) => value.toLocaleString(t.numberLocale);
9936
10521
  /**
9937
10522
  * The document's totals cover the actions the document holds — a filtered
@@ -9962,11 +10547,16 @@ async function commandPlan(args, pricing, t) {
9962
10547
  }
9963
10548
  for (const action of actions) {
9964
10549
  const name = action.label === UNLABELLED ? t.profile.unlabelled() : action.label;
9965
- const money = action.savingUsd !== null
9966
- ? t.plan.projected(formatUsd(action.savingUsd))
9967
- : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
10550
+ const edit = editLines(action);
10551
+ const money = edit !== null
10552
+ ? edit.money
10553
+ : action.savingUsd !== null
10554
+ ? t.plan.projected(formatUsd(action.savingUsd))
10555
+ : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
9968
10556
  lines.push('');
9969
10557
  lines.push(`### ${t.plan.action(action.kind, name, action.model)} — ${money}`);
10558
+ for (const row of edit?.rows ?? [])
10559
+ lines.push(`- ${row}`);
9970
10560
  if (action.detail.routeTo !== undefined) {
9971
10561
  lines.push(`- ${t.plan.routeTo(action.detail.routeTo.displayName, action.kind === 'route+batch')}`);
9972
10562
  }
@@ -9975,6 +10565,11 @@ async function commandPlan(args, pricing, t) {
9975
10565
  if (action.check !== null)
9976
10566
  lines.push(`- ${t.plan.check(action.check)}`);
9977
10567
  }
10568
+ if (editSkips.length > 0) {
10569
+ lines.push('');
10570
+ for (const skip of editSkips)
10571
+ lines.push(`- _${t.plan.editSkipped(skip.why, skip.label, skip.path)}_`);
10572
+ }
9978
10573
  if (filtered > 0) {
9979
10574
  lines.push('');
9980
10575
  lines.push(`_${t.plan.filtered(n(filtered), formatUsd(minUsd), formatUsd(droppedUsd))}_`);
@@ -10002,9 +10597,12 @@ async function commandPlan(args, pricing, t) {
10002
10597
  draw.text(t.plan.noClock(), { tone: 'dim' });
10003
10598
  for (const action of actions) {
10004
10599
  const name = action.label === UNLABELLED ? t.profile.unlabelled() : action.label;
10005
- const money = action.savingUsd !== null
10006
- ? t.plan.projected(formatUsd(action.savingUsd))
10007
- : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
10600
+ const edit = editLines(action);
10601
+ const money = edit !== null
10602
+ ? edit.money
10603
+ : action.savingUsd !== null
10604
+ ? t.plan.projected(formatUsd(action.savingUsd))
10605
+ : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
10008
10606
  draw.blank();
10009
10607
  // The action and its money on one line when the window holds them; the
10010
10608
  // money under the action when it does not, never split from its word.
@@ -10015,6 +10613,8 @@ async function commandPlan(args, pricing, t) {
10015
10613
  else
10016
10614
  draw.text(title, { first: ` ${draw.markOf('point')} `, indent: ' ', tone: 'bold' }).text(money, { indent: ' ' });
10017
10615
  // The module's `wrap`, at the widths these lines always had on a pipe.
10616
+ for (const row of edit?.rows ?? [])
10617
+ draw.line(` ${c.dim(wrap(row, 72, ' '))}`);
10018
10618
  if (action.detail.routeTo !== undefined) {
10019
10619
  draw.line(` ${c.dim(wrap(t.plan.routeTo(action.detail.routeTo.displayName, action.kind === 'route+batch'), 1000, ' '))}`);
10020
10620
  }
@@ -10024,6 +10624,10 @@ async function commandPlan(args, pricing, t) {
10024
10624
  if (action.check !== null)
10025
10625
  draw.line(` ${c.dim(wrap(t.plan.check(action.check), 72, ' '))}`);
10026
10626
  }
10627
+ if (editSkips.length > 0)
10628
+ draw.blank();
10629
+ for (const skip of editSkips)
10630
+ draw.text(t.plan.editSkipped(skip.why, skip.label, skip.path), { tone: 'dim' });
10027
10631
  if (filtered > 0)
10028
10632
  draw.blank().text(t.plan.filtered(n(filtered), formatUsd(minUsd), formatUsd(droppedUsd)), { tone: 'dim' });
10029
10633
  if (plan.batchExcludedUsd > 0)
@@ -11068,7 +11672,7 @@ async function scanPrompts(root, args, flagBudget, config, counter, level, t, lo
11068
11672
  }
11069
11673
  return { verdicts, declined, truncated, extensions, band: widestBand(judgedTexts) };
11070
11674
  }
11071
- async function checkDirectory(root, args, flagBudget, config, counter, level, t, locale, pricing, only) {
11675
+ async function checkDirectory(root, args, flagBudget, config, counter, level, t, locale, pricing, only, base = null) {
11072
11676
  const n = (value) => value.toLocaleString(t.numberLocale);
11073
11677
  /**
11074
11678
  * An explicit list with nothing checkable is a pass, not an error: the
@@ -11161,6 +11765,7 @@ async function checkDirectory(root, args, flagBudget, config, counter, level, t,
11161
11765
  path: baselineOutcome.path,
11162
11766
  }
11163
11767
  : undefined,
11768
+ ...(base === null ? {} : { againstBase: base }),
11164
11769
  t,
11165
11770
  }));
11166
11771
  if (boolFlag(args, 'json')) {
@@ -11181,9 +11786,12 @@ async function checkDirectory(root, args, flagBudget, config, counter, level, t,
11181
11786
  ? v.optimizedTokens <= v.maxTokens
11182
11787
  : null,
11183
11788
  })),
11789
+ ...(base === null ? {} : { againstBase: base }),
11184
11790
  }, null, 2));
11185
11791
  if (failures.length > 0 || declined.length > 0)
11186
11792
  process.exitCode = 1;
11793
+ if (base !== null && baseGateFails(base))
11794
+ process.exitCode = 1;
11187
11795
  return;
11188
11796
  }
11189
11797
  // Every column is sized from the whole set before anything is printed, so the
@@ -11252,9 +11860,14 @@ async function checkDirectory(root, args, flagBudget, config, counter, level, t,
11252
11860
  console.log();
11253
11861
  reportBaseline(baselineOutcome.comparison, baselineOutcome.breached, baselineOutcome.document, baselineOutcome.path, baselineOutcome.usage, pricing, t);
11254
11862
  }
11863
+ if (base !== null)
11864
+ printAgainstBase(base, t);
11255
11865
  console.log();
11256
11866
  if (bad)
11257
11867
  process.exitCode = 1;
11868
+ // A fourth verdict about the same run, and as independent as the others.
11869
+ if (base !== null && baseGateFails(base))
11870
+ process.exitCode = 1;
11258
11871
  }
11259
11872
  /** Joins two path fragments for display and glob matching, always with `/`. */
11260
11873
  function joinPosix(root, relativePath) {
@@ -12024,17 +12637,266 @@ function printRank(ranked, context) {
12024
12637
  console.log(`\n${c.dim(t.rank.densityNote())}`);
12025
12638
  console.log(`${c.dim(t.rank.recoverableNote())}\n`);
12026
12639
  }
12027
- async function main() {
12028
- const argv = process.argv.slice(2);
12029
- if (argv[0] === 'task') {
12030
- const { runTask } = await import('./task.js');
12031
- await runTask(argv.slice(1));
12640
+ /**
12641
+ * `trazum session-guard`: a Claude Code hook that warns, then stops a session,
12642
+ * at two dollar figures the person sets. The logic is in `session-guard.ts`;
12643
+ * this reads the flags and the machine once and says what happened.
12644
+ *
12645
+ * **It never loads the project's config or a pricing overlay.** `check` is the
12646
+ * hook Claude Code runs before every prompt and tool call, and a
12647
+ * `trazum.config.json` that fails to parse in whatever directory the session
12648
+ * is in must not decide whether a spending limit holds. It prices at the
12649
+ * bundled catalogue, dated, and reads only files already on this machine.
12650
+ */
12651
+ async function commandSessionGuard(args, t) {
12652
+ const action = args.positional[0] ?? 'status';
12653
+ if (!['status', 'install', 'uninstall', 'check'].includes(action))
12654
+ throw new Error(t.sessionGuard.unknownAction(action));
12655
+ for (const flag of ['pricing', 'pricing-live', 'config']) {
12656
+ if (args.flags.has(flag))
12657
+ throw new Error(t.sessionGuard.refusedFlag(`--${flag}`));
12658
+ }
12659
+ const parsed = parseGuardThresholds({
12660
+ warn: stringFlag(args, 'warn'),
12661
+ stop: stringFlag(args, 'stop'),
12662
+ policy: stringFlag(args, 'on-cannot-tell'),
12663
+ });
12664
+ const refusal = (given) => {
12665
+ if (given.ok)
12666
+ return '';
12667
+ const r = given.refusal;
12668
+ switch (r.code) {
12669
+ case 'missing':
12670
+ return t.sessionGuard.refusedMissing(r.flags.join(', '));
12671
+ case 'notAmount':
12672
+ return t.sessionGuard.refusedAmount(r.flag, r.given);
12673
+ case 'badPolicy':
12674
+ return t.sessionGuard.refusedPolicy(r.given, r.allowed);
12675
+ case 'warnNotBelowStop':
12676
+ return t.sessionGuard.refusedWarnNotBelowStop();
12677
+ }
12678
+ };
12679
+ if (action === 'check') {
12680
+ if (!parsed.ok)
12681
+ throw new Error(refusal(parsed));
12682
+ let stdin = '';
12683
+ if (process.stdin.isTTY !== true) {
12684
+ const chunks = [];
12685
+ for await (const chunk of process.stdin)
12686
+ chunks.push(Buffer.from(chunk));
12687
+ stdin = Buffer.concat(chunks).toString('utf8');
12688
+ }
12689
+ const result = await checkSessionGuard(stdin, parsed.thresholds, {
12690
+ catalogue: BUNDLED_CATALOGUE,
12691
+ env: process.env,
12692
+ now: new Date(),
12693
+ t,
12694
+ });
12695
+ if (result.stdout !== '')
12696
+ process.stdout.write(`${result.stdout}\n`);
12697
+ if (result.stderr !== '')
12698
+ process.stderr.write(`${result.stderr}\n`);
12699
+ process.exitCode = result.code;
12700
+ return;
12701
+ }
12702
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
12703
+ const entry = (() => {
12704
+ try {
12705
+ return realpathSync(process.argv[1] ?? '');
12706
+ }
12707
+ catch {
12708
+ return resolvePath(process.argv[1] ?? '');
12709
+ }
12710
+ })();
12711
+ const ctx = {
12712
+ home,
12713
+ cwd: process.cwd(),
12714
+ platform: process.platform,
12715
+ execPath: process.execPath,
12716
+ entry,
12717
+ trazumBin: process.env.TRAZUM_BIN,
12718
+ // Not used: the guard writes the settings file and the record, never the crontab.
12719
+ crontab: { read: () => ({ kind: 'none' }), write: () => undefined },
12720
+ script: async () => '',
12721
+ catalogue: BUNDLED_CATALOGUE,
12722
+ };
12723
+ const settings = pathsFor(ctx).settings;
12724
+ const file = shownPath(ctx, settings);
12725
+ if (action === 'status') {
12726
+ const read = await readJsonObject(ctx, settings, resolvePath(home));
12727
+ if (read.kind === 'refused') {
12728
+ console.log(t.proactive.reason[read.finding.code](read.finding.params));
12729
+ return;
12730
+ }
12731
+ const view = viewGuard(read.kind === 'ok' ? read.value : {});
12732
+ if (view.shape !== null) {
12733
+ console.log(t.sessionGuard.settingsShape(file, view.shape));
12734
+ return;
12735
+ }
12736
+ const state = guardState(view);
12737
+ const first = view.found.UserPromptSubmit ?? view.found.PreToolUse;
12738
+ if (state === 'off' || first === undefined)
12739
+ console.log(t.sessionGuard.statusOff(file));
12740
+ else {
12741
+ const line = t.sessionGuard.statusOn(file, formatUsd(first.warnUsd), formatUsd(first.stopUsd), first.policy);
12742
+ console.log(state === 'partial' ? t.sessionGuard.statusPartial(file) : line);
12743
+ }
12744
+ console.log(c.dim(t.sessionGuard.apiEquivalent()));
12745
+ return;
12746
+ }
12747
+ if (action === 'install' && !parsed.ok)
12748
+ throw new Error(refusal(parsed));
12749
+ const plan = await planGuard(ctx, action, parsed.ok ? parsed.thresholds : null, t);
12750
+ if (plan.kind !== 'plan') {
12751
+ console[plan.kind === 'refused' ? 'error' : 'log'](plan.message);
12752
+ if (plan.kind === 'refused')
12753
+ process.exitCode = 1;
12754
+ return;
12755
+ }
12756
+ const yes = boolFlag(args, 'yes');
12757
+ const terminal = process.stdin.isTTY === true;
12758
+ const dryRun = boolFlag(args, 'dry-run') || (!yes && !terminal);
12759
+ const header = action === 'install' ? t.sessionGuard.wouldInstall() : t.sessionGuard.wouldUninstall();
12760
+ const show = () => {
12761
+ console.log(header);
12762
+ for (const change of plan.changes) {
12763
+ console.log(` ${shownPath(ctx, change.target)}`);
12764
+ for (const line of change.removed)
12765
+ console.log(` ${c.red(`- ${line}`)}`);
12766
+ for (const line of change.added)
12767
+ console.log(` ${c.green(`+ ${line}`)}`);
12768
+ }
12769
+ };
12770
+ if (dryRun) {
12771
+ show();
12772
+ console.log(!boolFlag(args, 'dry-run') ? t.sessionGuard.dryRunNoTerminal() : t.sessionGuard.dryRun());
12773
+ return;
12774
+ }
12775
+ if (!yes) {
12776
+ show();
12777
+ const reader = createInterface({ input: process.stdin, output: process.stderr });
12778
+ const answer = await reader
12779
+ .question(action === 'install' ? t.sessionGuard.askInstall(file) : t.sessionGuard.askUninstall(file))
12780
+ .finally(() => reader.close());
12781
+ if (!/^(y|yes|s|si|sí)$/i.test(answer.trim())) {
12782
+ console.log(t.sessionGuard.declined());
12783
+ return;
12784
+ }
12785
+ }
12786
+ try {
12787
+ await applyGuardPlan(ctx, plan, action);
12788
+ }
12789
+ catch (error) {
12790
+ if (!(error instanceof GuardWriteFailed))
12791
+ throw error;
12792
+ console.error(t.sessionGuard.failed(t.proactive.reason[error.finding.code](error.finding.params)));
12793
+ process.exitCode = 1;
12794
+ return;
12795
+ }
12796
+ console.log(action === 'install' ? t.sessionGuard.didInstall(file) : t.sessionGuard.didUninstall(file));
12797
+ if (action === 'install')
12798
+ console.log(c.dim(t.sessionGuard.apiEquivalent()));
12799
+ }
12800
+ /**
12801
+ * `trazum waste <transcript.jsonl>`: what a coding-agent session paid for twice,
12802
+ * or for nothing, priced at the bundled catalogue from the session's own counts.
12803
+ *
12804
+ * It recommends and changes nothing: no file is written, edited or opened for
12805
+ * writing. It reads the transcript and its subagents' transcripts, and the
12806
+ * *size* of one CLAUDE.md. Like `session-guard` it never loads the project's
12807
+ * config or a pricing overlay, so every figure is the bundled, dated catalogue's.
12808
+ */
12809
+ async function commandWaste(args, t) {
12810
+ for (const flag of ['pricing', 'pricing-live', 'config']) {
12811
+ if (args.flags.has(flag))
12812
+ throw new Error(t.waste.refusedFlag(`--${flag}`));
12813
+ }
12814
+ const target = args.positional[0];
12815
+ if (target === undefined)
12816
+ throw new Error(t.waste.noPath());
12817
+ const rawMin = stringFlag(args, 'min-reads');
12818
+ const minReads = rawMin === undefined ? 3 : Number(rawMin);
12819
+ if (!Number.isInteger(minReads) || minReads < 2)
12820
+ throw new Error(t.waste.minReadsBad(rawMin ?? ''));
12821
+ const session = await readSession(resolvePath(target));
12822
+ if (!session.ok)
12823
+ throw new Error(session.cause === 'not-found' ? t.waste.notFound(target) : t.waste.unreadable(target));
12824
+ const explicit = stringFlag(args, 'claude-md');
12825
+ const cwd = sessionCwd(session.texts[0] ?? '');
12826
+ const claudePath = explicit ?? (cwd === undefined ? undefined : join(cwd, 'CLAUDE.md'));
12827
+ const size = claudePath === undefined ? null : await sizeOf(claudePath);
12828
+ const servers = (stringFlag(args, 'mcp-servers') ?? '')
12829
+ .split(',')
12830
+ .map((name) => name.trim())
12831
+ .filter((name) => name !== '');
12832
+ const report = analyzeSessionWaste(session.texts, {
12833
+ catalogue: BUNDLED_CATALOGUE,
12834
+ on: new Date(),
12835
+ minReads,
12836
+ mcpServers: servers,
12837
+ ...(size === null ? {} : { claudeMd: [size] }),
12838
+ });
12839
+ if (boolFlag(args, 'json')) {
12840
+ console.log(JSON.stringify(report, null, 2));
12841
+ return;
12842
+ }
12843
+ if (report.cannotTell !== null) {
12844
+ console.log(t.waste.cannotTell());
12032
12845
  return;
12033
12846
  }
12034
- // The stdin display filter has its own small grammar and no project config.
12035
- if (argv[0] === 'filter') {
12036
- const { runFilter } = await import('./filter.js');
12037
- await runFilter(argv.slice(1));
12847
+ const w = t.waste;
12848
+ console.log(c.bold(w.heading(report.session.calls, report.session.threads)));
12849
+ console.log(c.dim(w.apiEquivalent(report.pricing.lastReviewed)));
12850
+ if (report.unpricedModels.length > 0)
12851
+ console.log(c.dim(w.unpriced(report.unpricedModels.join(', '))));
12852
+ console.log(`\n${c.bold(w.readsHeading())}`);
12853
+ if (report.reads.findings.length === 0)
12854
+ console.log(w.readsNone(report.reads.minReads));
12855
+ for (const row of report.reads.findings) {
12856
+ console.log(` ${row.path}`);
12857
+ console.log(` ${w.readLine(row.reads, row.repeats, row.measured, row.tokens, row.usd === null ? null : formatUsd(row.usd))}`);
12858
+ }
12859
+ if (report.reads.omitted > 0)
12860
+ console.log(c.dim(w.readsOmitted(report.reads.omitted)));
12861
+ if (report.reads.usd !== null)
12862
+ console.log(w.readsTotal(formatUsd(report.reads.usd), report.reads.measured, report.reads.repeats));
12863
+ else if (report.reads.repeats > 0)
12864
+ console.log(w.readsUnmeasured(report.reads.repeats));
12865
+ console.log(`\n${c.bold(w.mcpHeading())}`);
12866
+ if (report.mcp.source === 'none')
12867
+ console.log(w.mcpNoList());
12868
+ else {
12869
+ console.log(report.mcp.unused.length === 0 ? w.mcpAllCalled(report.mcp.loaded) : w.mcpSummary(report.mcp.loaded, report.mcp.called, report.mcp.source));
12870
+ for (const server of report.mcp.unused)
12871
+ console.log(` ${w.mcpUnused(server.server, server.tools)}`);
12872
+ if (report.mcp.unused.length > 0)
12873
+ console.log(c.dim(w.mcpNotPriced()));
12874
+ }
12875
+ console.log(`\n${c.bold(w.claudeHeading())}`);
12876
+ if (report.claudeMd.findings.length === 0)
12877
+ console.log(w.claudeNone(claudePath ?? ''));
12878
+ for (const f of report.claudeMd.findings) {
12879
+ console.log(` ${f.path}`);
12880
+ console.log(` ${w.claudeLine(f.bytes, f.tokens, f.calls, formatUsd(f.usd), formatUsd(f.usdLow), formatUsd(f.usdHigh), report.claudeMd.bandPct)}`);
12881
+ }
12882
+ console.log(`\n${c.dim(w.nothingChanged())}`);
12883
+ }
12884
+ async function main() {
12885
+ const argv = process.argv.slice(2);
12886
+ // `task` and the stdin display filter have grammars of their own and no
12887
+ // project config. They still speak the reader's language: `--locale` is
12888
+ // read and taken out before their parsers see it, which refused it (#871).
12889
+ if (argv[0] === 'task' || argv[0] === 'filter') {
12890
+ const messages = getCliMessages(localeFromArgv(argv)).taskFilter;
12891
+ const own = withoutLocale(argv.slice(1));
12892
+ if (argv[0] === 'task') {
12893
+ const { runTask } = await import('./task.js');
12894
+ await runTask(own, messages);
12895
+ }
12896
+ else {
12897
+ const { runFilter } = await import('./filter.js');
12898
+ await runFilter(own, messages);
12899
+ }
12038
12900
  return;
12039
12901
  }
12040
12902
  let locale = localeFromArgv(argv);
@@ -12073,18 +12935,32 @@ async function main() {
12073
12935
  return;
12074
12936
  }
12075
12937
  if (boolFlag(args, 'help') || boolFlag(args, 'h') || !args.command) {
12076
- console.log(t.help({
12938
+ const defaults = {
12077
12939
  model: DEFAULT_USAGE.model,
12078
12940
  callsPerMonth: DEFAULT_USAGE.callsPerMonth,
12079
12941
  avgOutputTokens: DEFAULT_USAGE.avgOutputTokens,
12080
12942
  cacheHitRate: DEFAULT_USAGE.cacheHitRate,
12081
12943
  locales: LOCALES,
12082
12944
  contracts: CONTRACT_NAMES,
12083
- }, c.bold));
12945
+ };
12946
+ const full = t.help(defaults, c.bold);
12947
+ // `trazum <command> --help` is that command's part of the help (#865); the whole help is `trazum --help`.
12948
+ const own = args.command ? commandHelp(full, t.help(defaults, (s) => s), args.command, t.commandHelpMore) : undefined;
12949
+ console.log(own ?? full);
12084
12950
  return;
12085
12951
  }
12086
12952
  rejectUnknownFlags(args, t);
12087
12953
  rejectExtraPositionals(args, t);
12954
+ // Before the config loads, for the reason `commandSessionGuard` gives.
12955
+ if (args.command === 'session-guard') {
12956
+ await commandSessionGuard(args, t);
12957
+ return;
12958
+ }
12959
+ // The same for `waste`: it prices at the bundled catalogue and reads a transcript, not a project's config.
12960
+ if (args.command === 'waste') {
12961
+ await commandWaste(args, t);
12962
+ return;
12963
+ }
12088
12964
  // Loaded before dispatch so every command sees the same settings, and after
12089
12965
  // flag validation so a typo is reported before any file is touched. An
12090
12966
  // invalid config throws here rather than quietly reverting to defaults —
@@ -12155,7 +13031,7 @@ async function main() {
12155
13031
  await commandProfile(args, config, configDir, pricing, t);
12156
13032
  break;
12157
13033
  case 'plan':
12158
- await commandPlan(args, pricing, t);
13034
+ await commandPlan(args, config, pricing, t);
12159
13035
  break;
12160
13036
  case 'verify':
12161
13037
  await commandVerify(args, pricing, t);
@@ -12277,6 +13153,9 @@ async function main() {
12277
13153
  case 'ownrate':
12278
13154
  commandOwnrate(args, t);
12279
13155
  break;
13156
+ case 'model-pricing':
13157
+ await commandModelPricing(args, t);
13158
+ break;
12280
13159
  case 'pulse':
12281
13160
  await commandPulse(args, t);
12282
13161
  break;
@@ -12353,8 +13232,12 @@ function filesystemRefusal(error, t) {
12353
13232
  }
12354
13233
  }
12355
13234
  main().catch((error) => {
12356
- const t = getCliMessages(localeFromArgv(process.argv.slice(2)));
12357
- const message = filesystemRefusal(error, t) ?? (error instanceof Error ? error.message : String(error));
13235
+ const argv = process.argv.slice(2);
13236
+ const t = getCliMessages(localeFromArgv(argv));
13237
+ const raised = error instanceof Error ? error.message : String(error);
13238
+ // `task`, `filter` and the core's task analysis raise in English (#871).
13239
+ const own = argv[0] === 'task' || argv[0] === 'filter' ? t.taskFilter.say(raised) : raised;
13240
+ const message = filesystemRefusal(error, t) ?? own;
12358
13241
  console.error(`\n${c.red(t.errors.errorLabel())}: ${message}\n`);
12359
13242
  process.exitCode = 1;
12360
13243
  });