@trazum/cli 2.6.0 → 2.7.1

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
@@ -2,11 +2,13 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readdirSync, readFileSync } from 'node:fs';
4
4
  import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
+ import type { FileHandle } from 'node:fs/promises';
5
6
  import { cpus, homedir, tmpdir } from 'node:os';
6
7
  import { createInterface } from 'node:readline/promises';
7
8
  import { dirname, join, resolve as resolvePath } from 'node:path';
8
9
  import { fileURLToPath } from 'node:url';
9
- import { gunzipSync } from 'node:zlib';
10
+ import { createGunzip, gunzipSync } from 'node:zlib';
11
+ import { Readable } from 'node:stream';
10
12
 
11
13
  import {
12
14
  CONTRACT_NAMES,
@@ -116,6 +118,9 @@ import {
116
118
  claudeCodeRecords,
117
119
  codexRecords,
118
120
  looksLikeCodexTranscript,
121
+ geminiCliRecords,
122
+ looksLikeGeminiCliSession,
123
+ slimUsageLine,
119
124
  type CwdLabel,
120
125
  type WorkspaceLabel,
121
126
  type ProjectLabel,
@@ -168,6 +173,7 @@ import {
168
173
  sharedPrefixes,
169
174
  sharesOf,
170
175
  spendByMonth,
176
+ spendByPeriod,
171
177
  isOffered,
172
178
  SOURCE_EXTENSIONS,
173
179
  suggestRewrites,
@@ -219,6 +225,7 @@ import type {
219
225
  FailurePolicy,
220
226
  GatewayStanding,
221
227
  UsageProfileReport,
228
+ BillPeriodUnit,
222
229
  WaiverUse,
223
230
  InitDecline,
224
231
  InitJustification,
@@ -385,6 +392,8 @@ const VALUE_FLAGS = new Set([
385
392
  'what-if',
386
393
  'since',
387
394
  'until',
395
+ // `bill --by day|week|month`: the calendar unit the statement is split by.
396
+ 'by',
388
397
  'export',
389
398
  'limit',
390
399
  'locale',
@@ -593,14 +602,94 @@ async function usageIndexFrom(
593
602
  return indexUsage(records, { catalogue: pricing });
594
603
  }
595
604
 
605
+ /*
606
+ Past this many bytes a usage file is read line by line, its message text set
607
+ aside, rather than held as one string. JavaScript cannot hold a string much
608
+ past 512 MiB, and an agent session that read large files or ran chatty
609
+ commands outgrows that: reading one whole failed with the runtime's
610
+ "Invalid string length" and took the rest of the bill with it. The
611
+ environment variable exists so the tests can cross the line without writing
612
+ a quarter of a gigabyte.
613
+ */
614
+ const WHOLE_READ_MAX_BYTES = ((): number => {
615
+ const fromEnv = Number(process.env.TRAZUM_WHOLE_READ_MAX_BYTES);
616
+ return Number.isSafeInteger(fromEnv) && fromEnv > 0 ? fromEnv : 256 * 1024 * 1024;
617
+ })();
618
+ /*
619
+ What the lines kept may add up to: under the runtime's own string ceiling
620
+ (just short of 512 MiB). Its own variable, for the same reason as the one
621
+ above: so the refusal can be tested without filling a disk.
622
+ */
623
+ const SLIMMED_MAX_CHARS = ((): number => {
624
+ const fromEnv = Number(process.env.TRAZUM_SLIMMED_MAX_CHARS);
625
+ return Number.isSafeInteger(fromEnv) && fromEnv > 0 ? fromEnv : 500 * 1024 * 1024;
626
+ })();
627
+ const megabytesOf = (bytes: number): number => Math.round(bytes / 1_000_000);
628
+
596
629
  async function readUsageLog(file: string, t: CliMessages): Promise<string> {
597
- if (!file.endsWith('.gz')) return readFile(file, 'utf8');
598
- const compressed = await readFile(file);
630
+ /*
631
+ One open file, measured and read through the same handle, so the size
632
+ that chose the path is the size of what is read: a stat by name and a
633
+ read by name could see two different files.
634
+ */
635
+ const handle = await open(file, 'r');
636
+ try {
637
+ return await readUsageHandle(handle, file, t);
638
+ } finally {
639
+ await handle.close();
640
+ }
641
+ }
642
+
643
+ async function readUsageHandle(handle: FileHandle, file: string, t: CliMessages): Promise<string> {
644
+ const size = (await handle.stat()).size;
645
+ if (!file.endsWith('.gz')) {
646
+ if (size <= WHOLE_READ_MAX_BYTES) return handle.readFile('utf8');
647
+ return readInParts(handle.createReadStream({ autoClose: false }), file, size, t);
648
+ }
649
+ const compressed = await handle.readFile();
650
+ let inflated: Buffer;
599
651
  try {
600
- return gunzipSync(compressed).toString('utf8');
652
+ // Bounded, so a file that inflates past the line is streamed rather than refused.
653
+ inflated = gunzipSync(compressed, { maxOutputLength: WHOLE_READ_MAX_BYTES });
601
654
  } catch (error) {
655
+ if (error instanceof RangeError && (error as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE') {
656
+ const gunzip = createGunzip();
657
+ let failure: Error | undefined;
658
+ gunzip.on('error', (cause: Error) => { failure = cause; });
659
+ Readable.from([compressed]).pipe(gunzip);
660
+ const text = await readInParts(gunzip, file, size, t);
661
+ if (failure !== undefined) throw new Error(t.profile.badGzip(file, failure.message));
662
+ return text;
663
+ }
602
664
  throw new Error(t.profile.badGzip(file, error instanceof Error ? error.message : String(error)));
603
665
  }
666
+ return inflated.toString('utf8');
667
+ }
668
+
669
+ /**
670
+ * A file too large to hold whole, line by line, each line with its long
671
+ * strings set aside by `slimUsageLine`: the converters read the same short
672
+ * fields from it that they would have read from the whole file.
673
+ */
674
+ async function readInParts(input: NodeJS.ReadableStream, file: string, size: number, t: CliMessages): Promise<string> {
675
+ const kept: string[] = [];
676
+ let held = 0;
677
+ let slimmed = 0;
678
+ try {
679
+ for await (const line of createInterface({ input, crlfDelay: Infinity })) {
680
+ const next = slimUsageLine(line);
681
+ if (next !== line) slimmed += 1;
682
+ held += next.length + 1;
683
+ if (held > SLIMMED_MAX_CHARS) throw new Error(t.profile.tooLargeToRead(file, megabytesOf(size)));
684
+ kept.push(next);
685
+ }
686
+ } catch (error) {
687
+ // A single line past the runtime's ceiling fails inside the line reader.
688
+ if (error instanceof RangeError) throw new Error(t.profile.tooLargeToRead(file, megabytesOf(size)));
689
+ throw error;
690
+ }
691
+ console.error(t.profile.readInParts(file, megabytesOf(size), slimmed));
692
+ return kept.join('\n');
604
693
  }
605
694
 
606
695
  function usageFrom(
@@ -769,6 +858,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
769
858
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
770
859
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
771
860
  'from-codex': ['label', 'out', 'o'],
861
+ 'from-gemini-cli': ['label', 'out', 'o'],
772
862
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
773
863
  'from-otel': ['label-from-service', 'out', 'o'],
774
864
  'from-litellm': ['out', 'o'],
@@ -776,7 +866,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
776
866
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
777
867
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
778
868
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
779
- bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'since', 'until'],
869
+ bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'since', 'until', 'by'],
780
870
  'from-helicone': ['out', 'o'],
781
871
  'from-langsmith': ['out', 'o'],
782
872
  switch: ['to', 'migration-usd', 'cases'],
@@ -3433,6 +3523,7 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3433
3523
  type UsageSource =
3434
3524
  | 'claude-code'
3435
3525
  | 'codex'
3526
+ | 'gemini-cli'
3436
3527
  | 'otel'
3437
3528
  | 'litellm'
3438
3529
  | 'helicone'
@@ -3450,6 +3541,7 @@ type UsageSource =
3450
3541
  function usageSourcesOf(text: string): UsageSource[] {
3451
3542
  const claims: UsageSource[] = [];
3452
3543
  if (looksLikeCodexTranscript(text)) claims.push('codex');
3544
+ if (looksLikeGeminiCliSession(text)) claims.push('gemini-cli');
3453
3545
  if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3454
3546
  if (looksLikeOtel(text)) claims.push('otel');
3455
3547
  if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
@@ -3493,6 +3585,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3493
3585
  /* "What did this month cost" is the question a Claude Code folder of a
3494
3586
  year's sessions answers worst without a period. */
3495
3587
  const period = billingPeriod(args, t);
3588
+ const byFlag = stringFlag(args, 'by');
3589
+ if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
3590
+ throw new Error(t.bill.badBy(byFlag));
3591
+ }
3592
+ const by = byFlag as BillPeriodUnit | undefined;
3496
3593
 
3497
3594
  /*
3498
3595
  No path is the most common first run, and it used to be a refusal: the
@@ -3502,10 +3599,16 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3502
3599
  */
3503
3600
  let targets = args.positional;
3504
3601
  if (targets.length === 0) {
3505
- const { found, tried } = await claudeProjectFolders(process.env);
3602
+ /*
3603
+ Every coding agent whose sessions this reads, not only Claude Code:
3604
+ somebody who runs Codex or Gemini CLI as well wants one bill, and asking
3605
+ them to know three folder layouts is the friction this default removes.
3606
+ Each folder found is named on its own line, so nothing is read silently.
3607
+ */
3608
+ const { found, tried } = await agentSessionFolders(process.env);
3506
3609
  if (found.length === 0) throw new Error(t.bill.noPath(tried.join(', ')));
3507
- console.error(t.bill.defaultPath(found.join(', ')));
3508
- targets = found;
3610
+ for (const { agent, path } of found) console.error(t.bill.defaultPathFor(AGENT_NAMES[agent], path));
3611
+ targets = found.map(({ path }) => path);
3509
3612
  }
3510
3613
 
3511
3614
  /*
@@ -3559,6 +3662,10 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3559
3662
  /* Claude Code transcripts read: their money is an API-rate equivalent. */
3560
3663
  let claudeCodeFiles = 0;
3561
3664
  let codexFiles = 0;
3665
+ let geminiCliFiles = 0;
3666
+ let geminiRemainder = 0;
3667
+ /* Each agent's own records, so a bill that read more than one can say which spent what. */
3668
+ const agentLines = new Map<AgentId, string[]>();
3562
3669
  const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
3563
3670
  const lines: string[] = [];
3564
3671
  let sources = 0;
@@ -3606,6 +3713,18 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3606
3713
  if (leftOut > 0) console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
3607
3714
  break;
3608
3715
  }
3716
+ case 'gemini-cli': {
3717
+ geminiCliFiles += 1;
3718
+ const project =
3719
+ label === undefined && labelFromProject && walked.has(file) ? await geminiProjectLabelFor(file) : undefined;
3720
+ if (project !== undefined && project !== '') labelledByProject += 1;
3721
+ const c = geminiCliRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
3722
+ records = c.records;
3723
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
3724
+ geminiRemainder += c.remainderAsOutput;
3725
+ if (leftOut > 0) console.error(t.fromGeminiCli.gaps(c.missingModel, c.unsupported, c.unparseable));
3726
+ break;
3727
+ }
3609
3728
  case 'claude-code': {
3610
3729
  claudeCodeFiles += 1;
3611
3730
  const project =
@@ -3666,6 +3785,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3666
3785
  }
3667
3786
  }
3668
3787
  for (const record of records) lines.push(JSON.stringify(record));
3788
+ if (shape === 'claude-code' || shape === 'codex' || shape === 'gemini-cli') {
3789
+ const own = agentLines.get(shape) ?? [];
3790
+ for (const record of records) own.push(JSON.stringify(record));
3791
+ agentLines.set(shape, own);
3792
+ }
3669
3793
  sources += 1;
3670
3794
  const count = shape === 'usage-log' ? null : records.length;
3671
3795
  if (perFile) {
@@ -3683,6 +3807,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3683
3807
  for (const file of named) console.error(t.bill.unknown(file));
3684
3808
  if (unclaimed.length > named.length) console.error(t.bill.unknownMore(unclaimed.length - named.length));
3685
3809
  if (labelledByProject > 0) console.error(t.bill.labelledByProject(labelledByProject));
3810
+ if (geminiRemainder > 0) console.error(t.fromGeminiCli.remainder(geminiRemainder));
3686
3811
 
3687
3812
  if (sources === 0) throw new Error(t.bill.nothingRead());
3688
3813
 
@@ -3719,8 +3844,28 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3719
3844
  }
3720
3845
  console.error(t.bill.sources(sources, files.length));
3721
3846
  printReceiptSummary(document, t);
3722
- if (statement) printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3723
- await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles + codexFiles > 0);
3847
+ const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
3848
+ /*
3849
+ By agent, once more than one agent's sessions were read: each agent's own
3850
+ records priced through the same catalogue and window as the whole, so the
3851
+ rows are the total split, not a second estimate beside it.
3852
+ */
3853
+ const byAgent = [...agentLines.entries()]
3854
+ .filter(([, own]) => own.length > 0)
3855
+ .map(([agent, own]) => {
3856
+ const part = profileUsage(own.join('\n'), {
3857
+ catalogue: pricing,
3858
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3859
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3860
+ });
3861
+ return { name: AGENT_NAMES[agent], calls: part.total.calls, usd: part.total.totalUsd };
3862
+ })
3863
+ .filter((row) => row.calls > 0)
3864
+ .sort((a, b) => b.usd - a.usd);
3865
+ if (statement) {
3866
+ printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by);
3867
+ }
3868
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, agentSessions);
3724
3869
 
3725
3870
  /*
3726
3871
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3776,6 +3921,100 @@ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: st
3776
3921
  return { found, tried };
3777
3922
  }
3778
3923
 
3924
+ /** The coding agents whose local sessions `bill` reads by itself. */
3925
+ type AgentId = 'claude-code' | 'codex' | 'gemini-cli';
3926
+
3927
+ const AGENT_NAMES: Readonly<Record<AgentId, string>> = Object.freeze({
3928
+ 'claude-code': 'Claude Code',
3929
+ codex: 'Codex',
3930
+ 'gemini-cli': 'Gemini CLI',
3931
+ });
3932
+
3933
+ /**
3934
+ * Where each agent keeps its sessions, from each agent's own source.
3935
+ *
3936
+ * - Claude Code: `claudeProjectFolders`, unchanged.
3937
+ * - Codex: `$CODEX_HOME` (default `~/.codex`), its `sessions` and
3938
+ * `archived_sessions`; an archived session was billed when it ran.
3939
+ * - Gemini CLI: `$GEMINI_CLI_HOME` (default the home directory), then
3940
+ * `.gemini/tmp/<project>/chats`, and `~/.cache/.gemini/tmp` where the macOS
3941
+ * sandbox moves it. Only the `chats` folders: the rest of `tmp` is shell
3942
+ * history and checkpoints, not usage.
3943
+ *
3944
+ * Every folder that exists is returned once; `tried` is every candidate, for
3945
+ * the refusal to name when there is none.
3946
+ */
3947
+ async function agentSessionFolders(
3948
+ env: NodeJS.ProcessEnv,
3949
+ ): Promise<{ found: Array<{ agent: AgentId; path: string }>; tried: string[] }> {
3950
+ const claude = await claudeProjectFolders(env);
3951
+ const found: Array<{ agent: AgentId; path: string }> = claude.found.map((path) => ({ agent: 'claude-code', path }));
3952
+ const tried = [...claude.tried];
3953
+ const seen = new Set(claude.found.map((path) => resolvePath(path)));
3954
+ const isDirectory = async (path: string): Promise<boolean> => {
3955
+ try {
3956
+ return (await stat(path)).isDirectory();
3957
+ } catch {
3958
+ return false;
3959
+ }
3960
+ };
3961
+ const home = homedir();
3962
+ const codexHome = env.CODEX_HOME ? env.CODEX_HOME : join(home, '.codex');
3963
+ for (const candidate of [join(codexHome, 'sessions'), join(codexHome, 'archived_sessions')]) {
3964
+ tried.push(candidate);
3965
+ if (!seen.has(resolvePath(candidate)) && (await isDirectory(candidate))) {
3966
+ seen.add(resolvePath(candidate));
3967
+ found.push({ agent: 'codex', path: candidate });
3968
+ }
3969
+ }
3970
+ const geminiHome = env.GEMINI_CLI_HOME ? env.GEMINI_CLI_HOME : home;
3971
+ for (const tmp of [join(geminiHome, '.gemini', 'tmp'), join(geminiHome, '.cache', '.gemini', 'tmp')]) {
3972
+ tried.push(tmp);
3973
+ if (!(await isDirectory(tmp))) continue;
3974
+ let projects: string[] = [];
3975
+ try {
3976
+ projects = (await readdir(tmp, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
3977
+ } catch {
3978
+ continue;
3979
+ }
3980
+ for (const project of projects) {
3981
+ const chats = join(tmp, project, 'chats');
3982
+ if (!seen.has(resolvePath(chats)) && (await isDirectory(chats))) {
3983
+ seen.add(resolvePath(chats));
3984
+ found.push({ agent: 'gemini-cli', path: chats });
3985
+ }
3986
+ }
3987
+ }
3988
+ return { found, tried };
3989
+ }
3990
+
3991
+ /**
3992
+ * The project a Gemini CLI session belongs to.
3993
+ *
3994
+ * Gemini CLI keeps a folder per project under `tmp`, named by a short slug in
3995
+ * current versions (with the real working directory in `.project_root`
3996
+ * beside it) and by a SHA-256 of the path in older ones. The working
3997
+ * directory's last segment is the name a person recognises; a bare hash is
3998
+ * no name at all, so it labels nothing rather than putting 64 hex digits on
3999
+ * the bill.
4000
+ */
4001
+ async function geminiProjectLabelFor(file: string): Promise<string | undefined> {
4002
+ const parts = resolvePath(file).split('/');
4003
+ const at = parts.lastIndexOf('chats');
4004
+ if (at < 1) return undefined;
4005
+ const projectDir = parts.slice(0, at).join('/');
4006
+ try {
4007
+ const root = (await readFile(join(projectDir, '.project_root'), 'utf8')).trim();
4008
+ const name = root.replace(/[\\/]+$/, '').split(/[\\/]/).pop();
4009
+ if (name !== undefined && name !== '') return name;
4010
+ } catch {
4011
+ // Older versions keep no .project_root: fall back to the folder's name.
4012
+ }
4013
+ const folder = parts[at - 1];
4014
+ if (folder === undefined || folder === '' || /^[0-9a-f]{64}$/i.test(folder)) return undefined;
4015
+ return folder;
4016
+ }
4017
+
3779
4018
  /**
3780
4019
  * The bill as a person reads it: the total, by project, by model, and what
3781
4020
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
@@ -3787,6 +4026,8 @@ function printBillStatement(
3787
4026
  t: CliMessages,
3788
4027
  window?: { since: string; until: string },
3789
4028
  apiEquivalent = false,
4029
+ byAgent: { name: string; calls: number; usd: number }[] = [],
4030
+ by?: BillPeriodUnit,
3790
4031
  ): void {
3791
4032
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
3792
4033
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
@@ -3823,6 +4064,12 @@ function printBillStatement(
3823
4064
  */
3824
4065
  if (apiEquivalent) console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3825
4066
 
4067
+ // Which agent spent what, first: it is the split a person running more than one asks for.
4068
+ if (byAgent.length > 1) {
4069
+ console.log();
4070
+ for (const line of table(columns(t.bill.colAgent()), rowsOf(byAgent))) console.log(line);
4071
+ }
4072
+
3826
4073
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3827
4074
  if (labelled.length > 0) {
3828
4075
  console.log();
@@ -3849,20 +4096,33 @@ function printBillStatement(
3849
4096
  report's own days, oldest first, newest kept when there are many; shown
3850
4097
  only once the bill spans two calendar months, since one month is the total.
3851
4098
  */
3852
- const { months, undated } = spendByMonth(report);
3853
- if (months.length >= 2) {
3854
- const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
4099
+ /*
4100
+ `--by day` and `--by week` ask the same question at a finer grain, and
4101
+ are printed whenever asked, one period or many. The newest are kept when
4102
+ there are more than a screen holds: a month of days, twelve weeks.
4103
+ */
4104
+ const unit = by ?? 'month';
4105
+ const { periods, undated } = spendByPeriod(report, unit);
4106
+ if (periods.length >= (by === undefined ? 2 : 1)) {
4107
+ const keep = unit === 'day' ? 31 : LIMIT;
4108
+ const shown = periods.slice(-keep).map(({ period, calls, usd }) => {
3855
4109
  const share = total > 0 ? usd / total : 0;
3856
- return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
4110
+ return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3857
4111
  });
3858
- if (months.length > LIMIT) shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
4112
+ if (periods.length > keep) {
4113
+ const earlier = periods.length - keep;
4114
+ shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '']);
4115
+ }
3859
4116
  console.log();
3860
- for (const line of table(columns(t.bill.colMonth()), shown)) console.log(line);
4117
+ for (const line of table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown)) console.log(line);
3861
4118
  if (undated.calls > 0) {
3862
- console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
4119
+ const sentence = unit === 'month'
4120
+ ? t.bill.monthsUndated(undated.calls, formatUsd(undated.usd))
4121
+ : t.bill.periodsUndated(undated.calls, formatUsd(undated.usd), unit);
4122
+ console.log(c.dim(` ${wrap(sentence, 74, ' ')}`));
3863
4123
  }
3864
- const newest = months[months.length - 1]!;
3865
- console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
4124
+ const newest = periods[periods.length - 1]!;
4125
+ console.log(c.dim(` ${unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit)}`));
3866
4126
  }
3867
4127
 
3868
4128
  console.log();
@@ -4131,6 +4391,62 @@ async function commandFromCodex(args: Args, t: CliMessages): Promise<void> {
4131
4391
  } else console.log(text.trimEnd());
4132
4392
  }
4133
4393
 
4394
+ /**
4395
+ * `trazum from-gemini-cli <file|dir>`: Gemini CLI sessions as a usage log.
4396
+ *
4397
+ * Explicit paths, like `from-codex`; `bill` with no path is the door that
4398
+ * looks in `~/.gemini/tmp` by itself. A directory is walked for `.jsonl` and
4399
+ * `.json` files, and each one is converted only when its own text says it is
4400
+ * a Gemini CLI session, so the shell history and checkpoints that share
4401
+ * `tmp` are left alone rather than misread.
4402
+ */
4403
+ async function commandFromGeminiCli(args: Args, t: CliMessages): Promise<void> {
4404
+ const target = args.positional[0];
4405
+ if (target === undefined) throw new Error(t.fromGeminiCli.noPath());
4406
+ let info;
4407
+ try { info = await stat(target); } catch { throw new Error(t.fromGeminiCli.notFound(target)); }
4408
+ const files = info.isDirectory()
4409
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
4410
+ .filter((entry) => entry.isFile() && /\.(jsonl|json)$/i.test(entry.name))
4411
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
4412
+ : [target];
4413
+ if (files.length === 0) throw new Error(t.fromGeminiCli.noFiles(target));
4414
+ const label = stringFlag(args, 'label');
4415
+ const lines: string[] = [];
4416
+ let sessions = 0;
4417
+ let repeats = 0;
4418
+ let missingModel = 0;
4419
+ let unsupported = 0;
4420
+ let unparseable = 0;
4421
+ let remainder = 0;
4422
+ for (const file of files) {
4423
+ const text = await readFile(file, 'utf8');
4424
+ if (!looksLikeGeminiCliSession(text)) continue;
4425
+ sessions++;
4426
+ const conversion = geminiCliRecords(text, label === undefined ? {} : { label });
4427
+ for (const record of conversion.records) lines.push(JSON.stringify(record));
4428
+ repeats += conversion.repeats;
4429
+ missingModel += conversion.missingModel;
4430
+ unsupported += conversion.unsupported;
4431
+ unparseable += conversion.unparseable;
4432
+ remainder += conversion.remainderAsOutput;
4433
+ }
4434
+ if (sessions === 0) throw new Error(t.fromGeminiCli.noFiles(target));
4435
+ console.error(t.fromGeminiCli.summary(sessions, lines.length, repeats));
4436
+ if (missingModel + unsupported + unparseable > 0) {
4437
+ console.error(t.fromGeminiCli.gaps(missingModel, unsupported, unparseable));
4438
+ }
4439
+ if (remainder > 0) console.error(t.fromGeminiCli.remainder(remainder));
4440
+ console.error(t.fromGeminiCli.caveat());
4441
+ if (lines.length === 0) throw new Error(t.fromGeminiCli.noUsage());
4442
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
4443
+ const text = lines.join('\n') + '\n';
4444
+ if (out !== undefined) {
4445
+ await writeFile(out, text, 'utf8');
4446
+ console.error(t.fromGeminiCli.written(out));
4447
+ } else console.log(text.trimEnd());
4448
+ }
4449
+
4134
4450
  async function commandFromOtel(args: Args, t: CliMessages): Promise<void> {
4135
4451
  const target = args.positional[0];
4136
4452
  if (target === undefined) throw new Error(t.fromOtel.noPath());
@@ -13734,6 +14050,9 @@ async function main(): Promise<void> {
13734
14050
  case 'from-codex':
13735
14051
  await commandFromCodex(args, t);
13736
14052
  break;
14053
+ case 'from-gemini-cli':
14054
+ await commandFromGeminiCli(args, t);
14055
+ break;
13737
14056
  case 'from-otel':
13738
14057
  await commandFromOtel(args, t);
13739
14058
  break;
@@ -13,7 +13,7 @@ export const IMPORT_SCHEMAS = {
13
13
  UsageImportRequest: {
14
14
  type: 'object', required: ['format', 'text'], additionalProperties: false,
15
15
  properties: {
16
- format: { type: 'string', enum: ['claude-code', 'codex'] },
16
+ format: { type: 'string', enum: ['claude-code', 'codex', 'gemini-cli'] },
17
17
  text: { type: 'string', minLength: 1, description: 'Non-blank transcript JSONL contents, never a path. No automatic format detection or shared deduplication state.' },
18
18
  label: { type: 'string', minLength: 1, maxLength: 200, description: 'Optional explicit, non-blank workload label; limited to 200 UTF-16 code units. Never inferred from source metadata.' },
19
19
  },
@@ -22,6 +22,7 @@ export const IMPORT_SCHEMAS = {
22
22
  description: 'Complete JSON response is limited to 1,000,000 UTF-8 bytes. Empty output does not establish zero usage. Preserve diagnostics alongside downstream reports.',
23
23
  oneOf: [
24
24
  object({ ...common, format: { const: 'codex' }, diagnostics: object(counters(['duplicates', 'unparseable', 'missingModel', 'unsupported', 'otherLines'])) }),
25
+ object({ ...common, format: { const: 'gemini-cli' }, diagnostics: object(counters(['repeats', 'unparseable', 'unsupported', 'missingModel', 'remainderAsOutput'])) }),
25
26
  object({ ...common, format: { const: 'claude-code' }, diagnostics: object({
26
27
  ...counters(['collapsed', 'noRequestId', 'otherLines', 'unparseable', 'assistantWithoutUsage', 'streamed', 'disagreements', 'synthetic']),
27
28
  resume: object({ line: count, records: count }),
@@ -1,10 +1,10 @@
1
- import { claudeCodeRecords, codexRecords } from '@trazum/core';
1
+ import { claudeCodeRecords, codexRecords, geminiCliRecords } from '@trazum/core';
2
2
 
3
3
  /** Bound the complete serialized answer, including JSON escaping and repeated labels. */
4
4
  export const MAX_IMPORT_RESPONSE_BYTES = 1_000_000;
5
5
 
6
6
  interface ImportPayload {
7
- format: 'claude-code' | 'codex';
7
+ format: 'claude-code' | 'codex' | 'gemini-cli';
8
8
  text: string;
9
9
  label?: string;
10
10
  }
@@ -17,8 +17,8 @@ export function validateImportPayload(value: unknown): asserts value is ImportPa
17
17
  if (Object.keys(payload).some((key) => !['format', 'text', 'label'].includes(key))) {
18
18
  throw new Error('Unknown properties are not accepted for usage imports.');
19
19
  }
20
- if (payload.format !== 'claude-code' && payload.format !== 'codex') {
21
- throw new Error('format must be claude-code or codex.');
20
+ if (payload.format !== 'claude-code' && payload.format !== 'codex' && payload.format !== 'gemini-cli') {
21
+ throw new Error('format must be claude-code, codex or gemini-cli.');
22
22
  }
23
23
  if (typeof payload.text !== 'string' || payload.text.trim() === '') {
24
24
  throw new Error('text must be non-empty transcript contents, not a file path.');
@@ -33,7 +33,10 @@ export function validateImportPayload(value: unknown): asserts value is ImportPa
33
33
  export function importUsage(payload: ImportPayload) {
34
34
  const options = payload.label === undefined ? {} : { label: payload.label };
35
35
  const conversion = payload.format === 'codex'
36
- ? codexRecords(payload.text, options) : claudeCodeRecords(payload.text, options);
36
+ ? codexRecords(payload.text, options)
37
+ : payload.format === 'gemini-cli'
38
+ ? geminiCliRecords(payload.text, options)
39
+ : claudeCodeRecords(payload.text, options);
37
40
  const { records, ...diagnostics } = conversion;
38
41
  const result = {
39
42
  schemaVersion: 1 as const,
@@ -62,6 +62,7 @@ const schemas = {
62
62
  oneOf: [
63
63
  object({ command: { const: 'from-claude-code' }, format: { const: 'claude-code-transcript-jsonl' } }),
64
64
  object({ command: { const: 'from-codex' }, format: { const: 'codex-session-jsonl' } }),
65
+ object({ command: { const: 'from-gemini-cli' }, format: { const: 'gemini-cli-session-jsonl' } }),
65
66
  ],
66
67
  }),
67
68
  normalizedUsage: object({ command: { const: 'bill' }, format: { const: 'trazum-usage-jsonl' } }),