@trazum/cli 2.7.6 → 2.7.8

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
@@ -114,6 +114,10 @@ import {
114
114
  languagesWithStanding,
115
115
  indexUsage,
116
116
  parseUsageLine,
117
+ SHAPE_COMMAND,
118
+ notAUsageLog,
119
+ usageShapesOf,
120
+ type UsageShape,
117
121
  plannedCalls,
118
122
  claudeCodeRecords,
119
123
  codexRecords,
@@ -133,16 +137,7 @@ import {
133
137
  anthropicUsageRecords,
134
138
  looksLikeOpenaiCost,
135
139
  looksLikeAnthropicCost,
136
- looksLikeAnthropicUsage,
137
- looksLikeClaudeCodeTranscript,
138
- looksLikeHelicone,
139
- looksLikeLangsmith,
140
- looksLikeLiteLlm,
141
- looksLikeOpenaiUsage,
142
- looksLikeOpenrouterActivity,
143
- looksLikeBatchResults,
144
140
  batchResultRecords,
145
- looksLikeOtel,
146
141
  openaiCostReport,
147
142
  openaiUsageRecords,
148
143
  openrouterActivityRecords,
@@ -595,7 +590,7 @@ async function usageIndexFrom(
595
590
  ): Promise<ReturnType<typeof indexUsage> | null> {
596
591
  const logPath = stringFlag(args, 'log');
597
592
  if (logPath === undefined) return null;
598
- const text = await readUsageLog(logPath, t);
593
+ const text = await readUsageLogOnly(logPath, t);
599
594
  const records = text
600
595
  .split('\n')
601
596
  .filter((line) => line.trim() !== '')
@@ -2205,7 +2200,7 @@ async function commandInit(
2205
2200
  .sort()
2206
2201
  .map((name) => join(root, readable.where, name));
2207
2202
  if (files.length > 0) {
2208
- const texts = await Promise.all(files.map((file) => readUsageLog(file, t)));
2203
+ const texts = await Promise.all(files.map((file) => readUsageLogOnly(file, t)));
2209
2204
  measured = profileUsage(texts.join('\n'), { catalogue: pricing });
2210
2205
  }
2211
2206
  } catch (error) {
@@ -3318,7 +3313,7 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
3318
3313
  }
3319
3314
 
3320
3315
  /**
3321
- * `trazum receipt <usage.jsonl|dir>` — the bill's counts, with the provenance
3316
+ * `trazum receipt <usage.jsonl>` — the bill's counts, with the provenance
3322
3317
  * of every figure attached.
3323
3318
  *
3324
3319
  * A profile answers a question on the terminal that ran it. The same figures
@@ -3519,7 +3514,7 @@ async function commandReceipt(
3519
3514
  if (file === undefined) throw new Error(t.receipt.noLog());
3520
3515
  const period = billingPeriod(args, t);
3521
3516
 
3522
- const text = await readUsageLog(file, t);
3517
+ const text = await readUsageLogOnly(file, t);
3523
3518
  const report = profileUsage(text, {
3524
3519
  catalogue: pricing,
3525
3520
  ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
@@ -3582,45 +3577,37 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3582
3577
  if (searches > 0) console.error(t.receipt.webSearch(searches, formatUsd(searchUsd)));
3583
3578
  }
3584
3579
 
3585
- /** The shapes `bill` can tell apart from a file's own text. */
3586
- type UsageSource =
3587
- | 'claude-code'
3588
- | 'codex'
3589
- | 'gemini-cli'
3590
- | 'otel'
3591
- | 'litellm'
3592
- | 'helicone'
3593
- | 'langsmith'
3594
- | 'anthropic-usage'
3595
- | 'openai-usage'
3596
- | 'batch-results'
3597
- | 'openrouter'
3598
- | 'usage-log';
3599
-
3600
- /**
3601
- * Which shapes claim a text. Every sniffer is asked, not the first that says
3602
- * yes: a file two shapes claim is a file this must not convert, because
3603
- * whichever it picked would be a guess wearing a result's clothes.
3604
- */
3605
- function usageSourcesOf(text: string): UsageSource[] {
3606
- const claims: UsageSource[] = [];
3607
- if (looksLikeCodexTranscript(text)) claims.push('codex');
3608
- if (looksLikeGeminiCliSession(text)) claims.push('gemini-cli');
3609
- if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3610
- if (looksLikeOtel(text)) claims.push('otel');
3611
- if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
3612
- if (looksLikeOpenaiUsage(text)) claims.push('openai-usage');
3613
- if (looksLikeBatchResults(text)) claims.push('batch-results');
3614
- if (looksLikeOpenrouterActivity(text)) claims.push('openrouter');
3615
- if (looksLikeHelicone(text)) claims.push('helicone');
3616
- if (looksLikeLangsmith(text)) claims.push('langsmith');
3617
- if (looksLikeLiteLlm(text)) claims.push('litellm');
3618
- if (claims.length > 0) return claims;
3619
- /* A plain usage log has no signature but its own lines: if the first
3620
- non-blank one parses as a usage line, that is what it is. */
3621
- const first = text.split('\n').find((line) => line.trim() !== '');
3622
- if (first !== undefined && parseUsageLine(first) !== null) claims.push('usage-log');
3623
- return claims;
3580
+ /**
3581
+ * A usage log, for a command that reads nothing else.
3582
+ *
3583
+ * `profile` handed a Claude Code session answered "No usage records in that
3584
+ * file, 84 lines could not be read", which reads as a broken file, while
3585
+ * `bill` reads the same file as it is. So the shapes `bill` tells apart are
3586
+ * asked here too, and a file one of them claims is refused by name, with the
3587
+ * two commands that do read it. A provider's cost report is pointed at
3588
+ * `reconcile`, and a directory at `bill`, which walks one.
3589
+ *
3590
+ * Asked only when the first line is not already a usage line, so a usage log
3591
+ * pays one parse for it. A file nothing claims is returned as before, and its
3592
+ * unreadable lines are counted where they always were.
3593
+ *
3594
+ * `billPath` is what to name after `trazum bill`: the directory somebody
3595
+ * gave, when the file came out of one.
3596
+ */
3597
+ async function readUsageLogOnly(file: string, t: CliMessages, billPath: string = file): Promise<string> {
3598
+ const handle = await open(file, 'r');
3599
+ let text: string;
3600
+ try {
3601
+ if ((await handle.stat()).isDirectory()) throw new Error(t.errors.logIsDirectory(file));
3602
+ text = await readUsageHandle(handle, file, t);
3603
+ } finally {
3604
+ await handle.close();
3605
+ }
3606
+ const not = notAUsageLog(text);
3607
+ if (not === null) return text;
3608
+ if (not.kind === 'shape') throw new Error(t.errors.logIsOtherShape(file, not.shape, not.command, billPath));
3609
+ if (not.kind === 'ambiguous') throw new Error(t.errors.logIsAmbiguous(file, not.shapes.join(', ')));
3610
+ throw new Error(t.errors.logIsCostReport(file));
3624
3611
  }
3625
3612
 
3626
3613
  /**
@@ -3743,11 +3730,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3743
3730
  const unclaimed: string[] = [];
3744
3731
  /* The folders of the Claude Code sessions read, `<project>/<session>`, where the session keeps its other files. */
3745
3732
  const sessionFolders = new Set<string>();
3746
- const byShape = new Map<string, { files: number; records: number | null; leftOut: number }>();
3733
+ const byShape = new Map<UsageShape, { files: number; records: number | null; leftOut: number }>();
3747
3734
 
3748
3735
  for (const file of files) {
3749
3736
  const text = await readUsageLog(file, t);
3750
- const claims = usageSourcesOf(text);
3737
+ const claims = usageShapesOf(text);
3751
3738
 
3752
3739
  if (claims.length === 0) {
3753
3740
  if (looksLikeAnthropicCost(text) || looksLikeOpenaiCost(text)) {
@@ -3869,7 +3856,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3869
3856
  sources += 1;
3870
3857
  const count = shape === 'usage-log' ? null : records.length;
3871
3858
  if (perFile) {
3872
- console.error(t.bill.file(file, shape, count, leftOut));
3859
+ console.error(t.bill.file(file, shape, count, leftOut, SHAPE_COMMAND[shape]));
3873
3860
  } else {
3874
3861
  const sum = byShape.get(shape) ?? { files: 0, records: count === null ? null : 0, leftOut: 0 };
3875
3862
  sum.files += 1;
@@ -3878,7 +3865,9 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3878
3865
  byShape.set(shape, sum);
3879
3866
  }
3880
3867
  }
3881
- for (const [shape, sum] of byShape) console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut));
3868
+ for (const [shape, sum] of byShape) {
3869
+ console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut, SHAPE_COMMAND[shape]));
3870
+ }
3882
3871
  /*
3883
3872
  A Claude Code session keeps more than its transcript in the folder named
3884
3873
  after it: each subagent's metadata and prompt prefix, each workflow's
@@ -4334,7 +4323,7 @@ async function commandSwitch(args: Args, pricing: PricingCatalogue, t: CliMessag
4334
4323
  const migrationUsd = optional('migration-usd');
4335
4324
  const cases = optional('cases');
4336
4325
 
4337
- const text = await readUsageLog(file, t);
4326
+ const text = await readUsageLogOnly(file, t);
4338
4327
  const report = profileUsage(text, { catalogue: pricing });
4339
4328
  const analysis = switchAnalysis(report, target, {
4340
4329
  catalogue: pricing,
@@ -5039,7 +5028,7 @@ async function commandPosition(
5039
5028
  const file = args.positional[0];
5040
5029
  if (file === undefined) throw new Error(t.position.noLog());
5041
5030
 
5042
- const text = await readUsageLog(file, t);
5031
+ const text = await readUsageLogOnly(file, t);
5043
5032
  const records = text
5044
5033
  .split('\n')
5045
5034
  .filter((line) => line.trim() !== '')
@@ -5891,7 +5880,7 @@ async function commandLadder(
5891
5880
  if (path === undefined) {
5892
5881
  throw new Error(t.errors.missingInputFile());
5893
5882
  }
5894
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
5883
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
5895
5884
  const ladders = config.ladders ?? {};
5896
5885
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
5897
5886
  const pct = (value: number): string => `${(value * 100).toFixed(1)}%`;
@@ -6031,7 +6020,7 @@ async function commandExperiment(
6031
6020
  throw new Error(t.experiment.needsRule());
6032
6021
  }
6033
6022
 
6034
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6023
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6035
6024
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
6036
6025
  const pct = (value: number): string => `${(value * 100).toFixed(1)}%`;
6037
6026
 
@@ -6170,7 +6159,7 @@ async function commandQuality(
6170
6159
  * this whole module exists to avoid: two files gathered under conditions
6171
6160
  * nobody wrote down.
6172
6161
  */
6173
- const raw = await readUsageLog(path, t);
6162
+ const raw = await readUsageLogOnly(path, t);
6174
6163
  const sideOf = (since: number | undefined, until: number | undefined): GateSide => {
6175
6164
  const report = profileUsage(raw, { catalogue: pricing, label, sinceMs: since, untilMs: until });
6176
6165
  const slice = report.outcomeTallyByLabel.find((entry) => entry.label === label);
@@ -6424,7 +6413,7 @@ async function commandOwners(
6424
6413
  return;
6425
6414
  }
6426
6415
 
6427
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6416
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6428
6417
  const result = allocate(
6429
6418
  report.byLabel.map((entry) => ({
6430
6419
  label: entry.label,
@@ -6571,7 +6560,7 @@ async function commandCommitment(
6571
6560
  const months = Number(stringFlag(args, 'months') ?? 12);
6572
6561
  const terms = { monthlyFloorUsd: floor, discount, months };
6573
6562
 
6574
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6563
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6575
6564
  /**
6576
6565
  * Whole calendar months only.
6577
6566
  *
@@ -6721,7 +6710,7 @@ async function commandReport(
6721
6710
  const year = stringFlag(args, 'year');
6722
6711
  if (year === undefined || !/^\d{4}$/.test(year)) throw new Error(t.annual.needsYear());
6723
6712
 
6724
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6713
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6725
6714
 
6726
6715
  /**
6727
6716
  * One period per calendar month, built from the day series.
@@ -7180,7 +7169,7 @@ async function commandOptimize(
7180
7169
  if (fromLogPath === undefined) throw new Error(t.errors.allLabelsNeedsLog());
7181
7170
  const labelsMap = config.labels ?? {};
7182
7171
  if (Object.keys(labelsMap).length === 0) throw new Error(t.errors.allLabelsNeedsMap());
7183
- const report = profileUsage(await readUsageLog(fromLogPath, t), { catalogue: pricing });
7172
+ const report = profileUsage(await readUsageLogOnly(fromLogPath, t), { catalogue: pricing });
7184
7173
  const coverage = labelCoverage(report, labelsMap);
7185
7174
  const level = levelFlag(args, config, t);
7186
7175
 
@@ -7296,7 +7285,7 @@ async function commandOptimize(
7296
7285
  throw new Error(t.errors.fromLogConflict(flag));
7297
7286
  }
7298
7287
  }
7299
- const report = profileUsage(await readUsageLog(fromLog, t), { catalogue: pricing });
7288
+ const report = profileUsage(await readUsageLogOnly(fromLog, t), { catalogue: pricing });
7300
7289
 
7301
7290
  /**
7302
7291
  * Which label this prompt is. `--label` says it outright; otherwise the
@@ -9098,9 +9087,12 @@ async function commandVerify(
9098
9087
  .filter((entry) => entry.isFile() && READABLE.some((ext) => entry.name.endsWith(ext)))
9099
9088
  .map((entry) => join(againstPath, entry.name))
9100
9089
  .sort((a, b) => a.localeCompare(b));
9101
- if (files.length === 0) throw new Error(t.profile.noLogsInDirectory(againstPath, READABLE.join(', ')));
9090
+ if (files.length === 0) {
9091
+ const folders = entries.some((entry) => entry.isDirectory());
9092
+ throw new Error(t.profile.noLogsInDirectory(againstPath, READABLE.join(', '), folders));
9093
+ }
9102
9094
  }
9103
- const texts = await Promise.all(files.map((file) => readUsageLog(file, t)));
9095
+ const texts = await Promise.all(files.map((file) => readUsageLogOnly(file, t, againstPath)));
9104
9096
  const raw = texts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
9105
9097
  const report = profileUsage(raw, { catalogue: pricing });
9106
9098
 
@@ -10718,7 +10710,7 @@ function reportConversationHistory(report: UsageProfileReport, t: CliMessages):
10718
10710
  const label = growth.label === UNLABELLED ? t.profile.unlabelled() : growth.label;
10719
10711
  console.log();
10720
10712
  console.log(
10721
- ` ${c.bold(wrap(t.profile.historyGrowth(label, growth.modelName, n(Math.round(growth.minTurnTokens)), n(Math.round(growth.maxTurnTokens)), n(growth.longestSession)), 74, ' '))}`,
10713
+ ` ${c.bold(wrap(t.profile.historyGrowth(label, growth.modelName, n(Math.round(growth.minTurnTokens)), n(Math.round(growth.maxTurnTokens)), n(growth.longestSession), growth.sessions), 74, ' '))}`,
10722
10714
  );
10723
10715
  console.log(
10724
10716
  ` ${c.dim(wrap(t.profile.historyCeiling(formatUsd(growth.growthUsd), pct(growth.shareOfBill), formatUsd(growth.flatUsd), formatUsd(growth.inputUsd)), 74, ' '))}`,
@@ -11352,9 +11344,12 @@ async function commandPlan(
11352
11344
  .filter((entry) => entry.isFile() && READABLE.some((ext) => entry.name.endsWith(ext)))
11353
11345
  .map((entry) => join(path, entry.name))
11354
11346
  .sort((a, b) => a.localeCompare(b));
11355
- if (files.length === 0) throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', ')));
11347
+ if (files.length === 0) {
11348
+ const folders = entries.some((entry) => entry.isDirectory());
11349
+ throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', '), folders));
11350
+ }
11356
11351
  }
11357
- const texts = await Promise.all(files.map((file) => readUsageLog(file, t)));
11352
+ const texts = await Promise.all(files.map((file) => readUsageLogOnly(file, t, path)));
11358
11353
  const raw = texts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
11359
11354
 
11360
11355
  const report = profileUsage(raw, { catalogue: pricing });
@@ -11517,7 +11512,9 @@ async function commandProfile(
11517
11512
  .map((entry) => join(entry.parentPath ?? path, entry.name))
11518
11513
  .sort((a, b) => a.localeCompare(b));
11519
11514
  if (logFiles.length === 0) {
11520
- throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', ')));
11515
+ /* Folders only matter to the flat walk: --by-source went into them. */
11516
+ const folders = !bySourceMode && entries.some((entry) => entry.isDirectory());
11517
+ throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', '), folders));
11521
11518
  }
11522
11519
  }
11523
11520
  /**
@@ -11532,7 +11529,7 @@ async function commandProfile(
11532
11529
  * alternative — skipping it — is a total quietly missing a day, which is
11533
11530
  * the failure this repository refuses in every other place it can occur.
11534
11531
  */
11535
- const logTexts = await Promise.all(logFiles.map((file) => readUsageLog(file, t)));
11532
+ const logTexts = await Promise.all(logFiles.map((file) => readUsageLogOnly(file, t, path)));
11536
11533
  // A file that does not end in a newline would otherwise glue its last record
11537
11534
  // to the next file's first one, and both would be reported as unreadable.
11538
11535
  const raw = logTexts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
@@ -11691,7 +11688,7 @@ async function commandProfile(
11691
11688
  // The same reader as the log itself, so `--against last-month.jsonl.gz`
11692
11689
  // works: a comparison that could only read one of the two formats would
11693
11690
  // be a flag that fails on exactly the rotated file it exists to read.
11694
- ? profileUsage(await readUsageLog(againstPath, t), {
11691
+ ? profileUsage(await readUsageLogOnly(againstPath, t), {
11695
11692
  catalogue: pricing,
11696
11693
  label: onlyLabel,
11697
11694
  // The same window on both sides, for the same reason as the label:
package/src/markdown.ts CHANGED
@@ -1281,7 +1281,7 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
1281
1281
 
1282
1282
  for (const growth of report.conversations.slice(0, 3)) {
1283
1283
  lines.push(
1284
- `- ${mdText(t.profile.historyGrowth(showLabel(growth.label), growth.modelName, n(Math.round(growth.minTurnTokens)), n(Math.round(growth.maxTurnTokens)), n(growth.longestSession)))} ${mdText(t.profile.historyCeiling(formatUsd(growth.growthUsd), pct(growth.shareOfBill), formatUsd(growth.flatUsd), formatUsd(growth.inputUsd)))}`,
1284
+ `- ${mdText(t.profile.historyGrowth(showLabel(growth.label), growth.modelName, n(Math.round(growth.minTurnTokens)), n(Math.round(growth.maxTurnTokens)), n(growth.longestSession), growth.sessions))} ${mdText(t.profile.historyCeiling(formatUsd(growth.growthUsd), pct(growth.shareOfBill), formatUsd(growth.flatUsd), formatUsd(growth.inputUsd)))}`,
1285
1285
  );
1286
1286
  }
1287
1287
  if (report.conversations.length > 0) lines.push('');
@@ -1,5 +1,14 @@
1
1
  /** Pure HTTP savings handlers. Text only; never paths, provider calls or writes. */
2
- import { BUNDLED_CATALOGUE, profileUsage, billLevers, buildPlan, parsePlanDocument, verifyPlan } from '@trazum/core';
2
+ import {
3
+ AGENT_SHAPES,
4
+ BUNDLED_CATALOGUE,
5
+ billLevers,
6
+ buildPlan,
7
+ notAUsageLog,
8
+ parsePlanDocument,
9
+ profileUsage,
10
+ verifyPlan,
11
+ } from '@trazum/core';
3
12
  import type { PricingCatalogue } from '@trazum/core';
4
13
 
5
14
  export class SavingsInputError extends Error {}
@@ -19,7 +28,33 @@ export function validateSavingsPayload(value: unknown, verify: boolean): void {
19
28
  }
20
29
  }
21
30
 
31
+ /**
32
+ * A coding agent's session sent as `log` was refused as "no readable usage
33
+ * records", which reads as a broken file when `/usage/import` converts it in
34
+ * one request. Named instead, through the same verdict the CLI and the MCP
35
+ * server use, with the request or command that reads it.
36
+ */
37
+ function refuseOtherShape(log: string): void {
38
+ const not = notAUsageLog(log);
39
+ if (not === null) return;
40
+ if (not.kind === 'shape' && AGENT_SHAPES.includes(not.shape)) {
41
+ throw new SavingsInputError(
42
+ `log is a ${not.shape} session, not a usage log. POST it to /usage/import with format "${not.shape}", then send the log that returns.`,
43
+ );
44
+ }
45
+ if (not.kind === 'shape') {
46
+ throw new SavingsInputError(
47
+ `log is ${not.shape} data, not a usage log. ${not.command === null ? '' : `trazum ${not.command} turns it into one; `}trazum bill reads it as it is.`,
48
+ );
49
+ }
50
+ if (not.kind === 'ambiguous') {
51
+ throw new SavingsInputError(`log is not a usage log, and more than one format claims it (${not.shapes.join(', ')}), so it was not converted.`);
52
+ }
53
+ throw new SavingsInputError("log is a provider's cost report, a bill rather than usage. trazum reconcile sets it beside a receipt.");
54
+ }
55
+
22
56
  function savingsReport(log: string, catalogue: PricingCatalogue) {
57
+ refuseOtherShape(log);
23
58
  const report = profileUsage(log, { catalogue });
24
59
  if (report.total.calls + report.unpriced.calls === 0) {
25
60
  throw new SavingsInputError('log contains no readable usage records; pass normalized JSONL text with model and token counts');