@trazum/cli 2.3.0 → 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,
@@ -297,6 +318,10 @@ interface Args {
297
318
 
298
319
  const VALUE_FLAGS = new Set([
299
320
  'answers',
321
+ 'label-by-cwd',
322
+ 'label-by-workspace',
323
+ 'label-by-project',
324
+ 'against',
300
325
  'calls',
301
326
  'files-from',
302
327
  'log',
@@ -692,9 +717,14 @@ const COMMAND_FLAGS: Record<string, string[]> = {
692
717
  rollup: ['json', 'html-out'],
693
718
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
694
719
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live'],
695
- 'from-claude-code': ['label', 'label-from-project', 'out', 'o', 'state'],
720
+ 'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
696
721
  'from-otel': ['label-from-service', 'out', 'o'],
697
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'],
698
728
  'from-helicone': ['out', 'o'],
699
729
  'from-langsmith': ['out', 'o'],
700
730
  switch: ['to', 'migration-usd', 'cases'],
@@ -2655,6 +2685,167 @@ function projectLabelFor(file: string): string | undefined {
2655
2685
  }
2656
2686
 
2657
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
+
2658
2849
  /**
2659
2850
  * `--state`: read the part of a transcript that is new since last time.
2660
2851
  *
@@ -2809,6 +3000,25 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2809
3000
  * says so.
2810
3001
  */
2811
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);
2812
3022
  /**
2813
3023
  * `--state` is for one transcript, deliberately.
2814
3024
  *
@@ -2858,6 +3068,9 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2858
3068
  : projectLabel !== undefined && projectLabel !== ''
2859
3069
  ? { label: projectLabel }
2860
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 } : {}),
2861
3074
  });
2862
3075
  for (const record of conversion.records) lines.push(JSON.stringify(record));
2863
3076
  resumeLine = conversion.resume.line;
@@ -2932,7 +3145,10 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2932
3145
  if (disagreements > 0) console.error(t.fromClaudeCode.disagreements(disagreements));
2933
3146
  if (noRequestId > 0) console.error(t.fromClaudeCode.noRequestId(noRequestId));
2934
3147
  if (synthetic > 0) console.error(t.fromClaudeCode.synthetic(synthetic));
2935
- 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));
2936
3152
  console.error(t.fromClaudeCode.skipped(otherLines, unparseable, withoutUsage));
2937
3153
  }
2938
3154
 
@@ -2970,6 +3186,92 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
2970
3186
  * planting the 4 things that must never appear. This function only chooses the
2971
3187
  * log and the destination.
2972
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
+
2973
3275
  async function commandReceipt(
2974
3276
  args: Args,
2975
3277
  pricing: PricingCatalogue,
@@ -2995,12 +3297,17 @@ async function commandReceipt(
2995
3297
  console.log(json);
2996
3298
  }
2997
3299
 
2998
- /*
2999
- * Everything below goes to stderr, so `trazum receipt log.jsonl > receipt.json`
3000
- * writes a document and not a document with a summary stapled to the front.
3001
- * The gaps are read off the document rather than recomputed, so what the
3002
- * reader is told and what the file carries cannot drift apart.
3003
- */
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 {
3004
3311
  if (document.lines.length === 0) {
3005
3312
  console.error(t.receipt.nothingToBill());
3006
3313
  } else {
@@ -3014,6 +3321,189 @@ async function commandReceipt(
3014
3321
  }
3015
3322
  }
3016
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
+
3017
3507
  /**
3018
3508
  * `trazum from-otel <file|dir>` — OpenTelemetry GenAI spans as a usage log.
3019
3509
  *
@@ -3394,6 +3884,167 @@ async function commandFromLangsmith(args: Args, t: CliMessages): Promise<void> {
3394
3884
  * conversation-shaped findings stay unavailable. Both are printed, because a
3395
3885
  * gap that is not said reads as a gap that is not there.
3396
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
+
3397
4048
  async function commandFromHelicone(args: Args, t: CliMessages): Promise<void> {
3398
4049
  const target = args.positional[0];
3399
4050
  if (target === undefined) throw new Error(t.fromHelicone.noPath());
@@ -12546,6 +13197,9 @@ async function main(): Promise<void> {
12546
13197
  case 'receipt':
12547
13198
  await commandReceipt(args, pricing, t);
12548
13199
  break;
13200
+ case 'reconcile':
13201
+ await commandReconcile(args, t);
13202
+ break;
12549
13203
  case 'from-otel':
12550
13204
  await commandFromOtel(args, t);
12551
13205
  break;
@@ -12555,6 +13209,18 @@ async function main(): Promise<void> {
12555
13209
  case 'from-langsmith':
12556
13210
  await commandFromLangsmith(args, t);
12557
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;
12558
13224
  case 'from-helicone':
12559
13225
  await commandFromHelicone(args, t);
12560
13226
  break;