limitcast 0.11.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/grok.mjs ADDED
@@ -0,0 +1,585 @@
1
+ // @ts-check
2
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { codexServers, setEnabled } from './codex.mjs';
6
+ import { windowMs } from './forecast.mjs';
7
+ import { stateDir } from './store.mjs';
8
+ import { grokRoot } from './usage.mjs';
9
+
10
+ /** @typedef {import('./forecast.mjs').Sample} Sample */
11
+
12
+ export const grokHome = () => process.env.GROK_HOME ?? join(homedir(), '.grok');
13
+ export const grokConfigPath = () => join(grokHome(), 'config.toml');
14
+ export const grokHooksFile = () => join(grokHome(), 'hooks', 'limitcast.json');
15
+ const trimLedger = () => join(stateDir(), 'grok-trim-applied.json');
16
+ const statusLedger = () => join(stateDir(), 'grok-statusline.json');
17
+ const configFile = () => join(stateDir(), 'config.json');
18
+ const MARK = 'limitcast';
19
+ const TICKS = 10_000_000_000; // Grok costUsdTicks: 1e10 per USD
20
+ const norm = (/** @type {string} */ s) => s.toLowerCase().replace(/[^a-z0-9]/g, '_');
21
+
22
+ /** True when this command already runs limitcast's statusline (bin or `limitcast-hook.sh`). */
23
+ export function isLimitcastStatus(s) {
24
+ return typeof s === 'string' && s.includes(MARK) && /\bstatusline\b/.test(s);
25
+ }
26
+
27
+ /** Grok is present when it has a config or sessions, not merely an empty GROK_HOME (tests create one). */
28
+ export function grokPresent(home = grokHome()) {
29
+ return existsSync(join(home, 'config.toml')) || existsSync(join(home, 'sessions'));
30
+ }
31
+
32
+ /**
33
+ * @param {string} [path]
34
+ */
35
+ export const grokServers = (path = grokConfigPath()) => (existsSync(path) ? codexServers(readFileSync(path, 'utf8')) : []);
36
+
37
+ /**
38
+ * MCP servers Grok actually called since `since`, from each session's events.jsonl (`mcp_tool_call_started.server_name`).
39
+ * @param {number} since
40
+ * @param {string} [root]
41
+ */
42
+ export function grokUsedServers(since, root = grokRoot()) {
43
+ /** @type {Set<string>} */
44
+ const used = new Set();
45
+ for (const file of grokSessionFiles(root, since, 'events.jsonl')) {
46
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
47
+ if (!line.includes('"mcp_tool_call_started"')) continue;
48
+ try {
49
+ const ev = JSON.parse(line);
50
+ if (ev?.type === 'mcp_tool_call_started' && typeof ev.server_name === 'string') used.add(norm(ev.server_name));
51
+ } catch {
52
+ /* torn line */
53
+ }
54
+ }
55
+ }
56
+ return used;
57
+ }
58
+
59
+ /**
60
+ * Sizes from the newest session: the system prompt Grok loaded and the tool list (characters).
61
+ * @param {string} [root]
62
+ * @returns {{prompt:number, tools:number}|null}
63
+ */
64
+ 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') };
73
+ }
74
+
75
+ /**
76
+ * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{prompt:number, tools:number}|null, days:number, pro:boolean}} r
77
+ */
78
+ export function grokTrimReport({ servers, used, startup, days, pro }) {
79
+ const on = servers.filter((s) => s.enabled !== false);
80
+ const unused = on.filter((s) => !used.has(norm(s.name)));
81
+ const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
82
+ const out = ['# limitcast trim --grok', ''];
83
+ if (startup)
84
+ out.push(
85
+ `Grok sessions start with ~${tok(startup.prompt)} tokens of system prompt and ~${tok(startup.tools)} of tool definitions, re-sent on every turn.`,
86
+ '',
87
+ );
88
+ out.push(`## MCP servers: ${on.length} on, ${unused.length} not used in ${days} days`);
89
+ if (!unused.length) out.push('Every server that is on was used.');
90
+ else if (pro)
91
+ out.push(...unused.map((s) => `- ${s.name}`), '', 'Turn them off: `limitcast trim --grok --apply` (backed up; `--undo` reverses it).');
92
+ else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
93
+ out.push(
94
+ '',
95
+ 'Each server that is on starts with every Grok session and adds its tool list to the context. Moving unused servers off is `enabled = false` in ~/.grok/config.toml.',
96
+ );
97
+ return { text: out.join('\n'), unused: unused.map((s) => s.name) };
98
+ }
99
+
100
+ /**
101
+ * Turn the named servers off in Grok's config.toml.
102
+ * @param {string[]} names
103
+ */
104
+ export function applyGrokTrim(names, { now = Date.now(), path = grokConfigPath() } = {}) {
105
+ if (!names.length || !existsSync(path)) return [];
106
+ const toml = readFileSync(path, 'utf8');
107
+ const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
108
+ copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
109
+ writeText(path, setEnabled(toml, Object.fromEntries(names.map((n) => [n, false]))));
110
+ const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
111
+ mkdirSync(stateDir(), { recursive: true });
112
+ writeFileSync(trimLedger(), JSON.stringify([...loadTrimLedger(), { at: now, servers }], null, 2));
113
+ return servers;
114
+ }
115
+
116
+ /** Reverse the last --apply. Servers the user turned back on stay on. */
117
+ export function undoGrokTrim({ path = grokConfigPath() } = {}) {
118
+ const ledger = loadTrimLedger();
119
+ const last = ledger.pop();
120
+ if (!last || !existsSync(path)) return null;
121
+ const toml = readFileSync(path, 'utf8');
122
+ copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
123
+ const off = new Set(
124
+ codexServers(toml)
125
+ .filter((s) => s.enabled === false)
126
+ .map((s) => s.name),
127
+ );
128
+ writeText(path, setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev]))));
129
+ writeFileSync(trimLedger(), JSON.stringify(ledger, null, 2));
130
+ return last;
131
+ }
132
+
133
+ /** @returns {{at:number, servers:{name:string, prev:boolean|null}[]}[]} */
134
+ function loadTrimLedger() {
135
+ try {
136
+ return JSON.parse(readFileSync(trimLedger(), 'utf8'));
137
+ } catch {
138
+ return [];
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Dollar caps for Grok windows, from `limitcast budget grok`. Grok keeps no % used on disk, so a cap is what
144
+ * turns spend into a forecast the guard can block on.
145
+ * @returns {{'5h'?:number, '7d'?:number}|null}
146
+ */
147
+ export function getGrokBudget() {
148
+ try {
149
+ const b = JSON.parse(readFileSync(configFile(), 'utf8')).grokBudget;
150
+ if (typeof b === 'number' && b > 0) return { '5h': b };
151
+ if (b && typeof b === 'object') {
152
+ /** @type {{'5h'?:number, '7d'?:number}} */
153
+ const out = {};
154
+ for (const win of /** @type {const} */ (['5h', '7d'])) if (typeof b[win] === 'number' && b[win] > 0) out[win] = b[win];
155
+ return Object.keys(out).length ? out : null;
156
+ }
157
+ } catch {
158
+ /* none */
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /**
164
+ * @param {number|null} usd
165
+ * @param {'5h'|'7d'} [win]
166
+ */
167
+ export function setGrokBudget(usd, win = '5h') {
168
+ let cfg = {};
169
+ try {
170
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
171
+ } catch {
172
+ /* new */
173
+ }
174
+ /** @type {{'5h'?:number, '7d'?:number}} */
175
+ const cur = typeof cfg.grokBudget === 'number' ? { '5h': cfg.grokBudget } : { ...(cfg.grokBudget ?? {}) };
176
+ if (usd === null) delete cur[win];
177
+ else cur[win] = usd;
178
+ mkdirSync(stateDir(), { recursive: true });
179
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, grokBudget: Object.keys(cur).length ? cur : null }));
180
+ }
181
+
182
+ /**
183
+ * Spend in the current aligned windows, in USD. Null when there is no Grok ledger.
184
+ * @param {number} now
185
+ * @param {string} [root]
186
+ * @returns {{'5h':number, '7d':number}|null}
187
+ */
188
+ export function grokSpend(now, root = grokRoot()) {
189
+ if (!existsSync(root)) return null;
190
+ const turns = grokCosts(root, now - windowMs('7d'));
191
+ if (!turns.length && !newestFile(root, (n) => n === 'usage.json')) return null;
192
+ /** @type {{'5h':number, '7d':number}} */
193
+ const out = { '5h': 0, '7d': 0 };
194
+ for (const win of /** @type {const} */ (['5h', '7d'])) {
195
+ const start = alignedStart(now, win);
196
+ out[win] = turns.filter((t) => t.t >= start && t.t <= now).reduce((a, t) => a + t.usd, 0);
197
+ }
198
+ return out;
199
+ }
200
+
201
+ /**
202
+ * Forecast samples from Grok spend against the user's dollar cap. Empty without a budget: there is no % to judge.
203
+ * @param {number} now
204
+ * @param {{root?:string, budget?:ReturnType<typeof getGrokBudget>}} [opts]
205
+ * @returns {Sample[]}
206
+ */
207
+ export function grokSamples(now, { root = grokRoot(), budget = getGrokBudget() } = {}) {
208
+ if (!budget) return [];
209
+ const since = now - windowMs('7d');
210
+ const turns = grokCosts(root, since);
211
+ /** @type {Sample[]} */
212
+ const out = [];
213
+ for (const win of /** @type {const} */ (['5h', '7d'])) {
214
+ const cap = budget[win];
215
+ if (!(cap > 0)) continue;
216
+ const start = alignedStart(now, win);
217
+ const reset = (start + windowMs(win)) / 1000;
218
+ let spent = 0;
219
+ for (const t of turns) {
220
+ if (t.t < start || t.t > now) continue;
221
+ spent += t.usd;
222
+ out.push({ t: t.t, src: 'grok', win, pct: Math.min(100, (spent / cap) * 100), reset });
223
+ }
224
+ out.push({ t: now, src: 'grok', win, pct: Math.min(100, (spent / cap) * 100), reset });
225
+ }
226
+ return out;
227
+ }
228
+
229
+ /**
230
+ * Wire Grok's status line and, with `guard`, a PreToolUse hook on `spawn_subagent`.
231
+ * @param {{guard:boolean, self:string, home?:string}} opts
232
+ * @returns {string[]}
233
+ */
234
+ export function installGrok({ guard, self, home = grokHome() }) {
235
+ if (!grokPresent(home)) return [];
236
+ const changes = [];
237
+ const cfgPath = join(home, 'config.toml');
238
+ if (existsSync(cfgPath)) {
239
+ backup(cfgPath);
240
+ const prev = readFileSync(cfgPath, 'utf8');
241
+ const next = wrapGrokStatusLine(prev, self);
242
+ if (next !== prev) {
243
+ mkdirSync(stateDir(), { recursive: true });
244
+ const snap = statusLineTable(prev);
245
+ // Remember the user's table once; never snapshot a wrap we already own (launcher path includes "limitcast").
246
+ if (!isLimitcastStatus(snap ?? '') && (snap || !existsSync(statusLedger()))) writeFileSync(statusLedger(), JSON.stringify({ previous: snap }));
247
+ writeText(cfgPath, next);
248
+ changes.push(
249
+ isLimitcastStatus(statusLineCommand(prev)) ? 'Grok status line already installed (command path refreshed)' : 'wrapped the Grok status line',
250
+ );
251
+ }
252
+ }
253
+ if (guard) {
254
+ const path = join(home, 'hooks', 'limitcast.json');
255
+ mkdirSync(dirname(path), { recursive: true });
256
+ writeFileSync(
257
+ path,
258
+ `${JSON.stringify(
259
+ {
260
+ hooks: {
261
+ PreToolUse: [{ matcher: 'spawn_subagent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] }],
262
+ },
263
+ },
264
+ null,
265
+ 2,
266
+ )}\n`,
267
+ );
268
+ changes.push('added the Grok subagent guard (matcher spawn_subagent)');
269
+ }
270
+ return changes;
271
+ }
272
+
273
+ /**
274
+ * Remove the Grok hook file and restore the previous [ui.status_line] table.
275
+ * @param {{home?:string}} [opts]
276
+ */
277
+ export function uninstallGrok({ home = grokHome() } = {}) {
278
+ const changes = [];
279
+ const hook = join(home, 'hooks', 'limitcast.json');
280
+ if (existsSync(hook)) {
281
+ const text = readFileSync(hook, 'utf8');
282
+ if (text.includes(MARK)) {
283
+ unlinkSync(hook);
284
+ changes.push('removed the Grok subagent guard');
285
+ }
286
+ }
287
+ const cfgPath = join(home, 'config.toml');
288
+ if (existsSync(cfgPath)) {
289
+ const toml = readFileSync(cfgPath, 'utf8');
290
+ if (isLimitcastStatus(statusLineCommand(toml))) {
291
+ backup(cfgPath);
292
+ let previous = null;
293
+ try {
294
+ previous = JSON.parse(readFileSync(statusLedger(), 'utf8')).previous;
295
+ } catch {
296
+ /* missing ledger: drop the table */
297
+ }
298
+ writeText(cfgPath, restoreStatusLine(toml, previous));
299
+ changes.push(previous ? 'restored the Grok status line' : 'removed the Grok status line');
300
+ }
301
+ }
302
+ return changes;
303
+ }
304
+
305
+ /**
306
+ * @param {string} [home]
307
+ * @returns {{ok:boolean, line:string}[]}
308
+ */
309
+ export function grokDoctor(home = grokHome()) {
310
+ if (!grokPresent(home)) return [];
311
+ /** @type {{ok:boolean, line:string}[]} */
312
+ const out = [];
313
+ const cfgPath = join(home, 'config.toml');
314
+ const toml = existsSync(cfgPath) ? readFileSync(cfgPath, 'utf8') : '';
315
+ const sl = isLimitcastStatus(statusLineCommand(toml));
316
+ out.push({
317
+ ok: sl,
318
+ line: sl ? 'Grok status-line recorder installed' : 'Grok status-line recorder missing: run `limitcast install`',
319
+ });
320
+ const hook = join(home, 'hooks', 'limitcast.json');
321
+ let guard = false;
322
+ try {
323
+ const cfg = JSON.parse(readFileSync(hook, 'utf8'));
324
+ guard = JSON.stringify(cfg).includes('spawn_subagent') && JSON.stringify(cfg).includes(MARK);
325
+ } catch {
326
+ /* absent */
327
+ }
328
+ out.push({
329
+ ok: true,
330
+ line: guard ? 'Grok subagent guard installed' : 'Grok subagent guard not installed (optional: `limitcast install --guard`)',
331
+ });
332
+ const budget = getGrokBudget();
333
+ if (guard && !budget)
334
+ out.push({
335
+ ok: true,
336
+ line: 'Grok has no % limit on disk: set a 5-hour dollar cap so the guard can block (`limitcast budget grok <usd>`)',
337
+ });
338
+ else if (budget)
339
+ out.push({
340
+ ok: true,
341
+ line: `Grok budget: ${Object.entries(budget)
342
+ .map(([w, v]) => `${w} $${v}`)
343
+ .join(', ')}`,
344
+ });
345
+ return out;
346
+ }
347
+
348
+ /**
349
+ * Wrap or insert [ui.status_line] so it runs `self statusline`, keeping an existing command underneath.
350
+ * @param {string} toml
351
+ * @param {string} self
352
+ */
353
+ export function wrapGrokStatusLine(toml, self) {
354
+ const cmd = `${self} statusline`;
355
+ const range = tableRange(toml, 'ui.status_line');
356
+ if (!range) {
357
+ const block = ['', '[ui.status_line]', 'type = "command"', `command = ${tomlString(`${cmd}`)}`, 'refresh_interval = 60', ''].join('\n');
358
+ return `${toml.trimEnd()}${block}`;
359
+ }
360
+ const keys = parseTable(range.body);
361
+ const current = keys.command ?? '';
362
+ const inner = isLimitcastStatus(current) ? unwrapStatusline(current) : current;
363
+ keys.type = 'command';
364
+ keys.command = inner ? `${cmd} -- sh -c ${shQuote(inner)}` : cmd;
365
+ delete keys.items; // builtin item lists are not valid on a command row
366
+ if (keys.refresh_interval === undefined) keys.refresh_interval = '60';
367
+ return toml.slice(0, range.start) + renderTable('ui.status_line', keys, range.body) + toml.slice(range.end);
368
+ }
369
+
370
+ /**
371
+ * The [ui.status_line] table text, or null when the file has none.
372
+ * @param {string} toml
373
+ */
374
+ export function statusLineTable(toml) {
375
+ const range = tableRange(toml, 'ui.status_line');
376
+ return range ? range.body.trim() : null;
377
+ }
378
+
379
+ /**
380
+ * @param {string} toml
381
+ * @param {string|null} previous
382
+ */
383
+ export function restoreStatusLine(toml, previous) {
384
+ const range = tableRange(toml, 'ui.status_line');
385
+ if (!range) return toml;
386
+ if (!previous) {
387
+ const before = toml.slice(0, range.start).trimEnd();
388
+ const after = toml.slice(range.end).replace(/^\n+/, '');
389
+ return after ? `${before}\n\n${after}` : `${before}\n`;
390
+ }
391
+ return `${toml.slice(0, range.start)}${previous.trim()}${toml.slice(range.end)}`;
392
+ }
393
+
394
+ /**
395
+ * A one-line session summary from Grok's status-line JSON (model, context %, session cost).
396
+ * @param {any} feed
397
+ */
398
+ export function grokSessionLine(feed) {
399
+ if (!feed || typeof feed !== 'object') return '';
400
+ if (feed.rate_limits) return ''; // Claude Code feed
401
+ const bits = [];
402
+ if (typeof feed.model?.display_name === 'string' && feed.model.display_name) bits.push(feed.model.display_name);
403
+ const pct = Number(feed.context_window?.used_percentage);
404
+ if (Number.isFinite(pct)) bits.push(`${pct}% ctx`);
405
+ const usd = Number(feed.cost?.total_cost_usd);
406
+ if (Number.isFinite(usd) && usd >= 0.005) bits.push(`$${usd.toFixed(2)}`);
407
+ return bits.join(' · ');
408
+ }
409
+
410
+ /** Epoch-aligned window start for `win` ("5h", "7d"). */
411
+ export function alignedStart(now, win) {
412
+ const len = windowMs(win);
413
+ return Math.floor(now / len) * len;
414
+ }
415
+
416
+ /**
417
+ * @param {string} root
418
+ * @param {number} since
419
+ * @returns {{t:number, usd:number}[]}
420
+ */
421
+ function grokCosts(root, since) {
422
+ /** @type {{t:number, usd:number}[]} */
423
+ const out = [];
424
+ for (const file of grokSessionFiles(root, since, 'usage.json')) {
425
+ let ledger;
426
+ try {
427
+ ledger = JSON.parse(readFileSync(file, 'utf8'));
428
+ } catch {
429
+ continue;
430
+ }
431
+ for (const turn of Array.isArray(ledger?.turns) ? ledger.turns : []) {
432
+ const t = Date.parse(turn?.endedAt);
433
+ if (!Number.isFinite(t) || t < since) continue;
434
+ const ticks = Number(turn.costUsdTicks);
435
+ out.push({ t, usd: Number.isFinite(ticks) ? ticks / TICKS : 0 });
436
+ }
437
+ }
438
+ return out.sort((a, b) => a.t - b.t);
439
+ }
440
+
441
+ /**
442
+ * @param {string} root
443
+ * @param {number} since
444
+ * @param {string} name
445
+ */
446
+ function grokSessionFiles(root, since, name) {
447
+ if (!existsSync(root)) return [];
448
+ /** @type {string[]} */
449
+ const out = [];
450
+ for (const proj of readdirSync(root, { withFileTypes: true })) {
451
+ if (!proj.isDirectory()) continue;
452
+ for (const sess of readdirSync(join(root, proj.name), { withFileTypes: true })) {
453
+ const file = join(root, proj.name, sess.name, name);
454
+ if (sess.isDirectory() && existsSync(file) && statSync(file).mtimeMs >= since) out.push(file);
455
+ }
456
+ }
457
+ return out;
458
+ }
459
+
460
+ /**
461
+ * @param {string} dir
462
+ * @param {(name:string)=>boolean} keep
463
+ */
464
+ function newestFile(dir, keep) {
465
+ if (!existsSync(dir)) return null;
466
+ let best = null;
467
+ let bestM = -1;
468
+ /** @param {string} d */
469
+ const walk = (d) => {
470
+ for (const e of readdirSync(d, { withFileTypes: true })) {
471
+ const p = join(d, e.name);
472
+ if (e.isDirectory()) walk(p);
473
+ else if (keep(e.name)) {
474
+ const m = statSync(p).mtimeMs;
475
+ if (m > bestM) [best, bestM] = [p, m];
476
+ }
477
+ }
478
+ };
479
+ walk(dir);
480
+ return best;
481
+ }
482
+
483
+ /** @param {string} path @param {string} text */
484
+ function writeText(path, text) {
485
+ const tmp = `${path}.limitcast-tmp-${process.pid}-${Date.now().toString(36)}`;
486
+ const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
487
+ mkdirSync(dirname(path), { recursive: true });
488
+ writeFileSync(tmp, text, { mode });
489
+ chmodSync(tmp, mode);
490
+ renameSync(tmp, path);
491
+ }
492
+
493
+ /**
494
+ * Peel nested `self statusline -- sh -c '...'` wraps until the original command, or '' if there was none.
495
+ * @param {string} command
496
+ */
497
+ function unwrapStatusline(command) {
498
+ let cur = command;
499
+ for (let i = 0; i < 8 && isLimitcastStatus(cur); i++) {
500
+ const rest = cur.split(' statusline -- ')[1];
501
+ if (!rest) return '';
502
+ const m = rest.match(/^sh -c '((?:[^']|'\\'')*)'$/);
503
+ if (m) {
504
+ cur = m[1].replace(/'\\''/g, "'");
505
+ continue;
506
+ }
507
+ const plain = rest.match(/^sh -c (\S+)$/);
508
+ cur = plain ? plain[1] : rest;
509
+ }
510
+ return isLimitcastStatus(cur) ? '' : cur;
511
+ }
512
+
513
+ /** The [ui.status_line] command value, or ''. */
514
+ function statusLineCommand(toml) {
515
+ const range = tableRange(toml, 'ui.status_line');
516
+ return range ? (parseTable(range.body).command ?? '') : '';
517
+ }
518
+
519
+ /** @param {string} path */
520
+ function backup(path) {
521
+ if (existsSync(path)) copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
522
+ }
523
+
524
+ /** @param {string} s */
525
+ const tomlString = (s) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
526
+
527
+ /** @param {string} s */
528
+ const shQuote = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
529
+
530
+ /**
531
+ * @param {string} toml
532
+ * @param {string} name
533
+ * @returns {{start:number, end:number, body:string}|null}
534
+ */
535
+ function tableRange(toml, name) {
536
+ const re = new RegExp(`^\\[${name.replaceAll('.', '\\.')}\\][ \\t]*$`, 'm');
537
+ const m = re.exec(toml);
538
+ if (!m) return null;
539
+ const start = m.index;
540
+ const rest = toml.slice(start + m[0].length);
541
+ const next = rest.search(/\n\[/);
542
+ const end = next < 0 ? toml.length : start + m[0].length + next;
543
+ return { start, end, body: toml.slice(start, end) };
544
+ }
545
+
546
+ /** @param {string} body */
547
+ function parseTable(body) {
548
+ /** @type {Record<string, string>} */
549
+ const keys = {};
550
+ for (const line of body.split('\n').slice(1)) {
551
+ const m = /^\s*([A-Za-z0-9_]+)\s*=\s*(.*)$/.exec(line);
552
+ if (!m) continue;
553
+ keys[m[1]] = unquote(m[2].trim());
554
+ }
555
+ return keys;
556
+ }
557
+
558
+ /** @param {string} v */
559
+ function unquote(v) {
560
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
561
+ const inner = v.slice(1, -1);
562
+ return v.startsWith('"') ? inner.replace(/\\"/g, '"').replace(/\\\\/g, '\\') : inner;
563
+ }
564
+ return v;
565
+ }
566
+
567
+ /**
568
+ * @param {string} name
569
+ * @param {Record<string, string>} keys
570
+ * @param {string} previousBody
571
+ */
572
+ function renderTable(name, keys, previousBody) {
573
+ const order = [];
574
+ for (const line of previousBody.split('\n').slice(1)) {
575
+ const m = /^\s*([A-Za-z0-9_]+)\s*=/.exec(line);
576
+ if (m && keys[m[1]] !== undefined && !order.includes(m[1])) order.push(m[1]);
577
+ }
578
+ for (const k of Object.keys(keys)) if (!order.includes(k)) order.push(k);
579
+ const lines = [`[${name}]`];
580
+ for (const k of order) {
581
+ const v = keys[k];
582
+ lines.push(k === 'refresh_interval' && /^\d+$/.test(v) ? `${k} = ${v}` : `${k} = ${tomlString(v)}`);
583
+ }
584
+ return `${lines.join('\n')}\n`;
585
+ }
package/src/guard.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  // @ts-check
2
2
  import { forecastAll, oneClaudeAccount } from './forecast.mjs';
3
+ import { grokSamples } from './grok.mjs';
3
4
  import { logBlock } from './results.mjs';
4
5
  import { readCodex } from './sources.mjs';
5
6
  import { KEEP_MS, load } from './store.mjs';
6
- import { budgetMessage, budgetSpent, getBudget, loadSubagents, windowStart } from './subagents.mjs';
7
+ import { budgetMessage, budgetSpent, getBudget, loadSubagents, spawnNotice, windowStart } from './subagents.mjs';
7
8
 
8
9
  const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
9
10
 
@@ -24,7 +25,7 @@ export function spawnSource(tool) {
24
25
  * Reason to block a new subagent, or null to allow it.
25
26
  * Blocks only when the spawning tool's own window is on pace to run out before it resets within `minutes`.
26
27
  * A window already at 100% is left to the tool: with extra usage enabled, work continues past it.
27
- * Grok keeps no limit readings on disk, so its spawns are never blocked.
28
+ * Grok keeps no % used on disk; `grokSamples` only exist after `limitcast budget grok`, so without a cap its spawns are never blocked.
28
29
  * @param {string} tool
29
30
  * @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
30
31
  * @param {number} now epoch ms
@@ -63,13 +64,15 @@ function blockingForecast(tool, forecasts, now, minutes) {
63
64
  export async function runGuard(hook, now, minutes, { preview = false } = {}) {
64
65
  const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
65
66
  const src = spawnSource(tool);
66
- // Codex: only the last two hours of rollouts, so the hook stays fast; Grok has no readings to judge by.
67
+ // Codex: only the last two hours of rollouts, so the hook stays fast. Grok: spend vs the user's dollar cap.
67
68
  const samples =
68
69
  src === 'claude'
69
70
  ? oneClaudeAccount(load(now - KEEP_MS), hook.session_id ?? hook.sessionId)
70
71
  : src === 'codex'
71
72
  ? await readCodex(now - 2 * 3600_000)
72
- : [];
73
+ : src === 'grok'
74
+ ? grokSamples(now)
75
+ : [];
73
76
  const forecasts = forecastAll(samples, now);
74
77
  const reason = guardDecision(tool, forecasts, now, minutes);
75
78
  const f = reason ? blockingForecast(tool, forecasts, now, minutes) : undefined;
@@ -121,7 +124,14 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
121
124
  // Not blocked, but a window is tight: run a new Claude subagent on Sonnet instead of the main (usually Opus) model.
122
125
  const input = hook?.tool_input ?? hook?.toolInput;
123
126
  const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
124
- if (src !== 'claude' || !tight || !switchable(input?.model)) return null;
127
+ if (src !== 'claude') return null;
128
+ if (!tight || !switchable(input?.model)) {
129
+ // Allowed as is: tell the user (never the model) what this kind of subagent has cost so far.
130
+ if (preview) return null;
131
+ const win = forecasts.find((x) => x.src === 'claude' && x.win === '5h' && x.verdict !== 'RESET');
132
+ const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), input?.subagent_type, win);
133
+ return notice ? { notice } : null;
134
+ }
125
135
  try {
126
136
  logBlock({
127
137
  t: now,