@trazum/cli 2.6.0 → 2.7.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
@@ -116,6 +116,8 @@ import {
116
116
  claudeCodeRecords,
117
117
  codexRecords,
118
118
  looksLikeCodexTranscript,
119
+ geminiCliRecords,
120
+ looksLikeGeminiCliSession,
119
121
  type CwdLabel,
120
122
  type WorkspaceLabel,
121
123
  type ProjectLabel,
@@ -168,6 +170,7 @@ import {
168
170
  sharedPrefixes,
169
171
  sharesOf,
170
172
  spendByMonth,
173
+ spendByPeriod,
171
174
  isOffered,
172
175
  SOURCE_EXTENSIONS,
173
176
  suggestRewrites,
@@ -219,6 +222,7 @@ import type {
219
222
  FailurePolicy,
220
223
  GatewayStanding,
221
224
  UsageProfileReport,
225
+ BillPeriodUnit,
222
226
  WaiverUse,
223
227
  InitDecline,
224
228
  InitJustification,
@@ -385,6 +389,8 @@ const VALUE_FLAGS = new Set([
385
389
  'what-if',
386
390
  'since',
387
391
  'until',
392
+ // `bill --by day|week|month`: the calendar unit the statement is split by.
393
+ 'by',
388
394
  'export',
389
395
  'limit',
390
396
  'locale',
@@ -769,6 +775,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
769
775
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
770
776
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
771
777
  'from-codex': ['label', 'out', 'o'],
778
+ 'from-gemini-cli': ['label', 'out', 'o'],
772
779
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
773
780
  'from-otel': ['label-from-service', 'out', 'o'],
774
781
  'from-litellm': ['out', 'o'],
@@ -776,7 +783,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
776
783
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
777
784
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
778
785
  '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'],
786
+ 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
787
  'from-helicone': ['out', 'o'],
781
788
  'from-langsmith': ['out', 'o'],
782
789
  switch: ['to', 'migration-usd', 'cases'],
@@ -3433,6 +3440,7 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3433
3440
  type UsageSource =
3434
3441
  | 'claude-code'
3435
3442
  | 'codex'
3443
+ | 'gemini-cli'
3436
3444
  | 'otel'
3437
3445
  | 'litellm'
3438
3446
  | 'helicone'
@@ -3450,6 +3458,7 @@ type UsageSource =
3450
3458
  function usageSourcesOf(text: string): UsageSource[] {
3451
3459
  const claims: UsageSource[] = [];
3452
3460
  if (looksLikeCodexTranscript(text)) claims.push('codex');
3461
+ if (looksLikeGeminiCliSession(text)) claims.push('gemini-cli');
3453
3462
  if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3454
3463
  if (looksLikeOtel(text)) claims.push('otel');
3455
3464
  if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
@@ -3493,6 +3502,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3493
3502
  /* "What did this month cost" is the question a Claude Code folder of a
3494
3503
  year's sessions answers worst without a period. */
3495
3504
  const period = billingPeriod(args, t);
3505
+ const byFlag = stringFlag(args, 'by');
3506
+ if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
3507
+ throw new Error(t.bill.badBy(byFlag));
3508
+ }
3509
+ const by = byFlag as BillPeriodUnit | undefined;
3496
3510
 
3497
3511
  /*
3498
3512
  No path is the most common first run, and it used to be a refusal: the
@@ -3502,10 +3516,16 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3502
3516
  */
3503
3517
  let targets = args.positional;
3504
3518
  if (targets.length === 0) {
3505
- const { found, tried } = await claudeProjectFolders(process.env);
3519
+ /*
3520
+ Every coding agent whose sessions this reads, not only Claude Code:
3521
+ somebody who runs Codex or Gemini CLI as well wants one bill, and asking
3522
+ them to know three folder layouts is the friction this default removes.
3523
+ Each folder found is named on its own line, so nothing is read silently.
3524
+ */
3525
+ const { found, tried } = await agentSessionFolders(process.env);
3506
3526
  if (found.length === 0) throw new Error(t.bill.noPath(tried.join(', ')));
3507
- console.error(t.bill.defaultPath(found.join(', ')));
3508
- targets = found;
3527
+ for (const { agent, path } of found) console.error(t.bill.defaultPathFor(AGENT_NAMES[agent], path));
3528
+ targets = found.map(({ path }) => path);
3509
3529
  }
3510
3530
 
3511
3531
  /*
@@ -3559,6 +3579,10 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3559
3579
  /* Claude Code transcripts read: their money is an API-rate equivalent. */
3560
3580
  let claudeCodeFiles = 0;
3561
3581
  let codexFiles = 0;
3582
+ let geminiCliFiles = 0;
3583
+ let geminiRemainder = 0;
3584
+ /* Each agent's own records, so a bill that read more than one can say which spent what. */
3585
+ const agentLines = new Map<AgentId, string[]>();
3562
3586
  const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
3563
3587
  const lines: string[] = [];
3564
3588
  let sources = 0;
@@ -3606,6 +3630,18 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3606
3630
  if (leftOut > 0) console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
3607
3631
  break;
3608
3632
  }
3633
+ case 'gemini-cli': {
3634
+ geminiCliFiles += 1;
3635
+ const project =
3636
+ label === undefined && labelFromProject && walked.has(file) ? await geminiProjectLabelFor(file) : undefined;
3637
+ if (project !== undefined && project !== '') labelledByProject += 1;
3638
+ const c = geminiCliRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
3639
+ records = c.records;
3640
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
3641
+ geminiRemainder += c.remainderAsOutput;
3642
+ if (leftOut > 0) console.error(t.fromGeminiCli.gaps(c.missingModel, c.unsupported, c.unparseable));
3643
+ break;
3644
+ }
3609
3645
  case 'claude-code': {
3610
3646
  claudeCodeFiles += 1;
3611
3647
  const project =
@@ -3666,6 +3702,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3666
3702
  }
3667
3703
  }
3668
3704
  for (const record of records) lines.push(JSON.stringify(record));
3705
+ if (shape === 'claude-code' || shape === 'codex' || shape === 'gemini-cli') {
3706
+ const own = agentLines.get(shape) ?? [];
3707
+ for (const record of records) own.push(JSON.stringify(record));
3708
+ agentLines.set(shape, own);
3709
+ }
3669
3710
  sources += 1;
3670
3711
  const count = shape === 'usage-log' ? null : records.length;
3671
3712
  if (perFile) {
@@ -3683,6 +3724,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3683
3724
  for (const file of named) console.error(t.bill.unknown(file));
3684
3725
  if (unclaimed.length > named.length) console.error(t.bill.unknownMore(unclaimed.length - named.length));
3685
3726
  if (labelledByProject > 0) console.error(t.bill.labelledByProject(labelledByProject));
3727
+ if (geminiRemainder > 0) console.error(t.fromGeminiCli.remainder(geminiRemainder));
3686
3728
 
3687
3729
  if (sources === 0) throw new Error(t.bill.nothingRead());
3688
3730
 
@@ -3719,8 +3761,28 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3719
3761
  }
3720
3762
  console.error(t.bill.sources(sources, files.length));
3721
3763
  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);
3764
+ const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
3765
+ /*
3766
+ By agent, once more than one agent's sessions were read: each agent's own
3767
+ records priced through the same catalogue and window as the whole, so the
3768
+ rows are the total split, not a second estimate beside it.
3769
+ */
3770
+ const byAgent = [...agentLines.entries()]
3771
+ .filter(([, own]) => own.length > 0)
3772
+ .map(([agent, own]) => {
3773
+ const part = profileUsage(own.join('\n'), {
3774
+ catalogue: pricing,
3775
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3776
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3777
+ });
3778
+ return { name: AGENT_NAMES[agent], calls: part.total.calls, usd: part.total.totalUsd };
3779
+ })
3780
+ .filter((row) => row.calls > 0)
3781
+ .sort((a, b) => b.usd - a.usd);
3782
+ if (statement) {
3783
+ printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by);
3784
+ }
3785
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, agentSessions);
3724
3786
 
3725
3787
  /*
3726
3788
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3776,6 +3838,100 @@ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: st
3776
3838
  return { found, tried };
3777
3839
  }
3778
3840
 
3841
+ /** The coding agents whose local sessions `bill` reads by itself. */
3842
+ type AgentId = 'claude-code' | 'codex' | 'gemini-cli';
3843
+
3844
+ const AGENT_NAMES: Readonly<Record<AgentId, string>> = Object.freeze({
3845
+ 'claude-code': 'Claude Code',
3846
+ codex: 'Codex',
3847
+ 'gemini-cli': 'Gemini CLI',
3848
+ });
3849
+
3850
+ /**
3851
+ * Where each agent keeps its sessions, from each agent's own source.
3852
+ *
3853
+ * - Claude Code: `claudeProjectFolders`, unchanged.
3854
+ * - Codex: `$CODEX_HOME` (default `~/.codex`), its `sessions` and
3855
+ * `archived_sessions`; an archived session was billed when it ran.
3856
+ * - Gemini CLI: `$GEMINI_CLI_HOME` (default the home directory), then
3857
+ * `.gemini/tmp/<project>/chats`, and `~/.cache/.gemini/tmp` where the macOS
3858
+ * sandbox moves it. Only the `chats` folders: the rest of `tmp` is shell
3859
+ * history and checkpoints, not usage.
3860
+ *
3861
+ * Every folder that exists is returned once; `tried` is every candidate, for
3862
+ * the refusal to name when there is none.
3863
+ */
3864
+ async function agentSessionFolders(
3865
+ env: NodeJS.ProcessEnv,
3866
+ ): Promise<{ found: Array<{ agent: AgentId; path: string }>; tried: string[] }> {
3867
+ const claude = await claudeProjectFolders(env);
3868
+ const found: Array<{ agent: AgentId; path: string }> = claude.found.map((path) => ({ agent: 'claude-code', path }));
3869
+ const tried = [...claude.tried];
3870
+ const seen = new Set(claude.found.map((path) => resolvePath(path)));
3871
+ const isDirectory = async (path: string): Promise<boolean> => {
3872
+ try {
3873
+ return (await stat(path)).isDirectory();
3874
+ } catch {
3875
+ return false;
3876
+ }
3877
+ };
3878
+ const home = homedir();
3879
+ const codexHome = env.CODEX_HOME ? env.CODEX_HOME : join(home, '.codex');
3880
+ for (const candidate of [join(codexHome, 'sessions'), join(codexHome, 'archived_sessions')]) {
3881
+ tried.push(candidate);
3882
+ if (!seen.has(resolvePath(candidate)) && (await isDirectory(candidate))) {
3883
+ seen.add(resolvePath(candidate));
3884
+ found.push({ agent: 'codex', path: candidate });
3885
+ }
3886
+ }
3887
+ const geminiHome = env.GEMINI_CLI_HOME ? env.GEMINI_CLI_HOME : home;
3888
+ for (const tmp of [join(geminiHome, '.gemini', 'tmp'), join(geminiHome, '.cache', '.gemini', 'tmp')]) {
3889
+ tried.push(tmp);
3890
+ if (!(await isDirectory(tmp))) continue;
3891
+ let projects: string[] = [];
3892
+ try {
3893
+ projects = (await readdir(tmp, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
3894
+ } catch {
3895
+ continue;
3896
+ }
3897
+ for (const project of projects) {
3898
+ const chats = join(tmp, project, 'chats');
3899
+ if (!seen.has(resolvePath(chats)) && (await isDirectory(chats))) {
3900
+ seen.add(resolvePath(chats));
3901
+ found.push({ agent: 'gemini-cli', path: chats });
3902
+ }
3903
+ }
3904
+ }
3905
+ return { found, tried };
3906
+ }
3907
+
3908
+ /**
3909
+ * The project a Gemini CLI session belongs to.
3910
+ *
3911
+ * Gemini CLI keeps a folder per project under `tmp`, named by a short slug in
3912
+ * current versions (with the real working directory in `.project_root`
3913
+ * beside it) and by a SHA-256 of the path in older ones. The working
3914
+ * directory's last segment is the name a person recognises; a bare hash is
3915
+ * no name at all, so it labels nothing rather than putting 64 hex digits on
3916
+ * the bill.
3917
+ */
3918
+ async function geminiProjectLabelFor(file: string): Promise<string | undefined> {
3919
+ const parts = resolvePath(file).split('/');
3920
+ const at = parts.lastIndexOf('chats');
3921
+ if (at < 1) return undefined;
3922
+ const projectDir = parts.slice(0, at).join('/');
3923
+ try {
3924
+ const root = (await readFile(join(projectDir, '.project_root'), 'utf8')).trim();
3925
+ const name = root.replace(/[\\/]+$/, '').split(/[\\/]/).pop();
3926
+ if (name !== undefined && name !== '') return name;
3927
+ } catch {
3928
+ // Older versions keep no .project_root: fall back to the folder's name.
3929
+ }
3930
+ const folder = parts[at - 1];
3931
+ if (folder === undefined || folder === '' || /^[0-9a-f]{64}$/i.test(folder)) return undefined;
3932
+ return folder;
3933
+ }
3934
+
3779
3935
  /**
3780
3936
  * The bill as a person reads it: the total, by project, by model, and what
3781
3937
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
@@ -3787,6 +3943,8 @@ function printBillStatement(
3787
3943
  t: CliMessages,
3788
3944
  window?: { since: string; until: string },
3789
3945
  apiEquivalent = false,
3946
+ byAgent: { name: string; calls: number; usd: number }[] = [],
3947
+ by?: BillPeriodUnit,
3790
3948
  ): void {
3791
3949
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
3792
3950
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
@@ -3823,6 +3981,12 @@ function printBillStatement(
3823
3981
  */
3824
3982
  if (apiEquivalent) console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3825
3983
 
3984
+ // Which agent spent what, first: it is the split a person running more than one asks for.
3985
+ if (byAgent.length > 1) {
3986
+ console.log();
3987
+ for (const line of table(columns(t.bill.colAgent()), rowsOf(byAgent))) console.log(line);
3988
+ }
3989
+
3826
3990
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3827
3991
  if (labelled.length > 0) {
3828
3992
  console.log();
@@ -3849,20 +4013,33 @@ function printBillStatement(
3849
4013
  report's own days, oldest first, newest kept when there are many; shown
3850
4014
  only once the bill spans two calendar months, since one month is the total.
3851
4015
  */
3852
- const { months, undated } = spendByMonth(report);
3853
- if (months.length >= 2) {
3854
- const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
4016
+ /*
4017
+ `--by day` and `--by week` ask the same question at a finer grain, and
4018
+ are printed whenever asked, one period or many. The newest are kept when
4019
+ there are more than a screen holds: a month of days, twelve weeks.
4020
+ */
4021
+ const unit = by ?? 'month';
4022
+ const { periods, undated } = spendByPeriod(report, unit);
4023
+ if (periods.length >= (by === undefined ? 2 : 1)) {
4024
+ const keep = unit === 'day' ? 31 : LIMIT;
4025
+ const shown = periods.slice(-keep).map(({ period, calls, usd }) => {
3855
4026
  const share = total > 0 ? usd / total : 0;
3856
- return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
4027
+ return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3857
4028
  });
3858
- if (months.length > LIMIT) shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
4029
+ if (periods.length > keep) {
4030
+ const earlier = periods.length - keep;
4031
+ shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '']);
4032
+ }
3859
4033
  console.log();
3860
- for (const line of table(columns(t.bill.colMonth()), shown)) console.log(line);
4034
+ for (const line of table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown)) console.log(line);
3861
4035
  if (undated.calls > 0) {
3862
- console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
4036
+ const sentence = unit === 'month'
4037
+ ? t.bill.monthsUndated(undated.calls, formatUsd(undated.usd))
4038
+ : t.bill.periodsUndated(undated.calls, formatUsd(undated.usd), unit);
4039
+ console.log(c.dim(` ${wrap(sentence, 74, ' ')}`));
3863
4040
  }
3864
- const newest = months[months.length - 1]!;
3865
- console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
4041
+ const newest = periods[periods.length - 1]!;
4042
+ console.log(c.dim(` ${unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit)}`));
3866
4043
  }
3867
4044
 
3868
4045
  console.log();
@@ -4131,6 +4308,62 @@ async function commandFromCodex(args: Args, t: CliMessages): Promise<void> {
4131
4308
  } else console.log(text.trimEnd());
4132
4309
  }
4133
4310
 
4311
+ /**
4312
+ * `trazum from-gemini-cli <file|dir>`: Gemini CLI sessions as a usage log.
4313
+ *
4314
+ * Explicit paths, like `from-codex`; `bill` with no path is the door that
4315
+ * looks in `~/.gemini/tmp` by itself. A directory is walked for `.jsonl` and
4316
+ * `.json` files, and each one is converted only when its own text says it is
4317
+ * a Gemini CLI session, so the shell history and checkpoints that share
4318
+ * `tmp` are left alone rather than misread.
4319
+ */
4320
+ async function commandFromGeminiCli(args: Args, t: CliMessages): Promise<void> {
4321
+ const target = args.positional[0];
4322
+ if (target === undefined) throw new Error(t.fromGeminiCli.noPath());
4323
+ let info;
4324
+ try { info = await stat(target); } catch { throw new Error(t.fromGeminiCli.notFound(target)); }
4325
+ const files = info.isDirectory()
4326
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
4327
+ .filter((entry) => entry.isFile() && /\.(jsonl|json)$/i.test(entry.name))
4328
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
4329
+ : [target];
4330
+ if (files.length === 0) throw new Error(t.fromGeminiCli.noFiles(target));
4331
+ const label = stringFlag(args, 'label');
4332
+ const lines: string[] = [];
4333
+ let sessions = 0;
4334
+ let repeats = 0;
4335
+ let missingModel = 0;
4336
+ let unsupported = 0;
4337
+ let unparseable = 0;
4338
+ let remainder = 0;
4339
+ for (const file of files) {
4340
+ const text = await readFile(file, 'utf8');
4341
+ if (!looksLikeGeminiCliSession(text)) continue;
4342
+ sessions++;
4343
+ const conversion = geminiCliRecords(text, label === undefined ? {} : { label });
4344
+ for (const record of conversion.records) lines.push(JSON.stringify(record));
4345
+ repeats += conversion.repeats;
4346
+ missingModel += conversion.missingModel;
4347
+ unsupported += conversion.unsupported;
4348
+ unparseable += conversion.unparseable;
4349
+ remainder += conversion.remainderAsOutput;
4350
+ }
4351
+ if (sessions === 0) throw new Error(t.fromGeminiCli.noFiles(target));
4352
+ console.error(t.fromGeminiCli.summary(sessions, lines.length, repeats));
4353
+ if (missingModel + unsupported + unparseable > 0) {
4354
+ console.error(t.fromGeminiCli.gaps(missingModel, unsupported, unparseable));
4355
+ }
4356
+ if (remainder > 0) console.error(t.fromGeminiCli.remainder(remainder));
4357
+ console.error(t.fromGeminiCli.caveat());
4358
+ if (lines.length === 0) throw new Error(t.fromGeminiCli.noUsage());
4359
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
4360
+ const text = lines.join('\n') + '\n';
4361
+ if (out !== undefined) {
4362
+ await writeFile(out, text, 'utf8');
4363
+ console.error(t.fromGeminiCli.written(out));
4364
+ } else console.log(text.trimEnd());
4365
+ }
4366
+
4134
4367
  async function commandFromOtel(args: Args, t: CliMessages): Promise<void> {
4135
4368
  const target = args.positional[0];
4136
4369
  if (target === undefined) throw new Error(t.fromOtel.noPath());
@@ -13734,6 +13967,9 @@ async function main(): Promise<void> {
13734
13967
  case 'from-codex':
13735
13968
  await commandFromCodex(args, t);
13736
13969
  break;
13970
+ case 'from-gemini-cli':
13971
+ await commandFromGeminiCli(args, t);
13972
+ break;
13737
13973
  case 'from-otel':
13738
13974
  await commandFromOtel(args, t);
13739
13975
  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' } }),