@trazum/cli 2.5.2 → 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.
Files changed (50) hide show
  1. package/README.md +4 -2
  2. package/dist/filter.d.ts.map +1 -1
  3. package/dist/filter.js +43 -7
  4. package/dist/filter.js.map +1 -1
  5. package/dist/i18n/en.d.ts.map +1 -1
  6. package/dist/i18n/en.js +66 -7
  7. package/dist/i18n/en.js.map +1 -1
  8. package/dist/i18n/es.d.ts.map +1 -1
  9. package/dist/i18n/es.js +67 -7
  10. package/dist/i18n/es.js.map +1 -1
  11. package/dist/i18n/types.d.ts +22 -1
  12. package/dist/i18n/types.d.ts.map +1 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +271 -20
  15. package/dist/index.js.map +1 -1
  16. package/dist/serve-import-schema.d.ts +34 -0
  17. package/dist/serve-import-schema.d.ts.map +1 -0
  18. package/dist/serve-import-schema.js +32 -0
  19. package/dist/serve-import-schema.js.map +1 -0
  20. package/dist/serve-import.d.ts +49 -0
  21. package/dist/serve-import.d.ts.map +1 -0
  22. package/dist/serve-import.js +52 -0
  23. package/dist/serve-import.js.map +1 -0
  24. package/dist/serve-schema.d.ts +70 -0
  25. package/dist/serve-schema.d.ts.map +1 -1
  26. package/dist/serve-schema.js +9 -0
  27. package/dist/serve-schema.js.map +1 -1
  28. package/dist/serve.d.ts.map +1 -1
  29. package/dist/serve.js +9 -2
  30. package/dist/serve.js.map +1 -1
  31. package/dist/task-files.d.ts +9 -0
  32. package/dist/task-files.d.ts.map +1 -0
  33. package/dist/task-files.js +136 -0
  34. package/dist/task-files.js.map +1 -0
  35. package/dist/task.d.ts +2 -0
  36. package/dist/task.d.ts.map +1 -0
  37. package/dist/task.js +137 -0
  38. package/dist/task.js.map +1 -0
  39. package/package.json +7 -4
  40. package/src/filter.ts +46 -10
  41. package/src/i18n/en.ts +72 -7
  42. package/src/i18n/es.ts +75 -7
  43. package/src/i18n/types.ts +23 -1
  44. package/src/index.ts +259 -16
  45. package/src/serve-import-schema.ts +32 -0
  46. package/src/serve-import.ts +60 -0
  47. package/src/serve-schema.ts +9 -0
  48. package/src/serve.ts +9 -2
  49. package/src/task-files.ts +114 -0
  50. package/src/task.ts +119 -0
package/src/i18n/types.ts CHANGED
@@ -636,6 +636,19 @@ export interface CliMessages {
636
636
  written(file: string): string;
637
637
  };
638
638
 
639
+ fromGeminiCli: {
640
+ noPath(): string;
641
+ notFound(path: string): string;
642
+ noFiles(path: string): string;
643
+ noUsage(): string;
644
+ summary(files: number, records: number, repeats: number): string;
645
+ gaps(missingModel: number, unsupported: number, unparseable: number): string;
646
+ /** Replies whose total exceeded the parts an older recorder kept; the remainder is priced as output. */
647
+ remainder(replies: number): string;
648
+ caveat(): string;
649
+ written(file: string): string;
650
+ };
651
+
639
652
  fromOtel: {
640
653
  noPath(): string;
641
654
  notFound(path: string): string;
@@ -744,7 +757,8 @@ export interface CliMessages {
744
757
  /** No path given and no Claude Code folder where Claude Code keeps one. */
745
758
  noPath(tried: string): string;
746
759
  /** No path given: the folders found and read instead, named. */
747
- defaultPath(dirs: string): string;
760
+ /** One line per agent folder found when no path was given. */
761
+ defaultPathFor(agent: string, dir: string): string;
748
762
  /** Claude Code sessions took their label from their project folder. */
749
763
  labelledByProject(files: number): string;
750
764
  /** The unclaimed files past the first few, counted rather than listed. */
@@ -757,6 +771,14 @@ export interface CliMessages {
757
771
  colProject(): string;
758
772
  colWorkload(): string;
759
773
  colModel(): string;
774
+ /** The By-agent table's first column, shown once more than one agent's sessions were read. */
775
+ colAgent(): string;
776
+ /** `--by day|week`: the first column, the rows past the screen, the undated remainder, the hint. */
777
+ colPeriod(unit: 'day' | 'week' | 'month'): string;
778
+ earlierPeriods(count: number, unit: 'day' | 'week' | 'month'): string;
779
+ periodsUndated(calls: number, usd: string, unit: 'day' | 'week' | 'month'): string;
780
+ periodHint(since: string, until: string, unit: 'day' | 'week' | 'month'): string;
781
+ badBy(value: string): string;
760
782
  colCalls(): string;
761
783
  colShare(): string;
762
784
  moreRows(count: number): string;
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,
@@ -324,6 +328,7 @@ interface Args {
324
328
  }
325
329
 
326
330
  const VALUE_FLAGS = new Set([
331
+ 'id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions',
327
332
  'recovery-dir',
328
333
  'answers',
329
334
  'label-by-cwd',
@@ -384,6 +389,8 @@ const VALUE_FLAGS = new Set([
384
389
  'what-if',
385
390
  'since',
386
391
  'until',
392
+ // `bill --by day|week|month`: the calendar unit the statement is split by.
393
+ 'by',
387
394
  'export',
388
395
  'limit',
389
396
  'locale',
@@ -737,7 +744,8 @@ function disabledRules(args: Args, config: TrazumConfig): RuleId[] | undefined {
737
744
  */
738
745
  const GLOBAL_FLAGS = ['help', 'h', 'version', 'v', 'locale', 'json', 'config', 'pricing', 'pricing-live', 'max-input'];
739
746
  const COMMAND_FLAGS: Record<string, string[]> = {
740
- filter: ['recovery-dir'],
747
+ task: ['id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions', 'out', 'o', 'json'],
748
+ filter: ['recovery-dir', 'stats'],
741
749
  optimize: [
742
750
  'level', 'model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch',
743
751
  'disable', 'llm', 'exact-tokens', 'diff', 'reorder', 'out', 'o',
@@ -767,6 +775,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
767
775
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
768
776
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
769
777
  'from-codex': ['label', 'out', 'o'],
778
+ 'from-gemini-cli': ['label', 'out', 'o'],
770
779
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
771
780
  'from-otel': ['label-from-service', 'out', 'o'],
772
781
  'from-litellm': ['out', 'o'],
@@ -774,7 +783,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
774
783
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
775
784
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
776
785
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
777
- 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'],
778
787
  'from-helicone': ['out', 'o'],
779
788
  'from-langsmith': ['out', 'o'],
780
789
  switch: ['to', 'migration-usd', 'cases'],
@@ -3431,6 +3440,7 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3431
3440
  type UsageSource =
3432
3441
  | 'claude-code'
3433
3442
  | 'codex'
3443
+ | 'gemini-cli'
3434
3444
  | 'otel'
3435
3445
  | 'litellm'
3436
3446
  | 'helicone'
@@ -3448,6 +3458,7 @@ type UsageSource =
3448
3458
  function usageSourcesOf(text: string): UsageSource[] {
3449
3459
  const claims: UsageSource[] = [];
3450
3460
  if (looksLikeCodexTranscript(text)) claims.push('codex');
3461
+ if (looksLikeGeminiCliSession(text)) claims.push('gemini-cli');
3451
3462
  if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3452
3463
  if (looksLikeOtel(text)) claims.push('otel');
3453
3464
  if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
@@ -3491,6 +3502,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3491
3502
  /* "What did this month cost" is the question a Claude Code folder of a
3492
3503
  year's sessions answers worst without a period. */
3493
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;
3494
3510
 
3495
3511
  /*
3496
3512
  No path is the most common first run, and it used to be a refusal: the
@@ -3500,10 +3516,16 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3500
3516
  */
3501
3517
  let targets = args.positional;
3502
3518
  if (targets.length === 0) {
3503
- 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);
3504
3526
  if (found.length === 0) throw new Error(t.bill.noPath(tried.join(', ')));
3505
- console.error(t.bill.defaultPath(found.join(', ')));
3506
- targets = found;
3527
+ for (const { agent, path } of found) console.error(t.bill.defaultPathFor(AGENT_NAMES[agent], path));
3528
+ targets = found.map(({ path }) => path);
3507
3529
  }
3508
3530
 
3509
3531
  /*
@@ -3557,6 +3579,10 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3557
3579
  /* Claude Code transcripts read: their money is an API-rate equivalent. */
3558
3580
  let claudeCodeFiles = 0;
3559
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[]>();
3560
3586
  const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
3561
3587
  const lines: string[] = [];
3562
3588
  let sources = 0;
@@ -3604,6 +3630,18 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3604
3630
  if (leftOut > 0) console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
3605
3631
  break;
3606
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
+ }
3607
3645
  case 'claude-code': {
3608
3646
  claudeCodeFiles += 1;
3609
3647
  const project =
@@ -3664,6 +3702,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3664
3702
  }
3665
3703
  }
3666
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
+ }
3667
3710
  sources += 1;
3668
3711
  const count = shape === 'usage-log' ? null : records.length;
3669
3712
  if (perFile) {
@@ -3681,6 +3724,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3681
3724
  for (const file of named) console.error(t.bill.unknown(file));
3682
3725
  if (unclaimed.length > named.length) console.error(t.bill.unknownMore(unclaimed.length - named.length));
3683
3726
  if (labelledByProject > 0) console.error(t.bill.labelledByProject(labelledByProject));
3727
+ if (geminiRemainder > 0) console.error(t.fromGeminiCli.remainder(geminiRemainder));
3684
3728
 
3685
3729
  if (sources === 0) throw new Error(t.bill.nothingRead());
3686
3730
 
@@ -3717,8 +3761,28 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3717
3761
  }
3718
3762
  console.error(t.bill.sources(sources, files.length));
3719
3763
  printReceiptSummary(document, t);
3720
- if (statement) printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3721
- 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);
3722
3786
 
3723
3787
  /*
3724
3788
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3774,6 +3838,100 @@ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: st
3774
3838
  return { found, tried };
3775
3839
  }
3776
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
+
3777
3935
  /**
3778
3936
  * The bill as a person reads it: the total, by project, by model, and what
3779
3937
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
@@ -3785,6 +3943,8 @@ function printBillStatement(
3785
3943
  t: CliMessages,
3786
3944
  window?: { since: string; until: string },
3787
3945
  apiEquivalent = false,
3946
+ byAgent: { name: string; calls: number; usd: number }[] = [],
3947
+ by?: BillPeriodUnit,
3788
3948
  ): void {
3789
3949
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
3790
3950
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
@@ -3821,6 +3981,12 @@ function printBillStatement(
3821
3981
  */
3822
3982
  if (apiEquivalent) console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3823
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
+
3824
3990
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3825
3991
  if (labelled.length > 0) {
3826
3992
  console.log();
@@ -3847,20 +4013,33 @@ function printBillStatement(
3847
4013
  report's own days, oldest first, newest kept when there are many; shown
3848
4014
  only once the bill spans two calendar months, since one month is the total.
3849
4015
  */
3850
- const { months, undated } = spendByMonth(report);
3851
- if (months.length >= 2) {
3852
- 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 }) => {
3853
4026
  const share = total > 0 ? usd / total : 0;
3854
- return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
4027
+ return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3855
4028
  });
3856
- 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
+ }
3857
4033
  console.log();
3858
- 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);
3859
4035
  if (undated.calls > 0) {
3860
- 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, ' ')}`));
3861
4040
  }
3862
- const newest = months[months.length - 1]!;
3863
- 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)}`));
3864
4043
  }
3865
4044
 
3866
4045
  console.log();
@@ -4129,6 +4308,62 @@ async function commandFromCodex(args: Args, t: CliMessages): Promise<void> {
4129
4308
  } else console.log(text.trimEnd());
4130
4309
  }
4131
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
+
4132
4367
  async function commandFromOtel(args: Args, t: CliMessages): Promise<void> {
4133
4368
  const target = args.positional[0];
4134
4369
  if (target === undefined) throw new Error(t.fromOtel.noPath());
@@ -13507,6 +13742,11 @@ function printRank(
13507
13742
 
13508
13743
  async function main(): Promise<void> {
13509
13744
  const argv = process.argv.slice(2);
13745
+ if (argv[0] === 'task') {
13746
+ const { runTask } = await import('./task.js');
13747
+ await runTask(argv.slice(1));
13748
+ return;
13749
+ }
13510
13750
  // The stdin display filter has its own small grammar and no project config.
13511
13751
  if (argv[0] === 'filter') {
13512
13752
  const { runFilter } = await import('./filter.js');
@@ -13727,6 +13967,9 @@ async function main(): Promise<void> {
13727
13967
  case 'from-codex':
13728
13968
  await commandFromCodex(args, t);
13729
13969
  break;
13970
+ case 'from-gemini-cli':
13971
+ await commandFromGeminiCli(args, t);
13972
+ break;
13730
13973
  case 'from-otel':
13731
13974
  await commandFromOtel(args, t);
13732
13975
  break;
@@ -0,0 +1,32 @@
1
+ const object = (properties: Record<string, unknown>) => ({
2
+ type: 'object', properties, required: Object.keys(properties), additionalProperties: false,
3
+ });
4
+ const count = { type: 'integer', minimum: 0 };
5
+ const counters = (names: string[]) => Object.fromEntries(names.map((name) => [name, count]));
6
+ const common = {
7
+ schemaVersion: { const: 1 }, log: { type: 'string' }, records: count,
8
+ evidence: object({ billingMode: { const: 'unknown' }, valuation: { const: 'api-equivalent' }, completeness: { const: 'not-established' } }),
9
+ limitations: { type: 'array', items: { type: 'string' } },
10
+ };
11
+
12
+ export const IMPORT_SCHEMAS = {
13
+ UsageImportRequest: {
14
+ type: 'object', required: ['format', 'text'], additionalProperties: false,
15
+ properties: {
16
+ format: { type: 'string', enum: ['claude-code', 'codex', 'gemini-cli'] },
17
+ text: { type: 'string', minLength: 1, description: 'Non-blank transcript JSONL contents, never a path. No automatic format detection or shared deduplication state.' },
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
+ },
20
+ },
21
+ UsageImportAnswer: {
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
+ oneOf: [
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'])) }),
26
+ object({ ...common, format: { const: 'claude-code' }, diagnostics: object({
27
+ ...counters(['collapsed', 'noRequestId', 'otherLines', 'unparseable', 'assistantWithoutUsage', 'streamed', 'disagreements', 'synthetic']),
28
+ resume: object({ line: count, records: count }),
29
+ }) }),
30
+ ],
31
+ },
32
+ };
@@ -0,0 +1,60 @@
1
+ import { claudeCodeRecords, codexRecords, geminiCliRecords } from '@trazum/core';
2
+
3
+ /** Bound the complete serialized answer, including JSON escaping and repeated labels. */
4
+ export const MAX_IMPORT_RESPONSE_BYTES = 1_000_000;
5
+
6
+ interface ImportPayload {
7
+ format: 'claude-code' | 'codex' | 'gemini-cli';
8
+ text: string;
9
+ label?: string;
10
+ }
11
+
12
+ export function validateImportPayload(value: unknown): asserts value is ImportPayload {
13
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
14
+ throw new Error('The body must be a JSON object.');
15
+ }
16
+ const payload = value as Record<string, unknown>;
17
+ if (Object.keys(payload).some((key) => !['format', 'text', 'label'].includes(key))) {
18
+ throw new Error('Unknown properties are not accepted for usage imports.');
19
+ }
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
+ }
23
+ if (typeof payload.text !== 'string' || payload.text.trim() === '') {
24
+ throw new Error('text must be non-empty transcript contents, not a file path.');
25
+ }
26
+ if (payload.label !== undefined && (typeof payload.label !== 'string' ||
27
+ payload.label.trim() === '' || payload.label.length > 200)) {
28
+ throw new Error('label must be non-empty text of at most 200 characters.');
29
+ }
30
+ }
31
+
32
+ /** Explicit text only: no filesystem, measurement lookup or provider access. */
33
+ export function importUsage(payload: ImportPayload) {
34
+ const options = payload.label === undefined ? {} : { label: payload.label };
35
+ const conversion = payload.format === 'codex'
36
+ ? codexRecords(payload.text, options)
37
+ : payload.format === 'gemini-cli'
38
+ ? geminiCliRecords(payload.text, options)
39
+ : claudeCodeRecords(payload.text, options);
40
+ const { records, ...diagnostics } = conversion;
41
+ const result = {
42
+ schemaVersion: 1 as const,
43
+ format: payload.format,
44
+ log: records.map((record) => JSON.stringify(record)).join('\n'),
45
+ records: records.length,
46
+ diagnostics,
47
+ evidence: { billingMode: 'unknown', valuation: 'api-equivalent', completeness: 'not-established' },
48
+ limitations: [
49
+ 'Conversion diagnostics describe the supplied text only; missing source events and missing files cannot be detected.',
50
+ 'Usage priced downstream is API-equivalent, not a subscription invoice or proof of realized savings.',
51
+ 'No deduplication state is shared between calls. Do not concatenate overlapping imports.',
52
+ 'Session identifiers are retained. Prompt, tool, cwd and path content is not copied; labels are caller supplied.',
53
+ 'Empty output means no convertible records, not zero usage or zero cost. Preserve these diagnostics alongside downstream reports.',
54
+ ],
55
+ };
56
+ if (Buffer.byteLength(JSON.stringify(result), 'utf8') > MAX_IMPORT_RESPONSE_BYTES) {
57
+ throw new Error(`Normalized import response exceeds ${MAX_IMPORT_RESPONSE_BYTES} UTF-8 bytes; use a smaller complete source or a shorter label.`);
58
+ }
59
+ return result;
60
+ }
@@ -1,4 +1,5 @@
1
1
  import { SAVINGS_SCHEMAS } from './serve-savings-schema.js';
2
+ import { IMPORT_SCHEMAS } from './serve-import-schema.js';
2
3
  /** Public contract for local, read-only cost and savings analysis. No provider calls occur here. */
3
4
  const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` });
4
5
  const nullable = (schema: object) => ({ anyOf: [schema, { type: 'null' }] });
@@ -47,6 +48,7 @@ export function validateCostPayload(value: unknown): asserts value is Record<str
47
48
 
48
49
  const schemas = {
49
50
  ...SAVINGS_SCHEMAS,
51
+ ...IMPORT_SCHEMAS,
50
52
  CostRequest: COST_REQUEST_SCHEMA,
51
53
  HarnessCapabilities: object({
52
54
  schemaVersion: { const: 1 },
@@ -60,6 +62,7 @@ const schemas = {
60
62
  oneOf: [
61
63
  object({ command: { const: 'from-claude-code' }, format: { const: 'claude-code-transcript-jsonl' } }),
62
64
  object({ command: { const: 'from-codex' }, format: { const: 'codex-session-jsonl' } }),
65
+ object({ command: { const: 'from-gemini-cli' }, format: { const: 'gemini-cli-session-jsonl' } }),
63
66
  ],
64
67
  }),
65
68
  normalizedUsage: object({ command: { const: 'bill' }, format: { const: 'trazum-usage-jsonl' } }),
@@ -120,6 +123,12 @@ export const SERVE_OPENAPI = {
120
123
  info: { title: 'Trazum local cost and savings API', version: '1.0.0', description: 'Loopback-only read-only estimates, policy judgements and savings analysis. No authentication or CORS. Does not reserve budget, send model calls, or enforce an upstream decision. Measured positions are snapshots supplied by the CLI; inspect their windows.' },
121
124
  servers: [{ url: 'http://127.0.0.1:7317', description: 'Default TCP listener. Substitute the chosen --port, or use the Unix socket transport.' }],
122
125
  paths: {
126
+ '/usage/import': { post: {
127
+ operationId: 'importUsage', summary: 'Normalize explicit Claude Code or Codex transcript text',
128
+ description: 'Read-only conversion with explicit source format. No files, provider calls or measured-budget lookup. Prompts, tool content and cwd are excluded; session identifiers remain. Whole request and complete response each have a 1,000,000-byte UTF-8 limit, including JSON escaping. Unknown properties and blank inputs are refused. Conversion success does not certify source completeness or subscription billing.',
129
+ requestBody: { required: true, content: { 'application/json': { schema: ref('UsageImportRequest') } } },
130
+ responses: { '200': response('UsageImportAnswer', 'Normalized JSONL and conversion diagnostics, including zero-record imports.'), '400': response('Error', 'Malformed request, unsupported format, or input/output exceeding its byte limit.') },
131
+ } },
123
132
  '/capabilities': { get: { operationId: 'getCapabilities', summary: 'Discover native import formats and Trazum access channels', responses: { '200': response('HarnessCapabilities', 'Static metadata; no environment, filesystem, session or network discovery.') } } },
124
133
  '/health': { get: { operationId: 'getHealth', summary: 'Check the local process', responses: { '200': response('Health', 'Process is available.') } } },
125
134
  '/openapi.json': { get: { operationId: 'getOpenApi', summary: 'Read this OpenAPI document', responses: { '200': { description: 'OpenAPI 3.1 document.', content: { 'application/json': { schema: { type: 'object', required: ['openapi', 'info', 'paths', 'components'] } } } } } } },
package/src/serve.ts CHANGED
@@ -24,6 +24,7 @@
24
24
  */
25
25
 
26
26
  import { createServer } from 'node:http';
27
+ import { importUsage, validateImportPayload } from './serve-import.js';
27
28
  import { planSavings, verifySavings, validateSavingsPayload } from './serve-savings.js';
28
29
  import { SERVE_OPENAPI, validateCostPayload } from './serve-schema.js';
29
30
  import type { IncomingMessage, Server, ServerResponse } from 'node:http';
@@ -111,10 +112,11 @@ export function buildServer(context: ServeContext): Server {
111
112
  }
112
113
 
113
114
  const savings = url.pathname === '/savings/plan' || url.pathname === '/savings/verify';
114
- if (request.method !== 'POST' || (url.pathname !== '/cost' && !savings)) {
115
+ const importing = url.pathname === '/usage/import';
116
+ if (request.method !== 'POST' || (url.pathname !== '/cost' && !savings && !importing)) {
115
117
  send(response, 404, {
116
118
  error: 'not-found',
117
- detail: 'POST /cost, POST /savings/plan, POST /savings/verify, GET /health, GET /capabilities, or GET /openapi.json.',
119
+ detail: 'POST /cost, POST /usage/import, POST /savings/plan, POST /savings/verify, GET /health, GET /capabilities, or GET /openapi.json.',
118
120
  });
119
121
  return;
120
122
  }
@@ -123,6 +125,11 @@ export function buildServer(context: ServeContext): Server {
123
125
  try {
124
126
  const raw = await readBody(request);
125
127
  const parsed: unknown = raw.trim() === '' ? {} : JSON.parse(raw);
128
+ if (importing) {
129
+ validateImportPayload(parsed);
130
+ send(response, 200, importUsage(parsed));
131
+ return;
132
+ }
126
133
  if (savings) {
127
134
  if (url.pathname === '/savings/verify') {
128
135
  validateSavingsPayload(parsed, true);