@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/dist/index.js CHANGED
@@ -6,8 +6,9 @@ import { cpus, homedir, tmpdir } from 'node:os';
6
6
  import { createInterface } from 'node:readline/promises';
7
7
  import { dirname, join, resolve as resolvePath } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
- import { gunzipSync } from 'node:zlib';
10
- import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, evaluateWatch, firedKey, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, bandGoverns, countTokensAnthropic, DEFAULT_USAGE, budgetPositions, conform, BREAK_EVEN_BAND, allocate, annualRecord, replayCommitment, coversTheTerm, runExperiment, qualityGate, semanticPassCost, verifySemanticProposals, SEMANTIC_SYSTEM_PROMPT, ladderPosition, validateLadder, outcomeReport, rankPerOutcome, FAILURE_POLICIES, detectFromSource, matchLocale, parsePlanDocument, waiverDay, waiverHistory, proposeInit, MIN_RATE_DAYS, parseConfig, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, rollUp, heartbeats, ruleYield, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, receiptFrom, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, matchGlob, MAX_INPUT_CHARS, moneyIsComparable, mostSpecificMatch, assemble, interview, nearestName, slot, SLOT_IDS, optimize, parseBaseline, PHRASE_LANGUAGES, detectTextLanguage, dictionaryStanding, languagesWithStanding, indexUsage, parseUsageLine, plannedCalls, claudeCodeRecords, codexRecords, looksLikeCodexTranscript, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, looksLikeAnthropicUsage, looksLikeClaudeCodeTranscript, looksLikeHelicone, looksLikeLangsmith, looksLikeLiteLlm, looksLikeOpenaiUsage, looksLikeOpenrouterActivity, looksLikeOtel, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, spendByMonth, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
9
+ import { createGunzip, gunzipSync } from 'node:zlib';
10
+ import { Readable } from 'node:stream';
11
+ import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, evaluateWatch, firedKey, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, bandGoverns, countTokensAnthropic, DEFAULT_USAGE, budgetPositions, conform, BREAK_EVEN_BAND, allocate, annualRecord, replayCommitment, coversTheTerm, runExperiment, qualityGate, semanticPassCost, verifySemanticProposals, SEMANTIC_SYSTEM_PROMPT, ladderPosition, validateLadder, outcomeReport, rankPerOutcome, FAILURE_POLICIES, detectFromSource, matchLocale, parsePlanDocument, waiverDay, waiverHistory, proposeInit, MIN_RATE_DAYS, parseConfig, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, rollUp, heartbeats, ruleYield, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, receiptFrom, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, matchGlob, MAX_INPUT_CHARS, moneyIsComparable, mostSpecificMatch, assemble, interview, nearestName, slot, SLOT_IDS, optimize, parseBaseline, PHRASE_LANGUAGES, detectTextLanguage, dictionaryStanding, languagesWithStanding, indexUsage, parseUsageLine, plannedCalls, claudeCodeRecords, codexRecords, looksLikeCodexTranscript, geminiCliRecords, looksLikeGeminiCliSession, slimUsageLine, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, looksLikeAnthropicUsage, looksLikeClaudeCodeTranscript, looksLikeHelicone, looksLikeLangsmith, looksLikeLiteLlm, looksLikeOpenaiUsage, looksLikeOpenrouterActivity, looksLikeOtel, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, spendByPeriod, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
11
12
  import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
12
13
  import { OPTIONAL_COUNTERS } from './optional-counters.js';
13
14
  import { dayOf, formatGap, median, spanDays } from './time.js';
@@ -95,6 +96,8 @@ const VALUE_FLAGS = new Set([
95
96
  'what-if',
96
97
  'since',
97
98
  'until',
99
+ // `bill --by day|week|month`: the calendar unit the statement is split by.
100
+ 'by',
98
101
  'export',
99
102
  'limit',
100
103
  'locale',
@@ -287,16 +290,99 @@ async function usageIndexFrom(args, pricing, t) {
287
290
  .filter((record) => record !== null);
288
291
  return indexUsage(records, { catalogue: pricing });
289
292
  }
293
+ /*
294
+ Past this many bytes a usage file is read line by line, its message text set
295
+ aside, rather than held as one string. JavaScript cannot hold a string much
296
+ past 512 MiB, and an agent session that read large files or ran chatty
297
+ commands outgrows that: reading one whole failed with the runtime's
298
+ "Invalid string length" and took the rest of the bill with it. The
299
+ environment variable exists so the tests can cross the line without writing
300
+ a quarter of a gigabyte.
301
+ */
302
+ const WHOLE_READ_MAX_BYTES = (() => {
303
+ const fromEnv = Number(process.env.TRAZUM_WHOLE_READ_MAX_BYTES);
304
+ return Number.isSafeInteger(fromEnv) && fromEnv > 0 ? fromEnv : 256 * 1024 * 1024;
305
+ })();
306
+ /*
307
+ What the lines kept may add up to: under the runtime's own string ceiling
308
+ (just short of 512 MiB). Its own variable, for the same reason as the one
309
+ above: so the refusal can be tested without filling a disk.
310
+ */
311
+ const SLIMMED_MAX_CHARS = (() => {
312
+ const fromEnv = Number(process.env.TRAZUM_SLIMMED_MAX_CHARS);
313
+ return Number.isSafeInteger(fromEnv) && fromEnv > 0 ? fromEnv : 500 * 1024 * 1024;
314
+ })();
315
+ const megabytesOf = (bytes) => Math.round(bytes / 1_000_000);
290
316
  async function readUsageLog(file, t) {
291
- if (!file.endsWith('.gz'))
292
- return readFile(file, 'utf8');
293
- const compressed = await readFile(file);
317
+ /*
318
+ One open file, measured and read through the same handle, so the size
319
+ that chose the path is the size of what is read: a stat by name and a
320
+ read by name could see two different files.
321
+ */
322
+ const handle = await open(file, 'r');
294
323
  try {
295
- return gunzipSync(compressed).toString('utf8');
324
+ return await readUsageHandle(handle, file, t);
325
+ }
326
+ finally {
327
+ await handle.close();
328
+ }
329
+ }
330
+ async function readUsageHandle(handle, file, t) {
331
+ const size = (await handle.stat()).size;
332
+ if (!file.endsWith('.gz')) {
333
+ if (size <= WHOLE_READ_MAX_BYTES)
334
+ return handle.readFile('utf8');
335
+ return readInParts(handle.createReadStream({ autoClose: false }), file, size, t);
336
+ }
337
+ const compressed = await handle.readFile();
338
+ let inflated;
339
+ try {
340
+ // Bounded, so a file that inflates past the line is streamed rather than refused.
341
+ inflated = gunzipSync(compressed, { maxOutputLength: WHOLE_READ_MAX_BYTES });
296
342
  }
297
343
  catch (error) {
344
+ if (error instanceof RangeError && error.code === 'ERR_BUFFER_TOO_LARGE') {
345
+ const gunzip = createGunzip();
346
+ let failure;
347
+ gunzip.on('error', (cause) => { failure = cause; });
348
+ Readable.from([compressed]).pipe(gunzip);
349
+ const text = await readInParts(gunzip, file, size, t);
350
+ if (failure !== undefined)
351
+ throw new Error(t.profile.badGzip(file, failure.message));
352
+ return text;
353
+ }
298
354
  throw new Error(t.profile.badGzip(file, error instanceof Error ? error.message : String(error)));
299
355
  }
356
+ return inflated.toString('utf8');
357
+ }
358
+ /**
359
+ * A file too large to hold whole, line by line, each line with its long
360
+ * strings set aside by `slimUsageLine`: the converters read the same short
361
+ * fields from it that they would have read from the whole file.
362
+ */
363
+ async function readInParts(input, file, size, t) {
364
+ const kept = [];
365
+ let held = 0;
366
+ let slimmed = 0;
367
+ try {
368
+ for await (const line of createInterface({ input, crlfDelay: Infinity })) {
369
+ const next = slimUsageLine(line);
370
+ if (next !== line)
371
+ slimmed += 1;
372
+ held += next.length + 1;
373
+ if (held > SLIMMED_MAX_CHARS)
374
+ throw new Error(t.profile.tooLargeToRead(file, megabytesOf(size)));
375
+ kept.push(next);
376
+ }
377
+ }
378
+ catch (error) {
379
+ // A single line past the runtime's ceiling fails inside the line reader.
380
+ if (error instanceof RangeError)
381
+ throw new Error(t.profile.tooLargeToRead(file, megabytesOf(size)));
382
+ throw error;
383
+ }
384
+ console.error(t.profile.readInParts(file, megabytesOf(size), slimmed));
385
+ return kept.join('\n');
300
386
  }
301
387
  function usageFrom(args, config, t, detected) {
302
388
  const fromConfig = config.usage ?? {};
@@ -430,6 +516,7 @@ const COMMAND_FLAGS = {
430
516
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
431
517
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
432
518
  'from-codex': ['label', 'out', 'o'],
519
+ 'from-gemini-cli': ['label', 'out', 'o'],
433
520
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
434
521
  'from-otel': ['label-from-service', 'out', 'o'],
435
522
  'from-litellm': ['out', 'o'],
@@ -437,7 +524,7 @@ const COMMAND_FLAGS = {
437
524
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
438
525
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
439
526
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
440
- 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'],
527
+ 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'],
441
528
  'from-helicone': ['out', 'o'],
442
529
  'from-langsmith': ['out', 'o'],
443
530
  switch: ['to', 'migration-usd', 'cases'],
@@ -2750,6 +2837,8 @@ function usageSourcesOf(text) {
2750
2837
  const claims = [];
2751
2838
  if (looksLikeCodexTranscript(text))
2752
2839
  claims.push('codex');
2840
+ if (looksLikeGeminiCliSession(text))
2841
+ claims.push('gemini-cli');
2753
2842
  if (looksLikeClaudeCodeTranscript(text))
2754
2843
  claims.push('claude-code');
2755
2844
  if (looksLikeOtel(text))
@@ -2802,6 +2891,11 @@ async function commandBill(args, pricing, t) {
2802
2891
  /* "What did this month cost" is the question a Claude Code folder of a
2803
2892
  year's sessions answers worst without a period. */
2804
2893
  const period = billingPeriod(args, t);
2894
+ const byFlag = stringFlag(args, 'by');
2895
+ if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
2896
+ throw new Error(t.bill.badBy(byFlag));
2897
+ }
2898
+ const by = byFlag;
2805
2899
  /*
2806
2900
  No path is the most common first run, and it used to be a refusal: the
2807
2901
  person had to know where Claude Code keeps its sessions before the one
@@ -2810,11 +2904,18 @@ async function commandBill(args, pricing, t) {
2810
2904
  */
2811
2905
  let targets = args.positional;
2812
2906
  if (targets.length === 0) {
2813
- const { found, tried } = await claudeProjectFolders(process.env);
2907
+ /*
2908
+ Every coding agent whose sessions this reads, not only Claude Code:
2909
+ somebody who runs Codex or Gemini CLI as well wants one bill, and asking
2910
+ them to know three folder layouts is the friction this default removes.
2911
+ Each folder found is named on its own line, so nothing is read silently.
2912
+ */
2913
+ const { found, tried } = await agentSessionFolders(process.env);
2814
2914
  if (found.length === 0)
2815
2915
  throw new Error(t.bill.noPath(tried.join(', ')));
2816
- console.error(t.bill.defaultPath(found.join(', ')));
2817
- targets = found;
2916
+ for (const { agent, path } of found)
2917
+ console.error(t.bill.defaultPathFor(AGENT_NAMES[agent], path));
2918
+ targets = found.map(({ path }) => path);
2818
2919
  }
2819
2920
  /*
2820
2921
  Every path given, files and directories alike, because a shell glob hands
@@ -2872,6 +2973,10 @@ async function commandBill(args, pricing, t) {
2872
2973
  /* Claude Code transcripts read: their money is an API-rate equivalent. */
2873
2974
  let claudeCodeFiles = 0;
2874
2975
  let codexFiles = 0;
2976
+ let geminiCliFiles = 0;
2977
+ let geminiRemainder = 0;
2978
+ /* Each agent's own records, so a bill that read more than one can say which spent what. */
2979
+ const agentLines = new Map();
2875
2980
  const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
2876
2981
  const lines = [];
2877
2982
  let sources = 0;
@@ -2919,6 +3024,19 @@ async function commandBill(args, pricing, t) {
2919
3024
  console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
2920
3025
  break;
2921
3026
  }
3027
+ case 'gemini-cli': {
3028
+ geminiCliFiles += 1;
3029
+ const project = label === undefined && labelFromProject && walked.has(file) ? await geminiProjectLabelFor(file) : undefined;
3030
+ if (project !== undefined && project !== '')
3031
+ labelledByProject += 1;
3032
+ const c = geminiCliRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
3033
+ records = c.records;
3034
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
3035
+ geminiRemainder += c.remainderAsOutput;
3036
+ if (leftOut > 0)
3037
+ console.error(t.fromGeminiCli.gaps(c.missingModel, c.unsupported, c.unparseable));
3038
+ break;
3039
+ }
2922
3040
  case 'claude-code': {
2923
3041
  claudeCodeFiles += 1;
2924
3042
  const project = label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
@@ -2982,6 +3100,12 @@ async function commandBill(args, pricing, t) {
2982
3100
  }
2983
3101
  for (const record of records)
2984
3102
  lines.push(JSON.stringify(record));
3103
+ if (shape === 'claude-code' || shape === 'codex' || shape === 'gemini-cli') {
3104
+ const own = agentLines.get(shape) ?? [];
3105
+ for (const record of records)
3106
+ own.push(JSON.stringify(record));
3107
+ agentLines.set(shape, own);
3108
+ }
2985
3109
  sources += 1;
2986
3110
  const count = shape === 'usage-log' ? null : records.length;
2987
3111
  if (perFile) {
@@ -3005,6 +3129,8 @@ async function commandBill(args, pricing, t) {
3005
3129
  console.error(t.bill.unknownMore(unclaimed.length - named.length));
3006
3130
  if (labelledByProject > 0)
3007
3131
  console.error(t.bill.labelledByProject(labelledByProject));
3132
+ if (geminiRemainder > 0)
3133
+ console.error(t.fromGeminiCli.remainder(geminiRemainder));
3008
3134
  if (sources === 0)
3009
3135
  throw new Error(t.bill.nothingRead());
3010
3136
  const text = lines.join('\n');
@@ -3040,9 +3166,28 @@ async function commandBill(args, pricing, t) {
3040
3166
  }
3041
3167
  console.error(t.bill.sources(sources, files.length));
3042
3168
  printReceiptSummary(document, t);
3043
- if (statement)
3044
- printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3045
- await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles + codexFiles > 0);
3169
+ const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
3170
+ /*
3171
+ By agent, once more than one agent's sessions were read: each agent's own
3172
+ records priced through the same catalogue and window as the whole, so the
3173
+ rows are the total split, not a second estimate beside it.
3174
+ */
3175
+ const byAgent = [...agentLines.entries()]
3176
+ .filter(([, own]) => own.length > 0)
3177
+ .map(([agent, own]) => {
3178
+ const part = profileUsage(own.join('\n'), {
3179
+ catalogue: pricing,
3180
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3181
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3182
+ });
3183
+ return { name: AGENT_NAMES[agent], calls: part.total.calls, usd: part.total.totalUsd };
3184
+ })
3185
+ .filter((row) => row.calls > 0)
3186
+ .sort((a, b) => b.usd - a.usd);
3187
+ if (statement) {
3188
+ printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by);
3189
+ }
3190
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, agentSessions);
3046
3191
  /*
3047
3192
  A slug with a slash in it is how OpenRouter names a model, and the bundled
3048
3193
  catalogue does not carry those: the live overlay does. Said only when the
@@ -3097,12 +3242,105 @@ async function claudeProjectFolders(env) {
3097
3242
  }
3098
3243
  return { found, tried };
3099
3244
  }
3245
+ const AGENT_NAMES = Object.freeze({
3246
+ 'claude-code': 'Claude Code',
3247
+ codex: 'Codex',
3248
+ 'gemini-cli': 'Gemini CLI',
3249
+ });
3250
+ /**
3251
+ * Where each agent keeps its sessions, from each agent's own source.
3252
+ *
3253
+ * - Claude Code: `claudeProjectFolders`, unchanged.
3254
+ * - Codex: `$CODEX_HOME` (default `~/.codex`), its `sessions` and
3255
+ * `archived_sessions`; an archived session was billed when it ran.
3256
+ * - Gemini CLI: `$GEMINI_CLI_HOME` (default the home directory), then
3257
+ * `.gemini/tmp/<project>/chats`, and `~/.cache/.gemini/tmp` where the macOS
3258
+ * sandbox moves it. Only the `chats` folders: the rest of `tmp` is shell
3259
+ * history and checkpoints, not usage.
3260
+ *
3261
+ * Every folder that exists is returned once; `tried` is every candidate, for
3262
+ * the refusal to name when there is none.
3263
+ */
3264
+ async function agentSessionFolders(env) {
3265
+ const claude = await claudeProjectFolders(env);
3266
+ const found = claude.found.map((path) => ({ agent: 'claude-code', path }));
3267
+ const tried = [...claude.tried];
3268
+ const seen = new Set(claude.found.map((path) => resolvePath(path)));
3269
+ const isDirectory = async (path) => {
3270
+ try {
3271
+ return (await stat(path)).isDirectory();
3272
+ }
3273
+ catch {
3274
+ return false;
3275
+ }
3276
+ };
3277
+ const home = homedir();
3278
+ const codexHome = env.CODEX_HOME ? env.CODEX_HOME : join(home, '.codex');
3279
+ for (const candidate of [join(codexHome, 'sessions'), join(codexHome, 'archived_sessions')]) {
3280
+ tried.push(candidate);
3281
+ if (!seen.has(resolvePath(candidate)) && (await isDirectory(candidate))) {
3282
+ seen.add(resolvePath(candidate));
3283
+ found.push({ agent: 'codex', path: candidate });
3284
+ }
3285
+ }
3286
+ const geminiHome = env.GEMINI_CLI_HOME ? env.GEMINI_CLI_HOME : home;
3287
+ for (const tmp of [join(geminiHome, '.gemini', 'tmp'), join(geminiHome, '.cache', '.gemini', 'tmp')]) {
3288
+ tried.push(tmp);
3289
+ if (!(await isDirectory(tmp)))
3290
+ continue;
3291
+ let projects = [];
3292
+ try {
3293
+ projects = (await readdir(tmp, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
3294
+ }
3295
+ catch {
3296
+ continue;
3297
+ }
3298
+ for (const project of projects) {
3299
+ const chats = join(tmp, project, 'chats');
3300
+ if (!seen.has(resolvePath(chats)) && (await isDirectory(chats))) {
3301
+ seen.add(resolvePath(chats));
3302
+ found.push({ agent: 'gemini-cli', path: chats });
3303
+ }
3304
+ }
3305
+ }
3306
+ return { found, tried };
3307
+ }
3308
+ /**
3309
+ * The project a Gemini CLI session belongs to.
3310
+ *
3311
+ * Gemini CLI keeps a folder per project under `tmp`, named by a short slug in
3312
+ * current versions (with the real working directory in `.project_root`
3313
+ * beside it) and by a SHA-256 of the path in older ones. The working
3314
+ * directory's last segment is the name a person recognises; a bare hash is
3315
+ * no name at all, so it labels nothing rather than putting 64 hex digits on
3316
+ * the bill.
3317
+ */
3318
+ async function geminiProjectLabelFor(file) {
3319
+ const parts = resolvePath(file).split('/');
3320
+ const at = parts.lastIndexOf('chats');
3321
+ if (at < 1)
3322
+ return undefined;
3323
+ const projectDir = parts.slice(0, at).join('/');
3324
+ try {
3325
+ const root = (await readFile(join(projectDir, '.project_root'), 'utf8')).trim();
3326
+ const name = root.replace(/[\\/]+$/, '').split(/[\\/]/).pop();
3327
+ if (name !== undefined && name !== '')
3328
+ return name;
3329
+ }
3330
+ catch {
3331
+ // Older versions keep no .project_root: fall back to the folder's name.
3332
+ }
3333
+ const folder = parts[at - 1];
3334
+ if (folder === undefined || folder === '' || /^[0-9a-f]{64}$/i.test(folder))
3335
+ return undefined;
3336
+ return folder;
3337
+ }
3100
3338
  /**
3101
3339
  * The bill as a person reads it: the total, by project, by model, and what
3102
3340
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3103
3341
  * here is computed that the receipt does not carry.
3104
3342
  */
3105
- function printBillStatement(report, byProject, t, window, apiEquivalent = false) {
3343
+ function printBillStatement(report, byProject, t, window, apiEquivalent = false, byAgent = [], by) {
3106
3344
  const n = (value) => value.toLocaleString(t.numberLocale);
3107
3345
  const pct = (share) => `${(share * 100).toFixed(1)}%`;
3108
3346
  const total = report.total.totalUsd;
@@ -3139,6 +3377,12 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false)
3139
3377
  */
3140
3378
  if (apiEquivalent)
3141
3379
  console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3380
+ // Which agent spent what, first: it is the split a person running more than one asks for.
3381
+ if (byAgent.length > 1) {
3382
+ console.log();
3383
+ for (const line of table(columns(t.bill.colAgent()), rowsOf(byAgent)))
3384
+ console.log(line);
3385
+ }
3142
3386
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3143
3387
  if (labelled.length > 0) {
3144
3388
  console.log();
@@ -3164,22 +3408,34 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false)
3164
3408
  report's own days, oldest first, newest kept when there are many; shown
3165
3409
  only once the bill spans two calendar months, since one month is the total.
3166
3410
  */
3167
- const { months, undated } = spendByMonth(report);
3168
- if (months.length >= 2) {
3169
- const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
3411
+ /*
3412
+ `--by day` and `--by week` ask the same question at a finer grain, and
3413
+ are printed whenever asked, one period or many. The newest are kept when
3414
+ there are more than a screen holds: a month of days, twelve weeks.
3415
+ */
3416
+ const unit = by ?? 'month';
3417
+ const { periods, undated } = spendByPeriod(report, unit);
3418
+ if (periods.length >= (by === undefined ? 2 : 1)) {
3419
+ const keep = unit === 'day' ? 31 : LIMIT;
3420
+ const shown = periods.slice(-keep).map(({ period, calls, usd }) => {
3170
3421
  const share = total > 0 ? usd / total : 0;
3171
- return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3422
+ return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3172
3423
  });
3173
- if (months.length > LIMIT)
3174
- shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
3424
+ if (periods.length > keep) {
3425
+ const earlier = periods.length - keep;
3426
+ shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '']);
3427
+ }
3175
3428
  console.log();
3176
- for (const line of table(columns(t.bill.colMonth()), shown))
3429
+ for (const line of table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown))
3177
3430
  console.log(line);
3178
3431
  if (undated.calls > 0) {
3179
- console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
3432
+ const sentence = unit === 'month'
3433
+ ? t.bill.monthsUndated(undated.calls, formatUsd(undated.usd))
3434
+ : t.bill.periodsUndated(undated.calls, formatUsd(undated.usd), unit);
3435
+ console.log(c.dim(` ${wrap(sentence, 74, ' ')}`));
3180
3436
  }
3181
- const newest = months[months.length - 1];
3182
- console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
3437
+ const newest = periods[periods.length - 1];
3438
+ console.log(c.dim(` ${unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit)}`));
3183
3439
  }
3184
3440
  console.log();
3185
3441
  if (report.unpricedModels.length > 0) {
@@ -3450,6 +3706,75 @@ async function commandFromCodex(args, t) {
3450
3706
  else
3451
3707
  console.log(text.trimEnd());
3452
3708
  }
3709
+ /**
3710
+ * `trazum from-gemini-cli <file|dir>`: Gemini CLI sessions as a usage log.
3711
+ *
3712
+ * Explicit paths, like `from-codex`; `bill` with no path is the door that
3713
+ * looks in `~/.gemini/tmp` by itself. A directory is walked for `.jsonl` and
3714
+ * `.json` files, and each one is converted only when its own text says it is
3715
+ * a Gemini CLI session, so the shell history and checkpoints that share
3716
+ * `tmp` are left alone rather than misread.
3717
+ */
3718
+ async function commandFromGeminiCli(args, t) {
3719
+ const target = args.positional[0];
3720
+ if (target === undefined)
3721
+ throw new Error(t.fromGeminiCli.noPath());
3722
+ let info;
3723
+ try {
3724
+ info = await stat(target);
3725
+ }
3726
+ catch {
3727
+ throw new Error(t.fromGeminiCli.notFound(target));
3728
+ }
3729
+ const files = info.isDirectory()
3730
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
3731
+ .filter((entry) => entry.isFile() && /\.(jsonl|json)$/i.test(entry.name))
3732
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
3733
+ : [target];
3734
+ if (files.length === 0)
3735
+ throw new Error(t.fromGeminiCli.noFiles(target));
3736
+ const label = stringFlag(args, 'label');
3737
+ const lines = [];
3738
+ let sessions = 0;
3739
+ let repeats = 0;
3740
+ let missingModel = 0;
3741
+ let unsupported = 0;
3742
+ let unparseable = 0;
3743
+ let remainder = 0;
3744
+ for (const file of files) {
3745
+ const text = await readFile(file, 'utf8');
3746
+ if (!looksLikeGeminiCliSession(text))
3747
+ continue;
3748
+ sessions++;
3749
+ const conversion = geminiCliRecords(text, label === undefined ? {} : { label });
3750
+ for (const record of conversion.records)
3751
+ lines.push(JSON.stringify(record));
3752
+ repeats += conversion.repeats;
3753
+ missingModel += conversion.missingModel;
3754
+ unsupported += conversion.unsupported;
3755
+ unparseable += conversion.unparseable;
3756
+ remainder += conversion.remainderAsOutput;
3757
+ }
3758
+ if (sessions === 0)
3759
+ throw new Error(t.fromGeminiCli.noFiles(target));
3760
+ console.error(t.fromGeminiCli.summary(sessions, lines.length, repeats));
3761
+ if (missingModel + unsupported + unparseable > 0) {
3762
+ console.error(t.fromGeminiCli.gaps(missingModel, unsupported, unparseable));
3763
+ }
3764
+ if (remainder > 0)
3765
+ console.error(t.fromGeminiCli.remainder(remainder));
3766
+ console.error(t.fromGeminiCli.caveat());
3767
+ if (lines.length === 0)
3768
+ throw new Error(t.fromGeminiCli.noUsage());
3769
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3770
+ const text = lines.join('\n') + '\n';
3771
+ if (out !== undefined) {
3772
+ await writeFile(out, text, 'utf8');
3773
+ console.error(t.fromGeminiCli.written(out));
3774
+ }
3775
+ else
3776
+ console.log(text.trimEnd());
3777
+ }
3453
3778
  async function commandFromOtel(args, t) {
3454
3779
  const target = args.positional[0];
3455
3780
  if (target === undefined)
@@ -11380,6 +11705,9 @@ async function main() {
11380
11705
  case 'from-codex':
11381
11706
  await commandFromCodex(args, t);
11382
11707
  break;
11708
+ case 'from-gemini-cli':
11709
+ await commandFromGeminiCli(args, t);
11710
+ break;
11383
11711
  case 'from-otel':
11384
11712
  await commandFromOtel(args, t);
11385
11713
  break;