limitcast 0.19.3 → 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/src/grok.mjs CHANGED
@@ -57,23 +57,38 @@ export function grokUsedServers(since, root = grokRoot()) {
57
57
  }
58
58
 
59
59
  /**
60
- * Sizes from the newest session: the system prompt Grok loaded and the tool list (characters).
60
+ * Sizes from the newest interactive session (a subagent's child session is skipped: it carries its own prompt): the
61
+ * system prompt Grok loaded, the tool list, and the instruction files (AGENTS.md and the like), all in characters, and
62
+ * `at`, when the session started.
61
63
  * @param {string} [root]
62
- * @returns {{prompt:number, tools:number}|null}
64
+ * @returns {{prompt:number, tools:number, agentsMd:number, at?:number}|null}
63
65
  */
64
66
  export function grokStartup(root = grokRoot()) {
65
- const usage = newestFile(root, (n) => n === 'usage.json');
66
- if (!usage) return null;
67
- const dir = dirname(usage);
68
- const size = (/** @type {string} */ n) => {
69
- const p = join(dir, n);
70
- return existsSync(p) ? statSync(p).size : 0;
71
- };
72
- return { prompt: size('system_prompt.txt'), tools: size('tool_definitions.json') };
67
+ for (const usage of newestFiles(root, (n) => n === 'usage.json').slice(0, 40)) {
68
+ const dir = dirname(usage);
69
+ const json = (/** @type {string} */ n) => {
70
+ try {
71
+ return JSON.parse(readFileSync(join(dir, n), 'utf8'));
72
+ } catch {
73
+ return null;
74
+ }
75
+ };
76
+ const summary = json('summary.json');
77
+ if (summary?.session_kind === 'subagent') continue;
78
+ const at = Date.parse(summary?.created_at);
79
+ const size = (/** @type {string} */ n) => {
80
+ const p = join(dir, n);
81
+ return existsSync(p) ? statSync(p).size : 0;
82
+ };
83
+ const files = json('prompt_context.json')?.agents_md_files;
84
+ const agentsMd = Array.isArray(files) ? files.reduce((a, f) => a + String(f?.content ?? '').length, 0) : 0;
85
+ return { prompt: size('system_prompt.txt'), tools: size('tool_definitions.json'), agentsMd, ...(Number.isFinite(at) ? { at } : {}) };
86
+ }
87
+ return null;
73
88
  }
74
89
 
75
90
  /**
76
- * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{prompt:number, tools:number}|null, days:number, pro:boolean, keep?:string[]}} r
91
+ * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{prompt:number, tools:number, agentsMd?:number}|null, days:number, pro:boolean, keep?:string[]}} r
77
92
  * keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`.
78
93
  * usedMonth: normalized names used in 30 days. Servers in it stay out of `unused`.
79
94
  */
@@ -85,11 +100,14 @@ export function grokTrimReport({ servers, used, usedMonth = null, startup, days,
85
100
  const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s));
86
101
  const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
87
102
  const out = ['# limitcast trim --grok', ''];
88
- if (startup)
103
+ if (startup) {
104
+ const files = startup.agentsMd ? ` and ~${tok(startup.agentsMd)} of instruction files` : '';
105
+ const total = startup.prompt + startup.tools + (startup.agentsMd ?? 0);
89
106
  out.push(
90
- `Grok sessions start with ~${tok(startup.prompt)} tokens of system prompt and ~${tok(startup.tools)} of tool definitions, re-sent on every turn.`,
107
+ `Grok sessions start with ~${tok(startup.prompt)} tokens of system prompt, ~${tok(startup.tools)} of tool definitions${files}${startup.agentsMd ? ` (about ${tok(total)} in all, estimated from file sizes)` : ''}, re-sent on every turn.`,
91
108
  '',
92
109
  );
110
+ }
93
111
  out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
94
112
  if (standing.length)
95
113
  out.push('', `${standing.length} used in the last 30 days, so \`trim --apply\` leaves them on:`, ...standing.map((s) => `- ${s.name}`));
@@ -499,7 +517,7 @@ export function grokHistory(since, now, { root = grokRoot(), budget = getGrokBud
499
517
  * @param {{guard:boolean, self:string, home?:string}} opts
500
518
  * @returns {string[]}
501
519
  */
502
- export function installGrok({ guard, self, home = grokHome() }) {
520
+ export function installGrok({ guard, alerts = false, self, home = grokHome() }) {
503
521
  if (!grokPresent(home)) return [];
504
522
  const changes = [];
505
523
  const cfgPath = join(home, 'config.toml');
@@ -518,24 +536,35 @@ export function installGrok({ guard, self, home = grokHome() }) {
518
536
  );
519
537
  }
520
538
  }
521
- if (guard) {
522
- const path = join(home, 'hooks', 'limitcast.json');
539
+ const path = join(home, 'hooks', 'limitcast.json');
540
+ // One file holds both parts, so installing one never drops the other that an earlier install added.
541
+ const prev = existsSync(path) ? readFileSync(path, 'utf8') : '';
542
+ const mine = prev.includes(MARK) ? prev : '';
543
+ const wantGuard = guard || /\bsubagent-receipt\b/.test(mine);
544
+ const wantAlerts = alerts || /\btool-check\b/.test(mine);
545
+ if (wantGuard || wantAlerts) {
546
+ /** @type {Record<string, any[]>} */
547
+ const hooks = {};
548
+ if (wantGuard) {
549
+ hooks.PreToolUse = [{ matcher: 'spawn_subagent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] }];
550
+ // A subagent's stop clears the duplicate-spawn hold (the payload carries `subagentType`, not `agent_type`).
551
+ hooks.SubagentStop = [{ hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }];
552
+ }
553
+ if (wantAlerts) {
554
+ // Grok accepts Claude's tool names in a matcher (Read is read_file) and its MCP calls as mcp__server__tool.
555
+ (hooks.PreToolUse ??= []).push({
556
+ matcher: 'Read|Grep|mcp__.*',
557
+ hooks: [{ type: 'command', command: `${self} tool-limit --src grok`, timeout: 10 }],
558
+ });
559
+ hooks.PostToolUse = [
560
+ { matcher: 'Bash|Read|Grep|WebFetch|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-check --src grok`, timeout: 10 }] },
561
+ ];
562
+ hooks.SessionStart = [{ hooks: [{ type: 'command', command: `${self} drift --hook --src grok`, timeout: 15 }] }];
563
+ }
523
564
  mkdirSync(dirname(path), { recursive: true });
524
- writeFileSync(
525
- path,
526
- `${JSON.stringify(
527
- {
528
- hooks: {
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 }] }],
532
- },
533
- },
534
- null,
535
- 2,
536
- )}\n`,
537
- );
538
- changes.push('added the Grok subagent guard (matcher spawn_subagent) and its subagent-stop hook');
565
+ writeFileSync(path, `${JSON.stringify({ hooks }, null, 2)}\n`);
566
+ if (guard) changes.push('added the Grok subagent guard (matcher spawn_subagent) and its subagent-stop hook');
567
+ if (alerts) changes.push('added the Grok starting-context alert, large tool-output notice and fat-tool limit check');
539
568
  }
540
569
  return changes;
541
570
  }
@@ -782,22 +811,29 @@ function grokSessionFiles(root, since, name) {
782
811
  * @param {(name:string)=>boolean} keep
783
812
  */
784
813
  function newestFile(dir, keep) {
785
- if (!existsSync(dir)) return null;
786
- let best = null;
787
- let bestM = -1;
814
+ return newestFiles(dir, keep)[0] ?? null;
815
+ }
816
+
817
+ /**
818
+ * Every file under `dir` that `keep` accepts, newest first.
819
+ * @param {string} dir
820
+ * @param {(name:string)=>boolean} keep
821
+ * @returns {string[]}
822
+ */
823
+ function newestFiles(dir, keep) {
824
+ if (!existsSync(dir)) return [];
825
+ /** @type {{p:string, m:number}[]} */
826
+ const found = [];
788
827
  /** @param {string} d */
789
828
  const walk = (d) => {
790
829
  for (const e of readdirSync(d, { withFileTypes: true })) {
791
830
  const p = join(d, e.name);
792
831
  if (e.isDirectory()) walk(p);
793
- else if (keep(e.name)) {
794
- const m = statSync(p).mtimeMs;
795
- if (m > bestM) [best, bestM] = [p, m];
796
- }
832
+ else if (keep(e.name)) found.push({ p, m: statSync(p).mtimeMs });
797
833
  }
798
834
  };
799
835
  walk(dir);
800
- return best;
836
+ return found.sort((a, b) => b.m - a.m).map((f) => f.p);
801
837
  }
802
838
 
803
839
  /** @param {string} path @param {string} text */
package/src/guard.mjs CHANGED
@@ -160,9 +160,15 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
160
160
  // Not blocked, but a window is tight: run a new Claude subagent on Sonnet instead of the main (usually Opus) model.
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
- const type = String(input?.subagent_type ?? input?.subagentType ?? '');
163
+ const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '');
164
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
+ if (src === 'codex') {
167
+ // Codex has no Sonnet switch or model pin here; it gets the same "what this kind of subagent has cost" hint.
168
+ if (preview) return null;
169
+ const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, undefined, 'codex');
170
+ return notice ? { notice } : null;
171
+ }
166
172
  if (src !== 'claude') return null;
167
173
  const model = pinned ?? input?.model;
168
174
  if (!tight || !switchable(model)) {
@@ -287,6 +293,6 @@ function grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation
287
293
  }
288
294
  if (preview) return null;
289
295
  const win = forecasts.find((x) => x.src === 'grok' && x.win === '5h' && x.verdict !== 'RESET');
290
- const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, win);
296
+ const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, win, 'grok');
291
297
  return notice ? { notice } : null;
292
298
  }
package/src/inflight.mjs CHANGED
@@ -10,6 +10,7 @@ import { stateDir } from './store.mjs';
10
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
+ const ENCRYPTED = /^gAAAA[A-Za-z0-9_=-]{40,}$/; // a Fernet token, the shape Codex gave an encrypted spawn_agent message
13
14
 
14
15
  /** @typedef {{sid:string, type:string, hash:string, t:number}} Inflight */
15
16
 
@@ -25,12 +26,16 @@ export function spawnIdentity(hook) {
25
26
  const input = hook?.tool_input ?? hook?.toolInput ?? {};
26
27
  // Grok re-runs a finished subagent with resume_from: the same prompt again is a continuation, not a duplicate.
27
28
  if (input?.resume_from || input?.resumeFrom) return null;
28
- const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '').trim();
29
+ // Codex names no type when the model leaves it out, and reports such a subagent as "default" when it stops.
30
+ const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? (src === 'codex' ? 'default' : '')).trim();
29
31
  // Claude and Grok send `prompt`; Codex spawn_agent sends `message` (or `items`, a list of text parts).
30
32
  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 || '')
33
+ let prompt = String(input?.prompt || input?.message || input?.description || input?.task || items || '')
32
34
  .replace(/\s+/g, ' ')
33
35
  .trim();
36
+ // Codex encrypts spawn_agent arguments (a live call carried a `gAAAA…` token as its message), and the same prompt encrypts
37
+ // differently each time, so identical prompts cannot be told apart by content. The task name the model gave it still can.
38
+ if (src === 'codex' && (!prompt || ENCRYPTED.test(prompt)) && input?.task_name) prompt = `task ${String(input.task_name).trim()}`;
34
39
  const sid = String(hook?.session_id ?? hook?.sessionId ?? '').trim();
35
40
  if (!type || !prompt || !sid) return null;
36
41
  const hash = createHash('sha256').update(`${type.toLowerCase()}\0${prompt}`).digest('hex').slice(0, 16);
package/src/install.mjs CHANGED
@@ -139,10 +139,40 @@ export function install({
139
139
  upsertGuard(codex, { matcher: CODEX_MATCHER, hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] });
140
140
  // A subagent's stop clears the duplicate-spawn hold; without it a finished spawn blocks its own retry for 30 minutes.
141
141
  upsertHook(codex, 'SubagentStop', { matcher: '', hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }, isReceipt);
142
+ // Codex has no status line, so its limit notifications (limitcast notify on) are raised from a throttled Stop hook.
143
+ upsertHook(codex, 'Stop', { matcher: '', hooks: [{ type: 'command', command: `${self} codex-notify --hook`, timeout: 5 }] }, isCodexNotify);
142
144
  writeSettings(codexPath, codex);
143
- changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new hooks)');
145
+ changes.push(
146
+ 'added the Codex subagent guard and limit notifications (Codex runs them after you trust them: start Codex and approve the new hooks)',
147
+ );
148
+ }
149
+ if (alerts && existsSync(join(codexPath, '..'))) {
150
+ const codex = readSettings(codexPath);
151
+ backup(codexPath);
152
+ // Codex has no Read or Grep tool; its fat results come from shell commands and MCP tools. The check learns each
153
+ // tool's usual result size as it goes, and only MCP calls (which take a limit) are held.
154
+ upsertHook(
155
+ codex,
156
+ 'PostToolUse',
157
+ { matcher: 'Bash|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-check --src codex`, timeout: 10 }] },
158
+ isToolCheck,
159
+ );
160
+ upsertHook(
161
+ codex,
162
+ 'PreToolUse',
163
+ { matcher: 'mcp__.*', hooks: [{ type: 'command', command: `${self} tool-limit --src codex`, timeout: 10 }] },
164
+ isToolLimit,
165
+ );
166
+ upsertHook(
167
+ codex,
168
+ 'SessionStart',
169
+ { matcher: '', hooks: [{ type: 'command', command: `${self} drift --hook --src codex`, timeout: 15 }] },
170
+ isAlert,
171
+ );
172
+ writeSettings(codexPath, codex);
173
+ changes.push('added the Codex starting-context alert, large tool-output notice and fat-tool limit check (approve the new hooks in Codex)');
144
174
  }
145
- if (grokPresent(grokDir)) changes.push(...installGrok({ guard, self, home: grokDir }));
175
+ if (grokPresent(grokDir)) changes.push(...installGrok({ guard, alerts, self, home: grokDir }));
146
176
  if (optimize && existsSync(join(codexPath, '..'))) {
147
177
  const codex = readSettings(codexPath);
148
178
  backup(codexPath);
@@ -241,10 +271,14 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(),
241
271
  if (existsSync(codexPath)) {
242
272
  const codex = readSettings(codexPath);
243
273
  const list = codex.hooks?.PreToolUse ?? [];
244
- if (list.some(isGuard) || Object.values(codex.hooks ?? {}).some((entries) => entries.some((h) => isOptimizer(h) || isReceipt(h)))) {
274
+ const ours = (/** @type {any} */ h) => isOptimizer(h) || isReceipt(h) || isToolCheck(h) || isToolLimit(h) || isCodexNotify(h) || isAlert(h);
275
+ if (list.some(isGuard) || Object.values(codex.hooks ?? {}).some((entries) => entries.some(ours))) {
245
276
  backup(codexPath);
246
- codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h));
277
+ codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h) && !isToolLimit(h));
247
278
  if (codex.hooks.SubagentStop) codex.hooks.SubagentStop = codex.hooks.SubagentStop.filter((/** @type {any} */ h) => !isReceipt(h));
279
+ if (codex.hooks.PostToolUse) codex.hooks.PostToolUse = codex.hooks.PostToolUse.filter((/** @type {any} */ h) => !isToolCheck(h));
280
+ if (codex.hooks.Stop) codex.hooks.Stop = codex.hooks.Stop.filter((/** @type {any} */ h) => !isCodexNotify(h));
281
+ if (codex.hooks.SessionStart) codex.hooks.SessionStart = codex.hooks.SessionStart.filter((/** @type {any} */ h) => !isAlert(h));
248
282
  removeOptimizerHooks(codex);
249
283
  writeSettings(codexPath, codex);
250
284
  changes.push('removed the Codex subagent guard');
@@ -298,6 +332,7 @@ const isPromptCheck = runs(/\bprompt-check\b/);
298
332
  const isReceipt = runs(/\bsubagent-receipt\b/);
299
333
  const isToolCheck = runs(/\btool-check\b/);
300
334
  const isToolLimit = runs(/\btool-limit\b/);
335
+ const isCodexNotify = runs(/\bcodex-notify\b/);
301
336
  const isOptimizer = runs(/\b_optimize-hook\b/);
302
337
 
303
338
  /** @param {string} path */
package/src/notify.mjs CHANGED
@@ -14,6 +14,23 @@ const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
14
14
 
15
15
  export const notifyEnabled = () => existsSync(flag());
16
16
 
17
+ /**
18
+ * True at most once every few minutes (Codex has no status line, so a Stop hook asks this before it starts the background check).
19
+ * @param {number} now epoch ms
20
+ * @param {number} [gapMs]
21
+ */
22
+ export function codexNotifyDue(now, gapMs = 180_000) {
23
+ const mark = join(stateDir(), 'notify-codex.at');
24
+ try {
25
+ if (now - Number(readFileSync(mark, 'utf8')) < gapMs) return false;
26
+ } catch {
27
+ /* never checked */
28
+ }
29
+ mkdirSync(stateDir(), { recursive: true });
30
+ writeFileSync(mark, String(now));
31
+ return true;
32
+ }
33
+
17
34
  /** @param {boolean} on */
18
35
  export function setNotify(on) {
19
36
  mkdirSync(stateDir(), { recursive: true });
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
- const file = () => join(stateDir(), 'overhead.json');
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
- /** @returns {{first:Snapshot, last:Snapshot}|null} */
36
- export function loadOverhead() {
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
- /** @param {{first:Snapshot, last:Snapshot}} s */
45
- export function saveOverhead(s) {
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
- return `limitcast: your Claude Code starting context grew ~${(tok(d.delta) / 1000).toFixed(1)}k tokens since your last session${items ? ` (${items})` : ''}. Run \`limitcast trim\` for details.`;
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 Grok models; any other model is left out, never priced at 0.
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;
@@ -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,