@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/src/index.ts CHANGED
@@ -88,6 +88,7 @@ import {
88
88
  formatSignedUsd,
89
89
  formatUsd,
90
90
  receiptFrom,
91
+ type ReceiptDocument,
91
92
  getMessages,
92
93
  getModel,
93
94
  hasMarker,
@@ -113,10 +114,30 @@ import {
113
114
  parseUsageLine,
114
115
  plannedCalls,
115
116
  claudeCodeRecords,
117
+ type CwdLabel,
118
+ type WorkspaceLabel,
119
+ type ProjectLabel,
120
+ type OpenrouterWorkspaceLabel,
116
121
  ESTIMATE_ERROR_BAND_PCT,
117
122
  bandFor,
118
123
  foreignTokenizer,
119
124
  measuredForeignError,
125
+ anthropicCostReport,
126
+ anthropicUsageRecords,
127
+ looksLikeOpenaiCost,
128
+ looksLikeAnthropicCost,
129
+ looksLikeAnthropicUsage,
130
+ looksLikeClaudeCodeTranscript,
131
+ looksLikeHelicone,
132
+ looksLikeLangsmith,
133
+ looksLikeLiteLlm,
134
+ looksLikeOpenaiUsage,
135
+ looksLikeOpenrouterActivity,
136
+ looksLikeOtel,
137
+ openaiCostReport,
138
+ openaiUsageRecords,
139
+ openrouterActivityRecords,
140
+ reconcile,
120
141
  heliconeRecords,
121
142
  langsmithRecords,
122
143
  litellmRecords,
@@ -125,6 +146,7 @@ import {
125
146
  positionAt,
126
147
  positionReport,
127
148
  PRICING_LAST_REVIEWED,
149
+ reviewedForModels,
128
150
  PROVIDER_REVIEWED,
129
151
  STALE_PRICING_DAYS,
130
152
  profilePrompt,
@@ -296,6 +318,10 @@ interface Args {
296
318
 
297
319
  const VALUE_FLAGS = new Set([
298
320
  'answers',
321
+ 'label-by-cwd',
322
+ 'label-by-workspace',
323
+ 'label-by-project',
324
+ 'against',
299
325
  'calls',
300
326
  'files-from',
301
327
  'log',
@@ -691,9 +717,14 @@ const COMMAND_FLAGS: Record<string, string[]> = {
691
717
  rollup: ['json', 'html-out'],
692
718
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
693
719
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live'],
694
- 'from-claude-code': ['label', 'label-from-project', 'out', 'o', 'state'],
720
+ 'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
695
721
  'from-otel': ['label-from-service', 'out', 'o'],
696
722
  'from-litellm': ['out', 'o'],
723
+ reconcile: ['against', 'out', 'o'],
724
+ 'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
725
+ 'from-openai': ['label', 'label-by-project', 'out', 'o'],
726
+ 'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
727
+ bill: ['label', 'out', 'o', 'stamp', 'pricing', 'pricing-live'],
697
728
  'from-helicone': ['out', 'o'],
698
729
  'from-langsmith': ['out', 'o'],
699
730
  switch: ['to', 'migration-usd', 'cases'],
@@ -2654,6 +2685,167 @@ function projectLabelFor(file: string): string | undefined {
2654
2685
  }
2655
2686
 
2656
2687
 
2688
+ /**
2689
+ * The directory rules, read from a JSON file, or nothing when none was asked
2690
+ * for.
2691
+ *
2692
+ * **Every malformed entry is a refusal, never a skip.** A rules file with one
2693
+ * bad line that quietly labelled nothing would put a project's money on
2694
+ * another project's bill, silently, in the one direction nobody checks. The
2695
+ * message names the entry so it can be found.
2696
+ */
2697
+ /**
2698
+ * The workspace mapping, read the way the cwd rules are read.
2699
+ *
2700
+ * Every refusal here is the same refusal: a rules file that half-parsed would
2701
+ * put one project's money on another's bill, silently, in the direction
2702
+ * nobody checks. `workspace` may be `null` — that is the default workspace,
2703
+ * which the report names by absence — but it may not be missing, because a
2704
+ * missing field is a typo and `null` is a decision.
2705
+ */
2706
+ async function workspaceRulesFrom(
2707
+ file: string | undefined,
2708
+ t: CliMessages,
2709
+ ): Promise<WorkspaceLabel[] | undefined> {
2710
+ if (file === undefined) return undefined;
2711
+ let parsed: unknown;
2712
+ try {
2713
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2714
+ } catch {
2715
+ throw new Error(t.fromAnthropic.rulesUnreadable(file));
2716
+ }
2717
+ if (!Array.isArray(parsed)) throw new Error(t.fromAnthropic.rulesUnreadable(file));
2718
+
2719
+ const rules: WorkspaceLabel[] = [];
2720
+ for (const [at, entry] of parsed.entries()) {
2721
+ const rule = entry as Record<string, unknown> | null;
2722
+ if (
2723
+ typeof rule !== 'object'
2724
+ || rule === null
2725
+ || !('workspace' in rule)
2726
+ || (rule.workspace !== null && (typeof rule.workspace !== 'string' || rule.workspace === ''))
2727
+ || typeof rule.label !== 'string'
2728
+ || rule.label === ''
2729
+ ) {
2730
+ throw new Error(t.fromAnthropic.ruleBad(file, at));
2731
+ }
2732
+ rules.push({ workspace: rule.workspace as string | null, label: rule.label });
2733
+ }
2734
+ if (rules.length === 0) throw new Error(t.fromAnthropic.rulesEmpty(file));
2735
+ return rules;
2736
+ }
2737
+
2738
+ /**
2739
+ * The project mapping `from-openai` labels by, under the same refusals as
2740
+ * the workspace one. `project` may not be `null` here: every OpenAI request
2741
+ * belongs to a project with an id, so there is no default named by absence
2742
+ * and a `null` would be a rule for nothing.
2743
+ */
2744
+ async function projectRulesFrom(
2745
+ file: string | undefined,
2746
+ t: CliMessages,
2747
+ ): Promise<ProjectLabel[] | undefined> {
2748
+ if (file === undefined) return undefined;
2749
+ let parsed: unknown;
2750
+ try {
2751
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2752
+ } catch {
2753
+ throw new Error(t.fromOpenai.rulesUnreadable(file));
2754
+ }
2755
+ if (!Array.isArray(parsed)) throw new Error(t.fromOpenai.rulesUnreadable(file));
2756
+
2757
+ const rules: ProjectLabel[] = [];
2758
+ for (const [at, entry] of parsed.entries()) {
2759
+ const rule = entry as Record<string, unknown> | null;
2760
+ if (
2761
+ typeof rule !== 'object'
2762
+ || rule === null
2763
+ || typeof rule.project !== 'string'
2764
+ || rule.project === ''
2765
+ || typeof rule.label !== 'string'
2766
+ || rule.label === ''
2767
+ ) {
2768
+ throw new Error(t.fromOpenai.ruleBad(file, at));
2769
+ }
2770
+ rules.push({ project: rule.project, label: rule.label });
2771
+ }
2772
+ if (rules.length === 0) throw new Error(t.fromOpenai.rulesEmpty(file));
2773
+ return rules;
2774
+ }
2775
+
2776
+ /**
2777
+ * The workspace mapping `from-openrouter` labels by. Same refusals as the
2778
+ * other two; `workspace` may not be `null`, because OpenRouter's report
2779
+ * names no workspace by absence — a `null` there only means the request did
2780
+ * not group by workspace.
2781
+ */
2782
+ async function openrouterWorkspaceRulesFrom(
2783
+ file: string | undefined,
2784
+ t: CliMessages,
2785
+ ): Promise<OpenrouterWorkspaceLabel[] | undefined> {
2786
+ if (file === undefined) return undefined;
2787
+ let parsed: unknown;
2788
+ try {
2789
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2790
+ } catch {
2791
+ throw new Error(t.fromOpenrouter.rulesUnreadable(file));
2792
+ }
2793
+ if (!Array.isArray(parsed)) throw new Error(t.fromOpenrouter.rulesUnreadable(file));
2794
+
2795
+ const rules: OpenrouterWorkspaceLabel[] = [];
2796
+ for (const [at, entry] of parsed.entries()) {
2797
+ const rule = entry as Record<string, unknown> | null;
2798
+ if (
2799
+ typeof rule !== 'object'
2800
+ || rule === null
2801
+ || typeof rule.workspace !== 'string'
2802
+ || rule.workspace === ''
2803
+ || typeof rule.label !== 'string'
2804
+ || rule.label === ''
2805
+ ) {
2806
+ throw new Error(t.fromOpenrouter.ruleBad(file, at));
2807
+ }
2808
+ rules.push({ workspace: rule.workspace, label: rule.label });
2809
+ }
2810
+ if (rules.length === 0) throw new Error(t.fromOpenrouter.rulesEmpty(file));
2811
+ return rules;
2812
+ }
2813
+
2814
+ async function cwdRulesFrom(
2815
+ file: string | undefined,
2816
+ t: CliMessages,
2817
+ ): Promise<CwdLabel[] | undefined> {
2818
+ if (file === undefined) return undefined;
2819
+ let parsed: unknown;
2820
+ try {
2821
+ parsed = JSON.parse(await readFile(file, 'utf8'));
2822
+ } catch {
2823
+ throw new Error(t.fromClaudeCode.cwdRulesUnreadable(file));
2824
+ }
2825
+ if (!Array.isArray(parsed)) throw new Error(t.fromClaudeCode.cwdRulesUnreadable(file));
2826
+
2827
+ const rules: CwdLabel[] = [];
2828
+ for (const [at, entry] of parsed.entries()) {
2829
+ const rule = entry as Record<string, unknown> | null;
2830
+ if (
2831
+ typeof rule !== 'object'
2832
+ || rule === null
2833
+ || typeof rule.prefix !== 'string'
2834
+ || rule.prefix === ''
2835
+ || typeof rule.label !== 'string'
2836
+ || rule.label === ''
2837
+ ) {
2838
+ throw new Error(t.fromClaudeCode.cwdRuleBad(file, at));
2839
+ }
2840
+ rules.push({ prefix: rule.prefix, label: rule.label });
2841
+ }
2842
+ /* An empty list is refused rather than treated as "no rules": a caller who
2843
+ passed the flag meant to narrow something, and silently doing nothing is
2844
+ the shape `policy.ts` refuses one repository over. */
2845
+ if (rules.length === 0) throw new Error(t.fromClaudeCode.cwdRulesEmpty(file));
2846
+ return rules;
2847
+ }
2848
+
2657
2849
  /**
2658
2850
  * `--state`: read the part of a transcript that is new since last time.
2659
2851
  *
@@ -2808,6 +3000,25 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2808
3000
  * says so.
2809
3001
  */
2810
3002
  const labelFromProject = boolFlag(args, 'label-from-project', info.isDirectory());
3003
+ /**
3004
+ * `--label-by-cwd`: the one question a folder name cannot answer.
3005
+ *
3006
+ * `--label-from-project` labels by the transcript's own folder, which is
3007
+ * right when one folder is one project and useless when it is not. Two
3008
+ * repositories worked on in a single session share a transcript, share a
3009
+ * folder, and the transcript has no field saying which was which. It has a
3010
+ * `cwd`, per line.
3011
+ *
3012
+ * **A JSON file rather than a repeated flag or a delimited string.** The
3013
+ * values are absolute paths, and every delimiter worth choosing — comma,
3014
+ * colon, semicolon, equals — is a character a directory is allowed to
3015
+ * contain. A file has no such problem, and the rules are the kind of thing
3016
+ * written once and kept beside the config.
3017
+ *
3018
+ * Read here and never emitted: `claude-code.ts` states that contract and a
3019
+ * test plants a secret in `cwd` and greps the output for it.
3020
+ */
3021
+ const cwdRules = await cwdRulesFrom(stringFlag(args, 'label-by-cwd'), t);
2811
3022
  /**
2812
3023
  * `--state` is for one transcript, deliberately.
2813
3024
  *
@@ -2857,6 +3068,9 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2857
3068
  : projectLabel !== undefined && projectLabel !== ''
2858
3069
  ? { label: projectLabel }
2859
3070
  : {}),
3071
+ /* The directory rules sit on top: whatever the flat label would have
3072
+ been becomes the fallback for work outside every rule. */
3073
+ ...(cwdRules !== undefined ? { labelByCwd: cwdRules } : {}),
2860
3074
  });
2861
3075
  for (const record of conversion.records) lines.push(JSON.stringify(record));
2862
3076
  resumeLine = conversion.resume.line;
@@ -2931,7 +3145,10 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2931
3145
  if (disagreements > 0) console.error(t.fromClaudeCode.disagreements(disagreements));
2932
3146
  if (noRequestId > 0) console.error(t.fromClaudeCode.noRequestId(noRequestId));
2933
3147
  if (synthetic > 0) console.error(t.fromClaudeCode.synthetic(synthetic));
2934
- if (labelFromProject && label === undefined) console.error(t.fromClaudeCode.labelled());
3148
+ if (labelFromProject && label === undefined && cwdRules === undefined) {
3149
+ console.error(t.fromClaudeCode.labelled());
3150
+ }
3151
+ if (cwdRules !== undefined) console.error(t.fromClaudeCode.labelledByCwd(cwdRules.length));
2935
3152
  console.error(t.fromClaudeCode.skipped(otherLines, unparseable, withoutUsage));
2936
3153
  }
2937
3154
 
@@ -2969,6 +3186,92 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2969
3186
  * planting the 4 things that must never appear. This function only chooses the
2970
3187
  * log and the destination.
2971
3188
  */
3189
+ /**
3190
+ * What Trazum computed, beside what the provider billed.
3191
+ *
3192
+ * Two documents in, one comparison out. The receipt is a figure this product
3193
+ * derived from token counts and a rate table; the cost report is what the
3194
+ * provider charged. Neither corrects the other and neither is merged into the
3195
+ * other -- `anthropic-cost.ts` opens by arguing why -- and the remainder is
3196
+ * printed as its own number rather than folded into an explanation.
3197
+ */
3198
+ async function commandReconcile(args: Args, t: CliMessages): Promise<void> {
3199
+ const file = args.positional[0];
3200
+ if (file === undefined) throw new Error(t.reconcile.noReceipt());
3201
+ const against = stringFlag(args, 'against');
3202
+ if (against === undefined) throw new Error(t.reconcile.noReport());
3203
+
3204
+ let receipt: { total?: { usd?: unknown }; span?: { fromMs?: unknown; toMs?: unknown } };
3205
+ try {
3206
+ receipt = JSON.parse(await readFile(file, 'utf8'));
3207
+ } catch {
3208
+ throw new Error(t.reconcile.receiptUnreadable(file));
3209
+ }
3210
+ const usd = receipt?.total?.usd;
3211
+ const fromMs = receipt?.span?.fromMs;
3212
+ const toMs = receipt?.span?.toMs;
3213
+ if (typeof usd !== 'number' || typeof fromMs !== 'number' || typeof toMs !== 'number') {
3214
+ throw new Error(t.reconcile.notAReceipt(file));
3215
+ }
3216
+
3217
+ let billedText: string;
3218
+ try {
3219
+ billedText = await readFile(against, 'utf8');
3220
+ } catch {
3221
+ throw new Error(t.reconcile.reportUnreadable(against));
3222
+ }
3223
+ /* Which provider's report this is, told from the text itself: OpenAI's
3224
+ buckets carry a numeric `start_time`, Anthropic's a `starting_at`. */
3225
+ const openai = looksLikeOpenaiCost(billedText) ? openaiCostReport(billedText) : null;
3226
+ const billed = openai ?? anthropicCostReport(billedText);
3227
+ if (billed.unparseable) throw new Error(t.reconcile.notAReport(against));
3228
+
3229
+ const answer = reconcile({ usd, fromMs, toMs }, billed);
3230
+ const json = JSON.stringify(answer, null, 2);
3231
+
3232
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3233
+ if (out !== undefined) {
3234
+ await writeFile(out, json + '\n', 'utf8');
3235
+ console.error(t.reconcile.written(out));
3236
+ } else {
3237
+ console.log(json);
3238
+ }
3239
+
3240
+ /* Everything below on stderr, so the document redirects cleanly. */
3241
+ if (answer.refusal !== null) {
3242
+ if (answer.refusal.reason === 'other-currency') {
3243
+ console.error(t.reconcile.otherCurrency(answer.refusal.currencies.join(', ')));
3244
+ } else if (answer.refusal.reason === 'no-billed-window') {
3245
+ console.error(t.reconcile.noBilledWindow());
3246
+ } else {
3247
+ console.error(
3248
+ t.reconcile.windowNotCovered(
3249
+ new Date(answer.refusal.computed.fromMs).toISOString(),
3250
+ new Date(answer.refusal.computed.toMs).toISOString(),
3251
+ new Date(answer.refusal.billed.fromMs).toISOString(),
3252
+ new Date(answer.refusal.billed.toMs).toISOString(),
3253
+ ),
3254
+ );
3255
+ }
3256
+ return;
3257
+ }
3258
+
3259
+ console.error(t.reconcile.summary(answer.computedUsd, answer.billedUsd, answer.differenceUsd));
3260
+ if (answer.attributable) {
3261
+ if (answer.notTokensUsd !== 0) console.error(t.reconcile.notTokens(answer.notTokensUsd));
3262
+ if (answer.batchUsd !== 0) console.error(t.reconcile.batch(answer.batchUsd));
3263
+ console.error(t.reconcile.remainder(answer.remainderUsd));
3264
+ if (!answer.batchSeparable) console.error(t.reconcile.batchNotSeparable());
3265
+ if (openai !== null && openai.unknownUnitUsd !== 0) {
3266
+ console.error(t.reconcile.unknownUnit(openai.unknownUnitUsd));
3267
+ }
3268
+ } else {
3269
+ console.error(openai === null ? t.reconcile.notAttributable() : t.reconcile.notAttributableByLineItem());
3270
+ }
3271
+ if (billed.truncated) console.error(t.reconcile.truncated());
3272
+ if (billed.unreadableAmount > 0) console.error(t.reconcile.unreadableAmount(billed.unreadableAmount));
3273
+ }
3274
+
2972
3275
  async function commandReceipt(
2973
3276
  args: Args,
2974
3277
  pricing: PricingCatalogue,
@@ -2994,12 +3297,17 @@ async function commandReceipt(
2994
3297
  console.log(json);
2995
3298
  }
2996
3299
 
2997
- /*
2998
- * Everything below goes to stderr, so `trazum receipt log.jsonl > receipt.json`
2999
- * writes a document and not a document with a summary stapled to the front.
3000
- * The gaps are read off the document rather than recomputed, so what the
3001
- * reader is told and what the file carries cannot drift apart.
3002
- */
3300
+ printReceiptSummary(document, t);
3301
+ }
3302
+
3303
+ /*
3304
+ * Everything here goes to stderr, so `trazum receipt log.jsonl > receipt.json`
3305
+ * writes a document and not a document with a summary stapled to the front.
3306
+ * The gaps are read off the document rather than recomputed, so what the
3307
+ * reader is told and what the file carries cannot drift apart. Shared with
3308
+ * `bill`, which ends on the same receipt.
3309
+ */
3310
+ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3003
3311
  if (document.lines.length === 0) {
3004
3312
  console.error(t.receipt.nothingToBill());
3005
3313
  } else {
@@ -3013,6 +3321,189 @@ async function commandReceipt(
3013
3321
  }
3014
3322
  }
3015
3323
 
3324
+ /** The shapes `bill` can tell apart from a file's own text. */
3325
+ type UsageSource =
3326
+ | 'claude-code'
3327
+ | 'otel'
3328
+ | 'litellm'
3329
+ | 'helicone'
3330
+ | 'langsmith'
3331
+ | 'anthropic-usage'
3332
+ | 'openai-usage'
3333
+ | 'openrouter'
3334
+ | 'usage-log';
3335
+
3336
+ /**
3337
+ * Which shapes claim a text. Every sniffer is asked, not the first that says
3338
+ * yes: a file two shapes claim is a file this must not convert, because
3339
+ * whichever it picked would be a guess wearing a result's clothes.
3340
+ */
3341
+ function usageSourcesOf(text: string): UsageSource[] {
3342
+ const claims: UsageSource[] = [];
3343
+ if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3344
+ if (looksLikeOtel(text)) claims.push('otel');
3345
+ if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
3346
+ if (looksLikeOpenaiUsage(text)) claims.push('openai-usage');
3347
+ if (looksLikeOpenrouterActivity(text)) claims.push('openrouter');
3348
+ if (looksLikeHelicone(text)) claims.push('helicone');
3349
+ if (looksLikeLangsmith(text)) claims.push('langsmith');
3350
+ if (looksLikeLiteLlm(text)) claims.push('litellm');
3351
+ if (claims.length > 0) return claims;
3352
+ /* A plain usage log has no signature but its own lines: if the first
3353
+ non-blank one parses as a usage line, that is what it is. */
3354
+ const first = text.split('\n').find((line) => line.trim() !== '');
3355
+ if (first !== undefined && parseUsageLine(first) !== null) claims.push('usage-log');
3356
+ return claims;
3357
+ }
3358
+
3359
+ /**
3360
+ * `trazum bill <file|dir>`: one door, from `docs/plan-2.4.md`.
3361
+ *
3362
+ * Forty-nine commands behind two hundred downloads a month said the product
3363
+ * was deep and nobody arrived, and one reason was that a person with a log
3364
+ * had to know what their log was called before Trazum would read it. This
3365
+ * reads anything the converters read, tells each file's shape from its own
3366
+ * text, converts in memory, prices, and ends on the same receipt `receipt`
3367
+ * writes.
3368
+ *
3369
+ * It is the dedicated commands composed, not a looser version of them: each
3370
+ * file's rows go through the same converter `from-<shape>` uses, so every
3371
+ * refusal those make is made here. What differs is how the refusals are
3372
+ * told. This names each file, its shape, the records it became and how many
3373
+ * rows were left out, and points at the dedicated command for the reasons,
3374
+ * rather than repeating eight commands' worth of explanation on one screen.
3375
+ * A file no shape claims is named and not guessed; a file two shapes claim is
3376
+ * named as ambiguous and not converted; a provider's cost report is named as
3377
+ * a bill rather than usage, and pointed at `reconcile`.
3378
+ */
3379
+ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
3380
+ const target = args.positional[0];
3381
+ if (target === undefined) throw new Error(t.bill.noPath());
3382
+
3383
+ let info;
3384
+ try {
3385
+ info = await stat(target);
3386
+ } catch {
3387
+ throw new Error(t.bill.notFound(target));
3388
+ }
3389
+ const files: string[] = [];
3390
+ if (info.isDirectory()) {
3391
+ const entries = await readdir(target, { recursive: true, withFileTypes: true });
3392
+ for (const entry of entries) {
3393
+ if (entry.isFile() && /\.(json|jsonl|ndjson)(\.gz)?$/i.test(entry.name)) {
3394
+ files.push(join(entry.parentPath, entry.name));
3395
+ }
3396
+ }
3397
+ files.sort();
3398
+ if (files.length === 0) throw new Error(t.bill.noFiles(target));
3399
+ } else {
3400
+ files.push(target);
3401
+ }
3402
+
3403
+ const label = stringFlag(args, 'label');
3404
+ const withLabel = label === undefined ? {} : { label };
3405
+ const lines: string[] = [];
3406
+ let sources = 0;
3407
+
3408
+ for (const file of files) {
3409
+ const text = await readUsageLog(file, t);
3410
+ const claims = usageSourcesOf(text);
3411
+
3412
+ if (claims.length === 0) {
3413
+ if (looksLikeAnthropicCost(text) || looksLikeOpenaiCost(text)) {
3414
+ console.error(t.bill.costReport(file));
3415
+ } else {
3416
+ console.error(t.bill.unknown(file));
3417
+ }
3418
+ continue;
3419
+ }
3420
+ if (claims.length > 1) {
3421
+ console.error(t.bill.ambiguous(file, claims.join(', ')));
3422
+ continue;
3423
+ }
3424
+
3425
+ const [shape] = claims;
3426
+ if (shape === undefined) continue;
3427
+ let records: unknown[] = [];
3428
+ let leftOut = 0;
3429
+ switch (shape) {
3430
+ case 'claude-code': {
3431
+ const c = claudeCodeRecords(text, withLabel);
3432
+ records = c.records;
3433
+ leftOut = c.assistantWithoutUsage + c.unparseable;
3434
+ break;
3435
+ }
3436
+ case 'otel': {
3437
+ const c = otelRecords(text);
3438
+ records = c.records;
3439
+ leftOut = c.otherSpans + c.unparseable;
3440
+ break;
3441
+ }
3442
+ case 'litellm': {
3443
+ const c = litellmRecords(text);
3444
+ records = c.records;
3445
+ leftOut = c.unnamedModel + c.unparseable;
3446
+ break;
3447
+ }
3448
+ case 'helicone': {
3449
+ const c = heliconeRecords(text);
3450
+ records = c.records;
3451
+ leftOut = c.unnamedModel + c.unparseable;
3452
+ break;
3453
+ }
3454
+ case 'langsmith': {
3455
+ const c = langsmithRecords(text);
3456
+ records = c.records;
3457
+ leftOut = c.notModelCalls + c.unnamedModel + c.unparseable;
3458
+ break;
3459
+ }
3460
+ case 'anthropic-usage': {
3461
+ const c = anthropicUsageRecords(text, withLabel);
3462
+ records = c.records;
3463
+ leftOut = c.unnamedModel + c.nonStandardTier;
3464
+ break;
3465
+ }
3466
+ case 'openai-usage': {
3467
+ const c = openaiUsageRecords(text, withLabel);
3468
+ records = c.records;
3469
+ leftOut = c.unnamedModel + c.batch + c.nonDefaultTier + c.unsplitRows;
3470
+ break;
3471
+ }
3472
+ case 'openrouter': {
3473
+ const c = openrouterActivityRecords(text, withLabel);
3474
+ records = c.records;
3475
+ leftOut = c.unnamedModel + c.undatedRows;
3476
+ break;
3477
+ }
3478
+ case 'usage-log': {
3479
+ /* Already the shape every door reads: passed through line by line,
3480
+ and what does not parse is the receipt's own unread-lines gap. */
3481
+ for (const line of text.split('\n')) if (line.trim() !== '') lines.push(line);
3482
+ break;
3483
+ }
3484
+ }
3485
+ for (const record of records) lines.push(JSON.stringify(record));
3486
+ sources += 1;
3487
+ console.error(t.bill.file(file, shape, shape === 'usage-log' ? null : records.length, leftOut));
3488
+ }
3489
+
3490
+ if (sources === 0) throw new Error(t.bill.nothingRead());
3491
+
3492
+ const report = profileUsage(lines.join('\n'), { catalogue: pricing });
3493
+ const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3494
+ const json = JSON.stringify(document, null, 2);
3495
+
3496
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3497
+ if (out !== undefined) {
3498
+ await writeFile(out, json + '\n', 'utf8');
3499
+ console.error(t.bill.written(out));
3500
+ } else {
3501
+ console.log(json);
3502
+ }
3503
+ console.error(t.bill.sources(sources, files.length));
3504
+ printReceiptSummary(document, t);
3505
+ }
3506
+
3016
3507
  /**
3017
3508
  * `trazum from-otel <file|dir>` — OpenTelemetry GenAI spans as a usage log.
3018
3509
  *
@@ -3393,6 +3884,167 @@ async function commandFromLangsmith(args: Args, t: CliMessages): Promise<void> {
3393
3884
  * conversation-shaped findings stay unavailable. Both are printed, because a
3394
3885
  * gap that is not said reads as a gap that is not there.
3395
3886
  */
3887
+ /**
3888
+ * The provider's own usage report, priced from the catalogue.
3889
+ *
3890
+ * One file in, usage-log records out, like every other converter here. What
3891
+ * makes this one different is where the file comes from: the operator runs
3892
+ * the `curl` themselves, with their own admin credential, and this command
3893
+ * never sees it. `anthropic-usage.ts` opens by arguing why that is the only
3894
+ * arrangement this project can offer.
3895
+ */
3896
+ async function commandFromAnthropic(args: Args, t: CliMessages): Promise<void> {
3897
+ const target = args.positional[0];
3898
+ if (target === undefined) throw new Error(t.fromAnthropic.noPath());
3899
+
3900
+ let text: string;
3901
+ try {
3902
+ text = await readFile(target, 'utf8');
3903
+ } catch {
3904
+ throw new Error(t.fromAnthropic.notFound(target));
3905
+ }
3906
+
3907
+ const label = stringFlag(args, 'label');
3908
+ const byWorkspace = await workspaceRulesFrom(stringFlag(args, 'label-by-workspace'), t);
3909
+ const conversion = anthropicUsageRecords(text, {
3910
+ ...(label === undefined ? {} : { label }),
3911
+ ...(byWorkspace === undefined ? {} : { labelByWorkspace: byWorkspace }),
3912
+ });
3913
+ if (conversion.unparseable > 0) throw new Error(t.fromAnthropic.unparseable());
3914
+
3915
+ const lines = conversion.records.map((record) => JSON.stringify(record));
3916
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3917
+ if (out !== undefined) {
3918
+ await writeFile(out, lines.join('\n') + (lines.length > 0 ? '\n' : ''), 'utf8');
3919
+ console.error(t.fromAnthropic.written(out));
3920
+ } else if (lines.length > 0) {
3921
+ console.log(lines.join('\n'));
3922
+ }
3923
+
3924
+ /* Every refusal on stderr, so a pipeline reads records on stdout and a
3925
+ person reads what could not be priced. The order is the order somebody
3926
+ acts in: what was read, then what was left out, then what to ask for. */
3927
+ console.error(t.fromAnthropic.summary(conversion.buckets, conversion.rows));
3928
+ if (conversion.unnamedModel > 0) console.error(t.fromAnthropic.unnamedModel(conversion.unnamedModel));
3929
+ if (conversion.nonStandardTier > 0) {
3930
+ console.error(t.fromAnthropic.nonStandardTier(conversion.nonStandardTier));
3931
+ }
3932
+ if (!conversion.tierNamed && conversion.rows > 0) console.error(t.fromAnthropic.tierUnknown());
3933
+ if (conversion.webSearchRequests > 0) console.error(t.fromAnthropic.webSearch(conversion.webSearchRequests));
3934
+ if (conversion.labelledByWorkspace > 0) {
3935
+ console.error(t.fromAnthropic.labelledByWorkspace(conversion.labelledByWorkspace));
3936
+ }
3937
+ if (conversion.unruledWorkspace > 0) {
3938
+ console.error(t.fromAnthropic.unruledWorkspace(conversion.unruledWorkspace));
3939
+ }
3940
+ if (conversion.workspaceNotGrouped) console.error(t.fromAnthropic.workspaceNotGrouped());
3941
+ if (conversion.truncated) console.error(t.fromAnthropic.truncated());
3942
+ }
3943
+
3944
+ /**
3945
+ * `from-openai`: the other provider's usage report, under the same
3946
+ * arrangement as `from-anthropic` — the operator's curl, the operator's
3947
+ * admin key, and this command reading only what came back. What differs is
3948
+ * in `openai-usage.ts`: the record is written in the Chat Completions shape
3949
+ * because that is how this report counts, and audio and image tokens are
3950
+ * set aside rather than priced at a text rate.
3951
+ */
3952
+ async function commandFromOpenai(args: Args, t: CliMessages): Promise<void> {
3953
+ const target = args.positional[0];
3954
+ if (target === undefined) throw new Error(t.fromOpenai.noPath());
3955
+
3956
+ let text: string;
3957
+ try {
3958
+ text = await readFile(target, 'utf8');
3959
+ } catch {
3960
+ throw new Error(t.fromOpenai.notFound(target));
3961
+ }
3962
+
3963
+ const label = stringFlag(args, 'label');
3964
+ const byProject = await projectRulesFrom(stringFlag(args, 'label-by-project'), t);
3965
+ const conversion = openaiUsageRecords(text, {
3966
+ ...(label === undefined ? {} : { label }),
3967
+ ...(byProject === undefined ? {} : { labelByProject: byProject }),
3968
+ });
3969
+ if (conversion.unparseable > 0) throw new Error(t.fromOpenai.unparseable());
3970
+
3971
+ const lines = conversion.records.map((record) => JSON.stringify(record));
3972
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3973
+ if (out !== undefined) {
3974
+ await writeFile(out, lines.join('\n') + (lines.length > 0 ? '\n' : ''), 'utf8');
3975
+ console.error(t.fromOpenai.written(out));
3976
+ } else if (lines.length > 0) {
3977
+ console.log(lines.join('\n'));
3978
+ }
3979
+
3980
+ /* Refusals on stderr, in the order somebody acts in: what was read, what
3981
+ was left out and why, what to ask the endpoint for next time. */
3982
+ console.error(t.fromOpenai.summary(conversion.buckets, conversion.rows, conversion.requests));
3983
+ if (conversion.unnamedModel > 0) console.error(t.fromOpenai.unnamedModel(conversion.unnamedModel));
3984
+ if (conversion.batch > 0) console.error(t.fromOpenai.batch(conversion.batch));
3985
+ if (!conversion.batchNamed && conversion.rows > 0) console.error(t.fromOpenai.batchUnknown());
3986
+ if (conversion.nonDefaultTier > 0) {
3987
+ console.error(t.fromOpenai.nonDefaultTier(conversion.nonDefaultTier, conversion.tiersRefused.join(', ')));
3988
+ }
3989
+ if (!conversion.tierNamed && conversion.rows > 0) console.error(t.fromOpenai.tierUnknown());
3990
+ if (conversion.mixedRows > 0) {
3991
+ console.error(t.fromOpenai.mixed(conversion.mixedRows, conversion.nonTextTokens, conversion.cacheWriteUnplaced));
3992
+ }
3993
+ if (conversion.unsplitRows > 0) console.error(t.fromOpenai.unsplit(conversion.unsplitRows));
3994
+ if (conversion.labelledByProject > 0) console.error(t.fromOpenai.labelledByProject(conversion.labelledByProject));
3995
+ if (conversion.unruledProject > 0) console.error(t.fromOpenai.unruledProject(conversion.unruledProject));
3996
+ if (conversion.projectNotGrouped) console.error(t.fromOpenai.projectNotGrouped());
3997
+ if (conversion.truncated) console.error(t.fromOpenai.truncated());
3998
+ }
3999
+
4000
+ /**
4001
+ * `from-openrouter`: the router's activity report, read as a log. The one
4002
+ * provider Trazum already prices from a live catalogue (`pricing --from
4003
+ * openrouter`), keyed by the same slugs this report carries. What OpenRouter
4004
+ * charged is printed beside the records and never merged into them.
4005
+ */
4006
+ async function commandFromOpenrouter(args: Args, t: CliMessages): Promise<void> {
4007
+ const target = args.positional[0];
4008
+ if (target === undefined) throw new Error(t.fromOpenrouter.noPath());
4009
+
4010
+ let text: string;
4011
+ try {
4012
+ text = await readFile(target, 'utf8');
4013
+ } catch {
4014
+ throw new Error(t.fromOpenrouter.notFound(target));
4015
+ }
4016
+
4017
+ const label = stringFlag(args, 'label');
4018
+ const byWorkspace = await openrouterWorkspaceRulesFrom(stringFlag(args, 'label-by-workspace'), t);
4019
+ const conversion = openrouterActivityRecords(text, {
4020
+ ...(label === undefined ? {} : { label }),
4021
+ ...(byWorkspace === undefined ? {} : { labelByWorkspace: byWorkspace }),
4022
+ });
4023
+ if (conversion.unparseable > 0) throw new Error(t.fromOpenrouter.unparseable());
4024
+
4025
+ const lines = conversion.records.map((record) => JSON.stringify(record));
4026
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
4027
+ if (out !== undefined) {
4028
+ await writeFile(out, lines.join('\n') + (lines.length > 0 ? '\n' : ''), 'utf8');
4029
+ console.error(t.fromOpenrouter.written(out));
4030
+ } else if (lines.length > 0) {
4031
+ console.log(lines.join('\n'));
4032
+ }
4033
+
4034
+ console.error(t.fromOpenrouter.summary(conversion.rows, conversion.days, conversion.requests));
4035
+ if (conversion.reportedUsageUsd > 0 || conversion.byokUsd > 0) {
4036
+ console.error(t.fromOpenrouter.reportedUsage(conversion.reportedUsageUsd, conversion.byokUsd));
4037
+ }
4038
+ if (conversion.reasoningTokens > 0) console.error(t.fromOpenrouter.reasoning(conversion.reasoningTokens));
4039
+ if (conversion.unnamedModel > 0) console.error(t.fromOpenrouter.unnamedModel(conversion.unnamedModel));
4040
+ if (conversion.undatedRows > 0) console.error(t.fromOpenrouter.undated(conversion.undatedRows));
4041
+ if (conversion.labelledByWorkspace > 0) {
4042
+ console.error(t.fromOpenrouter.labelledByWorkspace(conversion.labelledByWorkspace));
4043
+ }
4044
+ if (conversion.unruledWorkspace > 0) console.error(t.fromOpenrouter.unruledWorkspace(conversion.unruledWorkspace));
4045
+ if (conversion.workspaceNotGrouped) console.error(t.fromOpenrouter.workspaceNotGrouped());
4046
+ }
4047
+
3396
4048
  async function commandFromHelicone(args: Args, t: CliMessages): Promise<void> {
3397
4049
  const target = args.positional[0];
3398
4050
  if (target === undefined) throw new Error(t.fromHelicone.noPath());
@@ -9970,6 +10622,8 @@ async function commandProfile(
9970
10622
  }
9971
10623
  const windowed = sinceMs !== undefined || untilMs !== undefined;
9972
10624
 
10625
+ const report = profileUsage(raw, { catalogue: pricing, label: onlyLabel, sinceMs, untilMs });
10626
+
9973
10627
  /**
9974
10628
  * How old the price table behind every dollar below is. Stated only when it
9975
10629
  * is old enough to matter: `models` and `doctor` always print the date, but
@@ -9978,14 +10632,26 @@ async function commandProfile(
9978
10632
  * The threshold is in the sentence, and the number behind it is
9979
10633
  * `STALE_PRICING_DAYS` — shared with the MCP report and the browser's bill,
9980
10634
  * which used to keep their own copies of it.
10635
+ *
10636
+ * **The date is this report's, not the catalogue's**, and it is computed
10637
+ * after the report for that reason rather than before it as it used to be.
10638
+ * `PRICING_LAST_REVIEWED` is the oldest provider's, so a log of Claude and
10639
+ * OpenAI calls was told its prices were 68 days old on a morning when both
10640
+ * halves had been read that week — by a sentence that says, in these words,
10641
+ * that the table behind *every dollar here* was reviewed then. It was not.
10642
+ * `reviewedForModels` answers for the providers that actually priced this
10643
+ * report and falls back to the catalogue's own date wherever it cannot.
9981
10644
  */
9982
- const pricingAgeDays = reviewAgeDays(pricing.lastReviewed, new Date());
10645
+ const reportReviewed = reviewedForModels(
10646
+ report.byModel.map((row) => row.model),
10647
+ pricing,
10648
+ );
10649
+ const pricingAgeDays = reviewAgeDays(reportReviewed, new Date());
9983
10650
  const pricingStale =
9984
10651
  pricingAgeDays !== null && pricingAgeDays > STALE_PRICING_DAYS
9985
- ? { date: pricing.lastReviewed, days: pricingAgeDays }
10652
+ ? { date: reportReviewed, days: pricingAgeDays }
9986
10653
  : null;
9987
10654
 
9988
- const report = profileUsage(raw, { catalogue: pricing, label: onlyLabel, sinceMs, untilMs });
9989
10655
  if (report.total.calls === 0 && report.unpriced.calls === 0) {
9990
10656
  if (onlyLabel !== undefined || windowed) {
9991
10657
  // Diagnose against the log without the failed filter, so the error can
@@ -10208,8 +10874,32 @@ async function commandProfile(
10208
10874
  label: r.label,
10209
10875
  cache: cacheEconomics(r.breakdown),
10210
10876
  })),
10211
- // The provenance of every dollar above: which price table, how old.
10212
- pricing: { lastReviewed: pricing.lastReviewed, ageDays: pricingAgeDays },
10877
+ /*
10878
+ The provenance of every dollar above, in two parts that are not the
10879
+ same question.
10880
+
10881
+ `lastReviewed` and `ageDays` are the **table's**: its oldest
10882
+ provider, which is what "how old is this catalogue" means and what
10883
+ these two keys have always carried. Unchanged, because a key cannot
10884
+ change meaning under a minor and a consumer branching on them keeps
10885
+ working.
10886
+
10887
+ `reportReviewed` and `reportAgeDays` are **these figures'**: the
10888
+ oldest provider among the models actually priced here, which is the
10889
+ pair the staleness warning is decided from. They are new keys, and
10890
+ new keys are additions the contract allows.
10891
+
10892
+ The two differ exactly when a report uses none of the models
10893
+ holding the table back — which was the whole defect: a log of
10894
+ Claude and OpenAI calls was told its prices were 68 days old on a
10895
+ morning both halves had been read that week.
10896
+ */
10897
+ pricing: {
10898
+ lastReviewed: pricing.lastReviewed,
10899
+ ageDays: reviewAgeDays(pricing.lastReviewed, new Date()),
10900
+ reportReviewed,
10901
+ reportAgeDays: pricingAgeDays,
10902
+ },
10213
10903
  levers: billLevers(report, { catalogue: pricing }),
10214
10904
  // Present only when --against was passed: null delta means the
10215
10905
  // previous log had nothing priced, which is a different answer from
@@ -12507,6 +13197,9 @@ async function main(): Promise<void> {
12507
13197
  case 'receipt':
12508
13198
  await commandReceipt(args, pricing, t);
12509
13199
  break;
13200
+ case 'reconcile':
13201
+ await commandReconcile(args, t);
13202
+ break;
12510
13203
  case 'from-otel':
12511
13204
  await commandFromOtel(args, t);
12512
13205
  break;
@@ -12516,6 +13209,18 @@ async function main(): Promise<void> {
12516
13209
  case 'from-langsmith':
12517
13210
  await commandFromLangsmith(args, t);
12518
13211
  break;
13212
+ case 'from-anthropic':
13213
+ await commandFromAnthropic(args, t);
13214
+ break;
13215
+ case 'from-openai':
13216
+ await commandFromOpenai(args, t);
13217
+ break;
13218
+ case 'from-openrouter':
13219
+ await commandFromOpenrouter(args, t);
13220
+ break;
13221
+ case 'bill':
13222
+ await commandBill(args, pricing, t);
13223
+ break;
12519
13224
  case 'from-helicone':
12520
13225
  await commandFromHelicone(args, t);
12521
13226
  break;
@@ -12849,11 +13554,14 @@ function printDoctor(
12849
13554
  console.log(
12850
13555
  c.dim(t.doctor.subheading(model?.displayName ?? usage.model, n(usage.callsPerMonth))),
12851
13556
  );
12852
- console.log(
12853
- c.dim(
12854
- t.doctor.pricesReviewed(pricing.lastReviewed, reviewAgeDays(pricing.lastReviewed, new Date())),
12855
- ),
12856
- );
13557
+ /*
13558
+ This prompt's own model, not the catalogue's oldest provider. `doctor`
13559
+ reports on one model and one bill, so the date that qualifies it is the
13560
+ date that model's provider was read — the catalogue-wide answer named a
13561
+ provider this prompt does not use.
13562
+ */
13563
+ const reviewed = reviewedForModels([usage.model], pricing);
13564
+ console.log(c.dim(t.doctor.pricesReviewed(reviewed, reviewAgeDays(reviewed, new Date()))));
12857
13565
 
12858
13566
  // Budgets first. Everything below is money; this is whether anything is
12859
13567
  // watching at all, and an unwatched prompt is how the money got there.