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.
@@ -0,0 +1,85 @@
1
+ // @ts-check
2
+ import { spawn } from 'node:child_process';
3
+ import { homedir } from 'node:os';
4
+ import { createInterface } from 'node:readline';
5
+
6
+ // Codex trusts a hook by a hash of its definition (`trusted_hash` in config.toml), which cannot be recomputed from outside:
7
+ // a hook that was edited keeps its key and still fails the hash. So ask Codex itself, the way its own /hooks screen does:
8
+ // the app server's `hooks/list` says each hook's trust status.
9
+
10
+ /** @typedef {{key:string, trustStatus:string, enabled:boolean, command:string}} HookRow */
11
+
12
+ /**
13
+ * Every hook Codex has configured for `cwd`, with its trust status. Null when Codex does not answer.
14
+ * @param {{cwd?:string, timeoutMs?:number, command?:string[]}} [o] command: the app-server command line, `codex app-server` by default
15
+ * @returns {Promise<HookRow[]|null>}
16
+ */
17
+ export function codexHooks({ cwd = homedir(), timeoutMs = 15_000, command = ['codex', 'app-server'] } = {}) {
18
+ return new Promise((resolve) => {
19
+ let child;
20
+ try {
21
+ child = spawn(command[0], command.slice(1), { cwd, stdio: ['pipe', 'pipe', 'ignore'] });
22
+ } catch {
23
+ resolve(null);
24
+ return;
25
+ }
26
+ let done = false;
27
+ /** @param {HookRow[]|null} rows */
28
+ const finish = (rows) => {
29
+ if (done) return;
30
+ done = true;
31
+ clearTimeout(timer);
32
+ child.kill();
33
+ resolve(rows);
34
+ };
35
+ const timer = setTimeout(() => finish(null), timeoutMs);
36
+ child.on('error', () => finish(null));
37
+ child.on('exit', () => finish(null));
38
+ /** @param {unknown} msg */
39
+ const send = (msg) => child.stdin.write(`${JSON.stringify(msg)}\n`);
40
+ createInterface({ input: child.stdout }).on('line', (line) => {
41
+ let msg;
42
+ try {
43
+ msg = JSON.parse(line);
44
+ } catch {
45
+ return;
46
+ }
47
+ if (msg?.id === 1) {
48
+ send({ method: 'initialized' });
49
+ send({ id: 2, method: 'hooks/list', params: { cwds: [cwd] } });
50
+ } else if (msg?.id === 2) {
51
+ if (msg.error) return finish(null);
52
+ const rows = (msg.result?.data ?? []).flatMap((/** @type {any} */ entry) => entry?.hooks ?? []);
53
+ finish(
54
+ rows.map((/** @type {any} */ h) => ({
55
+ key: String(h.key ?? ''),
56
+ trustStatus: String(h.trustStatus ?? ''),
57
+ enabled: h.enabled !== false,
58
+ command: String(h.command ?? ''),
59
+ })),
60
+ );
61
+ }
62
+ });
63
+ send({ id: 1, method: 'initialize', params: { clientInfo: { name: 'limitcast-doctor', title: 'limitcast doctor', version: '1' } } });
64
+ });
65
+ }
66
+
67
+ /**
68
+ * Doctor line for limitcast's own hooks, from what Codex says about them. Null when none of them is configured.
69
+ * @param {HookRow[]} rows
70
+ * @returns {{ok:boolean, line:string}|null}
71
+ */
72
+ export function trustLine(rows) {
73
+ const mine = rows.filter((h) => /limitcast/i.test(h.command));
74
+ if (!mine.length) return null;
75
+ const waiting = mine.filter((h) => h.trustStatus !== 'trusted');
76
+ if (!waiting.length) return { ok: true, line: `Codex hooks: all ${mine.length} limitcast hooks are trusted` };
77
+ const what = waiting
78
+ .map((h) => h.key.replace(/^.*[\\/]/, '').replace(/^hooks\.json:/, ''))
79
+ .slice(0, 4)
80
+ .join(', ');
81
+ return {
82
+ ok: false,
83
+ line: `Codex hooks: ${waiting.length} of ${mine.length} limitcast hooks are not trusted (${what}): start Codex, open /hooks and approve them. Codex skips an unreviewed hook`,
84
+ };
85
+ }
package/src/codex.mjs CHANGED
@@ -91,34 +91,64 @@ export async function codexUsedServers(since, root = join(codexHome(), 'sessions
91
91
  }
92
92
 
93
93
  /**
94
- * Sizes from the newest rollout's head: the AGENTS.md chain Codex loaded and its own base instructions (characters).
95
- * @returns {Promise<{agentsMd:number, base:number}|null>}
94
+ * What a rollout's head shows of how the session started. A subagent's rollout is its own thread (forked, with its own
95
+ * instructions), so it says nothing about what your interactive sessions load.
96
+ * @param {string} file
97
+ * @returns {Promise<{subagent:boolean, agentsMd:number, base:number, first?:number, at?:number}>}
96
98
  */
97
- export async function codexStartup(root = join(codexHome(), 'sessions')) {
98
- const files = jsonlFiles(root, 0, (n) => n.startsWith('rollout-'))
99
- .map((p) => ({ p, m: statSync(p).mtimeMs }))
100
- .sort((a, b) => b.m - a.m);
101
- if (!files.length) return null;
99
+ async function rolloutHead(file) {
102
100
  let agentsMd = 0;
103
101
  let base = 0;
102
+ let subagent = false;
103
+ /** @type {number|undefined} */
104
+ let first;
105
+ /** @type {number|undefined} */
106
+ let at;
104
107
  let n = 0;
105
- const rl = createInterface({ input: createReadStream(files[0].p), crlfDelay: Infinity });
108
+ const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
106
109
  for await (const line of rl) {
107
- if (++n > 40) break;
110
+ if (++n > 400) break;
108
111
  try {
109
112
  const ev = JSON.parse(line);
110
- if (ev.type === 'session_meta') base = String(ev.payload?.base_instructions?.text ?? '').length;
113
+ if (ev.type === 'session_meta') {
114
+ base = String(ev.payload?.base_instructions?.text ?? '').length;
115
+ subagent = ev.payload?.thread_source === 'subagent' || Boolean(ev.payload?.source?.subagent);
116
+ const started = Date.parse(ev.payload?.timestamp ?? ev.timestamp);
117
+ if (Number.isFinite(started)) at = started;
118
+ }
111
119
  if (ev.type === 'world_state') agentsMd = String(ev.payload?.state?.agents_md?.text ?? '').length;
120
+ const total = ev?.payload?.info?.total_token_usage;
121
+ if (total?.input_tokens) {
122
+ first = total.input_tokens; // the first model call's whole prompt: what a session starts with, measured
123
+ break;
124
+ }
112
125
  } catch {
113
126
  /* skip */
114
127
  }
115
128
  }
116
129
  rl.close();
117
- return { agentsMd, base };
130
+ return { subagent, agentsMd, base, ...(first ? { first } : {}), ...(at ? { at } : {}) };
131
+ }
132
+
133
+ /**
134
+ * Sizes from the newest interactive rollout's head: the AGENTS.md chain Codex loaded and its own base instructions
135
+ * (characters), `first`, the tokens of its first model call when the log reaches one, and `at`, when it started.
136
+ * @returns {Promise<{agentsMd:number, base:number, first?:number, at?:number}|null>}
137
+ */
138
+ export async function codexStartup(root = join(codexHome(), 'sessions')) {
139
+ const files = jsonlFiles(root, 0, (n) => n.startsWith('rollout-'))
140
+ .map((p) => ({ p, m: statSync(p).mtimeMs }))
141
+ .sort((a, b) => b.m - a.m)
142
+ .slice(0, 40);
143
+ for (const f of files) {
144
+ const { subagent, ...sizes } = await rolloutHead(f.p);
145
+ if (!subagent) return sizes;
146
+ }
147
+ return null;
118
148
  }
119
149
 
120
150
  /**
121
- * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean, keep?:string[]}} r
151
+ * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{agentsMd:number, base:number, first?:number}|null, days:number, pro:boolean, keep?:string[]}} r
122
152
  * keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`.
123
153
  * usedMonth: normalized names used in 30 days. Servers in it stay out of `unused`.
124
154
  */
@@ -132,7 +162,9 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
132
162
  const out = ['# limitcast trim --codex', ''];
133
163
  if (startup)
134
164
  out.push(
135
- `Codex sessions start with ~${tok(startup.agentsMd)} tokens of AGENTS.md (your instruction files) and ~${tok(startup.base)} of Codex's own instructions, re-sent on every turn.`,
165
+ startup.first
166
+ ? `Your latest Codex session started with ${(startup.first / 1000).toFixed(1)}k tokens on its first call (measured): ~${tok(startup.agentsMd)} of AGENTS.md (your instruction files), ~${tok(startup.base)} of Codex's own instructions, and the rest tool definitions and environment context, all re-sent on every turn.`
167
+ : `Codex sessions start with ~${tok(startup.agentsMd)} tokens of AGENTS.md (your instruction files) and ~${tok(startup.base)} of Codex's own instructions, re-sent on every turn.`,
136
168
  '',
137
169
  );
138
170
  out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
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}`));
@@ -462,12 +480,44 @@ export function grokSamples(now, { root = grokRoot(), budget = getGrokBudget() }
462
480
  return out;
463
481
  }
464
482
 
483
+ /**
484
+ * Past Grok window readings for `results` and the value rollup: for every 5-hour and 7-day window since `since`,
485
+ * the running spend against the user's dollar cap, one reading per turn. `grokSamples` only builds the current
486
+ * window, which left every earlier Grok block without readings and made `results` invent its outcome.
487
+ * Real weekly readings (`grok-usage on`) replace a 7-day cap, as in `grokSamples`.
488
+ * @param {number} since epoch ms
489
+ * @param {number} now epoch ms
490
+ * @param {{root?:string, budget?:ReturnType<typeof getGrokBudget>}} [opts]
491
+ * @returns {Sample[]}
492
+ */
493
+ export function grokHistory(since, now, { root = grokRoot(), budget = getGrokBudget() } = {}) {
494
+ const quota = grokQuotaSamples(now).filter((s) => s.t >= since);
495
+ if (!budget) return quota;
496
+ const turns = grokCosts(root, since);
497
+ /** @type {Sample[]} */
498
+ const out = [...quota];
499
+ for (const win of /** @type {const} */ (['5h', '7d'])) {
500
+ const cap = budget[win];
501
+ if (!(cap > 0) || (win === '7d' && quota.length)) continue;
502
+ const len = windowMs(win);
503
+ for (let start = alignedStart(since, win); start <= now; start += len) {
504
+ let spent = 0;
505
+ for (const t of turns) {
506
+ if (t.t < start || t.t >= start + len || t.t > now) continue;
507
+ spent += t.usd;
508
+ out.push({ t: t.t, src: 'grok', win, pct: Math.min(100, (spent / cap) * 100), reset: (start + len) / 1000 });
509
+ }
510
+ }
511
+ }
512
+ return out;
513
+ }
514
+
465
515
  /**
466
516
  * Wire Grok's status line and, with `guard`, a PreToolUse hook on `spawn_subagent`.
467
517
  * @param {{guard:boolean, self:string, home?:string}} opts
468
518
  * @returns {string[]}
469
519
  */
470
- export function installGrok({ guard, self, home = grokHome() }) {
520
+ export function installGrok({ guard, alerts = false, self, home = grokHome() }) {
471
521
  if (!grokPresent(home)) return [];
472
522
  const changes = [];
473
523
  const cfgPath = join(home, 'config.toml');
@@ -486,22 +536,35 @@ export function installGrok({ guard, self, home = grokHome() }) {
486
536
  );
487
537
  }
488
538
  }
489
- if (guard) {
490
- 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
+ }
491
564
  mkdirSync(dirname(path), { recursive: true });
492
- writeFileSync(
493
- path,
494
- `${JSON.stringify(
495
- {
496
- hooks: {
497
- PreToolUse: [{ matcher: 'spawn_subagent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] }],
498
- },
499
- },
500
- null,
501
- 2,
502
- )}\n`,
503
- );
504
- changes.push('added the Grok subagent guard (matcher spawn_subagent)');
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');
505
568
  }
506
569
  return changes;
507
570
  }
@@ -748,22 +811,29 @@ function grokSessionFiles(root, since, name) {
748
811
  * @param {(name:string)=>boolean} keep
749
812
  */
750
813
  function newestFile(dir, keep) {
751
- if (!existsSync(dir)) return null;
752
- let best = null;
753
- 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 = [];
754
827
  /** @param {string} d */
755
828
  const walk = (d) => {
756
829
  for (const e of readdirSync(d, { withFileTypes: true })) {
757
830
  const p = join(d, e.name);
758
831
  if (e.isDirectory()) walk(p);
759
- else if (keep(e.name)) {
760
- const m = statSync(p).mtimeMs;
761
- if (m > bestM) [best, bestM] = [p, m];
762
- }
832
+ else if (keep(e.name)) found.push({ p, m: statSync(p).mtimeMs });
763
833
  }
764
834
  };
765
835
  walk(dir);
766
- return best;
836
+ return found.sort((a, b) => b.m - a.m).map((f) => f.p);
767
837
  }
768
838
 
769
839
  /** @param {string} path @param {string} text */
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
  }
@@ -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 ?? '');
164
- const pinned = isUnset(input?.model) && type ? pinnedModel(type) : undefined;
163
+ const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '');
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
@@ -6,10 +6,11 @@ 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 the Claude one. Codex and Grok have no stop event here, so a record older than
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
+ 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
 
@@ -23,10 +24,18 @@ export function spawnIdentity(hook) {
23
24
  const src = spawnSource(tool);
24
25
  if (!src) return null;
25
26
  const input = hook?.tool_input ?? hook?.toolInput ?? {};
26
- const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '').trim();
27
- const prompt = String(input?.prompt ?? input?.description ?? input?.task ?? '')
27
+ // Grok re-runs a finished subagent with resume_from: the same prompt again is a continuation, not a duplicate.
28
+ if (input?.resume_from || input?.resumeFrom) return null;
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();
31
+ // Claude and Grok send `prompt`; Codex spawn_agent sends `message` (or `items`, a list of text parts).
32
+ const items = Array.isArray(input?.items) ? input.items.map((x) => (typeof x === 'string' ? x : (x?.text ?? ''))).join(' ') : '';
33
+ let prompt = String(input?.prompt || input?.message || input?.description || input?.task || items || '')
28
34
  .replace(/\s+/g, ' ')
29
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()}`;
30
39
  const sid = String(hook?.session_id ?? hook?.sessionId ?? '').trim();
31
40
  if (!type || !prompt || !sid) return null;
32
41
  const hash = createHash('sha256').update(`${type.toLowerCase()}\0${prompt}`).digest('hex').slice(0, 16);
@@ -67,7 +76,11 @@ export function rememberInflight(entries, id, now) {
67
76
  export function forgetInflight(entries, sid, type, now) {
68
77
  const live = pruneInflight(entries, now);
69
78
  if (!sid || !type) return live;
70
- const i = live.findIndex((e) => e.sid === sid && e.type.toLowerCase() === type.toLowerCase());
79
+ const same = (/** @type {Inflight} */ e) => e.type.toLowerCase() === type.toLowerCase();
80
+ // Some hosts report the subagent's own session on its stop event. Match the parent session first, else the type alone:
81
+ // clearing the wrong record only lets a duplicate through, which is the safe way to be wrong.
82
+ let i = live.findIndex((e) => e.sid === sid && same(e));
83
+ if (i < 0) i = live.findIndex(same);
71
84
  if (i >= 0) live.splice(i, 1);
72
85
  return live;
73
86
  }
package/src/install.mjs CHANGED
@@ -137,10 +137,42 @@ 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);
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);
140
144
  writeSettings(codexPath, codex);
141
- changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new hook)');
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)');
142
174
  }
143
- if (grokPresent(grokDir)) changes.push(...installGrok({ guard, self, home: grokDir }));
175
+ if (grokPresent(grokDir)) changes.push(...installGrok({ guard, alerts, self, home: grokDir }));
144
176
  if (optimize && existsSync(join(codexPath, '..'))) {
145
177
  const codex = readSettings(codexPath);
146
178
  backup(codexPath);
@@ -239,9 +271,14 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(),
239
271
  if (existsSync(codexPath)) {
240
272
  const codex = readSettings(codexPath);
241
273
  const list = codex.hooks?.PreToolUse ?? [];
242
- if (list.some(isGuard) || Object.values(codex.hooks ?? {}).some((entries) => entries.some(isOptimizer))) {
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))) {
243
276
  backup(codexPath);
244
- codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h));
277
+ codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h) && !isToolLimit(h));
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));
245
282
  removeOptimizerHooks(codex);
246
283
  writeSettings(codexPath, codex);
247
284
  changes.push('removed the Codex subagent guard');
@@ -295,6 +332,7 @@ const isPromptCheck = runs(/\bprompt-check\b/);
295
332
  const isReceipt = runs(/\bsubagent-receipt\b/);
296
333
  const isToolCheck = runs(/\btool-check\b/);
297
334
  const isToolLimit = runs(/\btool-limit\b/);
335
+ const isCodexNotify = runs(/\bcodex-notify\b/);
298
336
  const isOptimizer = runs(/\b_optimize-hook\b/);
299
337
 
300
338
  /** @param {string} path */
package/src/notify.mjs CHANGED
@@ -10,10 +10,27 @@ 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
 
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 });
@@ -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(HOSTS.map((h) => [h, { completedSessions: state.hosts[h]?.completed ?? 0, proposed: capabilityProposals(state, h) }])),
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
  };