@trazum/cli 2.2.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, TTL_1H_MS, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
10
+ import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, evaluateWatch, firedKey, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, bandGoverns, countTokensAnthropic, DEFAULT_USAGE, budgetPositions, conform, BREAK_EVEN_BAND, allocate, annualRecord, replayCommitment, coversTheTerm, runExperiment, qualityGate, semanticPassCost, verifySemanticProposals, SEMANTIC_SYSTEM_PROMPT, ladderPosition, validateLadder, outcomeReport, rankPerOutcome, FAILURE_POLICIES, detectFromSource, matchLocale, parsePlanDocument, waiverDay, waiverHistory, proposeInit, MIN_RATE_DAYS, parseConfig, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, rollUp, heartbeats, ruleYield, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, receiptFrom, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, matchGlob, MAX_INPUT_CHARS, moneyIsComparable, mostSpecificMatch, assemble, interview, nearestName, slot, SLOT_IDS, optimize, parseBaseline, PHRASE_LANGUAGES, detectTextLanguage, dictionaryStanding, languagesWithStanding, indexUsage, parseUsageLine, plannedCalls, claudeCodeRecords, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, looksLikeAnthropicUsage, looksLikeClaudeCodeTranscript, looksLikeHelicone, looksLikeLangsmith, looksLikeLiteLlm, looksLikeOpenaiUsage, looksLikeOpenrouterActivity, looksLikeOtel, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, TTL_1H_MS, 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,10 @@ import { renderPositionHtml, renderProfileHtml, renderRollupHtml } from './html.
34
34
  import { bar, c, sectionHeading, table } from './style.js';
35
35
  const VALUE_FLAGS = new Set([
36
36
  'answers',
37
+ 'label-by-cwd',
38
+ 'label-by-workspace',
39
+ 'label-by-project',
40
+ 'against',
37
41
  'calls',
38
42
  'files-from',
39
43
  'log',
@@ -383,9 +387,14 @@ const COMMAND_FLAGS = {
383
387
  rollup: ['json', 'html-out'],
384
388
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
385
389
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live'],
386
- 'from-claude-code': ['label', 'label-from-project', 'out', 'o', 'state'],
390
+ 'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
387
391
  'from-otel': ['label-from-service', 'out', 'o'],
388
392
  'from-litellm': ['out', 'o'],
393
+ reconcile: ['against', 'out', 'o'],
394
+ 'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
395
+ 'from-openai': ['label', 'label-by-project', 'out', 'o'],
396
+ 'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
397
+ bill: ['label', 'out', 'o', 'stamp', 'pricing', 'pricing-live'],
389
398
  'from-helicone': ['out', 'o'],
390
399
  'from-langsmith': ['out', 'o'],
391
400
  switch: ['to', 'migration-usd', 'cases'],
@@ -2059,6 +2068,155 @@ function projectLabelFor(file) {
2059
2068
  const trimmed = folder.replace(/^-+/, '');
2060
2069
  return trimmed !== '' ? trimmed : folder;
2061
2070
  }
2071
+ /**
2072
+ * The directory rules, read from a JSON file, or nothing when none was asked
2073
+ * for.
2074
+ *
2075
+ * **Every malformed entry is a refusal, never a skip.** A rules file with one
2076
+ * bad line that quietly labelled nothing would put a project's money on
2077
+ * another project's bill, silently, in the one direction nobody checks. The
2078
+ * message names the entry so it can be found.
2079
+ */
2080
+ /**
2081
+ * The workspace mapping, read the way the cwd rules are read.
2082
+ *
2083
+ * Every refusal here is the same refusal: a rules file that half-parsed would
2084
+ * put one project's money on another's bill, silently, in the direction
2085
+ * nobody checks. `workspace` may be `null` — that is the default workspace,
2086
+ * which the report names by absence — but it may not be missing, because a
2087
+ * missing field is a typo and `null` is a decision.
2088
+ */
2089
+ async function workspaceRulesFrom(file, t) {
2090
+ if (file === undefined)
2091
+ return undefined;
2092
+ let parsed;
2093
+ try {
2094
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2095
+ }
2096
+ catch {
2097
+ throw new Error(t.fromAnthropic.rulesUnreadable(file));
2098
+ }
2099
+ if (!Array.isArray(parsed))
2100
+ throw new Error(t.fromAnthropic.rulesUnreadable(file));
2101
+ const rules = [];
2102
+ for (const [at, entry] of parsed.entries()) {
2103
+ const rule = entry;
2104
+ if (typeof rule !== 'object'
2105
+ || rule === null
2106
+ || !('workspace' in rule)
2107
+ || (rule.workspace !== null && (typeof rule.workspace !== 'string' || rule.workspace === ''))
2108
+ || typeof rule.label !== 'string'
2109
+ || rule.label === '') {
2110
+ throw new Error(t.fromAnthropic.ruleBad(file, at));
2111
+ }
2112
+ rules.push({ workspace: rule.workspace, label: rule.label });
2113
+ }
2114
+ if (rules.length === 0)
2115
+ throw new Error(t.fromAnthropic.rulesEmpty(file));
2116
+ return rules;
2117
+ }
2118
+ /**
2119
+ * The project mapping `from-openai` labels by, under the same refusals as
2120
+ * the workspace one. `project` may not be `null` here: every OpenAI request
2121
+ * belongs to a project with an id, so there is no default named by absence
2122
+ * and a `null` would be a rule for nothing.
2123
+ */
2124
+ async function projectRulesFrom(file, t) {
2125
+ if (file === undefined)
2126
+ return undefined;
2127
+ let parsed;
2128
+ try {
2129
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2130
+ }
2131
+ catch {
2132
+ throw new Error(t.fromOpenai.rulesUnreadable(file));
2133
+ }
2134
+ if (!Array.isArray(parsed))
2135
+ throw new Error(t.fromOpenai.rulesUnreadable(file));
2136
+ const rules = [];
2137
+ for (const [at, entry] of parsed.entries()) {
2138
+ const rule = entry;
2139
+ if (typeof rule !== 'object'
2140
+ || rule === null
2141
+ || typeof rule.project !== 'string'
2142
+ || rule.project === ''
2143
+ || typeof rule.label !== 'string'
2144
+ || rule.label === '') {
2145
+ throw new Error(t.fromOpenai.ruleBad(file, at));
2146
+ }
2147
+ rules.push({ project: rule.project, label: rule.label });
2148
+ }
2149
+ if (rules.length === 0)
2150
+ throw new Error(t.fromOpenai.rulesEmpty(file));
2151
+ return rules;
2152
+ }
2153
+ /**
2154
+ * The workspace mapping `from-openrouter` labels by. Same refusals as the
2155
+ * other two; `workspace` may not be `null`, because OpenRouter's report
2156
+ * names no workspace by absence — a `null` there only means the request did
2157
+ * not group by workspace.
2158
+ */
2159
+ async function openrouterWorkspaceRulesFrom(file, t) {
2160
+ if (file === undefined)
2161
+ return undefined;
2162
+ let parsed;
2163
+ try {
2164
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2165
+ }
2166
+ catch {
2167
+ throw new Error(t.fromOpenrouter.rulesUnreadable(file));
2168
+ }
2169
+ if (!Array.isArray(parsed))
2170
+ throw new Error(t.fromOpenrouter.rulesUnreadable(file));
2171
+ const rules = [];
2172
+ for (const [at, entry] of parsed.entries()) {
2173
+ const rule = entry;
2174
+ if (typeof rule !== 'object'
2175
+ || rule === null
2176
+ || typeof rule.workspace !== 'string'
2177
+ || rule.workspace === ''
2178
+ || typeof rule.label !== 'string'
2179
+ || rule.label === '') {
2180
+ throw new Error(t.fromOpenrouter.ruleBad(file, at));
2181
+ }
2182
+ rules.push({ workspace: rule.workspace, label: rule.label });
2183
+ }
2184
+ if (rules.length === 0)
2185
+ throw new Error(t.fromOpenrouter.rulesEmpty(file));
2186
+ return rules;
2187
+ }
2188
+ async function cwdRulesFrom(file, t) {
2189
+ if (file === undefined)
2190
+ return undefined;
2191
+ let parsed;
2192
+ try {
2193
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2194
+ }
2195
+ catch {
2196
+ throw new Error(t.fromClaudeCode.cwdRulesUnreadable(file));
2197
+ }
2198
+ if (!Array.isArray(parsed))
2199
+ throw new Error(t.fromClaudeCode.cwdRulesUnreadable(file));
2200
+ const rules = [];
2201
+ for (const [at, entry] of parsed.entries()) {
2202
+ const rule = entry;
2203
+ if (typeof rule !== 'object'
2204
+ || rule === null
2205
+ || typeof rule.prefix !== 'string'
2206
+ || rule.prefix === ''
2207
+ || typeof rule.label !== 'string'
2208
+ || rule.label === '') {
2209
+ throw new Error(t.fromClaudeCode.cwdRuleBad(file, at));
2210
+ }
2211
+ rules.push({ prefix: rule.prefix, label: rule.label });
2212
+ }
2213
+ /* An empty list is refused rather than treated as "no rules": a caller who
2214
+ passed the flag meant to narrow something, and silently doing nothing is
2215
+ the shape `policy.ts` refuses one repository over. */
2216
+ if (rules.length === 0)
2217
+ throw new Error(t.fromClaudeCode.cwdRulesEmpty(file));
2218
+ return rules;
2219
+ }
2062
2220
  /** How much of the run-up to `offset` is fingerprinted. */
2063
2221
  const STATE_DIGEST_BYTES = 4096;
2064
2222
  const digestOf = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -2170,6 +2328,25 @@ async function commandFromClaudeCode(args, t) {
2170
2328
  * says so.
2171
2329
  */
2172
2330
  const labelFromProject = boolFlag(args, 'label-from-project', info.isDirectory());
2331
+ /**
2332
+ * `--label-by-cwd`: the one question a folder name cannot answer.
2333
+ *
2334
+ * `--label-from-project` labels by the transcript's own folder, which is
2335
+ * right when one folder is one project and useless when it is not. Two
2336
+ * repositories worked on in a single session share a transcript, share a
2337
+ * folder, and the transcript has no field saying which was which. It has a
2338
+ * `cwd`, per line.
2339
+ *
2340
+ * **A JSON file rather than a repeated flag or a delimited string.** The
2341
+ * values are absolute paths, and every delimiter worth choosing — comma,
2342
+ * colon, semicolon, equals — is a character a directory is allowed to
2343
+ * contain. A file has no such problem, and the rules are the kind of thing
2344
+ * written once and kept beside the config.
2345
+ *
2346
+ * Read here and never emitted: `claude-code.ts` states that contract and a
2347
+ * test plants a secret in `cwd` and greps the output for it.
2348
+ */
2349
+ const cwdRules = await cwdRulesFrom(stringFlag(args, 'label-by-cwd'), t);
2173
2350
  /**
2174
2351
  * `--state` is for one transcript, deliberately.
2175
2352
  *
@@ -2220,6 +2397,9 @@ async function commandFromClaudeCode(args, t) {
2220
2397
  : projectLabel !== undefined && projectLabel !== ''
2221
2398
  ? { label: projectLabel }
2222
2399
  : {}),
2400
+ /* The directory rules sit on top: whatever the flat label would have
2401
+ been becomes the fallback for work outside every rule. */
2402
+ ...(cwdRules !== undefined ? { labelByCwd: cwdRules } : {}),
2223
2403
  });
2224
2404
  for (const record of conversion.records)
2225
2405
  lines.push(JSON.stringify(record));
@@ -2303,8 +2483,11 @@ async function commandFromClaudeCode(args, t) {
2303
2483
  console.error(t.fromClaudeCode.noRequestId(noRequestId));
2304
2484
  if (synthetic > 0)
2305
2485
  console.error(t.fromClaudeCode.synthetic(synthetic));
2306
- if (labelFromProject && label === undefined)
2486
+ if (labelFromProject && label === undefined && cwdRules === undefined) {
2307
2487
  console.error(t.fromClaudeCode.labelled());
2488
+ }
2489
+ if (cwdRules !== undefined)
2490
+ console.error(t.fromClaudeCode.labelledByCwd(cwdRules.length));
2308
2491
  console.error(t.fromClaudeCode.skipped(otherLines, unparseable, withoutUsage));
2309
2492
  }
2310
2493
  /**
@@ -2341,6 +2524,92 @@ async function commandFromClaudeCode(args, t) {
2341
2524
  * planting the 4 things that must never appear. This function only chooses the
2342
2525
  * log and the destination.
2343
2526
  */
2527
+ /**
2528
+ * What Trazum computed, beside what the provider billed.
2529
+ *
2530
+ * Two documents in, one comparison out. The receipt is a figure this product
2531
+ * derived from token counts and a rate table; the cost report is what the
2532
+ * provider charged. Neither corrects the other and neither is merged into the
2533
+ * other -- `anthropic-cost.ts` opens by arguing why -- and the remainder is
2534
+ * printed as its own number rather than folded into an explanation.
2535
+ */
2536
+ async function commandReconcile(args, t) {
2537
+ const file = args.positional[0];
2538
+ if (file === undefined)
2539
+ throw new Error(t.reconcile.noReceipt());
2540
+ const against = stringFlag(args, 'against');
2541
+ if (against === undefined)
2542
+ throw new Error(t.reconcile.noReport());
2543
+ let receipt;
2544
+ try {
2545
+ receipt = JSON.parse(await readFile(file, 'utf8'));
2546
+ }
2547
+ catch {
2548
+ throw new Error(t.reconcile.receiptUnreadable(file));
2549
+ }
2550
+ const usd = receipt?.total?.usd;
2551
+ const fromMs = receipt?.span?.fromMs;
2552
+ const toMs = receipt?.span?.toMs;
2553
+ if (typeof usd !== 'number' || typeof fromMs !== 'number' || typeof toMs !== 'number') {
2554
+ throw new Error(t.reconcile.notAReceipt(file));
2555
+ }
2556
+ let billedText;
2557
+ try {
2558
+ billedText = await readFile(against, 'utf8');
2559
+ }
2560
+ catch {
2561
+ throw new Error(t.reconcile.reportUnreadable(against));
2562
+ }
2563
+ /* Which provider's report this is, told from the text itself: OpenAI's
2564
+ buckets carry a numeric `start_time`, Anthropic's a `starting_at`. */
2565
+ const openai = looksLikeOpenaiCost(billedText) ? openaiCostReport(billedText) : null;
2566
+ const billed = openai ?? anthropicCostReport(billedText);
2567
+ if (billed.unparseable)
2568
+ throw new Error(t.reconcile.notAReport(against));
2569
+ const answer = reconcile({ usd, fromMs, toMs }, billed);
2570
+ const json = JSON.stringify(answer, null, 2);
2571
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
2572
+ if (out !== undefined) {
2573
+ await writeFile(out, json + '\n', 'utf8');
2574
+ console.error(t.reconcile.written(out));
2575
+ }
2576
+ else {
2577
+ console.log(json);
2578
+ }
2579
+ /* Everything below on stderr, so the document redirects cleanly. */
2580
+ if (answer.refusal !== null) {
2581
+ if (answer.refusal.reason === 'other-currency') {
2582
+ console.error(t.reconcile.otherCurrency(answer.refusal.currencies.join(', ')));
2583
+ }
2584
+ else if (answer.refusal.reason === 'no-billed-window') {
2585
+ console.error(t.reconcile.noBilledWindow());
2586
+ }
2587
+ else {
2588
+ console.error(t.reconcile.windowNotCovered(new Date(answer.refusal.computed.fromMs).toISOString(), new Date(answer.refusal.computed.toMs).toISOString(), new Date(answer.refusal.billed.fromMs).toISOString(), new Date(answer.refusal.billed.toMs).toISOString()));
2589
+ }
2590
+ return;
2591
+ }
2592
+ console.error(t.reconcile.summary(answer.computedUsd, answer.billedUsd, answer.differenceUsd));
2593
+ if (answer.attributable) {
2594
+ if (answer.notTokensUsd !== 0)
2595
+ console.error(t.reconcile.notTokens(answer.notTokensUsd));
2596
+ if (answer.batchUsd !== 0)
2597
+ console.error(t.reconcile.batch(answer.batchUsd));
2598
+ console.error(t.reconcile.remainder(answer.remainderUsd));
2599
+ if (!answer.batchSeparable)
2600
+ console.error(t.reconcile.batchNotSeparable());
2601
+ if (openai !== null && openai.unknownUnitUsd !== 0) {
2602
+ console.error(t.reconcile.unknownUnit(openai.unknownUnitUsd));
2603
+ }
2604
+ }
2605
+ else {
2606
+ console.error(openai === null ? t.reconcile.notAttributable() : t.reconcile.notAttributableByLineItem());
2607
+ }
2608
+ if (billed.truncated)
2609
+ console.error(t.reconcile.truncated());
2610
+ if (billed.unreadableAmount > 0)
2611
+ console.error(t.reconcile.unreadableAmount(billed.unreadableAmount));
2612
+ }
2344
2613
  async function commandReceipt(args, pricing, t) {
2345
2614
  const file = args.positional[0];
2346
2615
  if (file === undefined)
@@ -2357,12 +2626,16 @@ async function commandReceipt(args, pricing, t) {
2357
2626
  else {
2358
2627
  console.log(json);
2359
2628
  }
2360
- /*
2361
- * Everything below goes to stderr, so `trazum receipt log.jsonl > receipt.json`
2362
- * writes a document and not a document with a summary stapled to the front.
2363
- * The gaps are read off the document rather than recomputed, so what the
2364
- * reader is told and what the file carries cannot drift apart.
2365
- */
2629
+ printReceiptSummary(document, t);
2630
+ }
2631
+ /*
2632
+ * Everything here goes to stderr, so `trazum receipt log.jsonl > receipt.json`
2633
+ * writes a document and not a document with a summary stapled to the front.
2634
+ * The gaps are read off the document rather than recomputed, so what the
2635
+ * reader is told and what the file carries cannot drift apart. Shared with
2636
+ * `bill`, which ends on the same receipt.
2637
+ */
2638
+ function printReceiptSummary(document, t) {
2366
2639
  if (document.lines.length === 0) {
2367
2640
  console.error(t.receipt.nothingToBill());
2368
2641
  }
@@ -2378,6 +2651,188 @@ async function commandReceipt(args, pricing, t) {
2378
2651
  console.error(t.receipt.noClock());
2379
2652
  }
2380
2653
  }
2654
+ /**
2655
+ * Which shapes claim a text. Every sniffer is asked, not the first that says
2656
+ * yes: a file two shapes claim is a file this must not convert, because
2657
+ * whichever it picked would be a guess wearing a result's clothes.
2658
+ */
2659
+ function usageSourcesOf(text) {
2660
+ const claims = [];
2661
+ if (looksLikeClaudeCodeTranscript(text))
2662
+ claims.push('claude-code');
2663
+ if (looksLikeOtel(text))
2664
+ claims.push('otel');
2665
+ if (looksLikeAnthropicUsage(text))
2666
+ claims.push('anthropic-usage');
2667
+ if (looksLikeOpenaiUsage(text))
2668
+ claims.push('openai-usage');
2669
+ if (looksLikeOpenrouterActivity(text))
2670
+ claims.push('openrouter');
2671
+ if (looksLikeHelicone(text))
2672
+ claims.push('helicone');
2673
+ if (looksLikeLangsmith(text))
2674
+ claims.push('langsmith');
2675
+ if (looksLikeLiteLlm(text))
2676
+ claims.push('litellm');
2677
+ if (claims.length > 0)
2678
+ return claims;
2679
+ /* A plain usage log has no signature but its own lines: if the first
2680
+ non-blank one parses as a usage line, that is what it is. */
2681
+ const first = text.split('\n').find((line) => line.trim() !== '');
2682
+ if (first !== undefined && parseUsageLine(first) !== null)
2683
+ claims.push('usage-log');
2684
+ return claims;
2685
+ }
2686
+ /**
2687
+ * `trazum bill <file|dir>`: one door, from `docs/plan-2.4.md`.
2688
+ *
2689
+ * Forty-nine commands behind two hundred downloads a month said the product
2690
+ * was deep and nobody arrived, and one reason was that a person with a log
2691
+ * had to know what their log was called before Trazum would read it. This
2692
+ * reads anything the converters read, tells each file's shape from its own
2693
+ * text, converts in memory, prices, and ends on the same receipt `receipt`
2694
+ * writes.
2695
+ *
2696
+ * It is the dedicated commands composed, not a looser version of them: each
2697
+ * file's rows go through the same converter `from-<shape>` uses, so every
2698
+ * refusal those make is made here. What differs is how the refusals are
2699
+ * told. This names each file, its shape, the records it became and how many
2700
+ * rows were left out, and points at the dedicated command for the reasons,
2701
+ * rather than repeating eight commands' worth of explanation on one screen.
2702
+ * A file no shape claims is named and not guessed; a file two shapes claim is
2703
+ * named as ambiguous and not converted; a provider's cost report is named as
2704
+ * a bill rather than usage, and pointed at `reconcile`.
2705
+ */
2706
+ async function commandBill(args, pricing, t) {
2707
+ const target = args.positional[0];
2708
+ if (target === undefined)
2709
+ throw new Error(t.bill.noPath());
2710
+ let info;
2711
+ try {
2712
+ info = await stat(target);
2713
+ }
2714
+ catch {
2715
+ throw new Error(t.bill.notFound(target));
2716
+ }
2717
+ const files = [];
2718
+ if (info.isDirectory()) {
2719
+ const entries = await readdir(target, { recursive: true, withFileTypes: true });
2720
+ for (const entry of entries) {
2721
+ if (entry.isFile() && /\.(json|jsonl|ndjson)(\.gz)?$/i.test(entry.name)) {
2722
+ files.push(join(entry.parentPath, entry.name));
2723
+ }
2724
+ }
2725
+ files.sort();
2726
+ if (files.length === 0)
2727
+ throw new Error(t.bill.noFiles(target));
2728
+ }
2729
+ else {
2730
+ files.push(target);
2731
+ }
2732
+ const label = stringFlag(args, 'label');
2733
+ const withLabel = label === undefined ? {} : { label };
2734
+ const lines = [];
2735
+ let sources = 0;
2736
+ for (const file of files) {
2737
+ const text = await readUsageLog(file, t);
2738
+ const claims = usageSourcesOf(text);
2739
+ if (claims.length === 0) {
2740
+ if (looksLikeAnthropicCost(text) || looksLikeOpenaiCost(text)) {
2741
+ console.error(t.bill.costReport(file));
2742
+ }
2743
+ else {
2744
+ console.error(t.bill.unknown(file));
2745
+ }
2746
+ continue;
2747
+ }
2748
+ if (claims.length > 1) {
2749
+ console.error(t.bill.ambiguous(file, claims.join(', ')));
2750
+ continue;
2751
+ }
2752
+ const [shape] = claims;
2753
+ if (shape === undefined)
2754
+ continue;
2755
+ let records = [];
2756
+ let leftOut = 0;
2757
+ switch (shape) {
2758
+ case 'claude-code': {
2759
+ const c = claudeCodeRecords(text, withLabel);
2760
+ records = c.records;
2761
+ leftOut = c.assistantWithoutUsage + c.unparseable;
2762
+ break;
2763
+ }
2764
+ case 'otel': {
2765
+ const c = otelRecords(text);
2766
+ records = c.records;
2767
+ leftOut = c.otherSpans + c.unparseable;
2768
+ break;
2769
+ }
2770
+ case 'litellm': {
2771
+ const c = litellmRecords(text);
2772
+ records = c.records;
2773
+ leftOut = c.unnamedModel + c.unparseable;
2774
+ break;
2775
+ }
2776
+ case 'helicone': {
2777
+ const c = heliconeRecords(text);
2778
+ records = c.records;
2779
+ leftOut = c.unnamedModel + c.unparseable;
2780
+ break;
2781
+ }
2782
+ case 'langsmith': {
2783
+ const c = langsmithRecords(text);
2784
+ records = c.records;
2785
+ leftOut = c.notModelCalls + c.unnamedModel + c.unparseable;
2786
+ break;
2787
+ }
2788
+ case 'anthropic-usage': {
2789
+ const c = anthropicUsageRecords(text, withLabel);
2790
+ records = c.records;
2791
+ leftOut = c.unnamedModel + c.nonStandardTier;
2792
+ break;
2793
+ }
2794
+ case 'openai-usage': {
2795
+ const c = openaiUsageRecords(text, withLabel);
2796
+ records = c.records;
2797
+ leftOut = c.unnamedModel + c.batch + c.nonDefaultTier + c.unsplitRows;
2798
+ break;
2799
+ }
2800
+ case 'openrouter': {
2801
+ const c = openrouterActivityRecords(text, withLabel);
2802
+ records = c.records;
2803
+ leftOut = c.unnamedModel + c.undatedRows;
2804
+ break;
2805
+ }
2806
+ case 'usage-log': {
2807
+ /* Already the shape every door reads: passed through line by line,
2808
+ and what does not parse is the receipt's own unread-lines gap. */
2809
+ for (const line of text.split('\n'))
2810
+ if (line.trim() !== '')
2811
+ lines.push(line);
2812
+ break;
2813
+ }
2814
+ }
2815
+ for (const record of records)
2816
+ lines.push(JSON.stringify(record));
2817
+ sources += 1;
2818
+ console.error(t.bill.file(file, shape, shape === 'usage-log' ? null : records.length, leftOut));
2819
+ }
2820
+ if (sources === 0)
2821
+ throw new Error(t.bill.nothingRead());
2822
+ const report = profileUsage(lines.join('\n'), { catalogue: pricing });
2823
+ const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
2824
+ const json = JSON.stringify(document, null, 2);
2825
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
2826
+ if (out !== undefined) {
2827
+ await writeFile(out, json + '\n', 'utf8');
2828
+ console.error(t.bill.written(out));
2829
+ }
2830
+ else {
2831
+ console.log(json);
2832
+ }
2833
+ console.error(t.bill.sources(sources, files.length));
2834
+ printReceiptSummary(document, t);
2835
+ }
2381
2836
  /**
2382
2837
  * `trazum from-otel <file|dir>` — OpenTelemetry GenAI spans as a usage log.
2383
2838
  *
@@ -2775,6 +3230,183 @@ async function commandFromLangsmith(args, t) {
2775
3230
  * conversation-shaped findings stay unavailable. Both are printed, because a
2776
3231
  * gap that is not said reads as a gap that is not there.
2777
3232
  */
3233
+ /**
3234
+ * The provider's own usage report, priced from the catalogue.
3235
+ *
3236
+ * One file in, usage-log records out, like every other converter here. What
3237
+ * makes this one different is where the file comes from: the operator runs
3238
+ * the `curl` themselves, with their own admin credential, and this command
3239
+ * never sees it. `anthropic-usage.ts` opens by arguing why that is the only
3240
+ * arrangement this project can offer.
3241
+ */
3242
+ async function commandFromAnthropic(args, t) {
3243
+ const target = args.positional[0];
3244
+ if (target === undefined)
3245
+ throw new Error(t.fromAnthropic.noPath());
3246
+ let text;
3247
+ try {
3248
+ text = await readFile(target, 'utf8');
3249
+ }
3250
+ catch {
3251
+ throw new Error(t.fromAnthropic.notFound(target));
3252
+ }
3253
+ const label = stringFlag(args, 'label');
3254
+ const byWorkspace = await workspaceRulesFrom(stringFlag(args, 'label-by-workspace'), t);
3255
+ const conversion = anthropicUsageRecords(text, {
3256
+ ...(label === undefined ? {} : { label }),
3257
+ ...(byWorkspace === undefined ? {} : { labelByWorkspace: byWorkspace }),
3258
+ });
3259
+ if (conversion.unparseable > 0)
3260
+ throw new Error(t.fromAnthropic.unparseable());
3261
+ const lines = conversion.records.map((record) => JSON.stringify(record));
3262
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3263
+ if (out !== undefined) {
3264
+ await writeFile(out, lines.join('\n') + (lines.length > 0 ? '\n' : ''), 'utf8');
3265
+ console.error(t.fromAnthropic.written(out));
3266
+ }
3267
+ else if (lines.length > 0) {
3268
+ console.log(lines.join('\n'));
3269
+ }
3270
+ /* Every refusal on stderr, so a pipeline reads records on stdout and a
3271
+ person reads what could not be priced. The order is the order somebody
3272
+ acts in: what was read, then what was left out, then what to ask for. */
3273
+ console.error(t.fromAnthropic.summary(conversion.buckets, conversion.rows));
3274
+ if (conversion.unnamedModel > 0)
3275
+ console.error(t.fromAnthropic.unnamedModel(conversion.unnamedModel));
3276
+ if (conversion.nonStandardTier > 0) {
3277
+ console.error(t.fromAnthropic.nonStandardTier(conversion.nonStandardTier));
3278
+ }
3279
+ if (!conversion.tierNamed && conversion.rows > 0)
3280
+ console.error(t.fromAnthropic.tierUnknown());
3281
+ if (conversion.webSearchRequests > 0)
3282
+ console.error(t.fromAnthropic.webSearch(conversion.webSearchRequests));
3283
+ if (conversion.labelledByWorkspace > 0) {
3284
+ console.error(t.fromAnthropic.labelledByWorkspace(conversion.labelledByWorkspace));
3285
+ }
3286
+ if (conversion.unruledWorkspace > 0) {
3287
+ console.error(t.fromAnthropic.unruledWorkspace(conversion.unruledWorkspace));
3288
+ }
3289
+ if (conversion.workspaceNotGrouped)
3290
+ console.error(t.fromAnthropic.workspaceNotGrouped());
3291
+ if (conversion.truncated)
3292
+ console.error(t.fromAnthropic.truncated());
3293
+ }
3294
+ /**
3295
+ * `from-openai`: the other provider's usage report, under the same
3296
+ * arrangement as `from-anthropic` — the operator's curl, the operator's
3297
+ * admin key, and this command reading only what came back. What differs is
3298
+ * in `openai-usage.ts`: the record is written in the Chat Completions shape
3299
+ * because that is how this report counts, and audio and image tokens are
3300
+ * set aside rather than priced at a text rate.
3301
+ */
3302
+ async function commandFromOpenai(args, t) {
3303
+ const target = args.positional[0];
3304
+ if (target === undefined)
3305
+ throw new Error(t.fromOpenai.noPath());
3306
+ let text;
3307
+ try {
3308
+ text = await readFile(target, 'utf8');
3309
+ }
3310
+ catch {
3311
+ throw new Error(t.fromOpenai.notFound(target));
3312
+ }
3313
+ const label = stringFlag(args, 'label');
3314
+ const byProject = await projectRulesFrom(stringFlag(args, 'label-by-project'), t);
3315
+ const conversion = openaiUsageRecords(text, {
3316
+ ...(label === undefined ? {} : { label }),
3317
+ ...(byProject === undefined ? {} : { labelByProject: byProject }),
3318
+ });
3319
+ if (conversion.unparseable > 0)
3320
+ throw new Error(t.fromOpenai.unparseable());
3321
+ const lines = conversion.records.map((record) => JSON.stringify(record));
3322
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3323
+ if (out !== undefined) {
3324
+ await writeFile(out, lines.join('\n') + (lines.length > 0 ? '\n' : ''), 'utf8');
3325
+ console.error(t.fromOpenai.written(out));
3326
+ }
3327
+ else if (lines.length > 0) {
3328
+ console.log(lines.join('\n'));
3329
+ }
3330
+ /* Refusals on stderr, in the order somebody acts in: what was read, what
3331
+ was left out and why, what to ask the endpoint for next time. */
3332
+ console.error(t.fromOpenai.summary(conversion.buckets, conversion.rows, conversion.requests));
3333
+ if (conversion.unnamedModel > 0)
3334
+ console.error(t.fromOpenai.unnamedModel(conversion.unnamedModel));
3335
+ if (conversion.batch > 0)
3336
+ console.error(t.fromOpenai.batch(conversion.batch));
3337
+ if (!conversion.batchNamed && conversion.rows > 0)
3338
+ console.error(t.fromOpenai.batchUnknown());
3339
+ if (conversion.nonDefaultTier > 0) {
3340
+ console.error(t.fromOpenai.nonDefaultTier(conversion.nonDefaultTier, conversion.tiersRefused.join(', ')));
3341
+ }
3342
+ if (!conversion.tierNamed && conversion.rows > 0)
3343
+ console.error(t.fromOpenai.tierUnknown());
3344
+ if (conversion.mixedRows > 0) {
3345
+ console.error(t.fromOpenai.mixed(conversion.mixedRows, conversion.nonTextTokens, conversion.cacheWriteUnplaced));
3346
+ }
3347
+ if (conversion.unsplitRows > 0)
3348
+ console.error(t.fromOpenai.unsplit(conversion.unsplitRows));
3349
+ if (conversion.labelledByProject > 0)
3350
+ console.error(t.fromOpenai.labelledByProject(conversion.labelledByProject));
3351
+ if (conversion.unruledProject > 0)
3352
+ console.error(t.fromOpenai.unruledProject(conversion.unruledProject));
3353
+ if (conversion.projectNotGrouped)
3354
+ console.error(t.fromOpenai.projectNotGrouped());
3355
+ if (conversion.truncated)
3356
+ console.error(t.fromOpenai.truncated());
3357
+ }
3358
+ /**
3359
+ * `from-openrouter`: the router's activity report, read as a log. The one
3360
+ * provider Trazum already prices from a live catalogue (`pricing --from
3361
+ * openrouter`), keyed by the same slugs this report carries. What OpenRouter
3362
+ * charged is printed beside the records and never merged into them.
3363
+ */
3364
+ async function commandFromOpenrouter(args, t) {
3365
+ const target = args.positional[0];
3366
+ if (target === undefined)
3367
+ throw new Error(t.fromOpenrouter.noPath());
3368
+ let text;
3369
+ try {
3370
+ text = await readFile(target, 'utf8');
3371
+ }
3372
+ catch {
3373
+ throw new Error(t.fromOpenrouter.notFound(target));
3374
+ }
3375
+ const label = stringFlag(args, 'label');
3376
+ const byWorkspace = await openrouterWorkspaceRulesFrom(stringFlag(args, 'label-by-workspace'), t);
3377
+ const conversion = openrouterActivityRecords(text, {
3378
+ ...(label === undefined ? {} : { label }),
3379
+ ...(byWorkspace === undefined ? {} : { labelByWorkspace: byWorkspace }),
3380
+ });
3381
+ if (conversion.unparseable > 0)
3382
+ throw new Error(t.fromOpenrouter.unparseable());
3383
+ const lines = conversion.records.map((record) => JSON.stringify(record));
3384
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3385
+ if (out !== undefined) {
3386
+ await writeFile(out, lines.join('\n') + (lines.length > 0 ? '\n' : ''), 'utf8');
3387
+ console.error(t.fromOpenrouter.written(out));
3388
+ }
3389
+ else if (lines.length > 0) {
3390
+ console.log(lines.join('\n'));
3391
+ }
3392
+ console.error(t.fromOpenrouter.summary(conversion.rows, conversion.days, conversion.requests));
3393
+ if (conversion.reportedUsageUsd > 0 || conversion.byokUsd > 0) {
3394
+ console.error(t.fromOpenrouter.reportedUsage(conversion.reportedUsageUsd, conversion.byokUsd));
3395
+ }
3396
+ if (conversion.reasoningTokens > 0)
3397
+ console.error(t.fromOpenrouter.reasoning(conversion.reasoningTokens));
3398
+ if (conversion.unnamedModel > 0)
3399
+ console.error(t.fromOpenrouter.unnamedModel(conversion.unnamedModel));
3400
+ if (conversion.undatedRows > 0)
3401
+ console.error(t.fromOpenrouter.undated(conversion.undatedRows));
3402
+ if (conversion.labelledByWorkspace > 0) {
3403
+ console.error(t.fromOpenrouter.labelledByWorkspace(conversion.labelledByWorkspace));
3404
+ }
3405
+ if (conversion.unruledWorkspace > 0)
3406
+ console.error(t.fromOpenrouter.unruledWorkspace(conversion.unruledWorkspace));
3407
+ if (conversion.workspaceNotGrouped)
3408
+ console.error(t.fromOpenrouter.workspaceNotGrouped());
3409
+ }
2778
3410
  async function commandFromHelicone(args, t) {
2779
3411
  const target = args.positional[0];
2780
3412
  if (target === undefined)
@@ -8167,6 +8799,7 @@ async function commandProfile(args, config, configDir, pricing, t) {
8167
8799
  throw new Error(t.profile.sinceAfterUntil());
8168
8800
  }
8169
8801
  const windowed = sinceMs !== undefined || untilMs !== undefined;
8802
+ const report = profileUsage(raw, { catalogue: pricing, label: onlyLabel, sinceMs, untilMs });
8170
8803
  /**
8171
8804
  * How old the price table behind every dollar below is. Stated only when it
8172
8805
  * is old enough to matter: `models` and `doctor` always print the date, but
@@ -8175,12 +8808,21 @@ async function commandProfile(args, config, configDir, pricing, t) {
8175
8808
  * The threshold is in the sentence, and the number behind it is
8176
8809
  * `STALE_PRICING_DAYS` — shared with the MCP report and the browser's bill,
8177
8810
  * which used to keep their own copies of it.
8811
+ *
8812
+ * **The date is this report's, not the catalogue's**, and it is computed
8813
+ * after the report for that reason rather than before it as it used to be.
8814
+ * `PRICING_LAST_REVIEWED` is the oldest provider's, so a log of Claude and
8815
+ * OpenAI calls was told its prices were 68 days old on a morning when both
8816
+ * halves had been read that week — by a sentence that says, in these words,
8817
+ * that the table behind *every dollar here* was reviewed then. It was not.
8818
+ * `reviewedForModels` answers for the providers that actually priced this
8819
+ * report and falls back to the catalogue's own date wherever it cannot.
8178
8820
  */
8179
- const pricingAgeDays = reviewAgeDays(pricing.lastReviewed, new Date());
8821
+ const reportReviewed = reviewedForModels(report.byModel.map((row) => row.model), pricing);
8822
+ const pricingAgeDays = reviewAgeDays(reportReviewed, new Date());
8180
8823
  const pricingStale = pricingAgeDays !== null && pricingAgeDays > STALE_PRICING_DAYS
8181
- ? { date: pricing.lastReviewed, days: pricingAgeDays }
8824
+ ? { date: reportReviewed, days: pricingAgeDays }
8182
8825
  : null;
8183
- const report = profileUsage(raw, { catalogue: pricing, label: onlyLabel, sinceMs, untilMs });
8184
8826
  if (report.total.calls === 0 && report.unpriced.calls === 0) {
8185
8827
  if (onlyLabel !== undefined || windowed) {
8186
8828
  // Diagnose against the log without the failed filter, so the error can
@@ -8376,8 +9018,32 @@ async function commandProfile(args, config, configDir, pricing, t) {
8376
9018
  label: r.label,
8377
9019
  cache: cacheEconomics(r.breakdown),
8378
9020
  })),
8379
- // The provenance of every dollar above: which price table, how old.
8380
- pricing: { lastReviewed: pricing.lastReviewed, ageDays: pricingAgeDays },
9021
+ /*
9022
+ The provenance of every dollar above, in two parts that are not the
9023
+ same question.
9024
+
9025
+ `lastReviewed` and `ageDays` are the **table's**: its oldest
9026
+ provider, which is what "how old is this catalogue" means and what
9027
+ these two keys have always carried. Unchanged, because a key cannot
9028
+ change meaning under a minor and a consumer branching on them keeps
9029
+ working.
9030
+
9031
+ `reportReviewed` and `reportAgeDays` are **these figures'**: the
9032
+ oldest provider among the models actually priced here, which is the
9033
+ pair the staleness warning is decided from. They are new keys, and
9034
+ new keys are additions the contract allows.
9035
+
9036
+ The two differ exactly when a report uses none of the models
9037
+ holding the table back — which was the whole defect: a log of
9038
+ Claude and OpenAI calls was told its prices were 68 days old on a
9039
+ morning both halves had been read that week.
9040
+ */
9041
+ pricing: {
9042
+ lastReviewed: pricing.lastReviewed,
9043
+ ageDays: reviewAgeDays(pricing.lastReviewed, new Date()),
9044
+ reportReviewed,
9045
+ reportAgeDays: pricingAgeDays,
9046
+ },
8381
9047
  levers: billLevers(report, { catalogue: pricing }),
8382
9048
  // Present only when --against was passed: null delta means the
8383
9049
  // previous log had nothing priced, which is a different answer from
@@ -10194,6 +10860,9 @@ async function main() {
10194
10860
  case 'receipt':
10195
10861
  await commandReceipt(args, pricing, t);
10196
10862
  break;
10863
+ case 'reconcile':
10864
+ await commandReconcile(args, t);
10865
+ break;
10197
10866
  case 'from-otel':
10198
10867
  await commandFromOtel(args, t);
10199
10868
  break;
@@ -10203,6 +10872,18 @@ async function main() {
10203
10872
  case 'from-langsmith':
10204
10873
  await commandFromLangsmith(args, t);
10205
10874
  break;
10875
+ case 'from-anthropic':
10876
+ await commandFromAnthropic(args, t);
10877
+ break;
10878
+ case 'from-openai':
10879
+ await commandFromOpenai(args, t);
10880
+ break;
10881
+ case 'from-openrouter':
10882
+ await commandFromOpenrouter(args, t);
10883
+ break;
10884
+ case 'bill':
10885
+ await commandBill(args, pricing, t);
10886
+ break;
10206
10887
  case 'from-helicone':
10207
10888
  await commandFromHelicone(args, t);
10208
10889
  break;
@@ -10455,7 +11136,14 @@ function printDoctor(report, context) {
10455
11136
  const model = pricing.models.find((m) => m.id === usage.model);
10456
11137
  console.log(`\n${c.bold(t.doctor.heading(root, seen.length))}`);
10457
11138
  console.log(c.dim(t.doctor.subheading(model?.displayName ?? usage.model, n(usage.callsPerMonth))));
10458
- console.log(c.dim(t.doctor.pricesReviewed(pricing.lastReviewed, reviewAgeDays(pricing.lastReviewed, new Date()))));
11139
+ /*
11140
+ This prompt's own model, not the catalogue's oldest provider. `doctor`
11141
+ reports on one model and one bill, so the date that qualifies it is the
11142
+ date that model's provider was read — the catalogue-wide answer named a
11143
+ provider this prompt does not use.
11144
+ */
11145
+ const reviewed = reviewedForModels([usage.model], pricing);
11146
+ console.log(c.dim(t.doctor.pricesReviewed(reviewed, reviewAgeDays(reviewed, new Date()))));
10459
11147
  // Budgets first. Everything below is money; this is whether anything is
10460
11148
  // watching at all, and an unwatched prompt is how the money got there.
10461
11149
  console.log(`\n${c.bold(t.doctor.budgetsHeading())}`);