limitcast 0.19.1 → 0.19.3
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/bin/limitcast.mjs +38 -15
- package/package.json +1 -1
- package/src/capabilities.mjs +70 -8
- package/src/grok.mjs +35 -1
- package/src/guard.mjs +2 -2
- package/src/inflight.mjs +12 -4
- package/src/install.mjs +5 -2
- package/src/notify.mjs +1 -1
- package/src/optimize-cli.mjs +4 -2
- package/src/optimize.mjs +53 -6
- package/src/prices.mjs +2 -1
- package/src/repomap.mjs +5 -3
- package/src/report.mjs +2 -1
- package/src/results.mjs +5 -3
- package/src/subagents.mjs +7 -4
- package/src/usage.mjs +20 -4
package/bin/limitcast.mjs
CHANGED
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
applyGrokTrim,
|
|
34
34
|
getGrokBudget,
|
|
35
35
|
grokConfigPath,
|
|
36
|
+
grokHistory,
|
|
36
37
|
grokPresent,
|
|
37
38
|
grokQuotaDue,
|
|
38
39
|
grokQuotaEnabled,
|
|
@@ -119,7 +120,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
119
120
|
limitcast optimize status inspect repository evidence, proposals and optimization receipts
|
|
120
121
|
limitcast optimize learn on|off learn safe check-command alternatives; three independent sessions to promote
|
|
121
122
|
limitcast optimize map [on|off] show a bounded source-symbol map or opt into session-start injection
|
|
122
|
-
limitcast optimize capabilities --codex
|
|
123
|
+
limitcast optimize capabilities [--codex|--grok] preview unused tools (Claude), built-in packages and MCP servers (Codex), MCP servers (Grok); --apply <names> / --undo
|
|
123
124
|
limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
|
|
124
125
|
[--share] totals only, safe to post
|
|
125
126
|
limitcast license show the MIT license status
|
|
@@ -157,7 +158,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
157
158
|
and when your Claude limit itself changes
|
|
158
159
|
limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
|
|
159
160
|
limitcast notify webhook <url>|off also send them to a Slack or Discord webhook
|
|
160
|
-
limitcast after-reset [--src claude|codex] [--window 5h|7d] [--detach] -- <command>
|
|
161
|
+
limitcast after-reset [--src claude|codex|grok] [--window 5h|7d] [--detach] -- <command>
|
|
161
162
|
run a heavy job once the window has reset
|
|
162
163
|
limitcast results --html [--out FILE] results, current windows and the burn report as one page
|
|
163
164
|
limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
|
|
@@ -246,7 +247,8 @@ if (cmd === '_optimize-hook') {
|
|
|
246
247
|
feed = JSON.parse(input);
|
|
247
248
|
sid = feed?.session_id;
|
|
248
249
|
record(claudeSamples(feed, now));
|
|
249
|
-
|
|
250
|
+
// Grok runs the same status-line command. Its feed gets its own file, so `doctor`'s Claude checks only see Claude feeds.
|
|
251
|
+
saveFeedShape(feed, grokSessionLine(feed) ? 'last-feed-grok.json' : 'last-feed.json');
|
|
250
252
|
// Readings are kept 8 days; the daily rollup folds what they showed into the long-term value record.
|
|
251
253
|
if (dailyDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'rollup'], { detached: true, stdio: 'ignore' }).unref();
|
|
252
254
|
const health = healthHint();
|
|
@@ -468,7 +470,16 @@ if (cmd === '_optimize-hook') {
|
|
|
468
470
|
// Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
|
|
469
471
|
try {
|
|
470
472
|
const hook = JSON.parse(readStdin());
|
|
471
|
-
|
|
473
|
+
// Claude Code and Codex send snake_case; Grok sends `sessionId` and `subagentType`. Every host clears the duplicate hold;
|
|
474
|
+
// only Claude transcripts are priced below (a Codex or Grok transcript yields no calls, so nothing is logged for them).
|
|
475
|
+
saveInflight(
|
|
476
|
+
forgetInflight(
|
|
477
|
+
loadInflight(),
|
|
478
|
+
String(hook?.session_id ?? hook?.sessionId ?? ''),
|
|
479
|
+
String(hook?.agent_type ?? hook?.subagentType ?? hook?.agentType ?? ''),
|
|
480
|
+
now,
|
|
481
|
+
),
|
|
482
|
+
);
|
|
472
483
|
const path = hook?.agent_transcript_path;
|
|
473
484
|
if (hook?.agent_type && typeof path === 'string') {
|
|
474
485
|
const u = subagentUsage(path);
|
|
@@ -898,7 +909,7 @@ if (cmd === '_optimize-hook') {
|
|
|
898
909
|
// Once a week, what limitcast did: shown to the user at session start, never to the model.
|
|
899
910
|
if (weeklyDue(now)) {
|
|
900
911
|
const since = now - 7 * 86400_000;
|
|
901
|
-
const samples = [...load(since), ...(await readCodex(since))];
|
|
912
|
+
const samples = [...load(since), ...(await readCodex(since)), ...grokHistory(since, now)];
|
|
902
913
|
const s = loadOverhead();
|
|
903
914
|
// The daily rollup keeps the value record current; a session-start hook must not scan transcripts itself.
|
|
904
915
|
const week = valuePeriod(loadValue(), since, now);
|
|
@@ -939,7 +950,7 @@ if (cmd === '_optimize-hook') {
|
|
|
939
950
|
? savedSummary(s, 0).split('\n')[0] // the per-session drop; the value section above has the totals
|
|
940
951
|
: 'Run `limitcast trim` once to record your starting context, then check back here.';
|
|
941
952
|
}
|
|
942
|
-
const samples = [...load(since), ...(await readCodex(since))];
|
|
953
|
+
const samples = [...load(since), ...(await readCodex(since)), ...grokHistory(since, now)];
|
|
943
954
|
const blocks = loadBlocks(since);
|
|
944
955
|
const usage = await readUsage(Math.min(since - days() * 86400_000, now - KEEP_MS), {}); // one read feeds both below
|
|
945
956
|
const value = await refreshValue(usage);
|
|
@@ -958,7 +969,7 @@ if (cmd === '_optimize-hook') {
|
|
|
958
969
|
);
|
|
959
970
|
else if (args.includes('--html')) {
|
|
960
971
|
// results, the current windows and the burn report on one page, opened in the browser.
|
|
961
|
-
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
|
|
972
|
+
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS)), ...grokSamples(now)]), now);
|
|
962
973
|
const burn = burnReport(
|
|
963
974
|
usage.filter((u) => u.t >= since),
|
|
964
975
|
{ since, now },
|
|
@@ -1051,15 +1062,21 @@ if (cmd === '_optimize-hook') {
|
|
|
1051
1062
|
const sep = args.indexOf('--');
|
|
1052
1063
|
const command = sep >= 0 ? args.slice(sep + 1) : [];
|
|
1053
1064
|
const src = flag('--src') ?? 'claude';
|
|
1054
|
-
const win = flag('--window') ?? '5h';
|
|
1055
1065
|
if (!command.length) {
|
|
1056
|
-
console.log('Usage: limitcast after-reset [--src claude|codex] [--window 5h|7d] [--detach] -- <command...>');
|
|
1066
|
+
console.log('Usage: limitcast after-reset [--src claude|codex|grok] [--window 5h|7d] [--detach] -- <command...>');
|
|
1057
1067
|
process.exit(1);
|
|
1058
1068
|
}
|
|
1059
|
-
const samples = src === 'codex' ? await readCodex(now - KEEP_MS) : oneClaudeAccount(load(now - KEEP_MS));
|
|
1060
|
-
const
|
|
1069
|
+
const samples = src === 'codex' ? await readCodex(now - KEEP_MS) : src === 'grok' ? grokSamples(now) : oneClaudeAccount(load(now - KEEP_MS));
|
|
1070
|
+
const rows = forecastAll(samples, now).filter((x) => x.src === src);
|
|
1071
|
+
// Without --window, use the shortest window this tool reports: a Codex plan may report only a 7-day window.
|
|
1072
|
+
const f = flag('--window') ? rows.find((x) => x.win === flag('--window')) : (rows.find((x) => x.win === '5h') ?? rows.find((x) => x.win === '7d'));
|
|
1073
|
+
const win = f?.win ?? flag('--window') ?? '5h';
|
|
1061
1074
|
if (!f) {
|
|
1062
|
-
console.log(
|
|
1075
|
+
console.log(
|
|
1076
|
+
src === 'grok'
|
|
1077
|
+
? 'No grok readings yet, so the reset time is unknown. Set a dollar cap first: limitcast budget grok <usd>'
|
|
1078
|
+
: `No ${src} ${win} readings yet, so the reset time is unknown.`,
|
|
1079
|
+
);
|
|
1063
1080
|
process.exit(1);
|
|
1064
1081
|
}
|
|
1065
1082
|
const at = resetTarget(f, now);
|
|
@@ -1154,7 +1171,12 @@ async function refreshValue(preread) {
|
|
|
1154
1171
|
const o = loadOverhead();
|
|
1155
1172
|
// limitcast started watching at its first status-line reading (or first measurement), not when Codex's logs begin.
|
|
1156
1173
|
const start = Math.min(now, o?.first.at ?? now, ...claude.map((s) => s.t));
|
|
1157
|
-
const v = foldEvents(loadValue(), {
|
|
1174
|
+
const v = foldEvents(loadValue(), {
|
|
1175
|
+
now,
|
|
1176
|
+
samples: [...claude, ...(await readCodex(since)), ...grokHistory(since, now)],
|
|
1177
|
+
blocks: loadBlocks(since),
|
|
1178
|
+
start,
|
|
1179
|
+
});
|
|
1158
1180
|
await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
|
|
1159
1181
|
// Recalibrate from the last 8 days when there is enough data; keep the last good calibration otherwise.
|
|
1160
1182
|
const usage = preread ? preread.filter((u) => u.t >= since) : await readUsage(since, {});
|
|
@@ -1235,10 +1257,11 @@ function undoMessage(e) {
|
|
|
1235
1257
|
/**
|
|
1236
1258
|
* Keep the latest feed's structure (key names and rate_limits only, no prompt or path content) for diagnosing parsing.
|
|
1237
1259
|
* @param {any} feed
|
|
1260
|
+
* @param {string} [file]
|
|
1238
1261
|
*/
|
|
1239
|
-
function saveFeedShape(feed) {
|
|
1262
|
+
function saveFeedShape(feed, file = 'last-feed.json') {
|
|
1240
1263
|
const shape = { at: now, keys: Object.keys(feed ?? {}), session_id: feed?.session_id, rate_limits: feed?.rate_limits };
|
|
1241
|
-
writeFileSync(join(stateDir(),
|
|
1264
|
+
writeFileSync(join(stateDir(), file), JSON.stringify(shape, null, 2));
|
|
1242
1265
|
}
|
|
1243
1266
|
|
|
1244
1267
|
function readStdin() {
|
package/package.json
CHANGED
package/src/capabilities.mjs
CHANGED
|
@@ -1,11 +1,40 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
2
|
import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
|
|
3
3
|
import { dirname, join, relative, sep } from 'node:path';
|
|
4
|
+
import { codexConfigPath, codexServers } from './codex.mjs';
|
|
5
|
+
import { grokServers } from './grok.mjs';
|
|
4
6
|
import { capabilityProposals, changeOptimization, digest, readOptimization, saveOptimization } from './optimize.mjs';
|
|
5
7
|
import { writeAtomic } from './store.mjs';
|
|
6
8
|
|
|
7
9
|
const KEYS = { collaboration: ['multi_agent'], goals: ['goals'], image_media: ['view_image'] };
|
|
8
|
-
const
|
|
10
|
+
const CONFIG = { claude: '.claude/settings.local.json', codex: '.codex/config.toml', grok: '.grok/config.toml' };
|
|
11
|
+
const configPath = (repo, host) => join(repo.root, CONFIG[host]);
|
|
12
|
+
|
|
13
|
+
/** The MCP servers a host has configured in its own user-level config, which a project file can switch off. */
|
|
14
|
+
export function configuredServers(host) {
|
|
15
|
+
try {
|
|
16
|
+
if (host === 'codex') return existsSync(codexConfigPath()) ? codexServers(readFileSync(codexConfigPath(), 'utf8')) : [];
|
|
17
|
+
if (host === 'grok') return grokServers();
|
|
18
|
+
} catch {
|
|
19
|
+
/* an unreadable configuration proposes nothing */
|
|
20
|
+
}
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Add `[mcp_servers.<name>] enabled = false` tables to a project config.toml. The user-level definition (command, env)
|
|
26
|
+
* stays where it is: the project table only overrides `enabled`. Refuses a server the file already configures.
|
|
27
|
+
*/
|
|
28
|
+
export function patchMcpServers(text, names) {
|
|
29
|
+
const existing = codexServers(text);
|
|
30
|
+
for (const name of names) {
|
|
31
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) throw new Error(`unsupported MCP server name ${name}`);
|
|
32
|
+
if (existing.some((s) => s.name === name)) throw new Error(`preserve explicit ${name} server setting; change it yourself`);
|
|
33
|
+
}
|
|
34
|
+
const tables = names.map((name) => `[mcp_servers.${name}]\nenabled = false # limitcast optimizer`).join('\n\n');
|
|
35
|
+
const body = text.trimEnd();
|
|
36
|
+
return `${body ? `${body}\n\n` : ''}${tables}\n`;
|
|
37
|
+
}
|
|
9
38
|
|
|
10
39
|
function safePath(repo, file) {
|
|
11
40
|
for (let path = file; path !== repo.root; path = dirname(path)) {
|
|
@@ -38,27 +67,55 @@ export function validateCodex(repo, disabled = []) {
|
|
|
38
67
|
// `features list` ignores -C on Codex 0.167; its actual cwd decides which project config is loaded.
|
|
39
68
|
const output = execFileSync('codex', ['features', 'list'], { cwd: repo.root, encoding: 'utf8', timeout: 5000, maxBuffer: 100_000 });
|
|
40
69
|
for (const key of Object.values(KEYS).flat()) {
|
|
41
|
-
|
|
70
|
+
// Codex 0.169 lists multi_agent as "deprecated" yet still honors it; a "removed" key has no control to switch.
|
|
71
|
+
if (!new RegExp(`^${key}\\s+(?:stable|experimental|under development|deprecated)\\s+(?:true|false)$`, 'm').test(output))
|
|
42
72
|
throw new Error(`Codex does not expose supported ${key} control`);
|
|
43
73
|
}
|
|
44
74
|
for (const key of disabled.flatMap((name) => KEYS[name] ?? [])) {
|
|
45
75
|
if (!new RegExp(`^${key}\\s+.*\\s+false$`, 'm').test(output)) throw new Error(`Codex ignored the project ${key} setting; check project trust`);
|
|
46
76
|
}
|
|
77
|
+
const servers = disabled.filter((name) => !Object.hasOwn(KEYS, name));
|
|
78
|
+
if (servers.length) checkServersOff('codex', repo, servers, 'Codex');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Grok: the effective MCP server list, read from the real project directory, must show each named server off. */
|
|
82
|
+
export function validateGrok(repo, disabled = []) {
|
|
83
|
+
if (disabled.length) checkServersOff('grok', repo, disabled, 'Grok');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** `<host> mcp list --json` reports the settings the host actually loads, so an untrusted project that ignores the file shows up here. */
|
|
87
|
+
function checkServersOff(command, repo, names, label) {
|
|
88
|
+
const list = JSON.parse(
|
|
89
|
+
execFileSync(command, ['mcp', 'list', '--json'], { cwd: repo.root, encoding: 'utf8', timeout: 10_000, maxBuffer: 1_000_000 }),
|
|
90
|
+
);
|
|
91
|
+
if (!Array.isArray(list)) throw new Error(`${label} returned an unexpected MCP server list`);
|
|
92
|
+
for (const name of names) {
|
|
93
|
+
if (list.find((s) => s?.name === name)?.enabled !== false)
|
|
94
|
+
throw new Error(`${label} ignored the project setting for ${name}; check project trust`);
|
|
95
|
+
}
|
|
47
96
|
}
|
|
48
97
|
|
|
49
|
-
export function applyCapabilities(repo, host, names, { validate = validateCodex } = {}) {
|
|
50
|
-
if (!['claude', 'codex'].includes(host) || !names.length)
|
|
98
|
+
export function applyCapabilities(repo, host, names, { validate = host === 'grok' ? validateGrok : validateCodex } = {}) {
|
|
99
|
+
if (!['claude', 'codex', 'grok'].includes(host) || !names.length)
|
|
100
|
+
throw new Error('choose proposed Claude tools, or Codex or Grok capabilities and MCP servers');
|
|
51
101
|
const file = configPath(repo, host);
|
|
52
102
|
safePath(repo, file);
|
|
53
103
|
if (host === 'codex') validate(repo);
|
|
104
|
+
const servers = configuredServers(host);
|
|
54
105
|
const result = changeOptimization(repo, (state) => {
|
|
55
|
-
const proposal = capabilityProposals(state, host);
|
|
106
|
+
const proposal = capabilityProposals(state, host, servers);
|
|
56
107
|
if (names.some((n) => !proposal.includes(n))) throw new Error('selection is protected, used, or lacks evidence; preview again');
|
|
57
108
|
if (state.applied?.[host]) throw new Error('restore the previous capability change before applying another');
|
|
58
109
|
if (existsSync(file) && statSync(file).size > 100_000) throw new Error('project configuration exceeds safe editing limit');
|
|
59
110
|
const before = existsSync(file) ? readFileSync(file, 'utf8') : null;
|
|
60
111
|
let after;
|
|
61
|
-
if (host === 'codex')
|
|
112
|
+
if (host === 'codex') {
|
|
113
|
+
const features = names.filter((n) => Object.hasOwn(KEYS, n));
|
|
114
|
+
const mcp = names.filter((n) => !Object.hasOwn(KEYS, n));
|
|
115
|
+
after = before ?? '';
|
|
116
|
+
if (features.length) after = patchCodexCapabilities(after, features);
|
|
117
|
+
if (mcp.length) after = patchMcpServers(after, mcp);
|
|
118
|
+
} else if (host === 'grok') after = patchMcpServers(before ?? '', names);
|
|
62
119
|
else {
|
|
63
120
|
const cfg = JSON.parse(before ?? '{}');
|
|
64
121
|
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw new Error('settings must be an object');
|
|
@@ -89,7 +146,7 @@ export function applyCapabilities(repo, host, names, { validate = validateCodex
|
|
|
89
146
|
return { path: file, names, restart: true };
|
|
90
147
|
});
|
|
91
148
|
try {
|
|
92
|
-
if (host === 'codex') validate(repo, names);
|
|
149
|
+
if (host === 'codex' || host === 'grok') validate(repo, names);
|
|
93
150
|
} catch (error) {
|
|
94
151
|
restoreCapabilities(repo, host, { protect: false });
|
|
95
152
|
throw error;
|
|
@@ -121,5 +178,10 @@ export function restoreCapabilities(repo, host, { protect = true } = {}) {
|
|
|
121
178
|
export function capabilityStatus(repo, host) {
|
|
122
179
|
const state = readOptimization(repo);
|
|
123
180
|
if (host === 'codex') validateCodex(repo);
|
|
124
|
-
return {
|
|
181
|
+
return {
|
|
182
|
+
host,
|
|
183
|
+
proposed: capabilityProposals(state, host, configuredServers(host)),
|
|
184
|
+
applied: state.applied?.[host]?.names ?? [],
|
|
185
|
+
keep: state.config.keep,
|
|
186
|
+
};
|
|
125
187
|
}
|
package/src/grok.mjs
CHANGED
|
@@ -462,6 +462,38 @@ export function grokSamples(now, { root = grokRoot(), budget = getGrokBudget() }
|
|
|
462
462
|
return out;
|
|
463
463
|
}
|
|
464
464
|
|
|
465
|
+
/**
|
|
466
|
+
* Past Grok window readings for `results` and the value rollup: for every 5-hour and 7-day window since `since`,
|
|
467
|
+
* the running spend against the user's dollar cap, one reading per turn. `grokSamples` only builds the current
|
|
468
|
+
* window, which left every earlier Grok block without readings and made `results` invent its outcome.
|
|
469
|
+
* Real weekly readings (`grok-usage on`) replace a 7-day cap, as in `grokSamples`.
|
|
470
|
+
* @param {number} since epoch ms
|
|
471
|
+
* @param {number} now epoch ms
|
|
472
|
+
* @param {{root?:string, budget?:ReturnType<typeof getGrokBudget>}} [opts]
|
|
473
|
+
* @returns {Sample[]}
|
|
474
|
+
*/
|
|
475
|
+
export function grokHistory(since, now, { root = grokRoot(), budget = getGrokBudget() } = {}) {
|
|
476
|
+
const quota = grokQuotaSamples(now).filter((s) => s.t >= since);
|
|
477
|
+
if (!budget) return quota;
|
|
478
|
+
const turns = grokCosts(root, since);
|
|
479
|
+
/** @type {Sample[]} */
|
|
480
|
+
const out = [...quota];
|
|
481
|
+
for (const win of /** @type {const} */ (['5h', '7d'])) {
|
|
482
|
+
const cap = budget[win];
|
|
483
|
+
if (!(cap > 0) || (win === '7d' && quota.length)) continue;
|
|
484
|
+
const len = windowMs(win);
|
|
485
|
+
for (let start = alignedStart(since, win); start <= now; start += len) {
|
|
486
|
+
let spent = 0;
|
|
487
|
+
for (const t of turns) {
|
|
488
|
+
if (t.t < start || t.t >= start + len || t.t > now) continue;
|
|
489
|
+
spent += t.usd;
|
|
490
|
+
out.push({ t: t.t, src: 'grok', win, pct: Math.min(100, (spent / cap) * 100), reset: (start + len) / 1000 });
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return out;
|
|
495
|
+
}
|
|
496
|
+
|
|
465
497
|
/**
|
|
466
498
|
* Wire Grok's status line and, with `guard`, a PreToolUse hook on `spawn_subagent`.
|
|
467
499
|
* @param {{guard:boolean, self:string, home?:string}} opts
|
|
@@ -495,13 +527,15 @@ export function installGrok({ guard, self, home = grokHome() }) {
|
|
|
495
527
|
{
|
|
496
528
|
hooks: {
|
|
497
529
|
PreToolUse: [{ matcher: 'spawn_subagent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] }],
|
|
530
|
+
// A subagent's stop clears the duplicate-spawn hold (the payload carries `subagentType`, not `agent_type`).
|
|
531
|
+
SubagentStop: [{ hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }],
|
|
498
532
|
},
|
|
499
533
|
},
|
|
500
534
|
null,
|
|
501
535
|
2,
|
|
502
536
|
)}\n`,
|
|
503
537
|
);
|
|
504
|
-
changes.push('added the Grok subagent guard (matcher spawn_subagent)');
|
|
538
|
+
changes.push('added the Grok subagent guard (matcher spawn_subagent) and its subagent-stop hook');
|
|
505
539
|
}
|
|
506
540
|
return changes;
|
|
507
541
|
}
|
package/src/guard.mjs
CHANGED
|
@@ -46,7 +46,7 @@ export function guardDecision(tool, forecasts, now, minutes) {
|
|
|
46
46
|
if (!f || f.wall === null) return null;
|
|
47
47
|
const left = Math.max(0, Math.round((f.wall - now) / 60_000));
|
|
48
48
|
return (
|
|
49
|
-
`limitcast: ${NAMES[/** @type {'claude'} */ (f.src)]} ${f.win} limit is ${f.pct}% used and on pace to run out in ~${left} min, before it resets. ` +
|
|
49
|
+
`limitcast: ${NAMES[/** @type {'claude'} */ (f.src)]} ${f.win} limit is ${Math.round(f.pct)}% used and on pace to run out in ~${left} min, before it resets. ` +
|
|
50
50
|
'Finish with the agents already running, or set LIMITCAST_ALLOW=1 to spawn anyway.'
|
|
51
51
|
);
|
|
52
52
|
}
|
|
@@ -161,7 +161,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
161
161
|
const input = hook?.tool_input ?? hook?.toolInput;
|
|
162
162
|
const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
|
|
163
163
|
const type = String(input?.subagent_type ?? input?.subagentType ?? '');
|
|
164
|
-
const pinned = isUnset(input?.model) && type ? pinnedModel(type) : undefined;
|
|
164
|
+
const pinned = isUnset(input?.model) && type && src ? pinnedModel(type, src) : undefined;
|
|
165
165
|
if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation);
|
|
166
166
|
if (src !== 'claude') return null;
|
|
167
167
|
const model = pinned ?? input?.model;
|
package/src/inflight.mjs
CHANGED
|
@@ -6,8 +6,8 @@ import { spawnSource } from './guard.mjs';
|
|
|
6
6
|
import { stateDir } from './store.mjs';
|
|
7
7
|
|
|
8
8
|
// A second spawn of the same type and prompt, in the same session, while the first has not finished.
|
|
9
|
-
// SubagentStop clears
|
|
10
|
-
// 30 minutes is forgotten: a missed stop must not hold the same prompt for the rest of the day.
|
|
9
|
+
// SubagentStop clears it on all three hosts (Claude Code, Codex and Grok each send one). A record older than
|
|
10
|
+
// 30 minutes is forgotten anyway: a missed stop must not hold the same prompt for the rest of the day.
|
|
11
11
|
|
|
12
12
|
export const INFLIGHT_MS = 30 * 60_000;
|
|
13
13
|
|
|
@@ -23,8 +23,12 @@ export function spawnIdentity(hook) {
|
|
|
23
23
|
const src = spawnSource(tool);
|
|
24
24
|
if (!src) return null;
|
|
25
25
|
const input = hook?.tool_input ?? hook?.toolInput ?? {};
|
|
26
|
+
// Grok re-runs a finished subagent with resume_from: the same prompt again is a continuation, not a duplicate.
|
|
27
|
+
if (input?.resume_from || input?.resumeFrom) return null;
|
|
26
28
|
const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '').trim();
|
|
27
|
-
|
|
29
|
+
// Claude and Grok send `prompt`; Codex spawn_agent sends `message` (or `items`, a list of text parts).
|
|
30
|
+
const items = Array.isArray(input?.items) ? input.items.map((x) => (typeof x === 'string' ? x : (x?.text ?? ''))).join(' ') : '';
|
|
31
|
+
const prompt = String(input?.prompt || input?.message || input?.description || input?.task || items || '')
|
|
28
32
|
.replace(/\s+/g, ' ')
|
|
29
33
|
.trim();
|
|
30
34
|
const sid = String(hook?.session_id ?? hook?.sessionId ?? '').trim();
|
|
@@ -67,7 +71,11 @@ export function rememberInflight(entries, id, now) {
|
|
|
67
71
|
export function forgetInflight(entries, sid, type, now) {
|
|
68
72
|
const live = pruneInflight(entries, now);
|
|
69
73
|
if (!sid || !type) return live;
|
|
70
|
-
const
|
|
74
|
+
const same = (/** @type {Inflight} */ e) => e.type.toLowerCase() === type.toLowerCase();
|
|
75
|
+
// Some hosts report the subagent's own session on its stop event. Match the parent session first, else the type alone:
|
|
76
|
+
// clearing the wrong record only lets a duplicate through, which is the safe way to be wrong.
|
|
77
|
+
let i = live.findIndex((e) => e.sid === sid && same(e));
|
|
78
|
+
if (i < 0) i = live.findIndex(same);
|
|
71
79
|
if (i >= 0) live.splice(i, 1);
|
|
72
80
|
return live;
|
|
73
81
|
}
|
package/src/install.mjs
CHANGED
|
@@ -137,8 +137,10 @@ export function install({
|
|
|
137
137
|
const codex = readSettings(codexPath);
|
|
138
138
|
backup(codexPath);
|
|
139
139
|
upsertGuard(codex, { matcher: CODEX_MATCHER, hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] });
|
|
140
|
+
// A subagent's stop clears the duplicate-spawn hold; without it a finished spawn blocks its own retry for 30 minutes.
|
|
141
|
+
upsertHook(codex, 'SubagentStop', { matcher: '', hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }, isReceipt);
|
|
140
142
|
writeSettings(codexPath, codex);
|
|
141
|
-
changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new
|
|
143
|
+
changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new hooks)');
|
|
142
144
|
}
|
|
143
145
|
if (grokPresent(grokDir)) changes.push(...installGrok({ guard, self, home: grokDir }));
|
|
144
146
|
if (optimize && existsSync(join(codexPath, '..'))) {
|
|
@@ -239,9 +241,10 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(),
|
|
|
239
241
|
if (existsSync(codexPath)) {
|
|
240
242
|
const codex = readSettings(codexPath);
|
|
241
243
|
const list = codex.hooks?.PreToolUse ?? [];
|
|
242
|
-
if (list.some(isGuard) || Object.values(codex.hooks ?? {}).some((entries) => entries.some(isOptimizer))) {
|
|
244
|
+
if (list.some(isGuard) || Object.values(codex.hooks ?? {}).some((entries) => entries.some((h) => isOptimizer(h) || isReceipt(h)))) {
|
|
243
245
|
backup(codexPath);
|
|
244
246
|
codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h));
|
|
247
|
+
if (codex.hooks.SubagentStop) codex.hooks.SubagentStop = codex.hooks.SubagentStop.filter((/** @type {any} */ h) => !isReceipt(h));
|
|
245
248
|
removeOptimizerHooks(codex);
|
|
246
249
|
writeSettings(codexPath, codex);
|
|
247
250
|
changes.push('removed the Codex subagent guard');
|
package/src/notify.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { stateDir } from './store.mjs';
|
|
|
10
10
|
const flag = () => join(stateDir(), 'notify.on');
|
|
11
11
|
const stateFile = () => join(stateDir(), 'notified.json');
|
|
12
12
|
const RANK = { OK: 0, RESET: 0, NEAR: 1, AT_RISK: 2, HIT: 3 };
|
|
13
|
-
const NAMES = { claude: 'Claude', codex: 'Codex' };
|
|
13
|
+
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
14
14
|
|
|
15
15
|
export const notifyEnabled = () => existsSync(flag());
|
|
16
16
|
|
package/src/optimize-cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { closeSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
|
|
2
|
-
import { applyCapabilities, capabilityStatus, restoreCapabilities } from './capabilities.mjs';
|
|
2
|
+
import { applyCapabilities, capabilityStatus, configuredServers, restoreCapabilities } from './capabilities.mjs';
|
|
3
3
|
import { reserveModelJob, startModelWorker } from './model-optimize.mjs';
|
|
4
4
|
import { capabilityProposals, changeOptimization, HOSTS, normalizeEvent, processEvent, readOptimization, repository } from './optimize.mjs';
|
|
5
5
|
import { installOptimizerHost } from './optimizer-hosts.mjs';
|
|
@@ -121,7 +121,9 @@ export function runOptimize(args, cwd = process.cwd()) {
|
|
|
121
121
|
return {
|
|
122
122
|
config: state.config,
|
|
123
123
|
facts: state.facts.length,
|
|
124
|
-
hosts: Object.fromEntries(
|
|
124
|
+
hosts: Object.fromEntries(
|
|
125
|
+
HOSTS.map((h) => [h, { completedSessions: state.hosts[h]?.completed ?? 0, proposed: capabilityProposals(state, h, configuredServers(h)) }]),
|
|
126
|
+
),
|
|
125
127
|
receipts: state.receipts,
|
|
126
128
|
applied: Object.fromEntries(Object.entries(state.applied ?? {}).map(([h, a]) => [h, a.names])),
|
|
127
129
|
};
|
package/src/optimize.mjs
CHANGED
|
@@ -14,6 +14,22 @@ const CAPABILITIES = {
|
|
|
14
14
|
image_media: /view_image|imagegen|image_generation|generatedImage|emitImage/,
|
|
15
15
|
};
|
|
16
16
|
const validTool = (name) => typeof name === 'string' && /^[\w:.-]{1,100}$/.test(name) && !Object.hasOwn(Object.prototype, name);
|
|
17
|
+
/** The tool catalog a session can declare, per host. Claude sessions with many connectors declare a few hundred tools. */
|
|
18
|
+
const CATALOG_LIMIT = 400;
|
|
19
|
+
export const normServer = (name) =>
|
|
20
|
+
String(name)
|
|
21
|
+
.toLowerCase()
|
|
22
|
+
.replace(/[^a-z0-9]/g, '_');
|
|
23
|
+
/**
|
|
24
|
+
* The MCP server a tool call belongs to, by the name each host reports: Codex `mcp__<server>__<tool>`, Grok `<server>__<tool>`.
|
|
25
|
+
* Claude's own `mcp__<server>__<tool>` names are pruned per tool, not per server.
|
|
26
|
+
*/
|
|
27
|
+
export function serverOf(host, tool) {
|
|
28
|
+
if (typeof tool !== 'string') return undefined;
|
|
29
|
+
if (host === 'codex') return tool.startsWith('mcp__') ? tool.split('__')[1] : undefined;
|
|
30
|
+
if (host === 'grok') return tool.includes('__') ? tool.split('__')[0] : undefined;
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
17
33
|
|
|
18
34
|
export function repository(cwd = process.cwd()) {
|
|
19
35
|
const root = realpathSync(execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 2000 }).trim());
|
|
@@ -71,6 +87,12 @@ export function commandShape(command) {
|
|
|
71
87
|
return null;
|
|
72
88
|
}
|
|
73
89
|
|
|
90
|
+
function checkIdentity(command) {
|
|
91
|
+
return commandShape(command)
|
|
92
|
+
?.replace(/^(?:python3?|\.venv\/bin\/python3?) -m (pytest|unittest)$/, '$1')
|
|
93
|
+
.replace(/^npm run test$/, 'npm test');
|
|
94
|
+
}
|
|
95
|
+
|
|
74
96
|
function responseText(value) {
|
|
75
97
|
if (typeof value === 'string') return value.slice(0, 16000);
|
|
76
98
|
if (!value || typeof value !== 'object') return '';
|
|
@@ -192,7 +214,7 @@ export function normalizeEvent(hook, host) {
|
|
|
192
214
|
? hook.tools
|
|
193
215
|
.map((t) => (typeof t === 'string' ? t : t?.name))
|
|
194
216
|
.filter(validTool)
|
|
195
|
-
.slice(0,
|
|
217
|
+
.slice(0, CATALOG_LIMIT)
|
|
196
218
|
: [],
|
|
197
219
|
};
|
|
198
220
|
}
|
|
@@ -219,7 +241,7 @@ function learn(state, session, e) {
|
|
|
219
241
|
if (!e.succeeded) return;
|
|
220
242
|
for (const from of session.failed ?? []) {
|
|
221
243
|
if (from === e.command) continue;
|
|
222
|
-
if (
|
|
244
|
+
if (checkIdentity(from) !== checkIdentity(e.command)) continue;
|
|
223
245
|
let fact = state.facts.find((f) => f.from === from && f.to === e.command);
|
|
224
246
|
if (!fact) {
|
|
225
247
|
fact = { id: digest(`${from}\0${e.command}`).slice(0, 16), from, to: e.command, state: 'candidate', sessions: [] };
|
|
@@ -236,7 +258,7 @@ function learn(state, session, e) {
|
|
|
236
258
|
export function learnedContext(state) {
|
|
237
259
|
if (!state.config.learn) return '';
|
|
238
260
|
return state.facts
|
|
239
|
-
.filter((f) => f.state === 'active' && commandShape(f.to) && (f.kind === 'check' ||
|
|
261
|
+
.filter((f) => f.state === 'active' && commandShape(f.to) && (f.kind === 'check' || checkIdentity(f.from) === checkIdentity(f.to)))
|
|
240
262
|
.slice(0, 4)
|
|
241
263
|
.map((f) =>
|
|
242
264
|
f.kind === 'check'
|
|
@@ -255,6 +277,7 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
255
277
|
prompts: 0,
|
|
256
278
|
used: [],
|
|
257
279
|
usedTools: [],
|
|
280
|
+
usedServers: [],
|
|
258
281
|
catalog: {},
|
|
259
282
|
productive: [],
|
|
260
283
|
});
|
|
@@ -268,8 +291,11 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
268
291
|
};
|
|
269
292
|
host.used = [...new Set([...host.used, ...e.capabilities])];
|
|
270
293
|
if (validTool(e.name) && host.usedTools.length < 200) host.usedTools = [...new Set([...host.usedTools, e.name])];
|
|
294
|
+
// Servers are tracked on their own: a used server must stay protected after the 200-name tool list fills up.
|
|
295
|
+
const server = serverOf(e.host, e.name);
|
|
296
|
+
if (server && (host.usedServers ??= []).length < 200) host.usedServers = [...new Set([...host.usedServers, normServer(server)])];
|
|
271
297
|
for (const tool of e.tools) {
|
|
272
|
-
if (Object.keys(host.catalog).length <
|
|
298
|
+
if (Object.keys(host.catalog).length < CATALOG_LIMIT) host.catalog[tool] ??= { used: host.usedTools.includes(tool), sessions: [] };
|
|
273
299
|
}
|
|
274
300
|
if (Object.hasOwn(host.catalog, e.name)) host.catalog[e.name].used = true;
|
|
275
301
|
if (e.event === 'SessionStart' || (e.host === 'grok' && /^PostToolUse(?:Failure)?$/.test(e.event) && !session.injected)) {
|
|
@@ -384,11 +410,32 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
384
410
|
return {};
|
|
385
411
|
}
|
|
386
412
|
|
|
387
|
-
|
|
413
|
+
/**
|
|
414
|
+
* What `optimize capabilities` can propose to switch off in this repository, from the evidence of its own sessions.
|
|
415
|
+
* Claude: declared tools never used. Codex: three built-in packages, plus configured MCP servers never called.
|
|
416
|
+
* Grok: configured MCP servers never called (Grok has no persistent setting that removes a built-in tool).
|
|
417
|
+
* Every host needs five completed sessions and ten prompts first, and a keep-list entry always protects a name.
|
|
418
|
+
* @param {any} state
|
|
419
|
+
* @param {string} host
|
|
420
|
+
* @param {{name:string, enabled?:boolean}[]} [servers] the MCP servers the host has configured (from its config.toml)
|
|
421
|
+
*/
|
|
422
|
+
export function capabilityProposals(state, host, servers = []) {
|
|
388
423
|
const h = state.hosts[host];
|
|
389
424
|
if (!h || h.completed < 5 || h.prompts < 10) return [];
|
|
390
425
|
const keep = state.config.keep ?? [];
|
|
391
|
-
|
|
426
|
+
const idleServers = () => {
|
|
427
|
+
const used = new Set([
|
|
428
|
+
...(h.usedServers ?? []),
|
|
429
|
+
...h.usedTools
|
|
430
|
+
.map((t) => serverOf(host, t))
|
|
431
|
+
.filter(Boolean)
|
|
432
|
+
.map(normServer),
|
|
433
|
+
]);
|
|
434
|
+
const kept = new Set(keep.map(normServer));
|
|
435
|
+
return servers.filter((s) => s.enabled !== false && !used.has(normServer(s.name)) && !kept.has(normServer(s.name))).map((s) => s.name);
|
|
436
|
+
};
|
|
437
|
+
if (host === 'codex') return [...Object.keys(CAPABILITIES).filter((c) => !h.used.includes(c) && !keep.includes(c)), ...idleServers()];
|
|
438
|
+
if (host === 'grok') return idleServers();
|
|
392
439
|
if (host === 'claude')
|
|
393
440
|
return Object.entries(h.catalog)
|
|
394
441
|
.filter(([n, t]) => !CORE_TOOLS.test(n) && !t.used && t.sessions.length >= 5 && !keep.includes(n))
|
package/src/prices.mjs
CHANGED
|
@@ -63,10 +63,11 @@ export function priceFor(model, table) {
|
|
|
63
63
|
|
|
64
64
|
/**
|
|
65
65
|
* API-equivalent dollars of one model call, or null when its model has no price.
|
|
66
|
-
* @param {{model?:string, input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number}} u
|
|
66
|
+
* @param {{model?:string, input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number, costUsd?:number}} u
|
|
67
67
|
* @param {Record<string, Price>} [table]
|
|
68
68
|
*/
|
|
69
69
|
export function callCost(u, table = priceTable()) {
|
|
70
|
+
if (typeof u.costUsd === 'number' && Number.isFinite(u.costUsd)) return u.costUsd; // the tool's own record of this usage
|
|
70
71
|
const base = priceFor(u.model, table);
|
|
71
72
|
if (!base) return null;
|
|
72
73
|
const p = base.over && u.input + u.cacheWrite + u.cacheRead > base.over.above ? { ...base, ...base.over } : base;
|
package/src/repomap.mjs
CHANGED
|
@@ -16,7 +16,7 @@ export function repositoryMap(repo, { refresh = false, maxChars = 6000 } = {}) {
|
|
|
16
16
|
const path = join(stateDir(), 'optimize', `${repo.id}.map.json`);
|
|
17
17
|
if (!refresh && !dirty && existsSync(path)) {
|
|
18
18
|
const cached = JSON.parse(readFileSync(path, 'utf8'));
|
|
19
|
-
if (cached.head === head && cached.budget === maxChars) return cached.text;
|
|
19
|
+
if (cached.version === 2 && cached.head === head && cached.budget === maxChars) return cached.text;
|
|
20
20
|
}
|
|
21
21
|
const files = git('ls-files', '-z')
|
|
22
22
|
.split('\0')
|
|
@@ -47,7 +47,9 @@ export function repositoryMap(repo, { refresh = false, maxChars = 6000 } = {}) {
|
|
|
47
47
|
const line = `${row.name}${row.symbols.length ? `: ${row.symbols.join(', ')}` : ''}\n`;
|
|
48
48
|
if (text.length + line.length <= maxChars) text += line;
|
|
49
49
|
}
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
if (!dirty) {
|
|
51
|
+
mkdirSync(join(stateDir(), 'optimize'), { recursive: true, mode: 0o700 });
|
|
52
|
+
writeAtomic(path, JSON.stringify({ version: 2, head, budget: maxChars, fingerprint: digest(text), text }));
|
|
53
|
+
}
|
|
52
54
|
return text;
|
|
53
55
|
}
|
package/src/report.mjs
CHANGED
|
@@ -85,7 +85,8 @@ export function burnReport(usage, { since, now }) {
|
|
|
85
85
|
table(
|
|
86
86
|
lines,
|
|
87
87
|
'Heaviest sessions',
|
|
88
|
-
|
|
88
|
+
// Codex and Grok ids are UUIDv7: their first characters are a timestamp, so sessions started close together share them.
|
|
89
|
+
group(usage, (u) => `${u.src} ${u.session.slice(-8)} · ${short(u.project)}`),
|
|
89
90
|
fresh,
|
|
90
91
|
allFresh,
|
|
91
92
|
true,
|
package/src/results.mjs
CHANGED
|
@@ -289,9 +289,11 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
|
|
|
289
289
|
o.outcome === 'hit'
|
|
290
290
|
? `reached 100% at ${when(/** @type {number} */ (o.hitAt))}`
|
|
291
291
|
: o.outcome === 'under'
|
|
292
|
-
? `reset at ${o.peak}%`
|
|
293
|
-
: `now at ${o.peak}%, resets ${when(o.reset)}`;
|
|
294
|
-
out.push(
|
|
292
|
+
? `reset at ${Math.round(o.peak)}%`
|
|
293
|
+
: `now at ${Math.round(o.peak)}%, resets ${when(o.reset)}`;
|
|
294
|
+
out.push(
|
|
295
|
+
`- ${when(o.t)}: ${name(o)} at ${Math.round(o.pct)}%, forecast out in ~${Math.max(0, Math.round((o.wall - o.t) / 60_000))} min; ${what}`,
|
|
296
|
+
);
|
|
295
297
|
}
|
|
296
298
|
}
|
|
297
299
|
if (st.switches)
|
package/src/subagents.mjs
CHANGED
|
@@ -143,14 +143,17 @@ export const validModel = (/** @type {unknown} */ m) => typeof m === 'string' &&
|
|
|
143
143
|
|
|
144
144
|
/**
|
|
145
145
|
* The pinned model for a subagent type, matching the stored name case-insensitively (Claude "Explore" vs Grok "explore").
|
|
146
|
+
* With a host, only a model that host can run is returned: Grok takes grok-... ids, Claude takes everything else,
|
|
147
|
+
* so `subagent-model explore grok-4.3` never rewrites a Claude `Explore` spawn.
|
|
146
148
|
* @param {unknown} type
|
|
149
|
+
* @param {'claude'|'codex'|'grok'} [host]
|
|
147
150
|
*/
|
|
148
|
-
export function pinnedModel(type) {
|
|
151
|
+
export function pinnedModel(type, host) {
|
|
149
152
|
if (typeof type !== 'string' || !type) return undefined;
|
|
150
|
-
const
|
|
151
|
-
|
|
153
|
+
const fits = (/** @type {string} */ m) => (host === 'grok' ? /^grok-/i.test(m) : host === 'claude' ? !/^grok-/i.test(m) : host === undefined);
|
|
154
|
+
const models = Object.entries(getSubagentModels()).filter(([, m]) => fits(m));
|
|
152
155
|
const want = type.toLowerCase();
|
|
153
|
-
return
|
|
156
|
+
return (models.find(([t]) => t === type) ?? models.find(([t]) => t.toLowerCase() === want))?.[1];
|
|
154
157
|
}
|
|
155
158
|
|
|
156
159
|
/** @returns {Record<string, string>} the model each subagent type runs on by default, e.g. {Explore: 'haiku'} */
|
package/src/usage.mjs
CHANGED
|
@@ -8,8 +8,9 @@ import { stateDir, writeAtomic } from './store.mjs';
|
|
|
8
8
|
/**
|
|
9
9
|
* One model response's token usage.
|
|
10
10
|
* @typedef {{t:number, src:'claude'|'codex'|'grok', session:string, project:string, model:string, sidechain:boolean,
|
|
11
|
-
* input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number, entry?:string}} Usage
|
|
12
|
-
* entry: how Claude Code was launched (cli, sdk-py, ...); cacheWrite1h: the part of cacheWrite that used the 1-hour cache
|
|
11
|
+
* input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number, entry?:string, costUsd?:number}} Usage
|
|
12
|
+
* entry: how Claude Code was launched (cli, sdk-py, ...); cacheWrite1h: the part of cacheWrite that used the 1-hour cache;
|
|
13
|
+
* costUsd: dollars the tool itself recorded for this record (Grok's costUsdTicks), preferred over re-pricing it
|
|
13
14
|
*/
|
|
14
15
|
|
|
15
16
|
export const claudeRoot = () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'projects');
|
|
@@ -134,7 +135,22 @@ export function grokUsage(ledger, session, project) {
|
|
|
134
135
|
const input = Math.max(0, (turn.inputTokens ?? 0) - cacheRead - cacheWrite);
|
|
135
136
|
const output = turn.outputTokens ?? 0;
|
|
136
137
|
const model = turn.primaryModelId ?? Object.keys(turn.modelUsage ?? {})[0] ?? '';
|
|
137
|
-
|
|
138
|
+
// A Grok record is a whole turn (up to dozens of model calls). Re-pricing its summed tokens would apply the
|
|
139
|
+
// above-200k long-context tier to the turn, overstating cost by about 1.8x, so carry Grok's own recorded cost.
|
|
140
|
+
const ticks = Number(turn.costUsdTicks);
|
|
141
|
+
out.push({
|
|
142
|
+
t,
|
|
143
|
+
src: 'grok',
|
|
144
|
+
session,
|
|
145
|
+
project,
|
|
146
|
+
model,
|
|
147
|
+
sidechain: false,
|
|
148
|
+
input,
|
|
149
|
+
cacheWrite,
|
|
150
|
+
cacheRead,
|
|
151
|
+
output,
|
|
152
|
+
...(Number.isFinite(ticks) && ticks >= 0 ? { costUsd: ticks / 1e10 } : {}),
|
|
153
|
+
});
|
|
138
154
|
}
|
|
139
155
|
return out;
|
|
140
156
|
}
|
|
@@ -237,7 +253,7 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
237
253
|
}
|
|
238
254
|
|
|
239
255
|
const CACHE_KEEP_MS = 35 * 86400_000;
|
|
240
|
-
const USAGE_CACHE_VERSION =
|
|
256
|
+
const USAGE_CACHE_VERSION = 3; // 3: Grok records carry costUsd; 2: records carry cacheWrite1h. An older cache is read again
|
|
241
257
|
const usageCacheFile = () => join(stateDir(), 'usage-cache.json');
|
|
242
258
|
|
|
243
259
|
/** @returns {Record<string, {s:number, m:number, u:Usage[], a?:{skills:string[], mcp:string[]}}>} */
|