chompyy 0.4.7 → 0.6.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 +40 -6
- package/dist/advice.js +2 -1
- package/dist/agentlimits.js +77 -0
- package/dist/agentusage.js +96 -0
- package/dist/appstate.js +72 -5
- package/dist/away.js +44 -5
- package/dist/blueprint.js +3 -7
- package/dist/board.js +4 -0
- package/dist/cli.js +328 -15
- package/dist/codexquota.js +106 -0
- package/dist/codexusage.js +10 -0
- package/dist/config.js +2 -0
- package/dist/context.js +30 -0
- package/dist/costs.js +1 -0
- package/dist/daytime.js +68 -0
- package/dist/demon.js +20 -0
- package/dist/didwork.js +46 -0
- package/dist/label.js +33 -0
- package/dist/learning.js +35 -0
- package/dist/menu.js +17 -0
- package/dist/nightcap.js +60 -0
- package/dist/nudge.js +47 -18
- package/dist/pacing.js +16 -1
- package/dist/questions.js +71 -0
- package/dist/recap.js +74 -0
- package/dist/receipt.js +48 -0
- package/dist/recipe.js +79 -0
- package/dist/send.js +46 -20
- package/dist/stamps.js +14 -0
- package/dist/taste.js +67 -7
- package/dist/triggers.js +5 -0
- package/dist/unkeep.js +220 -0
- package/dist/usage.js +21 -1
- package/dist/vendor/codeburn/antigravity.js +309 -0
- package/dist/vendor/codeburn/codex.js +429 -0
- package/dist/vendor/codeburn/copilot.js +292 -0
- package/dist/vendor/codeburn/gemini.js +195 -0
- package/dist/vendor/codeburn/grokbot.js +182 -0
- package/dist/vendor/codeburn/kimi.js +178 -0
- package/dist/vendor/codeburn/shims/chalk.js +14 -0
- package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
- package/dist/vendor/codeburn/src/act/backup.js +83 -0
- package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
- package/dist/vendor/codeburn/src/act/types.js +37 -0
- package/dist/vendor/codeburn/src/bash-utils.js +204 -0
- package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
- package/dist/vendor/codeburn/src/cache-dir.js +26 -0
- package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
- package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
- package/dist/vendor/codeburn/src/classifier.js +209 -0
- package/dist/vendor/codeburn/src/claude-identity.js +223 -0
- package/dist/vendor/codeburn/src/codex-cache.js +377 -0
- package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
- package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
- package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
- package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
- package/dist/vendor/codeburn/src/compare-stats.js +405 -0
- package/dist/vendor/codeburn/src/config.js +145 -0
- package/dist/vendor/codeburn/src/content-utils.js +56 -0
- package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
- package/dist/vendor/codeburn/src/context-tree.js +664 -0
- package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
- package/dist/vendor/codeburn/src/currency.js +189 -0
- package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
- package/dist/vendor/codeburn/src/cursor-import.js +402 -0
- package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
- package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
- package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
- package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
- package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
- package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
- package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
- package/dist/vendor/codeburn/src/format.js +118 -0
- package/dist/vendor/codeburn/src/fs-utils.js +270 -0
- package/dist/vendor/codeburn/src/git-origin.js +334 -0
- package/dist/vendor/codeburn/src/granular-history.js +328 -0
- package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
- package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
- package/dist/vendor/codeburn/src/live-sessions.js +358 -0
- package/dist/vendor/codeburn/src/math-utils.js +8 -0
- package/dist/vendor/codeburn/src/menubar-json.js +294 -0
- package/dist/vendor/codeburn/src/models.js +1879 -0
- package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
- package/dist/vendor/codeburn/src/optimize.js +4110 -0
- package/dist/vendor/codeburn/src/parse-workers.js +219 -0
- package/dist/vendor/codeburn/src/parser.js +6953 -0
- package/dist/vendor/codeburn/src/path-privacy.js +26 -0
- package/dist/vendor/codeburn/src/plans.js +135 -0
- package/dist/vendor/codeburn/src/pr-signals.js +132 -0
- package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
- package/dist/vendor/codeburn/src/provider-issues.js +30 -0
- package/dist/vendor/codeburn/src/providers/amp.js +286 -0
- package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
- package/dist/vendor/codeburn/src/providers/claude.js +551 -0
- package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
- package/dist/vendor/codeburn/src/providers/cline.js +63 -0
- package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
- package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
- package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
- package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
- package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
- package/dist/vendor/codeburn/src/providers/crush.js +226 -0
- package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
- package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
- package/dist/vendor/codeburn/src/providers/devin.js +569 -0
- package/dist/vendor/codeburn/src/providers/droid.js +324 -0
- package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
- package/dist/vendor/codeburn/src/providers/forge.js +245 -0
- package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
- package/dist/vendor/codeburn/src/providers/goose.js +252 -0
- package/dist/vendor/codeburn/src/providers/grok.js +581 -0
- package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
- package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
- package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
- package/dist/vendor/codeburn/src/providers/index.js +360 -0
- package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
- package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
- package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
- package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
- package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
- package/dist/vendor/codeburn/src/providers/mux.js +242 -0
- package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
- package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
- package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
- package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
- package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
- package/dist/vendor/codeburn/src/providers/pi.js +429 -0
- package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
- package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
- package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
- package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
- package/dist/vendor/codeburn/src/providers/types.js +5 -0
- package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
- package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
- package/dist/vendor/codeburn/src/providers/warp.js +575 -0
- package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
- package/dist/vendor/codeburn/src/providers/zed.js +187 -0
- package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
- package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
- package/dist/vendor/codeburn/src/quota/claude.js +244 -0
- package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
- package/dist/vendor/codeburn/src/quota/security.js +299 -0
- package/dist/vendor/codeburn/src/quota/types.js +1 -0
- package/dist/vendor/codeburn/src/scan-facts.js +99 -0
- package/dist/vendor/codeburn/src/session-cache.js +3040 -0
- package/dist/vendor/codeburn/src/session-count-label.js +14 -0
- package/dist/vendor/codeburn/src/session-output.js +139 -0
- package/dist/vendor/codeburn/src/session-population.js +30 -0
- package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
- package/dist/vendor/codeburn/src/sqlite.js +528 -0
- package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
- package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
- package/dist/vendor/codeburn/src/token-estimate.js +5 -0
- package/dist/vendor/codeburn/src/types.js +16 -0
- package/dist/vendor/codeburn/src/work-units.js +126 -0
- package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
- package/dist/vendor/codeburn/src/wsl.js +198 -0
- package/dist/vendor/codeburn/src/yield.js +666 -0
- package/package.json +11 -3
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
import { readdir, stat } from 'fs/promises';
|
|
3
|
+
import { basename, dirname, join } from 'path';
|
|
4
|
+
import { homedir } from 'os';
|
|
5
|
+
import { FS_SCAN_CONCURRENCY, mapWithConcurrency, readSessionFile, readSessionLines } from '../fs-utils.js';
|
|
6
|
+
import { calculateCost, getModelCosts, getShortModelName, ownValue } from '../models.js';
|
|
7
|
+
import { extractBashCommands } from '../bash-utils.js';
|
|
8
|
+
// Grok Build (xAI's coding CLI) stores one session per directory at
|
|
9
|
+
// <grok-home>/sessions/<url-encoded-cwd>/<uuid>/, where grok-home is $GROK_HOME
|
|
10
|
+
// or ~/.grok. Each session dir holds summary.json, signals.json, and the ACP
|
|
11
|
+
// log updates.jsonl.
|
|
12
|
+
//
|
|
13
|
+
// Newer Grok CLI versions append a `turn_completed` update with provider-recorded
|
|
14
|
+
// input/output/cache/reasoning usage. That record is authoritative: cached reads
|
|
15
|
+
// are part of input, and reasoning is a subset of output. Cache creation is
|
|
16
|
+
// treated as another input subset by analogy because the record exposes no
|
|
17
|
+
// separate fresh-input field; any per-record violation is clamped before pricing.
|
|
18
|
+
// Older sessions only carry
|
|
19
|
+
// `signals.json.contextTokensUsed` and the running `_meta.totalTokens` curve; for
|
|
20
|
+
// those we retain the old compaction-aware estimate and mark its cost estimated.
|
|
21
|
+
// `costUsdTicks` is deliberately ignored because its scale is not documented.
|
|
22
|
+
//
|
|
23
|
+
// <grok-home>/logs/unified.jsonl outlives the session dirs and logs every
|
|
24
|
+
// inference as `shell.turn.inference_done` (prompt_tokens includes
|
|
25
|
+
// cached_prompt_tokens, completion_tokens includes reasoning_tokens). A session
|
|
26
|
+
// with records there is read from the log, one call per request so the
|
|
27
|
+
// long-context tier applies per request; its session dir is then skipped. Session
|
|
28
|
+
// dirs only count for sessions the log no longer holds (rotated or truncated).
|
|
29
|
+
const toolNameMap = {
|
|
30
|
+
bash: 'Bash',
|
|
31
|
+
run_terminal_command: 'Bash',
|
|
32
|
+
read_file: 'Read',
|
|
33
|
+
read: 'Read',
|
|
34
|
+
write_file: 'Write',
|
|
35
|
+
edit_file: 'Edit',
|
|
36
|
+
edit: 'Edit',
|
|
37
|
+
list_dir: 'Glob',
|
|
38
|
+
glob: 'Glob',
|
|
39
|
+
grep: 'Grep',
|
|
40
|
+
search: 'WebSearch',
|
|
41
|
+
web_search: 'WebSearch',
|
|
42
|
+
fetch: 'WebFetch',
|
|
43
|
+
task: 'Agent',
|
|
44
|
+
search_replace: 'Edit',
|
|
45
|
+
todo_write: 'TodoWrite',
|
|
46
|
+
spawn_subagent: 'Agent',
|
|
47
|
+
};
|
|
48
|
+
function defaultSessionsDir() {
|
|
49
|
+
const home = process.env['GROK_HOME'] ?? join(homedir(), '.grok');
|
|
50
|
+
return join(home, 'sessions');
|
|
51
|
+
}
|
|
52
|
+
async function readJson(path) {
|
|
53
|
+
const content = await readSessionFile(path);
|
|
54
|
+
if (content === null)
|
|
55
|
+
return null;
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(content);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function safeDecode(name) {
|
|
64
|
+
try {
|
|
65
|
+
return decodeURIComponent(name);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return name;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function emptyTokenTotals() {
|
|
72
|
+
return { input: 0, cacheRead: 0, output: 0, cacheCreation: 0, reasoning: 0 };
|
|
73
|
+
}
|
|
74
|
+
const authoritativeTokenFields = [
|
|
75
|
+
'inputTokens',
|
|
76
|
+
'outputTokens',
|
|
77
|
+
'cachedReadTokens',
|
|
78
|
+
'cacheCreationTokens',
|
|
79
|
+
'reasoningTokens',
|
|
80
|
+
];
|
|
81
|
+
function isRecord(value) {
|
|
82
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
83
|
+
}
|
|
84
|
+
// JSONL is third-party input. Keep the check local to this provider so bad
|
|
85
|
+
// usage fields become absent rather than leaking NaN, negative tokens, or a
|
|
86
|
+
// throwing arithmetic operation into the session aggregate.
|
|
87
|
+
function finiteNonNegative(value) {
|
|
88
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
|
|
89
|
+
return undefined;
|
|
90
|
+
// Token counts this large are not meaningful in a session and can overflow
|
|
91
|
+
// when summed or priced. Capping preserves the non-negative finite invariant.
|
|
92
|
+
return Math.min(value, Number.MAX_SAFE_INTEGER);
|
|
93
|
+
}
|
|
94
|
+
function addTokenCounts(left, right) {
|
|
95
|
+
return Math.min(Number.MAX_SAFE_INTEGER, left + right);
|
|
96
|
+
}
|
|
97
|
+
function readUsageNumber(usage, field) {
|
|
98
|
+
return finiteNonNegative(usage[field]);
|
|
99
|
+
}
|
|
100
|
+
function readModelUsage(usage) {
|
|
101
|
+
const modelUsage = usage['modelUsage'];
|
|
102
|
+
const result = new Map();
|
|
103
|
+
if (!isRecord(modelUsage))
|
|
104
|
+
return result;
|
|
105
|
+
for (const [modelId, rawModelUsage] of Object.entries(modelUsage)) {
|
|
106
|
+
if (!modelId || !isRecord(rawModelUsage))
|
|
107
|
+
continue;
|
|
108
|
+
const values = authoritativeTokenFields.map((field) => finiteNonNegative(rawModelUsage[field]));
|
|
109
|
+
if (!values.some((value) => value !== undefined))
|
|
110
|
+
continue;
|
|
111
|
+
result.set(modelId, {
|
|
112
|
+
inputTokens: values[0] ?? 0,
|
|
113
|
+
outputTokens: values[1] ?? 0,
|
|
114
|
+
cacheReadTokens: values[2] ?? 0,
|
|
115
|
+
cacheCreationTokens: values[3] ?? 0,
|
|
116
|
+
reasoningTokens: values[4] ?? 0,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
function parseAuthoritativeUsage(raw) {
|
|
122
|
+
if (!isRecord(raw))
|
|
123
|
+
return null;
|
|
124
|
+
const values = authoritativeTokenFields.map((field) => readUsageNumber(raw, field));
|
|
125
|
+
const modelUsage = readModelUsage(raw);
|
|
126
|
+
return {
|
|
127
|
+
inputTokens: values[0] ?? 0,
|
|
128
|
+
outputTokens: values[1] ?? 0,
|
|
129
|
+
cacheReadTokens: values[2] ?? 0,
|
|
130
|
+
cacheCreationTokens: values[3] ?? 0,
|
|
131
|
+
reasoningTokens: values[4] ?? 0,
|
|
132
|
+
modelUsage,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function chooseAuthoritativeModel(modelIds, existingModel) {
|
|
136
|
+
// modelUsage is the best attribution signal, but it may contain a newer
|
|
137
|
+
// provider id that this checkout cannot price yet (for example
|
|
138
|
+
// `grok-4.6-build`). Prefer an actual model id when it prices; otherwise keep
|
|
139
|
+
// the existing summary/signals id when that one prices, avoiding a truthful
|
|
140
|
+
// but $0 row. If neither prices, retain the actual model id for attribution.
|
|
141
|
+
const pricedActualModel = modelIds.find((modelId) => getModelCosts(modelId) !== null);
|
|
142
|
+
if (pricedActualModel)
|
|
143
|
+
return pricedActualModel;
|
|
144
|
+
if (getModelCosts(existingModel) !== null)
|
|
145
|
+
return existingModel;
|
|
146
|
+
return modelIds[0] ?? existingModel;
|
|
147
|
+
}
|
|
148
|
+
// Single pass over updates.jsonl: retain the old per-turn totalTokens estimate,
|
|
149
|
+
// the deduplicated authoritative turn records, and the real tool calls.
|
|
150
|
+
function parseUpdates(updates) {
|
|
151
|
+
const turns = new Map();
|
|
152
|
+
const completedUsages = new Map();
|
|
153
|
+
const tools = [];
|
|
154
|
+
const bashCommands = [];
|
|
155
|
+
const subagentTypes = [];
|
|
156
|
+
// Compaction-aware fresh input: a large drop in totalTokens means the context
|
|
157
|
+
// was compacted and rebuilt, so we sum each segment's peak rather than the
|
|
158
|
+
// single global peak (which would lose everything before the last compaction).
|
|
159
|
+
let prevTotal = -1;
|
|
160
|
+
let segmentPeak = 0;
|
|
161
|
+
let inputFresh = 0;
|
|
162
|
+
let completedWithoutPromptId = 0;
|
|
163
|
+
for (const line of updates.split('\n')) {
|
|
164
|
+
if (!line.trim())
|
|
165
|
+
continue;
|
|
166
|
+
let params;
|
|
167
|
+
try {
|
|
168
|
+
params = JSON.parse(line).params;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (!params)
|
|
174
|
+
continue;
|
|
175
|
+
const total = finiteNonNegative(params._meta?.totalTokens);
|
|
176
|
+
if (total !== undefined) {
|
|
177
|
+
if (prevTotal >= 0 && total < prevTotal * 0.5) {
|
|
178
|
+
inputFresh = addTokenCounts(inputFresh, segmentPeak); // close the segment a compaction just ended
|
|
179
|
+
segmentPeak = 0;
|
|
180
|
+
}
|
|
181
|
+
if (total > segmentPeak)
|
|
182
|
+
segmentPeak = total;
|
|
183
|
+
prevTotal = total;
|
|
184
|
+
const promptId = typeof params._meta?.promptId === 'string' ? params._meta.promptId : undefined;
|
|
185
|
+
if (promptId) {
|
|
186
|
+
const turn = turns.get(promptId);
|
|
187
|
+
if (!turn)
|
|
188
|
+
turns.set(promptId, { first: total, last: total });
|
|
189
|
+
else
|
|
190
|
+
turn.last = total;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const update = params.update;
|
|
194
|
+
if (update?.sessionUpdate === 'turn_completed') {
|
|
195
|
+
const usage = parseAuthoritativeUsage(update.usage);
|
|
196
|
+
if (usage) {
|
|
197
|
+
const promptId = typeof update.prompt_id === 'string' && update.prompt_id.length > 0
|
|
198
|
+
? update.prompt_id
|
|
199
|
+
: `turn_completed:${completedWithoutPromptId++}`;
|
|
200
|
+
// Re-emitted turn_completed notifications are cumulative updates for
|
|
201
|
+
// the same turn. Last write wins so they cannot double count.
|
|
202
|
+
completedUsages.set(promptId, usage);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (update?.sessionUpdate === 'tool_call' && typeof update.title === 'string') {
|
|
206
|
+
tools.push(ownValue(toolNameMap, update.title) ?? update.title);
|
|
207
|
+
if (update.title === 'run_terminal_command' && typeof update.rawInput?.command === 'string') {
|
|
208
|
+
bashCommands.push(...extractBashCommands(update.rawInput.command));
|
|
209
|
+
}
|
|
210
|
+
if (update.title === 'spawn_subagent' && typeof update.rawInput?.subagent_type === 'string') {
|
|
211
|
+
subagentTypes.push(update.rawInput.subagent_type);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
inputFresh = addTokenCounts(inputFresh, segmentPeak); // close the final segment
|
|
216
|
+
let sumFirst = 0;
|
|
217
|
+
let output = 0;
|
|
218
|
+
for (const { first, last } of turns.values()) {
|
|
219
|
+
sumFirst = addTokenCounts(sumFirst, first);
|
|
220
|
+
output = addTokenCounts(output, Math.max(0, last - first));
|
|
221
|
+
}
|
|
222
|
+
// Fresh input (summed segment peaks) is billed once; the rest of the per-turn
|
|
223
|
+
// re-sends are cache reads (Grok caches them, even though it reports nothing).
|
|
224
|
+
const estimated = {
|
|
225
|
+
input: inputFresh,
|
|
226
|
+
cacheRead: Math.max(0, sumFirst - inputFresh),
|
|
227
|
+
output,
|
|
228
|
+
};
|
|
229
|
+
const usageTotals = emptyTokenTotals();
|
|
230
|
+
const modelIds = [];
|
|
231
|
+
const seenModelIds = new Set();
|
|
232
|
+
for (const usage of completedUsages.values()) {
|
|
233
|
+
addUsageToTotals(usageTotals, usage);
|
|
234
|
+
for (const modelId of usage.modelUsage.keys()) {
|
|
235
|
+
if (seenModelIds.has(modelId))
|
|
236
|
+
continue;
|
|
237
|
+
seenModelIds.add(modelId);
|
|
238
|
+
modelIds.push(modelId);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
// Decide from the final, prompt-deduplicated records. A positive modelUsage
|
|
242
|
+
// entry is attribution metadata only; it is not a substitute for the
|
|
243
|
+
// top-level accounting fields. This also prevents a superseded positive
|
|
244
|
+
// record from suppressing the streaming fallback.
|
|
245
|
+
const hasPositiveCompletedUsage = [...completedUsages.values()].some(hasPositiveTopLevelUsage);
|
|
246
|
+
if (!hasPositiveCompletedUsage || !hasPositiveTotals(usageTotals)) {
|
|
247
|
+
// Older Grok CLI versions have no completed usage record. Keep the
|
|
248
|
+
// heuristic only here; blending it into a real record would reintroduce the
|
|
249
|
+
// large over-count this parser is fixing. A record that only has modelUsage,
|
|
250
|
+
// or whose final deduplicated values are empty, is treated the same way.
|
|
251
|
+
return {
|
|
252
|
+
usage: { input: estimated.input, cacheRead: estimated.cacheRead, output: estimated.output, cacheCreation: 0, reasoning: 0 },
|
|
253
|
+
modelIds: [],
|
|
254
|
+
authoritative: false,
|
|
255
|
+
hasUncompletedTurn: false,
|
|
256
|
+
tools,
|
|
257
|
+
bashCommands,
|
|
258
|
+
subagentTypes,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
const hasUncompletedTurn = [...turns.keys()].some(promptId => !completedUsages.has(promptId));
|
|
262
|
+
// calculateCost follows the cache-exclusive input convention used by the
|
|
263
|
+
// other real-usage providers. Each record is decomposed before its totals
|
|
264
|
+
// are added, so an inconsistent record cannot consume another record's fresh
|
|
265
|
+
// input budget.
|
|
266
|
+
return {
|
|
267
|
+
usage: usageTotals,
|
|
268
|
+
modelIds,
|
|
269
|
+
authoritative: true,
|
|
270
|
+
hasUncompletedTurn,
|
|
271
|
+
tools,
|
|
272
|
+
bashCommands,
|
|
273
|
+
subagentTypes,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
function hasPositiveTopLevelUsage(usage) {
|
|
277
|
+
return usage.inputTokens > 0
|
|
278
|
+
|| usage.outputTokens > 0
|
|
279
|
+
|| usage.cacheReadTokens > 0
|
|
280
|
+
|| usage.cacheCreationTokens > 0
|
|
281
|
+
|| usage.reasoningTokens > 0;
|
|
282
|
+
}
|
|
283
|
+
function addUsageToTotals(totals, usage) {
|
|
284
|
+
// `cacheCreationTokens` is treated as an input subset by analogy. Clamp the
|
|
285
|
+
// exclusive portion per record before summing the session. Reasoning is
|
|
286
|
+
// reported inside outputTokens by Grok, so clamp it to that same record's
|
|
287
|
+
// output before the session totals are accumulated.
|
|
288
|
+
const reasoningTokens = Math.min(usage.reasoningTokens, usage.outputTokens);
|
|
289
|
+
totals.input = addTokenCounts(totals.input, Math.max(0, usage.inputTokens - usage.cacheReadTokens - usage.cacheCreationTokens));
|
|
290
|
+
totals.cacheRead = addTokenCounts(totals.cacheRead, usage.cacheReadTokens);
|
|
291
|
+
totals.output = addTokenCounts(totals.output, usage.outputTokens);
|
|
292
|
+
totals.cacheCreation = addTokenCounts(totals.cacheCreation, usage.cacheCreationTokens);
|
|
293
|
+
totals.reasoning = addTokenCounts(totals.reasoning, reasoningTokens);
|
|
294
|
+
}
|
|
295
|
+
function hasPositiveTotals(totals) {
|
|
296
|
+
return totals.input > 0
|
|
297
|
+
|| totals.cacheRead > 0
|
|
298
|
+
|| totals.output > 0
|
|
299
|
+
|| totals.cacheCreation > 0
|
|
300
|
+
|| totals.reasoning > 0;
|
|
301
|
+
}
|
|
302
|
+
function createParser(source, seenKeys, unifiedLogPath) {
|
|
303
|
+
return {
|
|
304
|
+
async *parse() {
|
|
305
|
+
const dir = dirname(source.path);
|
|
306
|
+
const summary = await readJson(join(dir, 'summary.json'));
|
|
307
|
+
if (!summary)
|
|
308
|
+
return;
|
|
309
|
+
const logged = await loggedSessionIds(unifiedLogPath);
|
|
310
|
+
if (logged.has(summary.info?.id ?? basename(dir)) || logged.has(basename(dir)))
|
|
311
|
+
return;
|
|
312
|
+
const updates = await readSessionFile(source.path);
|
|
313
|
+
if (updates === null)
|
|
314
|
+
return;
|
|
315
|
+
const signals = await readJson(join(dir, 'signals.json'));
|
|
316
|
+
const existingModel = summary.current_model_id ?? signals?.primaryModelId ?? signals?.modelsUsed?.[0] ?? 'grok-build';
|
|
317
|
+
const parsed = parseUpdates(updates);
|
|
318
|
+
if (!hasPositiveTotals(parsed.usage))
|
|
319
|
+
return;
|
|
320
|
+
const timestamp = summary.updated_at ?? summary.last_active_at ?? summary.created_at ?? '';
|
|
321
|
+
const sessionId = summary.info?.id ?? basename(dir);
|
|
322
|
+
// Multi-model attribution is deliberately out of scope: modelUsage may
|
|
323
|
+
// help choose a priced attribution id, but top-level totals remain the
|
|
324
|
+
// accounting source and one session uses one model's rate.
|
|
325
|
+
const model = parsed.authoritative ? chooseAuthoritativeModel(parsed.modelIds, existingModel) : existingModel;
|
|
326
|
+
const baseDedupKey = `${source.provider}:${dir}:${timestamp}:${sessionId}`;
|
|
327
|
+
if (seenKeys.has(baseDedupKey))
|
|
328
|
+
return;
|
|
329
|
+
seenKeys.add(baseDedupKey);
|
|
330
|
+
// `addUsageToTotals` clamps reasoning per authoritative record before
|
|
331
|
+
// summing, so the aggregate preserves this identity as well.
|
|
332
|
+
const reasoningTokens = parsed.usage.reasoning;
|
|
333
|
+
yield {
|
|
334
|
+
provider: source.provider,
|
|
335
|
+
model,
|
|
336
|
+
inputTokens: parsed.usage.input,
|
|
337
|
+
// Grok reports reasoning INSIDE outputTokens, but the repo contract is
|
|
338
|
+
// the opposite: ParsedProviderCall.reasoningTokens is exclusive of
|
|
339
|
+
// outputTokens. Downstream consumers reconstitute the billable total
|
|
340
|
+
// through billableOutputTokens() (models.ts): it adds reasoning back on
|
|
341
|
+
// top for grok and every other provider, except the
|
|
342
|
+
// REASONING_INCLUDED_IN_OUTPUT set (claude, codex) whose reasoning is
|
|
343
|
+
// already inside output_tokens and must not be added again.
|
|
344
|
+
// tests/providers/kiro.test.ts states the exclusive contract outright.
|
|
345
|
+
// So split it here rather than special-casing grok in every downstream
|
|
346
|
+
// site: subtracting reasoning makes `output + reasoning` reconstruct
|
|
347
|
+
// exactly the number Grok reported.
|
|
348
|
+
outputTokens: parsed.usage.output - reasoningTokens,
|
|
349
|
+
cacheCreationInputTokens: parsed.usage.cacheCreation,
|
|
350
|
+
cacheReadInputTokens: parsed.usage.cacheRead,
|
|
351
|
+
cachedInputTokens: parsed.usage.cacheRead,
|
|
352
|
+
reasoningTokens,
|
|
353
|
+
webSearchRequests: 0,
|
|
354
|
+
// Authoritative token counts are measured even though CodeBurn applies
|
|
355
|
+
// its own pricing table; only the legacy context-curve path is an
|
|
356
|
+
// estimate. The full provider output is priced once here, which is
|
|
357
|
+
// what the downstream `output + reasoning` recompute reproduces.
|
|
358
|
+
costUSD: calculateCost(model, parsed.usage.input, parsed.usage.output, parsed.usage.cacheCreation, parsed.usage.cacheRead, 0),
|
|
359
|
+
costIsEstimated: !parsed.authoritative || parsed.hasUncompletedTurn,
|
|
360
|
+
tools: parsed.tools,
|
|
361
|
+
bashCommands: parsed.bashCommands,
|
|
362
|
+
subagentTypes: parsed.subagentTypes,
|
|
363
|
+
timestamp,
|
|
364
|
+
speed: 'standard',
|
|
365
|
+
deduplicationKey: baseDedupKey,
|
|
366
|
+
userMessage: summary.session_summary ?? summary.generated_title ?? '',
|
|
367
|
+
sessionId,
|
|
368
|
+
project: source.project,
|
|
369
|
+
projectPath: summary.info?.cwd,
|
|
370
|
+
};
|
|
371
|
+
},
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
function inferenceUsage(record) {
|
|
375
|
+
const { sid, ts, ctx } = record;
|
|
376
|
+
if (record.msg !== 'shell.turn.inference_done' || typeof sid !== 'string' || !sid || typeof ts !== 'string' || !isRecord(ctx))
|
|
377
|
+
return null;
|
|
378
|
+
const prompt = finiteNonNegative(ctx['prompt_tokens']);
|
|
379
|
+
const completion = finiteNonNegative(ctx['completion_tokens']);
|
|
380
|
+
if (prompt === undefined || completion === undefined || (prompt === 0 && completion === 0))
|
|
381
|
+
return null;
|
|
382
|
+
return {
|
|
383
|
+
sid,
|
|
384
|
+
ts,
|
|
385
|
+
prompt,
|
|
386
|
+
cached: Math.min(finiteNonNegative(ctx['cached_prompt_tokens']) ?? 0, prompt),
|
|
387
|
+
completion,
|
|
388
|
+
reasoning: Math.min(finiteNonNegative(ctx['reasoning_tokens']) ?? 0, completion),
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
let loggedSessions;
|
|
392
|
+
async function readLoggedSessionIds(path) {
|
|
393
|
+
const sids = new Set();
|
|
394
|
+
for await (const line of readSessionLines(path)) {
|
|
395
|
+
if (!line.includes('shell.turn.inference_done'))
|
|
396
|
+
continue;
|
|
397
|
+
try {
|
|
398
|
+
const usage = inferenceUsage(JSON.parse(line));
|
|
399
|
+
if (usage)
|
|
400
|
+
sids.add(usage.sid);
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return sids;
|
|
407
|
+
}
|
|
408
|
+
// Every session dir asks; read the log once per version of it.
|
|
409
|
+
async function loggedSessionIds(path) {
|
|
410
|
+
const st = await stat(path).catch(() => null);
|
|
411
|
+
if (!st)
|
|
412
|
+
return new Set();
|
|
413
|
+
const key = `${path}:${st.size}:${st.mtimeMs}`;
|
|
414
|
+
if (loggedSessions?.key !== key)
|
|
415
|
+
loggedSessions = { key, sids: readLoggedSessionIds(path) };
|
|
416
|
+
return loggedSessions.sids;
|
|
417
|
+
}
|
|
418
|
+
// createParser skips a session dir the log holds; its summary, tools and
|
|
419
|
+
// commands ride on that session's first logged call instead.
|
|
420
|
+
async function readSessionDirInfo(dir) {
|
|
421
|
+
const summary = dir ? await readJson(join(dir, 'summary.json')) : null;
|
|
422
|
+
const updates = dir ? await readSessionFile(join(dir, 'updates.jsonl')) : null;
|
|
423
|
+
const parsed = updates === null ? null : parseUpdates(updates);
|
|
424
|
+
return {
|
|
425
|
+
model: summary?.current_model_id,
|
|
426
|
+
cwd: summary?.info?.cwd,
|
|
427
|
+
userMessage: summary?.session_summary ?? summary?.generated_title ?? '',
|
|
428
|
+
tools: parsed?.tools ?? [],
|
|
429
|
+
bashCommands: parsed?.bashCommands ?? [],
|
|
430
|
+
subagentTypes: parsed?.subagentTypes ?? [],
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
function createUnifiedLogParser(source, seenKeys, sessionsDir) {
|
|
434
|
+
return {
|
|
435
|
+
async *parse() {
|
|
436
|
+
const models = new Map();
|
|
437
|
+
const pidModels = new Map();
|
|
438
|
+
const cwds = new Map();
|
|
439
|
+
const sessionDirs = new Map((await discoverSessions(sessionsDir)).map(s => [basename(dirname(s.path)), dirname(s.path)]));
|
|
440
|
+
const dirInfo = new Map();
|
|
441
|
+
for await (const line of readSessionLines(source.path)) {
|
|
442
|
+
let record;
|
|
443
|
+
try {
|
|
444
|
+
record = JSON.parse(line);
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
const sid = record.sid;
|
|
450
|
+
const ctx = record.ctx;
|
|
451
|
+
if (!isRecord(ctx))
|
|
452
|
+
continue;
|
|
453
|
+
// A process announces its model before a session that predates the log
|
|
454
|
+
// file's first line can name one.
|
|
455
|
+
if (record.msg === 'model catalog: notifying clients' && typeof ctx['current_model_id'] === 'string') {
|
|
456
|
+
pidModels.set(record.pid, ctx['current_model_id']);
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (typeof sid !== 'string' || !sid)
|
|
460
|
+
continue;
|
|
461
|
+
if (record.msg === 'model changed' && typeof ctx['model'] === 'string') {
|
|
462
|
+
models.set(sid, ctx['model']);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
if (record.msg === 'session created' && typeof ctx['cwd'] === 'string') {
|
|
466
|
+
cwds.set(sid, ctx['cwd']);
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
const usage = inferenceUsage(record);
|
|
470
|
+
if (!usage)
|
|
471
|
+
continue;
|
|
472
|
+
const { prompt, cached, completion, reasoning } = usage;
|
|
473
|
+
const deduplicationKey = `grok:unified:${sid}:${usage.ts}:${String(ctx['loop_index'] ?? 1)}`;
|
|
474
|
+
if (seenKeys.has(deduplicationKey))
|
|
475
|
+
continue;
|
|
476
|
+
seenKeys.add(deduplicationKey);
|
|
477
|
+
let info = dirInfo.get(sid);
|
|
478
|
+
const first = !info;
|
|
479
|
+
if (!info) {
|
|
480
|
+
info = await readSessionDirInfo(sessionDirs.get(sid));
|
|
481
|
+
dirInfo.set(sid, info);
|
|
482
|
+
}
|
|
483
|
+
const namedModel = models.get(sid) ?? pidModels.get(record.pid) ?? info.model;
|
|
484
|
+
const model = namedModel ?? 'grok-build';
|
|
485
|
+
const cwd = cwds.get(sid) ?? info.cwd;
|
|
486
|
+
yield {
|
|
487
|
+
provider: source.provider,
|
|
488
|
+
model,
|
|
489
|
+
inputTokens: prompt - cached,
|
|
490
|
+
outputTokens: completion - reasoning,
|
|
491
|
+
cacheCreationInputTokens: 0,
|
|
492
|
+
cacheReadInputTokens: cached,
|
|
493
|
+
cachedInputTokens: cached,
|
|
494
|
+
reasoningTokens: reasoning,
|
|
495
|
+
webSearchRequests: 0,
|
|
496
|
+
costUSD: calculateCost(model, prompt - cached, completion, 0, cached, 0),
|
|
497
|
+
costIsEstimated: namedModel === undefined,
|
|
498
|
+
tools: first ? info.tools : [],
|
|
499
|
+
bashCommands: first ? info.bashCommands : [],
|
|
500
|
+
subagentTypes: first ? info.subagentTypes : [],
|
|
501
|
+
timestamp: usage.ts,
|
|
502
|
+
speed: 'standard',
|
|
503
|
+
deduplicationKey,
|
|
504
|
+
userMessage: first ? info.userMessage : '',
|
|
505
|
+
sessionId: sid,
|
|
506
|
+
project: cwd ? basename(cwd) : source.project,
|
|
507
|
+
projectPath: cwd,
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
},
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
async function discoverSessions(sessionsDir) {
|
|
514
|
+
const sources = [];
|
|
515
|
+
let cwdDirs;
|
|
516
|
+
try {
|
|
517
|
+
cwdDirs = await readdir(sessionsDir);
|
|
518
|
+
}
|
|
519
|
+
catch {
|
|
520
|
+
return sources;
|
|
521
|
+
}
|
|
522
|
+
// Fanned out per level (the tree is one summary.json read per session); the
|
|
523
|
+
// per-level results are re-concatenated in readdir order so the emitted
|
|
524
|
+
// source order matches the serial walk exactly.
|
|
525
|
+
const cwds = (await mapWithConcurrency(cwdDirs, FS_SCAN_CONCURRENCY, async (cwdName) => {
|
|
526
|
+
const cwdPath = join(sessionsDir, cwdName);
|
|
527
|
+
const cwdStat = await stat(cwdPath).catch(() => null);
|
|
528
|
+
if (!cwdStat?.isDirectory())
|
|
529
|
+
return [];
|
|
530
|
+
const sessionDirs = await readdir(cwdPath).catch(() => null);
|
|
531
|
+
if (!sessionDirs)
|
|
532
|
+
return [];
|
|
533
|
+
return sessionDirs.map(sessionName => ({ cwdName, sessionPath: join(cwdPath, sessionName) }));
|
|
534
|
+
})).flat();
|
|
535
|
+
const sessions = await mapWithConcurrency(cwds, FS_SCAN_CONCURRENCY, async ({ cwdName, sessionPath }) => {
|
|
536
|
+
const sessionStat = await stat(sessionPath).catch(() => null);
|
|
537
|
+
if (!sessionStat?.isDirectory())
|
|
538
|
+
return null;
|
|
539
|
+
const summary = await readJson(join(sessionPath, 'summary.json'));
|
|
540
|
+
if (!summary)
|
|
541
|
+
return null;
|
|
542
|
+
const cwd = summary.info?.cwd ?? safeDecode(cwdName);
|
|
543
|
+
return { path: join(sessionPath, 'updates.jsonl'), project: basename(cwd), provider: 'grok' };
|
|
544
|
+
});
|
|
545
|
+
for (const source of sessions)
|
|
546
|
+
if (source)
|
|
547
|
+
sources.push(source);
|
|
548
|
+
return sources;
|
|
549
|
+
}
|
|
550
|
+
export function createGrokProvider(sessionsDir) {
|
|
551
|
+
const dir = sessionsDir ?? defaultSessionsDir();
|
|
552
|
+
const unifiedLogPath = join(dirname(dir), 'logs', 'unified.jsonl');
|
|
553
|
+
return {
|
|
554
|
+
name: 'grok',
|
|
555
|
+
displayName: 'Grok Build',
|
|
556
|
+
async probeRoots() {
|
|
557
|
+
return [{ path: dir, label: 'sessions' }, { path: unifiedLogPath, label: 'unified log' }];
|
|
558
|
+
},
|
|
559
|
+
modelDisplayName(model) {
|
|
560
|
+
if (model.startsWith('grok-build'))
|
|
561
|
+
return 'Grok Build';
|
|
562
|
+
return getShortModelName(model);
|
|
563
|
+
},
|
|
564
|
+
toolDisplayName(rawTool) {
|
|
565
|
+
return ownValue(toolNameMap, rawTool) ?? rawTool;
|
|
566
|
+
},
|
|
567
|
+
async discoverSessions() {
|
|
568
|
+
const sources = await discoverSessions(dir);
|
|
569
|
+
if (await stat(unifiedLogPath).catch(() => null)) {
|
|
570
|
+
sources.push({ path: unifiedLogPath, project: 'grok', provider: 'grok' });
|
|
571
|
+
}
|
|
572
|
+
return sources;
|
|
573
|
+
},
|
|
574
|
+
createSessionParser(source, seenKeys) {
|
|
575
|
+
if (source.path === unifiedLogPath)
|
|
576
|
+
return createUnifiedLogParser(source, seenKeys, dir);
|
|
577
|
+
return createParser(source, seenKeys, unifiedLogPath);
|
|
578
|
+
},
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
export const grok = createGrokProvider();
|