limitcast 0.19.2 → 0.19.4
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 +187 -45
- package/package.json +1 -1
- package/src/capabilities.mjs +84 -9
- package/src/codex-trust.mjs +85 -0
- package/src/codex.mjs +45 -13
- package/src/grok.mjs +107 -37
- package/src/guard.mjs +10 -4
- package/src/inflight.mjs +18 -5
- package/src/install.mjs +42 -4
- package/src/notify.mjs +18 -1
- package/src/optimize-cli.mjs +4 -2
- package/src/optimize.mjs +45 -4
- package/src/overhead.mjs +39 -13
- package/src/prices.mjs +11 -3
- package/src/receipts.mjs +188 -0
- package/src/report.mjs +11 -1
- package/src/results.mjs +26 -6
- package/src/subagents.mjs +42 -8
- package/src/toolcheck.mjs +50 -8
- package/src/toollimit.mjs +57 -4
- package/src/usage.mjs +71 -12
- package/src/value.mjs +13 -1
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());
|
|
@@ -198,7 +214,7 @@ export function normalizeEvent(hook, host) {
|
|
|
198
214
|
? hook.tools
|
|
199
215
|
.map((t) => (typeof t === 'string' ? t : t?.name))
|
|
200
216
|
.filter(validTool)
|
|
201
|
-
.slice(0,
|
|
217
|
+
.slice(0, CATALOG_LIMIT)
|
|
202
218
|
: [],
|
|
203
219
|
};
|
|
204
220
|
}
|
|
@@ -261,6 +277,7 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
261
277
|
prompts: 0,
|
|
262
278
|
used: [],
|
|
263
279
|
usedTools: [],
|
|
280
|
+
usedServers: [],
|
|
264
281
|
catalog: {},
|
|
265
282
|
productive: [],
|
|
266
283
|
});
|
|
@@ -274,8 +291,11 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
274
291
|
};
|
|
275
292
|
host.used = [...new Set([...host.used, ...e.capabilities])];
|
|
276
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)])];
|
|
277
297
|
for (const tool of e.tools) {
|
|
278
|
-
if (Object.keys(host.catalog).length <
|
|
298
|
+
if (Object.keys(host.catalog).length < CATALOG_LIMIT) host.catalog[tool] ??= { used: host.usedTools.includes(tool), sessions: [] };
|
|
279
299
|
}
|
|
280
300
|
if (Object.hasOwn(host.catalog, e.name)) host.catalog[e.name].used = true;
|
|
281
301
|
if (e.event === 'SessionStart' || (e.host === 'grok' && /^PostToolUse(?:Failure)?$/.test(e.event) && !session.injected)) {
|
|
@@ -390,11 +410,32 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
390
410
|
return {};
|
|
391
411
|
}
|
|
392
412
|
|
|
393
|
-
|
|
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 = []) {
|
|
394
423
|
const h = state.hosts[host];
|
|
395
424
|
if (!h || h.completed < 5 || h.prompts < 10) return [];
|
|
396
425
|
const keep = state.config.keep ?? [];
|
|
397
|
-
|
|
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();
|
|
398
439
|
if (host === 'claude')
|
|
399
440
|
return Object.entries(h.catalog)
|
|
400
441
|
.filter(([n, t]) => !CORE_TOOLS.test(n) && !t.used && t.sessions.length >= 5 && !keep.includes(n))
|
package/src/overhead.mjs
CHANGED
|
@@ -30,53 +30,79 @@ export function drift(prev, cur) {
|
|
|
30
30
|
return { delta: cur.chars - prev.chars, grew, alert: cur.chars - prev.chars >= ALERT_CHARS || grew.length > 0 };
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
/** Claude Code's record is overhead.json (`saved` and `results` read it); Codex and Grok keep their own beside it. @param {string} [host] */
|
|
34
|
+
const file = (host = 'claude') => join(stateDir(), host === 'claude' ? 'overhead.json' : `overhead-${host}.json`);
|
|
34
35
|
|
|
35
|
-
/**
|
|
36
|
-
|
|
36
|
+
/**
|
|
37
|
+
* Codex and Grok sessions have no transcript of pieces, so their starting context is the few sizes their logs hold.
|
|
38
|
+
* @param {'codex'|'grok'} host
|
|
39
|
+
* @param {{at?:number, agentsMd:number, base?:number, prompt?:number, tools?:number}} s sizes in characters
|
|
40
|
+
* @returns {Snapshot}
|
|
41
|
+
*/
|
|
42
|
+
export function hostSnapshot(host, s) {
|
|
43
|
+
/** @type {Record<string, number>} */
|
|
44
|
+
const items =
|
|
45
|
+
host === 'codex'
|
|
46
|
+
? { 'Instruction files|AGENTS.md': s.agentsMd, "Codex|Codex's own instructions": s.base ?? 0 }
|
|
47
|
+
: { 'Instruction files|AGENTS.md': s.agentsMd, 'Grok|system prompt': s.prompt ?? 0, 'Grok|tool definitions': s.tools ?? 0 };
|
|
48
|
+
return { at: s.at ?? 0, chars: Object.values(items).reduce((a, c) => a + c, 0), items };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {string} [host]
|
|
53
|
+
* @returns {{first:Snapshot, last:Snapshot}|null}
|
|
54
|
+
*/
|
|
55
|
+
export function loadOverhead(host = 'claude') {
|
|
37
56
|
try {
|
|
38
|
-
return JSON.parse(readFileSync(file(), 'utf8'));
|
|
57
|
+
return JSON.parse(readFileSync(file(host), 'utf8'));
|
|
39
58
|
} catch {
|
|
40
59
|
return null;
|
|
41
60
|
}
|
|
42
61
|
}
|
|
43
62
|
|
|
44
|
-
/**
|
|
45
|
-
|
|
63
|
+
/**
|
|
64
|
+
* @param {{first:Snapshot, last:Snapshot}} s
|
|
65
|
+
* @param {string} [host]
|
|
66
|
+
*/
|
|
67
|
+
export function saveOverhead(s, host = 'claude') {
|
|
46
68
|
mkdirSync(stateDir(), { recursive: true });
|
|
47
|
-
writeFileSync(file(), JSON.stringify(s));
|
|
69
|
+
writeFileSync(file(host), JSON.stringify(s));
|
|
48
70
|
}
|
|
49
71
|
|
|
50
72
|
/**
|
|
51
73
|
* Record `cur` and return what changed since the last recorded session (null the first time).
|
|
52
74
|
* A snapshot of the same session as last time changes nothing.
|
|
53
75
|
* @param {Snapshot} cur
|
|
76
|
+
* @param {string} [host]
|
|
54
77
|
*/
|
|
55
|
-
export function recordOverhead(cur) {
|
|
56
|
-
const s = existsSync(file()) ? loadOverhead() : null;
|
|
78
|
+
export function recordOverhead(cur, host = 'claude') {
|
|
79
|
+
const s = existsSync(file(host)) ? loadOverhead(host) : null;
|
|
57
80
|
if (!s) {
|
|
58
|
-
saveOverhead({ first: cur, last: cur });
|
|
81
|
+
saveOverhead({ first: cur, last: cur }, host);
|
|
59
82
|
return null;
|
|
60
83
|
}
|
|
61
84
|
if (cur.at === s.last.at) return { delta: 0, grew: [], alert: false };
|
|
62
85
|
const d = drift(s.last, cur);
|
|
63
|
-
saveOverhead({ first: s.first, last: cur });
|
|
86
|
+
saveOverhead({ first: s.first, last: cur }, host);
|
|
64
87
|
return d;
|
|
65
88
|
}
|
|
66
89
|
|
|
67
90
|
const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
68
91
|
const label = (/** @type {string} */ key) => key.replace('|', ': ').replace(/\/Users\/[^/]+/, '~');
|
|
92
|
+
const NAMES = /** @type {Record<string, string>} */ ({ claude: 'Claude Code', codex: 'Codex', grok: 'Grok' });
|
|
69
93
|
|
|
70
94
|
/**
|
|
71
95
|
* One-line alert for the user (never the model) when starting context grew.
|
|
72
96
|
* @param {ReturnType<typeof drift>} d
|
|
97
|
+
* @param {string} [host]
|
|
73
98
|
*/
|
|
74
|
-
export function driftMessage(d) {
|
|
99
|
+
export function driftMessage(d, host = 'claude') {
|
|
75
100
|
const items = d.grew
|
|
76
101
|
.slice(0, 3)
|
|
77
102
|
.map((g) => `${label(g.key)} ${g.isNew ? 'new' : '+'}~${(tok(g.delta) / 1000).toFixed(1)}k`)
|
|
78
103
|
.join(', ');
|
|
79
|
-
|
|
104
|
+
const more = host === 'claude' ? ' Run `limitcast trim` for details.' : ` Run \`limitcast trim --${host}\` for details.`;
|
|
105
|
+
return `limitcast: your ${NAMES[host] ?? host} starting context grew ~${(tok(d.delta) / 1000).toFixed(1)}k tokens since your last session${items ? ` (${items})` : ''}.${more}`;
|
|
80
106
|
}
|
|
81
107
|
|
|
82
108
|
/**
|
package/src/prices.mjs
CHANGED
|
@@ -4,13 +4,15 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { stateDir } from './store.mjs';
|
|
5
5
|
|
|
6
6
|
// What your tokens would cost at the API's list prices ("API-equivalent cost"). A subscription is not billed this way:
|
|
7
|
-
// it is a yardstick for what the plan covers. Claude and
|
|
7
|
+
// it is a yardstick for what the plan covers. Claude, Grok and the OpenAI models Codex runs; any other model is left out,
|
|
8
|
+
// never priced at 0.
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* USD per million tokens. input/output: base prices; readX: cache read as a multiple of input; over: the prices that
|
|
11
12
|
* apply to a call whose whole prompt is above `above` tokens. Cache writes default to 1.25x input (5 minutes) or 2x
|
|
12
13
|
* (1 hour) for Claude; Grok sets writeX 1 (xAI lists cached input, not a write multiplier).
|
|
13
|
-
* Sources: platform.claude.com/docs/en/about-claude/pricing and docs.x.ai/developers/models, read 2026-10-26
|
|
14
|
+
* Sources: platform.claude.com/docs/en/about-claude/pricing and docs.x.ai/developers/models, read 2026-10-26 (xAI rows checked
|
|
15
|
+
* again 2026-11-13 against docs.x.ai/developers/pricing); developers.openai.com/api/docs/pricing, read 2026-11-13.
|
|
14
16
|
* Override or add models in ~/.local/state/limitcast/prices.json:
|
|
15
17
|
* {"models": {"claude-opus-4-1": {"input": 15, "output": 75, "readX": 0.1}}}.
|
|
16
18
|
* @typedef {{input:number, output:number, readX:number, writeX?:number, write1hX?:number, over?:{above:number, input:number, output:number, readX?:number}}} Price
|
|
@@ -28,6 +30,11 @@ export const PRICES = {
|
|
|
28
30
|
'grok-4.3': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
|
|
29
31
|
'grok-4.20': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
|
|
30
32
|
'grok-build-0.1': { input: 1, output: 2, readX: 0.2, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2, output: 4 } },
|
|
33
|
+
// OpenAI (Codex): cached input is listed in $/1M and a Codex log records no cache writes. Above 272k prompt tokens the whole
|
|
34
|
+
// request bills 2x input and cache rates and 1.5x output. gpt-5.6-sol's price is promotional until 2026-11-30.
|
|
35
|
+
// `codex-auto-review` is a routing alias OpenAI lists no price for, so it stays unpriced.
|
|
36
|
+
'gpt-6.1-sol': { input: 2, output: 10, readX: 0.05, over: { above: 272_000, input: 4, output: 15 } },
|
|
37
|
+
'gpt-5.6-sol': { input: 4, output: 20, readX: 0.1, over: { above: 272_000, input: 8, output: 30 } },
|
|
31
38
|
};
|
|
32
39
|
|
|
33
40
|
const WRITE_5M = 1.25;
|
|
@@ -63,10 +70,11 @@ export function priceFor(model, table) {
|
|
|
63
70
|
|
|
64
71
|
/**
|
|
65
72
|
* 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
|
|
73
|
+
* @param {{model?:string, input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number, costUsd?:number}} u
|
|
67
74
|
* @param {Record<string, Price>} [table]
|
|
68
75
|
*/
|
|
69
76
|
export function callCost(u, table = priceTable()) {
|
|
77
|
+
if (typeof u.costUsd === 'number' && Number.isFinite(u.costUsd)) return u.costUsd; // the tool's own record of this usage
|
|
70
78
|
const base = priceFor(u.model, table);
|
|
71
79
|
if (!base) return null;
|
|
72
80
|
const p = base.over && u.input + u.cacheWrite + u.cacheRead > base.over.above ? { ...base, ...base.over } : base;
|
package/src/receipts.mjs
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { costOf } from './prices.mjs';
|
|
6
|
+
import { stateDir, writeAtomic } from './store.mjs';
|
|
7
|
+
import { logSubagent } from './subagents.mjs';
|
|
8
|
+
import { codexUsage, grokRoot, grokUsage } from './usage.mjs';
|
|
9
|
+
|
|
10
|
+
// What a finished Codex or Grok subagent used, for the SubagentStop receipt. Claude's receipt is priced from its own
|
|
11
|
+
// transcript in subagents.mjs; the other two hosts keep usage elsewhere (a Codex rollout, a Grok session ledger).
|
|
12
|
+
|
|
13
|
+
/** @typedef {{calls:number, fresh:number, read:number, usd:number|null}} HostUsage */
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Which tool sent a SubagentStop payload. Grok writes camelCase fields; Codex and Claude write snake_case, and tell
|
|
17
|
+
* apart by `turn_id` (Codex sends one, Claude Code does not; seen in a live run) or where the transcript lives. A Codex
|
|
18
|
+
* home that is not ~/.codex has no `.codex` in its paths, which is why the payload shape is checked first.
|
|
19
|
+
* @param {any} hook
|
|
20
|
+
* @returns {'claude'|'codex'|'grok'}
|
|
21
|
+
*/
|
|
22
|
+
export function stopHost(hook) {
|
|
23
|
+
const path = String(hook?.agent_transcript_path ?? hook?.transcriptPath ?? hook?.transcript_path ?? '');
|
|
24
|
+
if (hook?.sessionId !== undefined || hook?.subagentType !== undefined || hook?.transcriptPath !== undefined) return 'grok';
|
|
25
|
+
if (hook?.turn_id !== undefined || path.includes('/.codex/') || /\/rollout-[^/]*\.jsonl$/.test(path)) return 'codex';
|
|
26
|
+
if (path.includes('/.grok/')) return 'grok';
|
|
27
|
+
return 'claude';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @param {import('./usage.mjs').Usage[]} usages @returns {HostUsage} */
|
|
31
|
+
function summarize(usages) {
|
|
32
|
+
const cost = costOf(usages);
|
|
33
|
+
return {
|
|
34
|
+
calls: usages.length,
|
|
35
|
+
fresh: usages.reduce((a, u) => a + u.input + u.cacheWrite + u.output, 0),
|
|
36
|
+
read: usages.reduce((a, u) => a + u.cacheRead, 0),
|
|
37
|
+
// A partial dollar figure would read as the whole, so say nothing when any of the tokens had no price.
|
|
38
|
+
usd: usages.length && cost.unpriced === 0 ? cost.total : null,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A Codex subagent's rollout: its token_count events carry running totals, so each model call is the increase over the last.
|
|
44
|
+
* @param {string} path
|
|
45
|
+
* @returns {HostUsage}
|
|
46
|
+
*/
|
|
47
|
+
export function codexSubagentUsage(path) {
|
|
48
|
+
const file = path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
|
|
49
|
+
const st = { prev: null, cwd: '', model: '' };
|
|
50
|
+
/** @type {import('./usage.mjs').Usage[]} */
|
|
51
|
+
const usages = [];
|
|
52
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
53
|
+
const u = codexUsage(line, st, '');
|
|
54
|
+
if (u) usages.push(u);
|
|
55
|
+
}
|
|
56
|
+
return summarize(usages);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A Grok child session is a session of its own: its summary says so, and its usage.json is the ledger. @param {string} dir */
|
|
60
|
+
function subagentLedger(dir) {
|
|
61
|
+
try {
|
|
62
|
+
const kind = JSON.parse(readFileSync(join(dir, 'summary.json'), 'utf8'))?.session_kind;
|
|
63
|
+
if (kind !== 'subagent') return null;
|
|
64
|
+
return JSON.parse(readFileSync(join(dir, 'usage.json'), 'utf8'));
|
|
65
|
+
} catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A Grok subagent's session ledger. The hook names the subagent and a transcript; either one leads to the child
|
|
72
|
+
* session directory <root>/<project>/<child id>/. A directory that is not a subagent session (the parent's) is never used.
|
|
73
|
+
* @param {any} hook
|
|
74
|
+
* @param {string} [root]
|
|
75
|
+
* @returns {HostUsage|null}
|
|
76
|
+
*/
|
|
77
|
+
export function grokSubagentUsage(hook, root = grokRoot()) {
|
|
78
|
+
const ids = [hook?.subagentId, hook?.subagent_id, hook?.agent_id, hook?.sessionId, hook?.session_id].filter((s) => typeof s === 'string' && s);
|
|
79
|
+
const transcript = hook?.transcriptPath ?? hook?.transcript_path;
|
|
80
|
+
const dirs = typeof transcript === 'string' ? [dirname(transcript)] : [];
|
|
81
|
+
try {
|
|
82
|
+
if (existsSync(root)) {
|
|
83
|
+
for (const proj of readdirSync(root, { withFileTypes: true })) {
|
|
84
|
+
if (proj.isDirectory()) for (const id of ids) dirs.push(join(root, proj.name, id));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
/* an unreadable root: no receipt */
|
|
89
|
+
}
|
|
90
|
+
for (const dir of dirs) {
|
|
91
|
+
const ledger = subagentLedger(dir);
|
|
92
|
+
if (ledger) {
|
|
93
|
+
const usages = grokUsage(ledger, '', '');
|
|
94
|
+
if (usages.length) return { ...summarize(usages), calls: Number(ledger?.session?.modelCalls) || usages.length };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Grok writes a subagent's usage after its stop hook has run (measured live: the hook fired 1.6 s before usage.json
|
|
101
|
+
// appeared), so the receipt cannot be priced at the stop. It is parked and settled by the next limitcast hook.
|
|
102
|
+
const pendingFile = () => join(stateDir(), 'pending-receipts.json');
|
|
103
|
+
const PENDING_MAX_MS = 24 * 3600_000;
|
|
104
|
+
|
|
105
|
+
/** @returns {{t:number, type:string, hook:any}[]} */
|
|
106
|
+
function loadPending() {
|
|
107
|
+
try {
|
|
108
|
+
const list = JSON.parse(readFileSync(pendingFile(), 'utf8'));
|
|
109
|
+
return Array.isArray(list) ? list : [];
|
|
110
|
+
} catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Park a Grok subagent's receipt until its ledger exists.
|
|
117
|
+
* @param {number} now
|
|
118
|
+
* @param {string} type
|
|
119
|
+
* @param {any} hook the SubagentStop payload
|
|
120
|
+
*/
|
|
121
|
+
export function deferReceipt(now, type, hook) {
|
|
122
|
+
const keep = (({ subagentId, sessionId, transcriptPath, session_id }) => ({ subagentId, sessionId: sessionId ?? session_id, transcriptPath }))(
|
|
123
|
+
hook ?? {},
|
|
124
|
+
);
|
|
125
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
126
|
+
writeAtomic(
|
|
127
|
+
pendingFile(),
|
|
128
|
+
JSON.stringify([
|
|
129
|
+
...loadPending()
|
|
130
|
+
.filter((p) => now - p.t < PENDING_MAX_MS)
|
|
131
|
+
.slice(-49),
|
|
132
|
+
{ t: now, type, hook: keep },
|
|
133
|
+
]),
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Log the parked receipts whose ledgers exist now; drop the ones that never appeared. Cheap when nothing is parked.
|
|
139
|
+
* @param {number} now
|
|
140
|
+
* @param {string} [root] Grok sessions root
|
|
141
|
+
* @returns {number} how many were logged
|
|
142
|
+
*/
|
|
143
|
+
export function settleReceipts(now, root = grokRoot()) {
|
|
144
|
+
if (!existsSync(pendingFile())) return 0;
|
|
145
|
+
const left = [];
|
|
146
|
+
let settled = 0;
|
|
147
|
+
for (const p of loadPending()) {
|
|
148
|
+
const usage = grokSubagentUsage(p.hook, root);
|
|
149
|
+
if (usage?.calls) {
|
|
150
|
+
logSubagent({
|
|
151
|
+
t: p.t,
|
|
152
|
+
src: 'grok',
|
|
153
|
+
id: p.hook?.subagentId,
|
|
154
|
+
sid: p.hook?.sessionId,
|
|
155
|
+
type: p.type,
|
|
156
|
+
calls: usage.calls,
|
|
157
|
+
fresh: usage.fresh,
|
|
158
|
+
read: usage.read,
|
|
159
|
+
...(usage.usd === null ? {} : { usd: usage.usd }),
|
|
160
|
+
});
|
|
161
|
+
settled++;
|
|
162
|
+
} else if (now - p.t < PENDING_MAX_MS) left.push(p);
|
|
163
|
+
}
|
|
164
|
+
if (settled || left.length !== loadPending().length) writeAtomic(pendingFile(), JSON.stringify(left));
|
|
165
|
+
return settled;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Usage of the subagent a SubagentStop payload describes, or null when this host's transcript cannot be read.
|
|
170
|
+
* @param {any} hook
|
|
171
|
+
* @returns {{src:'codex'|'grok', usage:HostUsage}|null}
|
|
172
|
+
*/
|
|
173
|
+
export function hostSubagentUsage(hook) {
|
|
174
|
+
const src = stopHost(hook);
|
|
175
|
+
try {
|
|
176
|
+
if (src === 'codex') {
|
|
177
|
+
const path = hook?.agent_transcript_path;
|
|
178
|
+
return typeof path === 'string' ? { src, usage: codexSubagentUsage(path) } : null;
|
|
179
|
+
}
|
|
180
|
+
if (src === 'grok') {
|
|
181
|
+
const usage = grokSubagentUsage(hook);
|
|
182
|
+
return usage ? { src, usage } : null;
|
|
183
|
+
}
|
|
184
|
+
} catch {
|
|
185
|
+
/* an unreadable transcript: no receipt */
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
package/src/report.mjs
CHANGED
|
@@ -45,6 +45,15 @@ export function burnReport(usage, { since, now }) {
|
|
|
45
45
|
const side = sum(claude.filter((u) => u.sidechain));
|
|
46
46
|
lines.push('', `Subagents used **${pct(side, sum(claude))}** of Claude tokens.`);
|
|
47
47
|
}
|
|
48
|
+
// Codex and Grok run a subagent as a thread of its own; its usage counts under the session that spawned it.
|
|
49
|
+
for (const [src, name] of /** @type {const} */ ([
|
|
50
|
+
['codex', 'Codex'],
|
|
51
|
+
['grok', 'Grok'],
|
|
52
|
+
])) {
|
|
53
|
+
const own = usage.filter((u) => u.src === src);
|
|
54
|
+
const side = sum(own.filter((u) => u.sidechain));
|
|
55
|
+
if (side) lines.push('', `Subagents used **${pct(side, sum(own))}** of ${name} tokens.`);
|
|
56
|
+
}
|
|
48
57
|
|
|
49
58
|
table(
|
|
50
59
|
lines,
|
|
@@ -85,7 +94,8 @@ export function burnReport(usage, { since, now }) {
|
|
|
85
94
|
table(
|
|
86
95
|
lines,
|
|
87
96
|
'Heaviest sessions',
|
|
88
|
-
|
|
97
|
+
// Codex and Grok ids are UUIDv7: their first characters are a timestamp, so sessions started close together share them.
|
|
98
|
+
group(usage, (u) => `${u.src} ${u.session.slice(-8)} · ${short(u.project)}`),
|
|
89
99
|
fresh,
|
|
90
100
|
allFresh,
|
|
91
101
|
true,
|
package/src/results.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { claudeAccounts, forecast } from './forecast.mjs';
|
|
5
|
+
import { fmtUsd } from './prices.mjs';
|
|
5
6
|
import { stateDir } from './store.mjs';
|
|
6
7
|
|
|
7
8
|
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
@@ -289,9 +290,11 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
|
|
|
289
290
|
o.outcome === 'hit'
|
|
290
291
|
? `reached 100% at ${when(/** @type {number} */ (o.hitAt))}`
|
|
291
292
|
: o.outcome === 'under'
|
|
292
|
-
? `reset at ${o.peak}%`
|
|
293
|
-
: `now at ${o.peak}%, resets ${when(o.reset)}`;
|
|
294
|
-
out.push(
|
|
293
|
+
? `reset at ${Math.round(o.peak)}%`
|
|
294
|
+
: `now at ${Math.round(o.peak)}%, resets ${when(o.reset)}`;
|
|
295
|
+
out.push(
|
|
296
|
+
`- ${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}`,
|
|
297
|
+
);
|
|
295
298
|
}
|
|
296
299
|
}
|
|
297
300
|
if (st.switches)
|
|
@@ -313,14 +316,31 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
|
|
|
313
316
|
const recent = subagents.filter((e) => e.t >= now - days * 86400_000);
|
|
314
317
|
if (recent.length || st.colds || st.coldNotices) {
|
|
315
318
|
out.push('', '## Subagents and cold caches');
|
|
316
|
-
const
|
|
317
|
-
|
|
319
|
+
const claude = recent.filter((e) => (e.src ?? 'claude') === 'claude');
|
|
320
|
+
const priced = claude.filter((e) => e.pct !== undefined).map((e) => /** @type {number} */ (e.pct));
|
|
321
|
+
const named = recent.length > claude.length; // name the tool only once another tool's subagents are listed too
|
|
322
|
+
if (claude.length)
|
|
318
323
|
out.push(
|
|
319
|
-
`${
|
|
324
|
+
`${claude.length} ${named ? 'Claude Code subagent' : 'subagent'}${claude.length === 1 ? '' : 's'} finished` +
|
|
320
325
|
(priced.length
|
|
321
326
|
? `, ≈${pctText(priced.reduce((a, b) => a + b, 0))} of a 5-hour window in all; the biggest ≈${pctText(Math.max(...priced))}.${pro ? '' : " Pro shows each one's cost when it finishes and can cap them per window."}`
|
|
322
327
|
: '.'),
|
|
323
328
|
);
|
|
329
|
+
// Codex and Grok have no 5-hour calibration, so their receipts are in API-equivalent dollars, which are not a bill.
|
|
330
|
+
for (const [host, name] of /** @type {const} */ ([
|
|
331
|
+
['codex', 'Codex'],
|
|
332
|
+
['grok', 'Grok'],
|
|
333
|
+
])) {
|
|
334
|
+
const runs = recent.filter((e) => e.src === host);
|
|
335
|
+
if (!runs.length) continue;
|
|
336
|
+
const usd = runs.filter((e) => typeof e.usd === 'number').map((e) => /** @type {number} */ (e.usd));
|
|
337
|
+
out.push(
|
|
338
|
+
`${runs.length} ${name} subagent${runs.length === 1 ? '' : 's'} finished` +
|
|
339
|
+
(usd.length
|
|
340
|
+
? `, about ${fmtUsd(usd.reduce((a, b) => a + b, 0))} at API list prices in all; the biggest ${fmtUsd(Math.max(...usd))}.`
|
|
341
|
+
: '.'),
|
|
342
|
+
);
|
|
343
|
+
}
|
|
324
344
|
if (st.colds)
|
|
325
345
|
out.push(
|
|
326
346
|
`${pro ? 'Held' : 'Pro would have held'} ${st.colds} message${st.colds === 1 ? '' : 's'} sent after the prompt cache had expired` +
|
package/src/subagents.mjs
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
|
+
import { fmtUsd } from './prices.mjs';
|
|
5
6
|
import { stateDir, updateConfig } from './store.mjs';
|
|
6
7
|
|
|
7
8
|
// Subagent receipts and budgets. A SubagentStop hook prices each finished subagent against the 5-hour window
|
|
8
9
|
// (from the user's own calibration) and logs it; the guard holds new subagents once a window's budget is spent.
|
|
9
10
|
|
|
10
|
-
/** @typedef {{t:number, id?:string, sid?:string, type?:string, calls:number, fresh:number, read:number, pct?:number}} SubagentEntry
|
|
11
|
+
/** @typedef {{t:number, id?:string, sid?:string, type?:string, src?:'claude'|'codex'|'grok', calls:number, fresh:number, read:number, pct?:number, usd?:number}} SubagentEntry
|
|
12
|
+
* src: the tool that ran it (absent = Claude Code, before receipts covered the others); pct: % of Claude's 5-hour window;
|
|
13
|
+
* usd: API-equivalent dollars (Codex and Grok, which have no 5-hour calibration) */
|
|
11
14
|
|
|
12
15
|
const ledger = () => join(stateDir(), 'subagents.jsonl');
|
|
13
16
|
const configFile = () => join(stateDir(), 'config.json');
|
|
@@ -45,10 +48,13 @@ export function subagentUsage(path) {
|
|
|
45
48
|
* @param {string} type
|
|
46
49
|
* @param {{fresh:number, read:number, calls:number}} u
|
|
47
50
|
* @param {number|null} pct
|
|
51
|
+
* @param {number|null} [usd] API-equivalent dollars, for a tool with no 5-hour calibration
|
|
48
52
|
*/
|
|
49
|
-
export function receiptMessage(type, u, pct) {
|
|
53
|
+
export function receiptMessage(type, u, pct, usd = null) {
|
|
50
54
|
const what = type ? `that ${type} subagent` : 'that subagent';
|
|
51
55
|
const calls = `${u.calls} call${u.calls === 1 ? '' : 's'}`;
|
|
56
|
+
if (pct === null && usd !== null)
|
|
57
|
+
return `limitcast: ${what} used ${k(u.fresh + u.read)} tokens, ${k(u.fresh)} of them new (${calls}): about ${fmtUsd(usd)} at API list prices.`;
|
|
52
58
|
if (pct === null) return `limitcast: ${what} used ${k(u.fresh + u.read)} tokens, ${k(u.fresh)} of them new (${calls}).`;
|
|
53
59
|
return `limitcast: ${what} used ≈${pct < 1 ? pct.toFixed(2) : pct.toFixed(1)}% of your 5-hour window (${calls}, ${k(u.fresh)} new tokens).`;
|
|
54
60
|
}
|
|
@@ -67,9 +73,12 @@ const NOTICE_MIN_PCT = 1; // a typical run under 1% of a window is not worth a m
|
|
|
67
73
|
* @param {SubagentEntry[]} entries
|
|
68
74
|
* @param {unknown} type the subagent type about to start
|
|
69
75
|
* @param {{pct:number, verdict:string}|undefined} win the current 5-hour window
|
|
76
|
+
* @param {'claude'|'codex'|'grok'} [src] the tool about to spawn it: only its own receipts count (type names differ by tool)
|
|
70
77
|
*/
|
|
71
|
-
export function spawnNotice(entries, type, win) {
|
|
72
|
-
const
|
|
78
|
+
export function spawnNotice(entries, type, win, src = 'claude') {
|
|
79
|
+
const mine = entries.filter((e) => (e.src ?? 'claude') === src);
|
|
80
|
+
if (src !== 'claude') return dollarNotice(mine, type, win);
|
|
81
|
+
const priced = mine.filter((e) => typeof e.pct === 'number');
|
|
73
82
|
const same = typeof type === 'string' && type ? priced.filter((e) => e.type === type) : [];
|
|
74
83
|
const runs = same.length >= NOTICE_MIN_RUNS ? same : priced;
|
|
75
84
|
if (runs.length < NOTICE_MIN_RUNS) return null;
|
|
@@ -82,6 +91,28 @@ export function spawnNotice(entries, type, win) {
|
|
|
82
91
|
return `limitcast: ${who} cost you a median ≈${pct1(median)}% (max ≈${pct1(sorted.at(-1) ?? 0)}%) of a 5-hour window over ${runs.length} runs${used}.`;
|
|
83
92
|
}
|
|
84
93
|
|
|
94
|
+
const NOTICE_MIN_USD = 0.1; // the dollar counterpart of the 1% floor
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The same hint for Codex and Grok, which have no 5-hour calibration: what that kind has cost in API-equivalent dollars.
|
|
98
|
+
* @param {SubagentEntry[]} entries receipts of the spawning tool
|
|
99
|
+
* @param {unknown} type
|
|
100
|
+
* @param {{pct:number, verdict:string}|undefined} win
|
|
101
|
+
*/
|
|
102
|
+
function dollarNotice(entries, type, win) {
|
|
103
|
+
const priced = entries.filter((e) => typeof e.usd === 'number');
|
|
104
|
+
const same = typeof type === 'string' && type ? priced.filter((e) => e.type === type) : [];
|
|
105
|
+
const runs = same.length >= NOTICE_MIN_RUNS ? same : priced;
|
|
106
|
+
if (runs.length < NOTICE_MIN_RUNS) return null;
|
|
107
|
+
const sorted = runs.map((e) => /** @type {number} */ (e.usd)).sort((a, b) => a - b);
|
|
108
|
+
const mid = sorted.length >> 1;
|
|
109
|
+
const median = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
|
|
110
|
+
if (median < NOTICE_MIN_USD && win?.verdict !== 'NEAR') return null;
|
|
111
|
+
const who = runs === same ? `${type} subagents have` : 'Your subagents have';
|
|
112
|
+
const used = win ? `; this window is ${Math.round(win.pct)}% used` : '';
|
|
113
|
+
return `limitcast: ${who} cost a median ≈${fmtUsd(median)} (max ≈${fmtUsd(sorted.at(-1) ?? 0)}) at API list prices over ${runs.length} runs${used}.`;
|
|
114
|
+
}
|
|
115
|
+
|
|
85
116
|
/** @param {SubagentEntry} e */
|
|
86
117
|
export function logSubagent(e) {
|
|
87
118
|
mkdirSync(stateDir(), { recursive: true });
|
|
@@ -143,14 +174,17 @@ export const validModel = (/** @type {unknown} */ m) => typeof m === 'string' &&
|
|
|
143
174
|
|
|
144
175
|
/**
|
|
145
176
|
* The pinned model for a subagent type, matching the stored name case-insensitively (Claude "Explore" vs Grok "explore").
|
|
177
|
+
* With a host, only a model that host can run is returned: Grok takes grok-... ids, Claude takes everything else,
|
|
178
|
+
* so `subagent-model explore grok-4.3` never rewrites a Claude `Explore` spawn.
|
|
146
179
|
* @param {unknown} type
|
|
180
|
+
* @param {'claude'|'codex'|'grok'} [host]
|
|
147
181
|
*/
|
|
148
|
-
export function pinnedModel(type) {
|
|
182
|
+
export function pinnedModel(type, host) {
|
|
149
183
|
if (typeof type !== 'string' || !type) return undefined;
|
|
150
|
-
const
|
|
151
|
-
|
|
184
|
+
const fits = (/** @type {string} */ m) => (host === 'grok' ? /^grok-/i.test(m) : host === 'claude' ? !/^grok-/i.test(m) : host === undefined);
|
|
185
|
+
const models = Object.entries(getSubagentModels()).filter(([, m]) => fits(m));
|
|
152
186
|
const want = type.toLowerCase();
|
|
153
|
-
return
|
|
187
|
+
return (models.find(([t]) => t === type) ?? models.find(([t]) => t.toLowerCase() === want))?.[1];
|
|
154
188
|
}
|
|
155
189
|
|
|
156
190
|
/** @returns {Record<string, string>} the model each subagent type runs on by default, e.g. {Explore: 'haiku'} */
|