@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/dist/index.js CHANGED
@@ -7,7 +7,7 @@ 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
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';
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, geminiCliRecords, looksLikeGeminiCliSession, 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
11
  import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
12
12
  import { OPTIONAL_COUNTERS } from './optional-counters.js';
13
13
  import { dayOf, formatGap, median, spanDays } from './time.js';
@@ -34,6 +34,7 @@ import { renderProfilePdf } from './pdf.js';
34
34
  // to plain output, and a pipe stays plain.
35
35
  import { bar, c, sectionHeading, table } from './style.js';
36
36
  const VALUE_FLAGS = new Set([
37
+ 'id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions',
37
38
  'recovery-dir',
38
39
  'answers',
39
40
  'label-by-cwd',
@@ -94,6 +95,8 @@ const VALUE_FLAGS = new Set([
94
95
  'what-if',
95
96
  'since',
96
97
  'until',
98
+ // `bill --by day|week|month`: the calendar unit the statement is split by.
99
+ 'by',
97
100
  'export',
98
101
  'limit',
99
102
  'locale',
@@ -398,7 +401,8 @@ function disabledRules(args, config) {
398
401
  */
399
402
  const GLOBAL_FLAGS = ['help', 'h', 'version', 'v', 'locale', 'json', 'config', 'pricing', 'pricing-live', 'max-input'];
400
403
  const COMMAND_FLAGS = {
401
- filter: ['recovery-dir'],
404
+ task: ['id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions', 'out', 'o', 'json'],
405
+ filter: ['recovery-dir', 'stats'],
402
406
  optimize: [
403
407
  'level', 'model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch',
404
408
  'disable', 'llm', 'exact-tokens', 'diff', 'reorder', 'out', 'o',
@@ -428,6 +432,7 @@ const COMMAND_FLAGS = {
428
432
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
429
433
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
430
434
  'from-codex': ['label', 'out', 'o'],
435
+ 'from-gemini-cli': ['label', 'out', 'o'],
431
436
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
432
437
  'from-otel': ['label-from-service', 'out', 'o'],
433
438
  'from-litellm': ['out', 'o'],
@@ -435,7 +440,7 @@ const COMMAND_FLAGS = {
435
440
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
436
441
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
437
442
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
438
- 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'],
443
+ 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'],
439
444
  'from-helicone': ['out', 'o'],
440
445
  'from-langsmith': ['out', 'o'],
441
446
  switch: ['to', 'migration-usd', 'cases'],
@@ -2748,6 +2753,8 @@ function usageSourcesOf(text) {
2748
2753
  const claims = [];
2749
2754
  if (looksLikeCodexTranscript(text))
2750
2755
  claims.push('codex');
2756
+ if (looksLikeGeminiCliSession(text))
2757
+ claims.push('gemini-cli');
2751
2758
  if (looksLikeClaudeCodeTranscript(text))
2752
2759
  claims.push('claude-code');
2753
2760
  if (looksLikeOtel(text))
@@ -2800,6 +2807,11 @@ async function commandBill(args, pricing, t) {
2800
2807
  /* "What did this month cost" is the question a Claude Code folder of a
2801
2808
  year's sessions answers worst without a period. */
2802
2809
  const period = billingPeriod(args, t);
2810
+ const byFlag = stringFlag(args, 'by');
2811
+ if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
2812
+ throw new Error(t.bill.badBy(byFlag));
2813
+ }
2814
+ const by = byFlag;
2803
2815
  /*
2804
2816
  No path is the most common first run, and it used to be a refusal: the
2805
2817
  person had to know where Claude Code keeps its sessions before the one
@@ -2808,11 +2820,18 @@ async function commandBill(args, pricing, t) {
2808
2820
  */
2809
2821
  let targets = args.positional;
2810
2822
  if (targets.length === 0) {
2811
- const { found, tried } = await claudeProjectFolders(process.env);
2823
+ /*
2824
+ Every coding agent whose sessions this reads, not only Claude Code:
2825
+ somebody who runs Codex or Gemini CLI as well wants one bill, and asking
2826
+ them to know three folder layouts is the friction this default removes.
2827
+ Each folder found is named on its own line, so nothing is read silently.
2828
+ */
2829
+ const { found, tried } = await agentSessionFolders(process.env);
2812
2830
  if (found.length === 0)
2813
2831
  throw new Error(t.bill.noPath(tried.join(', ')));
2814
- console.error(t.bill.defaultPath(found.join(', ')));
2815
- targets = found;
2832
+ for (const { agent, path } of found)
2833
+ console.error(t.bill.defaultPathFor(AGENT_NAMES[agent], path));
2834
+ targets = found.map(({ path }) => path);
2816
2835
  }
2817
2836
  /*
2818
2837
  Every path given, files and directories alike, because a shell glob hands
@@ -2870,6 +2889,10 @@ async function commandBill(args, pricing, t) {
2870
2889
  /* Claude Code transcripts read: their money is an API-rate equivalent. */
2871
2890
  let claudeCodeFiles = 0;
2872
2891
  let codexFiles = 0;
2892
+ let geminiCliFiles = 0;
2893
+ let geminiRemainder = 0;
2894
+ /* Each agent's own records, so a bill that read more than one can say which spent what. */
2895
+ const agentLines = new Map();
2873
2896
  const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
2874
2897
  const lines = [];
2875
2898
  let sources = 0;
@@ -2917,6 +2940,19 @@ async function commandBill(args, pricing, t) {
2917
2940
  console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
2918
2941
  break;
2919
2942
  }
2943
+ case 'gemini-cli': {
2944
+ geminiCliFiles += 1;
2945
+ const project = label === undefined && labelFromProject && walked.has(file) ? await geminiProjectLabelFor(file) : undefined;
2946
+ if (project !== undefined && project !== '')
2947
+ labelledByProject += 1;
2948
+ const c = geminiCliRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
2949
+ records = c.records;
2950
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
2951
+ geminiRemainder += c.remainderAsOutput;
2952
+ if (leftOut > 0)
2953
+ console.error(t.fromGeminiCli.gaps(c.missingModel, c.unsupported, c.unparseable));
2954
+ break;
2955
+ }
2920
2956
  case 'claude-code': {
2921
2957
  claudeCodeFiles += 1;
2922
2958
  const project = label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
@@ -2980,6 +3016,12 @@ async function commandBill(args, pricing, t) {
2980
3016
  }
2981
3017
  for (const record of records)
2982
3018
  lines.push(JSON.stringify(record));
3019
+ if (shape === 'claude-code' || shape === 'codex' || shape === 'gemini-cli') {
3020
+ const own = agentLines.get(shape) ?? [];
3021
+ for (const record of records)
3022
+ own.push(JSON.stringify(record));
3023
+ agentLines.set(shape, own);
3024
+ }
2983
3025
  sources += 1;
2984
3026
  const count = shape === 'usage-log' ? null : records.length;
2985
3027
  if (perFile) {
@@ -3003,6 +3045,8 @@ async function commandBill(args, pricing, t) {
3003
3045
  console.error(t.bill.unknownMore(unclaimed.length - named.length));
3004
3046
  if (labelledByProject > 0)
3005
3047
  console.error(t.bill.labelledByProject(labelledByProject));
3048
+ if (geminiRemainder > 0)
3049
+ console.error(t.fromGeminiCli.remainder(geminiRemainder));
3006
3050
  if (sources === 0)
3007
3051
  throw new Error(t.bill.nothingRead());
3008
3052
  const text = lines.join('\n');
@@ -3038,9 +3082,28 @@ async function commandBill(args, pricing, t) {
3038
3082
  }
3039
3083
  console.error(t.bill.sources(sources, files.length));
3040
3084
  printReceiptSummary(document, t);
3041
- if (statement)
3042
- printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3043
- await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles + codexFiles > 0);
3085
+ const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
3086
+ /*
3087
+ By agent, once more than one agent's sessions were read: each agent's own
3088
+ records priced through the same catalogue and window as the whole, so the
3089
+ rows are the total split, not a second estimate beside it.
3090
+ */
3091
+ const byAgent = [...agentLines.entries()]
3092
+ .filter(([, own]) => own.length > 0)
3093
+ .map(([agent, own]) => {
3094
+ const part = profileUsage(own.join('\n'), {
3095
+ catalogue: pricing,
3096
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
3097
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
3098
+ });
3099
+ return { name: AGENT_NAMES[agent], calls: part.total.calls, usd: part.total.totalUsd };
3100
+ })
3101
+ .filter((row) => row.calls > 0)
3102
+ .sort((a, b) => b.usd - a.usd);
3103
+ if (statement) {
3104
+ printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by);
3105
+ }
3106
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, agentSessions);
3044
3107
  /*
3045
3108
  A slug with a slash in it is how OpenRouter names a model, and the bundled
3046
3109
  catalogue does not carry those: the live overlay does. Said only when the
@@ -3095,12 +3158,105 @@ async function claudeProjectFolders(env) {
3095
3158
  }
3096
3159
  return { found, tried };
3097
3160
  }
3161
+ const AGENT_NAMES = Object.freeze({
3162
+ 'claude-code': 'Claude Code',
3163
+ codex: 'Codex',
3164
+ 'gemini-cli': 'Gemini CLI',
3165
+ });
3166
+ /**
3167
+ * Where each agent keeps its sessions, from each agent's own source.
3168
+ *
3169
+ * - Claude Code: `claudeProjectFolders`, unchanged.
3170
+ * - Codex: `$CODEX_HOME` (default `~/.codex`), its `sessions` and
3171
+ * `archived_sessions`; an archived session was billed when it ran.
3172
+ * - Gemini CLI: `$GEMINI_CLI_HOME` (default the home directory), then
3173
+ * `.gemini/tmp/<project>/chats`, and `~/.cache/.gemini/tmp` where the macOS
3174
+ * sandbox moves it. Only the `chats` folders: the rest of `tmp` is shell
3175
+ * history and checkpoints, not usage.
3176
+ *
3177
+ * Every folder that exists is returned once; `tried` is every candidate, for
3178
+ * the refusal to name when there is none.
3179
+ */
3180
+ async function agentSessionFolders(env) {
3181
+ const claude = await claudeProjectFolders(env);
3182
+ const found = claude.found.map((path) => ({ agent: 'claude-code', path }));
3183
+ const tried = [...claude.tried];
3184
+ const seen = new Set(claude.found.map((path) => resolvePath(path)));
3185
+ const isDirectory = async (path) => {
3186
+ try {
3187
+ return (await stat(path)).isDirectory();
3188
+ }
3189
+ catch {
3190
+ return false;
3191
+ }
3192
+ };
3193
+ const home = homedir();
3194
+ const codexHome = env.CODEX_HOME ? env.CODEX_HOME : join(home, '.codex');
3195
+ for (const candidate of [join(codexHome, 'sessions'), join(codexHome, 'archived_sessions')]) {
3196
+ tried.push(candidate);
3197
+ if (!seen.has(resolvePath(candidate)) && (await isDirectory(candidate))) {
3198
+ seen.add(resolvePath(candidate));
3199
+ found.push({ agent: 'codex', path: candidate });
3200
+ }
3201
+ }
3202
+ const geminiHome = env.GEMINI_CLI_HOME ? env.GEMINI_CLI_HOME : home;
3203
+ for (const tmp of [join(geminiHome, '.gemini', 'tmp'), join(geminiHome, '.cache', '.gemini', 'tmp')]) {
3204
+ tried.push(tmp);
3205
+ if (!(await isDirectory(tmp)))
3206
+ continue;
3207
+ let projects = [];
3208
+ try {
3209
+ projects = (await readdir(tmp, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
3210
+ }
3211
+ catch {
3212
+ continue;
3213
+ }
3214
+ for (const project of projects) {
3215
+ const chats = join(tmp, project, 'chats');
3216
+ if (!seen.has(resolvePath(chats)) && (await isDirectory(chats))) {
3217
+ seen.add(resolvePath(chats));
3218
+ found.push({ agent: 'gemini-cli', path: chats });
3219
+ }
3220
+ }
3221
+ }
3222
+ return { found, tried };
3223
+ }
3224
+ /**
3225
+ * The project a Gemini CLI session belongs to.
3226
+ *
3227
+ * Gemini CLI keeps a folder per project under `tmp`, named by a short slug in
3228
+ * current versions (with the real working directory in `.project_root`
3229
+ * beside it) and by a SHA-256 of the path in older ones. The working
3230
+ * directory's last segment is the name a person recognises; a bare hash is
3231
+ * no name at all, so it labels nothing rather than putting 64 hex digits on
3232
+ * the bill.
3233
+ */
3234
+ async function geminiProjectLabelFor(file) {
3235
+ const parts = resolvePath(file).split('/');
3236
+ const at = parts.lastIndexOf('chats');
3237
+ if (at < 1)
3238
+ return undefined;
3239
+ const projectDir = parts.slice(0, at).join('/');
3240
+ try {
3241
+ const root = (await readFile(join(projectDir, '.project_root'), 'utf8')).trim();
3242
+ const name = root.replace(/[\\/]+$/, '').split(/[\\/]/).pop();
3243
+ if (name !== undefined && name !== '')
3244
+ return name;
3245
+ }
3246
+ catch {
3247
+ // Older versions keep no .project_root: fall back to the folder's name.
3248
+ }
3249
+ const folder = parts[at - 1];
3250
+ if (folder === undefined || folder === '' || /^[0-9a-f]{64}$/i.test(folder))
3251
+ return undefined;
3252
+ return folder;
3253
+ }
3098
3254
  /**
3099
3255
  * The bill as a person reads it: the total, by project, by model, and what
3100
3256
  * is not in the total, on stdout. The receipt's figures, rendered: nothing
3101
3257
  * here is computed that the receipt does not carry.
3102
3258
  */
3103
- function printBillStatement(report, byProject, t, window, apiEquivalent = false) {
3259
+ function printBillStatement(report, byProject, t, window, apiEquivalent = false, byAgent = [], by) {
3104
3260
  const n = (value) => value.toLocaleString(t.numberLocale);
3105
3261
  const pct = (share) => `${(share * 100).toFixed(1)}%`;
3106
3262
  const total = report.total.totalUsd;
@@ -3137,6 +3293,12 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false)
3137
3293
  */
3138
3294
  if (apiEquivalent)
3139
3295
  console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
3296
+ // Which agent spent what, first: it is the split a person running more than one asks for.
3297
+ if (byAgent.length > 1) {
3298
+ console.log();
3299
+ for (const line of table(columns(t.bill.colAgent()), rowsOf(byAgent)))
3300
+ console.log(line);
3301
+ }
3140
3302
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3141
3303
  if (labelled.length > 0) {
3142
3304
  console.log();
@@ -3162,22 +3324,34 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false)
3162
3324
  report's own days, oldest first, newest kept when there are many; shown
3163
3325
  only once the bill spans two calendar months, since one month is the total.
3164
3326
  */
3165
- const { months, undated } = spendByMonth(report);
3166
- if (months.length >= 2) {
3167
- const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
3327
+ /*
3328
+ `--by day` and `--by week` ask the same question at a finer grain, and
3329
+ are printed whenever asked, one period or many. The newest are kept when
3330
+ there are more than a screen holds: a month of days, twelve weeks.
3331
+ */
3332
+ const unit = by ?? 'month';
3333
+ const { periods, undated } = spendByPeriod(report, unit);
3334
+ if (periods.length >= (by === undefined ? 2 : 1)) {
3335
+ const keep = unit === 'day' ? 31 : LIMIT;
3336
+ const shown = periods.slice(-keep).map(({ period, calls, usd }) => {
3168
3337
  const share = total > 0 ? usd / total : 0;
3169
- return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3338
+ return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3170
3339
  });
3171
- if (months.length > LIMIT)
3172
- shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
3340
+ if (periods.length > keep) {
3341
+ const earlier = periods.length - keep;
3342
+ shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '']);
3343
+ }
3173
3344
  console.log();
3174
- for (const line of table(columns(t.bill.colMonth()), shown))
3345
+ for (const line of table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown))
3175
3346
  console.log(line);
3176
3347
  if (undated.calls > 0) {
3177
- console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
3348
+ const sentence = unit === 'month'
3349
+ ? t.bill.monthsUndated(undated.calls, formatUsd(undated.usd))
3350
+ : t.bill.periodsUndated(undated.calls, formatUsd(undated.usd), unit);
3351
+ console.log(c.dim(` ${wrap(sentence, 74, ' ')}`));
3178
3352
  }
3179
- const newest = months[months.length - 1];
3180
- console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
3353
+ const newest = periods[periods.length - 1];
3354
+ console.log(c.dim(` ${unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit)}`));
3181
3355
  }
3182
3356
  console.log();
3183
3357
  if (report.unpricedModels.length > 0) {
@@ -3448,6 +3622,75 @@ async function commandFromCodex(args, t) {
3448
3622
  else
3449
3623
  console.log(text.trimEnd());
3450
3624
  }
3625
+ /**
3626
+ * `trazum from-gemini-cli <file|dir>`: Gemini CLI sessions as a usage log.
3627
+ *
3628
+ * Explicit paths, like `from-codex`; `bill` with no path is the door that
3629
+ * looks in `~/.gemini/tmp` by itself. A directory is walked for `.jsonl` and
3630
+ * `.json` files, and each one is converted only when its own text says it is
3631
+ * a Gemini CLI session, so the shell history and checkpoints that share
3632
+ * `tmp` are left alone rather than misread.
3633
+ */
3634
+ async function commandFromGeminiCli(args, t) {
3635
+ const target = args.positional[0];
3636
+ if (target === undefined)
3637
+ throw new Error(t.fromGeminiCli.noPath());
3638
+ let info;
3639
+ try {
3640
+ info = await stat(target);
3641
+ }
3642
+ catch {
3643
+ throw new Error(t.fromGeminiCli.notFound(target));
3644
+ }
3645
+ const files = info.isDirectory()
3646
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
3647
+ .filter((entry) => entry.isFile() && /\.(jsonl|json)$/i.test(entry.name))
3648
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
3649
+ : [target];
3650
+ if (files.length === 0)
3651
+ throw new Error(t.fromGeminiCli.noFiles(target));
3652
+ const label = stringFlag(args, 'label');
3653
+ const lines = [];
3654
+ let sessions = 0;
3655
+ let repeats = 0;
3656
+ let missingModel = 0;
3657
+ let unsupported = 0;
3658
+ let unparseable = 0;
3659
+ let remainder = 0;
3660
+ for (const file of files) {
3661
+ const text = await readFile(file, 'utf8');
3662
+ if (!looksLikeGeminiCliSession(text))
3663
+ continue;
3664
+ sessions++;
3665
+ const conversion = geminiCliRecords(text, label === undefined ? {} : { label });
3666
+ for (const record of conversion.records)
3667
+ lines.push(JSON.stringify(record));
3668
+ repeats += conversion.repeats;
3669
+ missingModel += conversion.missingModel;
3670
+ unsupported += conversion.unsupported;
3671
+ unparseable += conversion.unparseable;
3672
+ remainder += conversion.remainderAsOutput;
3673
+ }
3674
+ if (sessions === 0)
3675
+ throw new Error(t.fromGeminiCli.noFiles(target));
3676
+ console.error(t.fromGeminiCli.summary(sessions, lines.length, repeats));
3677
+ if (missingModel + unsupported + unparseable > 0) {
3678
+ console.error(t.fromGeminiCli.gaps(missingModel, unsupported, unparseable));
3679
+ }
3680
+ if (remainder > 0)
3681
+ console.error(t.fromGeminiCli.remainder(remainder));
3682
+ console.error(t.fromGeminiCli.caveat());
3683
+ if (lines.length === 0)
3684
+ throw new Error(t.fromGeminiCli.noUsage());
3685
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3686
+ const text = lines.join('\n') + '\n';
3687
+ if (out !== undefined) {
3688
+ await writeFile(out, text, 'utf8');
3689
+ console.error(t.fromGeminiCli.written(out));
3690
+ }
3691
+ else
3692
+ console.log(text.trimEnd());
3693
+ }
3451
3694
  async function commandFromOtel(args, t) {
3452
3695
  const target = args.positional[0];
3453
3696
  if (target === undefined)
@@ -11163,6 +11406,11 @@ function printRank(ranked, context) {
11163
11406
  }
11164
11407
  async function main() {
11165
11408
  const argv = process.argv.slice(2);
11409
+ if (argv[0] === 'task') {
11410
+ const { runTask } = await import('./task.js');
11411
+ await runTask(argv.slice(1));
11412
+ return;
11413
+ }
11166
11414
  // The stdin display filter has its own small grammar and no project config.
11167
11415
  if (argv[0] === 'filter') {
11168
11416
  const { runFilter } = await import('./filter.js');
@@ -11373,6 +11621,9 @@ async function main() {
11373
11621
  case 'from-codex':
11374
11622
  await commandFromCodex(args, t);
11375
11623
  break;
11624
+ case 'from-gemini-cli':
11625
+ await commandFromGeminiCli(args, t);
11626
+ break;
11376
11627
  case 'from-otel':
11377
11628
  await commandFromOtel(args, t);
11378
11629
  break;