@trazum/cli 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +50 -7
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +51 -7
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/types.d.ts +22 -1
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +263 -19
- package/dist/index.js.map +1 -1
- package/dist/serve-import-schema.d.ts.map +1 -1
- package/dist/serve-import-schema.js +2 -1
- package/dist/serve-import-schema.js.map +1 -1
- package/dist/serve-import.d.ts +8 -2
- package/dist/serve-import.d.ts.map +1 -1
- package/dist/serve-import.js +7 -4
- package/dist/serve-import.js.map +1 -1
- package/dist/serve-schema.d.ts.map +1 -1
- package/dist/serve-schema.js +1 -0
- package/dist/serve-schema.js.map +1 -1
- package/package.json +7 -4
- package/src/i18n/en.ts +56 -7
- package/src/i18n/es.ts +59 -7
- package/src/i18n/types.ts +23 -1
- package/src/index.ts +251 -15
- package/src/serve-import-schema.ts +2 -1
- package/src/serve-import.ts +8 -5
- package/src/serve-schema.ts +1 -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,
|
|
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';
|
|
@@ -95,6 +95,8 @@ const VALUE_FLAGS = new Set([
|
|
|
95
95
|
'what-if',
|
|
96
96
|
'since',
|
|
97
97
|
'until',
|
|
98
|
+
// `bill --by day|week|month`: the calendar unit the statement is split by.
|
|
99
|
+
'by',
|
|
98
100
|
'export',
|
|
99
101
|
'limit',
|
|
100
102
|
'locale',
|
|
@@ -430,6 +432,7 @@ const COMMAND_FLAGS = {
|
|
|
430
432
|
position: ['json', 'html-out', 'pricing', 'pricing-live'],
|
|
431
433
|
receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
|
|
432
434
|
'from-codex': ['label', 'out', 'o'],
|
|
435
|
+
'from-gemini-cli': ['label', 'out', 'o'],
|
|
433
436
|
'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
|
|
434
437
|
'from-otel': ['label-from-service', 'out', 'o'],
|
|
435
438
|
'from-litellm': ['out', 'o'],
|
|
@@ -437,7 +440,7 @@ const COMMAND_FLAGS = {
|
|
|
437
440
|
'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
|
|
438
441
|
'from-openai': ['label', 'label-by-project', 'out', 'o'],
|
|
439
442
|
'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'],
|
|
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'],
|
|
441
444
|
'from-helicone': ['out', 'o'],
|
|
442
445
|
'from-langsmith': ['out', 'o'],
|
|
443
446
|
switch: ['to', 'migration-usd', 'cases'],
|
|
@@ -2750,6 +2753,8 @@ function usageSourcesOf(text) {
|
|
|
2750
2753
|
const claims = [];
|
|
2751
2754
|
if (looksLikeCodexTranscript(text))
|
|
2752
2755
|
claims.push('codex');
|
|
2756
|
+
if (looksLikeGeminiCliSession(text))
|
|
2757
|
+
claims.push('gemini-cli');
|
|
2753
2758
|
if (looksLikeClaudeCodeTranscript(text))
|
|
2754
2759
|
claims.push('claude-code');
|
|
2755
2760
|
if (looksLikeOtel(text))
|
|
@@ -2802,6 +2807,11 @@ async function commandBill(args, pricing, t) {
|
|
|
2802
2807
|
/* "What did this month cost" is the question a Claude Code folder of a
|
|
2803
2808
|
year's sessions answers worst without a period. */
|
|
2804
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;
|
|
2805
2815
|
/*
|
|
2806
2816
|
No path is the most common first run, and it used to be a refusal: the
|
|
2807
2817
|
person had to know where Claude Code keeps its sessions before the one
|
|
@@ -2810,11 +2820,18 @@ async function commandBill(args, pricing, t) {
|
|
|
2810
2820
|
*/
|
|
2811
2821
|
let targets = args.positional;
|
|
2812
2822
|
if (targets.length === 0) {
|
|
2813
|
-
|
|
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);
|
|
2814
2830
|
if (found.length === 0)
|
|
2815
2831
|
throw new Error(t.bill.noPath(tried.join(', ')));
|
|
2816
|
-
|
|
2817
|
-
|
|
2832
|
+
for (const { agent, path } of found)
|
|
2833
|
+
console.error(t.bill.defaultPathFor(AGENT_NAMES[agent], path));
|
|
2834
|
+
targets = found.map(({ path }) => path);
|
|
2818
2835
|
}
|
|
2819
2836
|
/*
|
|
2820
2837
|
Every path given, files and directories alike, because a shell glob hands
|
|
@@ -2872,6 +2889,10 @@ async function commandBill(args, pricing, t) {
|
|
|
2872
2889
|
/* Claude Code transcripts read: their money is an API-rate equivalent. */
|
|
2873
2890
|
let claudeCodeFiles = 0;
|
|
2874
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();
|
|
2875
2896
|
const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
|
|
2876
2897
|
const lines = [];
|
|
2877
2898
|
let sources = 0;
|
|
@@ -2919,6 +2940,19 @@ async function commandBill(args, pricing, t) {
|
|
|
2919
2940
|
console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
|
|
2920
2941
|
break;
|
|
2921
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
|
+
}
|
|
2922
2956
|
case 'claude-code': {
|
|
2923
2957
|
claudeCodeFiles += 1;
|
|
2924
2958
|
const project = label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
|
|
@@ -2982,6 +3016,12 @@ async function commandBill(args, pricing, t) {
|
|
|
2982
3016
|
}
|
|
2983
3017
|
for (const record of records)
|
|
2984
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
|
+
}
|
|
2985
3025
|
sources += 1;
|
|
2986
3026
|
const count = shape === 'usage-log' ? null : records.length;
|
|
2987
3027
|
if (perFile) {
|
|
@@ -3005,6 +3045,8 @@ async function commandBill(args, pricing, t) {
|
|
|
3005
3045
|
console.error(t.bill.unknownMore(unclaimed.length - named.length));
|
|
3006
3046
|
if (labelledByProject > 0)
|
|
3007
3047
|
console.error(t.bill.labelledByProject(labelledByProject));
|
|
3048
|
+
if (geminiRemainder > 0)
|
|
3049
|
+
console.error(t.fromGeminiCli.remainder(geminiRemainder));
|
|
3008
3050
|
if (sources === 0)
|
|
3009
3051
|
throw new Error(t.bill.nothingRead());
|
|
3010
3052
|
const text = lines.join('\n');
|
|
@@ -3040,9 +3082,28 @@ async function commandBill(args, pricing, t) {
|
|
|
3040
3082
|
}
|
|
3041
3083
|
console.error(t.bill.sources(sources, files.length));
|
|
3042
3084
|
printReceiptSummary(document, t);
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
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);
|
|
3046
3107
|
/*
|
|
3047
3108
|
A slug with a slash in it is how OpenRouter names a model, and the bundled
|
|
3048
3109
|
catalogue does not carry those: the live overlay does. Said only when the
|
|
@@ -3097,12 +3158,105 @@ async function claudeProjectFolders(env) {
|
|
|
3097
3158
|
}
|
|
3098
3159
|
return { found, tried };
|
|
3099
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
|
+
}
|
|
3100
3254
|
/**
|
|
3101
3255
|
* The bill as a person reads it: the total, by project, by model, and what
|
|
3102
3256
|
* is not in the total, on stdout. The receipt's figures, rendered: nothing
|
|
3103
3257
|
* here is computed that the receipt does not carry.
|
|
3104
3258
|
*/
|
|
3105
|
-
function printBillStatement(report, byProject, t, window, apiEquivalent = false) {
|
|
3259
|
+
function printBillStatement(report, byProject, t, window, apiEquivalent = false, byAgent = [], by) {
|
|
3106
3260
|
const n = (value) => value.toLocaleString(t.numberLocale);
|
|
3107
3261
|
const pct = (share) => `${(share * 100).toFixed(1)}%`;
|
|
3108
3262
|
const total = report.total.totalUsd;
|
|
@@ -3139,6 +3293,12 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false)
|
|
|
3139
3293
|
*/
|
|
3140
3294
|
if (apiEquivalent)
|
|
3141
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
|
+
}
|
|
3142
3302
|
const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
|
|
3143
3303
|
if (labelled.length > 0) {
|
|
3144
3304
|
console.log();
|
|
@@ -3164,22 +3324,34 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false)
|
|
|
3164
3324
|
report's own days, oldest first, newest kept when there are many; shown
|
|
3165
3325
|
only once the bill spans two calendar months, since one month is the total.
|
|
3166
3326
|
*/
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
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 }) => {
|
|
3170
3337
|
const share = total > 0 ? usd / total : 0;
|
|
3171
|
-
return [
|
|
3338
|
+
return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
|
|
3172
3339
|
});
|
|
3173
|
-
if (
|
|
3174
|
-
|
|
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
|
+
}
|
|
3175
3344
|
console.log();
|
|
3176
|
-
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))
|
|
3177
3346
|
console.log(line);
|
|
3178
3347
|
if (undated.calls > 0) {
|
|
3179
|
-
|
|
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, ' ')}`));
|
|
3180
3352
|
}
|
|
3181
|
-
const newest =
|
|
3182
|
-
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)}`));
|
|
3183
3355
|
}
|
|
3184
3356
|
console.log();
|
|
3185
3357
|
if (report.unpricedModels.length > 0) {
|
|
@@ -3450,6 +3622,75 @@ async function commandFromCodex(args, t) {
|
|
|
3450
3622
|
else
|
|
3451
3623
|
console.log(text.trimEnd());
|
|
3452
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
|
+
}
|
|
3453
3694
|
async function commandFromOtel(args, t) {
|
|
3454
3695
|
const target = args.positional[0];
|
|
3455
3696
|
if (target === undefined)
|
|
@@ -11380,6 +11621,9 @@ async function main() {
|
|
|
11380
11621
|
case 'from-codex':
|
|
11381
11622
|
await commandFromCodex(args, t);
|
|
11382
11623
|
break;
|
|
11624
|
+
case 'from-gemini-cli':
|
|
11625
|
+
await commandFromGeminiCli(args, t);
|
|
11626
|
+
break;
|
|
11383
11627
|
case 'from-otel':
|
|
11384
11628
|
await commandFromOtel(args, t);
|
|
11385
11629
|
break;
|