@trazum/cli 2.7.4 → 2.7.6

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
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash } from 'node:crypto';
3
- import { readdirSync, readFileSync } from 'node:fs';
3
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
4
4
  import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
5
  import type { FileHandle } from 'node:fs/promises';
6
6
  import { cpus, homedir, tmpdir } from 'node:os';
@@ -2815,12 +2815,40 @@ async function commandWrite(args: Args, t: CliMessages): Promise<void> {
2815
2815
  * exists to refuse, and it does not get an exception for being convenient.
2816
2816
  */
2817
2817
  function projectLabelFor(file: string): string | undefined {
2818
- const folder = dirname(resolvePath(file)).split('/').pop();
2818
+ const folder = projectFolderOf(file).split('/').pop();
2819
2819
  if (folder === undefined || folder === '') return undefined;
2820
2820
  const trimmed = folder.replace(/^-+/, '');
2821
2821
  return trimmed !== '' ? trimmed : folder;
2822
2822
  }
2823
2823
 
2824
+ /**
2825
+ * The project folder a transcript belongs to, which is not always its parent.
2826
+ *
2827
+ * A session's own transcript sits in the project folder,
2828
+ * `<project>/<session>.jsonl`, and everything the session spawned sits in a
2829
+ * folder named after it: subagents at `<project>/<session>/subagents/…`,
2830
+ * workflow agents at `<project>/<session>/subagents/workflows/wf_…/…`. The
2831
+ * parent of those is `subagents` or `wf_…`, and labelling by it filed a
2832
+ * session's subagent spend under projects that never existed: measured on
2833
+ * this repository's own transcripts, a quarter of a $569 bill under six
2834
+ * `wf_` names.
2835
+ *
2836
+ * So the folder is found the way Claude Code lays it out, not by a name: the
2837
+ * nearest ancestor that has a transcript of its own name beside it is the
2838
+ * session's folder, and the project is its parent. A transcript with no such
2839
+ * ancestor is a session's own, and its parent is the project, as before.
2840
+ */
2841
+ function projectFolderOf(file: string): string {
2842
+ const parent = dirname(resolvePath(file));
2843
+ let dir = parent;
2844
+ for (;;) {
2845
+ const up = dirname(dir);
2846
+ if (up === dir) return parent;
2847
+ if (existsSync(`${dir}.jsonl`)) return up;
2848
+ dir = up;
2849
+ }
2850
+ }
2851
+
2824
2852
 
2825
2853
  /**
2826
2854
  * The directory rules, read from a JSON file, or nothing when none was asked
@@ -3338,7 +3366,10 @@ async function commandReconcile(args: Args, t: CliMessages): Promise<void> {
3338
3366
  const against = stringFlag(args, 'against');
3339
3367
  if (against === undefined) throw new Error(t.reconcile.noReport());
3340
3368
 
3341
- let receipt: { total?: { usd?: unknown }; span?: { fromMs?: unknown; toMs?: unknown } };
3369
+ let receipt: {
3370
+ total?: { usd?: unknown; batchUsd?: unknown; webSearchUsd?: unknown };
3371
+ span?: { fromMs?: unknown; toMs?: unknown };
3372
+ };
3342
3373
  try {
3343
3374
  receipt = JSON.parse(await readFile(file, 'utf8'));
3344
3375
  } catch {
@@ -3363,7 +3394,19 @@ async function commandReconcile(args: Args, t: CliMessages): Promise<void> {
3363
3394
  const billed = openai ?? anthropicCostReport(billedText);
3364
3395
  if (billed.unparseable) throw new Error(t.reconcile.notAReport(against));
3365
3396
 
3366
- const answer = reconcile({ usd, fromMs, toMs }, billed);
3397
+ /* The receipt's own batch and search figures, when it is new enough to carry them. */
3398
+ const figure = (value: unknown): number | undefined =>
3399
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
3400
+ const batchUsd = figure(receipt.total?.batchUsd);
3401
+ const webSearchUsd = figure(receipt.total?.webSearchUsd);
3402
+ const answer = reconcile(
3403
+ {
3404
+ usd, fromMs, toMs,
3405
+ ...(batchUsd === undefined ? {} : { batchUsd }),
3406
+ ...(webSearchUsd === undefined ? {} : { webSearchUsd }),
3407
+ },
3408
+ billed,
3409
+ );
3367
3410
  const json = JSON.stringify(answer, null, 2);
3368
3411
 
3369
3412
  const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
@@ -3395,8 +3438,15 @@ async function commandReconcile(args: Args, t: CliMessages): Promise<void> {
3395
3438
 
3396
3439
  console.error(t.reconcile.summary(answer.computedUsd, answer.billedUsd, answer.differenceUsd));
3397
3440
  if (answer.attributable) {
3398
- if (answer.notTokensUsd !== 0) console.error(t.reconcile.notTokens(answer.notTokensUsd));
3399
- if (answer.batchUsd !== 0) console.error(t.reconcile.batch(answer.batchUsd));
3441
+ if (answer.notTokensUsd !== 0 || (answer.computedWebSearchUsd ?? 0) !== 0) {
3442
+ console.error(t.reconcile.notTokens(answer.notTokensUsd, answer.computedWebSearchUsd ?? 0));
3443
+ }
3444
+ if (answer.batchUsd !== 0 || (answer.computedBatchUsd ?? 0) !== 0) {
3445
+ console.error(t.reconcile.batch(answer.batchUsd, answer.computedBatchUsd ?? 0));
3446
+ }
3447
+ if (!answer.computedSplitKnown && (answer.batchUsd !== 0 || answer.notTokensUsd !== 0)) {
3448
+ console.error(t.reconcile.splitUnknown());
3449
+ }
3400
3450
  console.error(t.reconcile.remainder(answer.remainderUsd));
3401
3451
  if (!answer.batchSeparable) console.error(t.reconcile.batchNotSeparable());
3402
3452
  if (openai !== null && openai.unknownUnitUsd !== 0) {
@@ -3518,7 +3568,18 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3518
3568
  t.profile.tierCeiling(gap.calls, gap.models.join(', '), formatUsd(gap.ceilingUsd), formatUsd(gap.floorUsd)),
3519
3569
  );
3520
3570
  }
3571
+ if (gap.kind === 'unpriced-web-search') {
3572
+ console.error(t.receipt.unpricedWebSearch(gap.requests, gap.models.join(', ')));
3573
+ }
3521
3574
  }
3575
+ /*
3576
+ * Priced searches are not a gap: they are in the total. Said once anyway,
3577
+ * because a per-search fee is a line nobody expects on a token bill, and a
3578
+ * total that grew by it with nothing on screen reads as a pricing error.
3579
+ */
3580
+ const searches = document.lines.reduce((sum, line) => sum + line.webSearchRequests, 0);
3581
+ const searchUsd = document.lines.reduce((sum, line) => sum + line.money.webSearchUsd, 0);
3582
+ if (searches > 0) console.error(t.receipt.webSearch(searches, formatUsd(searchUsd)));
3522
3583
  }
3523
3584
 
3524
3585
  /** The shapes `bill` can tell apart from a file's own text. */
@@ -3680,6 +3741,8 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3680
3741
  */
3681
3742
  const perFile = files.length <= 8;
3682
3743
  const unclaimed: string[] = [];
3744
+ /* The folders of the Claude Code sessions read, `<project>/<session>`, where the session keeps its other files. */
3745
+ const sessionFolders = new Set<string>();
3683
3746
  const byShape = new Map<string, { files: number; records: number | null; leftOut: number }>();
3684
3747
 
3685
3748
  for (const file of files) {
@@ -3737,6 +3800,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3737
3800
  const c = claudeCodeRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
3738
3801
  records = c.records;
3739
3802
  leftOut = c.assistantWithoutUsage + c.unparseable;
3803
+ sessionFolders.add(resolvePath(file).replace(/\.jsonl$/, ''));
3740
3804
  break;
3741
3805
  }
3742
3806
  case 'otel': {
@@ -3815,9 +3879,30 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3815
3879
  }
3816
3880
  }
3817
3881
  for (const [shape, sum] of byShape) console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut));
3818
- const named = perFile ? unclaimed : unclaimed.slice(0, 3);
3882
+ /*
3883
+ A Claude Code session keeps more than its transcript in the folder named
3884
+ after it: each subagent's metadata and prompt prefix, each workflow's
3885
+ journal and script, tool output too long for the transcript. None of it is
3886
+ usage, and naming each as a file no shape claims made a first bill read as
3887
+ a hundred and fifty things gone wrong. Counted once instead, and only
3888
+ inside the folder of a session that was read, so a file anywhere else is
3889
+ still named.
3890
+ */
3891
+ const insideSession = (file: string): boolean => {
3892
+ let dir = dirname(resolvePath(file));
3893
+ for (;;) {
3894
+ if (sessionFolders.has(dir)) return true;
3895
+ const up = dirname(dir);
3896
+ if (up === dir) return false;
3897
+ dir = up;
3898
+ }
3899
+ };
3900
+ const sideFiles = unclaimed.filter(insideSession).length;
3901
+ const unknown = unclaimed.filter((file) => !insideSession(file));
3902
+ if (sideFiles > 0) console.error(t.bill.sessionSideFiles(sideFiles));
3903
+ const named = perFile ? unknown : unknown.slice(0, 3);
3819
3904
  for (const file of named) console.error(t.bill.unknown(file));
3820
- if (unclaimed.length > named.length) console.error(t.bill.unknownMore(unclaimed.length - named.length));
3905
+ if (unknown.length > named.length) console.error(t.bill.unknownMore(unknown.length - named.length));
3821
3906
  if (labelledByProject > 0) console.error(t.bill.labelledByProject(labelledByProject));
3822
3907
  if (geminiRemainder > 0) console.error(t.fromGeminiCli.remainder(geminiRemainder));
3823
3908
 
@@ -4753,6 +4838,7 @@ async function commandFromAnthropic(args: Args, t: CliMessages): Promise<void> {
4753
4838
  console.error(t.fromAnthropic.geoUnknown(conversion.geoUnknownMultiplied));
4754
4839
  }
4755
4840
  if (conversion.webSearchRequests > 0) console.error(t.fromAnthropic.webSearch(conversion.webSearchRequests));
4841
+ if (conversion.webSearchLeftOut > 0) console.error(t.fromAnthropic.webSearchLeftOut(conversion.webSearchLeftOut));
4756
4842
  if (conversion.labelledByWorkspace > 0) {
4757
4843
  console.error(t.fromAnthropic.labelledByWorkspace(conversion.labelledByWorkspace));
4758
4844
  }
@@ -11891,6 +11977,12 @@ async function commandProfile(
11891
11977
  for (const [name, usd, share, tokens] of parts) {
11892
11978
  console.log(` ${bar(share)} ${t.profile.part(name, formatUsd(usd), pct(share), n(tokens))}`);
11893
11979
  }
11980
+ // Billed per search, so it counts searches where the rows above count tokens.
11981
+ if (report.total.webSearchRequests > 0) {
11982
+ console.log(
11983
+ ` ${bar(shares.webSearch)} ${t.profile.partSearches(t.profile.partWebSearch(), formatUsd(report.total.webSearchUsd), pct(shares.webSearch), report.total.webSearchRequests)}`,
11984
+ );
11985
+ }
11894
11986
 
11895
11987
  /**
11896
11988
  * The line the command exists for: which part of the bill to argue with.
package/src/markdown.ts CHANGED
@@ -968,6 +968,12 @@ export function renderProfileMarkdown(input: ProfileMarkdownInput): string {
968
968
  // Catalogue text, not user data: no escaping into a code cell needed.
969
969
  lines.push(`| ${name} | ${formatUsd(usd)} | ${pct(share)} | ${n(tokens)} |`);
970
970
  }
971
+ // Billed per search, not per token, so its count is not in the tokens column.
972
+ if (report.total.webSearchRequests > 0) {
973
+ lines.push(
974
+ `| ${t.profile.partWebSearch()} (${n(report.total.webSearchRequests)}) | ${formatUsd(report.total.webSearchUsd)} | ${pct(shares.webSearch)} | — |`,
975
+ );
976
+ }
971
977
  lines.push('');
972
978
 
973
979
  /**