limitcast 0.19.2 → 0.19.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/limitcast.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // @ts-check
3
3
  import { spawn, spawnSync } from 'node:child_process';
4
- import { existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { existsSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import {
@@ -24,6 +24,7 @@ import {
24
24
  } from '../src/apply.mjs';
25
25
  import { calibrate, limitChange, limitChangeMessage, windowPct } from '../src/calibrate.mjs';
26
26
  import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
27
+ import { codexHooks, trustLine } from '../src/codex-trust.mjs';
27
28
  import { coldCost, coldMessage, coldNotice, firstNotice, firstWarning } from '../src/cold.mjs';
28
29
  import { unknownFlag } from '../src/flags.mjs';
29
30
  import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
@@ -33,6 +34,7 @@ import {
33
34
  applyGrokTrim,
34
35
  getGrokBudget,
35
36
  grokConfigPath,
37
+ grokHistory,
36
38
  grokPresent,
37
39
  grokQuotaDue,
38
40
  grokQuotaEnabled,
@@ -64,14 +66,25 @@ import {
64
66
  spawnIdentity,
65
67
  } from '../src/inflight.mjs';
66
68
  import { insightsReport, insightsShare, periodInsights } from '../src/insights.mjs';
67
- import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
69
+ import { codexHooksPath, doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
68
70
  import { memoryCheck, memoryDir, memoryReport, scanMemory } from '../src/memory.mjs';
69
- import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
71
+ import {
72
+ buildNotifierApp,
73
+ codexNotifyDue,
74
+ loadChannels,
75
+ notifierApp,
76
+ notifyChanges,
77
+ notifyEnabled,
78
+ send,
79
+ setChannel,
80
+ setNotify,
81
+ } from '../src/notify.mjs';
70
82
  import { onboardingReport } from '../src/onboarding.mjs';
71
83
  import { runOptimizationHook, runOptimize } from '../src/optimize-cli.mjs';
72
- import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
84
+ import { driftMessage, hostSnapshot, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
73
85
  import { advise, getPlan, loadPeaks, PLANS, planPrices, planStats, recordPeaks, setPlan } from '../src/plan.mjs';
74
86
  import { costOf, fmtUsd } from '../src/prices.mjs';
87
+ import { deferReceipt, hostSubagentUsage, settleReceipts, stopHost } from '../src/receipts.mjs';
75
88
  import { burnReport } from '../src/report.mjs';
76
89
  import { loadBlocks, logBlock, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
77
90
  import { claudeSamples, readCodex } from '../src/sources.mjs';
@@ -93,8 +106,8 @@ import {
93
106
  windowStart,
94
107
  } from '../src/subagents.mjs';
95
108
  import { forTerminal } from '../src/term.mjs';
96
- import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
97
- import { loadToolStats, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
109
+ import { firstFlag, resultTokens, toolKey, toolNotice } from '../src/toolcheck.mjs';
110
+ import { loadLiveStats, loadToolStats, recordToolSize, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
98
111
  import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
99
112
  import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
100
113
  import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valuePeriod, valueSection, valueTotals } from '../src/value.mjs';
@@ -119,7 +132,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
119
132
  limitcast optimize status inspect repository evidence, proposals and optimization receipts
120
133
  limitcast optimize learn on|off learn safe check-command alternatives; three independent sessions to promote
121
134
  limitcast optimize map [on|off] show a bounded source-symbol map or opt into session-start injection
122
- limitcast optimize capabilities --codex preview unused built-in packages; --apply <names> / --undo
135
+ limitcast optimize capabilities [--codex|--grok] preview unused tools (Claude), built-in packages and MCP servers (Codex), MCP servers (Grok); --apply <names> / --undo
123
136
  limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
124
137
  [--share] totals only, safe to post
125
138
  limitcast license show the MIT license status
@@ -157,7 +170,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
157
170
  and when your Claude limit itself changes
158
171
  limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
159
172
  limitcast notify webhook <url>|off also send them to a Slack or Discord webhook
160
- limitcast after-reset [--src claude|codex] [--window 5h|7d] [--detach] -- <command>
173
+ limitcast after-reset [--src claude|codex|grok] [--window 5h|7d] [--detach] -- <command>
161
174
  run a heavy job once the window has reset
162
175
  limitcast results --html [--out FILE] results, current windows and the burn report as one page
163
176
  limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
@@ -178,7 +191,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
178
191
  const [cmd, ...args] = process.argv.slice(2);
179
192
  const now = Date.now();
180
193
  // Hooks run unattended and fail open; everything else rejects a mistyped option instead of ignoring it.
181
- const typo = ['guard', 'prompt-check', 'tool-check', 'tool-limit', 'subagent-receipt', 'drift', 'statusline'].includes(cmd)
194
+ const typo = ['guard', 'prompt-check', 'tool-check', 'tool-limit', 'subagent-receipt', 'codex-notify', 'drift', 'statusline'].includes(cmd)
182
195
  ? undefined
183
196
  : unknownFlag(args);
184
197
  if (typo) {
@@ -189,6 +202,19 @@ const flag = (/** @type {string} */ name) => {
189
202
  const i = args.indexOf(name);
190
203
  return i >= 0 ? args[i + 1] : undefined;
191
204
  };
205
+ /** The tool a hook belongs to: `--src codex|grok` on hooks install writes for them, Claude Code otherwise. @returns {'claude'|'codex'|'grok'} */
206
+ const hookHost = () => {
207
+ const s = flag('--src');
208
+ return s === 'codex' || s === 'grok' ? s : 'claude';
209
+ };
210
+ /** Grok writes a finished subagent's usage after its stop hook ran: log the receipts parked at the stop. Never throws. */
211
+ const settleGrokReceipts = () => {
212
+ try {
213
+ settleReceipts(now);
214
+ } catch {
215
+ /* a hook must never break the session */
216
+ }
217
+ };
192
218
  const days = () => {
193
219
  const n = Number(flag('--days') ?? 7);
194
220
  if (!Number.isFinite(n) || n <= 0 || !Number.isFinite(new Date(now - n * 86400_000).getTime())) {
@@ -246,7 +272,8 @@ if (cmd === '_optimize-hook') {
246
272
  feed = JSON.parse(input);
247
273
  sid = feed?.session_id;
248
274
  record(claudeSamples(feed, now));
249
- saveFeedShape(feed);
275
+ // Grok runs the same status-line command. Its feed gets its own file, so `doctor`'s Claude checks only see Claude feeds.
276
+ saveFeedShape(feed, grokSessionLine(feed) ? 'last-feed-grok.json' : 'last-feed.json');
250
277
  // Readings are kept 8 days; the daily rollup folds what they showed into the long-term value record.
251
278
  if (dailyDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'rollup'], { detached: true, stdio: 'ignore' }).unref();
252
279
  const health = healthHint();
@@ -307,6 +334,7 @@ if (cmd === '_optimize-hook') {
307
334
  if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
308
335
  try {
309
336
  const hook = JSON.parse(readStdin());
337
+ settleGrokReceipts();
310
338
  const id = spawnIdentity(hook);
311
339
  const live = pruneInflight(loadInflight(), now);
312
340
  const dup = id ? findDuplicate(live, id) : null;
@@ -407,19 +435,24 @@ if (cmd === '_optimize-hook') {
407
435
  if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
408
436
  try {
409
437
  const hook = JSON.parse(readStdin());
438
+ // `--src codex|grok` (set by install) reads that tool's payload and its live-learned sizes; Claude's come from `report --why`.
439
+ const host = hookHost();
440
+ if (host === 'grok') settleGrokReceipts();
410
441
  const name = String(hook?.tool_name ?? hook?.toolName ?? '');
411
- const d = name ? toolLimitDecision(name, hook?.tool_input ?? hook?.toolInput, loadToolStats()) : null;
442
+ const stats = host === 'claude' ? loadToolStats() : loadLiveStats(host);
443
+ const d = name ? toolLimitDecision(name, hook?.tool_input ?? hook?.toolInput, stats, { host, rewrite: host !== 'codex' }) : null;
444
+ const opId = hook?.tool_use_id ?? hook?.toolUseId;
412
445
  if (d && 'deny' in d) {
413
446
  logBlock({
414
447
  t: now,
415
448
  kind: 'tool-limit',
416
- src: 'claude',
417
- win: '5h',
449
+ src: host,
450
+ win: host === 'codex' ? '7d' : '5h',
418
451
  pct: 0,
419
452
  wall: now,
420
453
  reset: now,
421
- sid: hook.session_id,
422
- ...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
454
+ sid: hook.session_id ?? hook.sessionId,
455
+ ...(typeof opId === 'string' ? { operation: opId } : {}),
423
456
  });
424
457
  console.log(
425
458
  JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d.deny } }),
@@ -428,13 +461,13 @@ if (cmd === '_optimize-hook') {
428
461
  logBlock({
429
462
  t: now,
430
463
  kind: 'tool-cap',
431
- src: 'claude',
432
- win: '5h',
464
+ src: host,
465
+ win: host === 'codex' ? '7d' : '5h',
433
466
  pct: 0,
434
467
  wall: now,
435
468
  reset: now,
436
- sid: hook.session_id,
437
- ...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
469
+ sid: hook.session_id ?? hook.sessionId,
470
+ ...(typeof opId === 'string' ? { operation: opId } : {}),
438
471
  });
439
472
  console.log(
440
473
  JSON.stringify({
@@ -456,9 +489,16 @@ if (cmd === '_optimize-hook') {
456
489
  try {
457
490
  {
458
491
  const hook = JSON.parse(readStdin());
459
- const name = String(hook?.tool_name ?? '');
460
- const notice = name ? toolNotice(name, hook?.tool_response, loadValue().calib, Number(process.env.LIMITCAST_TOOL_TOKENS) || undefined) : null;
461
- if (notice && firstFlag(String(hook.session_id), toolKey(name))) console.log(JSON.stringify({ systemMessage: notice }));
492
+ const host = hookHost();
493
+ if (host === 'grok') settleGrokReceipts();
494
+ const name = String(hook?.tool_name ?? hook?.toolName ?? '');
495
+ const response = hook?.tool_response ?? hook?.tool_result ?? hook?.toolResult;
496
+ // Codex and Grok have no 5-hour calibration, and no transcript report to learn tool sizes from: learn them here.
497
+ if (name && host !== 'claude') recordToolSize(host, toolKey(name, host), resultTokens(response));
498
+ const notice = name
499
+ ? toolNotice(name, response, host === 'claude' ? loadValue().calib : null, Number(process.env.LIMITCAST_TOOL_TOKENS) || undefined, host)
500
+ : null;
501
+ if (notice && firstFlag(String(hook.session_id ?? hook.sessionId), toolKey(name, host))) console.log(JSON.stringify({ systemMessage: notice }));
462
502
  }
463
503
  } catch {
464
504
  /* a hook must never break the session */
@@ -468,9 +508,40 @@ if (cmd === '_optimize-hook') {
468
508
  // Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
469
509
  try {
470
510
  const hook = JSON.parse(readStdin());
471
- saveInflight(forgetInflight(loadInflight(), String(hook?.session_id ?? ''), String(hook?.agent_type ?? ''), now));
511
+ // Claude Code and Codex send snake_case; Grok sends `sessionId` and `subagentType`. Every host clears the duplicate hold
512
+ // and gets a receipt: Claude's from its transcript, Codex's from the child rollout, Grok's from the child session ledger.
513
+ saveInflight(
514
+ forgetInflight(
515
+ loadInflight(),
516
+ String(hook?.session_id ?? hook?.sessionId ?? ''),
517
+ String(hook?.agent_type ?? hook?.subagentType ?? hook?.agentType ?? ''),
518
+ now,
519
+ ),
520
+ );
472
521
  const path = hook?.agent_transcript_path;
473
- if (hook?.agent_type && typeof path === 'string') {
522
+ const host = stopHost(hook);
523
+ if (host !== 'claude') {
524
+ const type = String(hook?.agent_type ?? hook?.subagentType ?? hook?.agentType ?? '');
525
+ if (host === 'grok') settleGrokReceipts();
526
+ const got = type ? hostSubagentUsage(hook) : null;
527
+ // Grok has not written this subagent's usage yet (it does a moment after the stop): park it for the next hook.
528
+ if (!got?.usage.calls && host === 'grok' && type) deferReceipt(now, type, hook);
529
+ if (got?.usage.calls) {
530
+ const { usage } = got;
531
+ logSubagent({
532
+ t: now,
533
+ src: got.src,
534
+ id: hook.agent_id ?? hook.subagentId,
535
+ sid: hook.session_id ?? hook.sessionId,
536
+ type,
537
+ calls: usage.calls,
538
+ fresh: usage.fresh,
539
+ read: usage.read,
540
+ ...(usage.usd === null ? {} : { usd: usage.usd }),
541
+ });
542
+ console.log(JSON.stringify({ systemMessage: receiptMessage(type, usage, null, usage.usd) }));
543
+ }
544
+ } else if (hook?.agent_type && typeof path === 'string') {
474
545
  const u = subagentUsage(path);
475
546
  const calib = loadValue().calib;
476
547
  const pct = calib ? windowPct(calib, { writes: u.fresh, reads: u.read }) : null;
@@ -491,6 +562,23 @@ if (cmd === '_optimize-hook') {
491
562
  } catch {
492
563
  /* a hook must never break the session */
493
564
  }
565
+ } else if (cmd === 'codex-notify') {
566
+ // Codex has no status line to raise a notification from. A Stop hook (installed with --guard) calls this with --hook; at most
567
+ // every few minutes it starts the check below in the background, so no Codex turn waits on reading the rollouts.
568
+ try {
569
+ if (args.includes('--hook')) {
570
+ readStdin();
571
+ if (notifyEnabled() && codexNotifyDue(now))
572
+ spawn(process.execPath, [fileURLToPath(import.meta.url), 'codex-notify'], { detached: true, stdio: 'ignore' }).unref();
573
+ } else if (notifyEnabled()) {
574
+ notifyChanges(
575
+ forecastAll(oneClaudeAccount(await readCodex(now - KEEP_MS)), now).filter((f) => f.src === 'codex'),
576
+ clock,
577
+ );
578
+ }
579
+ } catch {
580
+ /* a hook must never break the session */
581
+ }
494
582
  } else if (cmd === 'plan') {
495
583
  if (args[0] === 'set') {
496
584
  const id = args[1];
@@ -689,6 +777,21 @@ if (cmd === '_optimize-hook') {
689
777
  }
690
778
  const checks = await healthChecks();
691
779
  saveHealth(checks);
780
+ // The key in Codex's config.toml only says a hook was approved once, not that this version of it was. When limitcast has hooks
781
+ // in Codex, ask Codex itself which ones it trusts (it takes a second, so it belongs here and not in the daily background check).
782
+ try {
783
+ if (readFileSync(codexHooksPath(), 'utf8').includes('limitcast')) {
784
+ const rows = await codexHooks();
785
+ const line = rows ? trustLine(rows) : null;
786
+ if (line) {
787
+ const at = checks.findIndex((c) => c.line.startsWith('Codex subagent guard installed'));
788
+ if (at >= 0) checks.splice(at, 1);
789
+ checks.push(line);
790
+ }
791
+ }
792
+ } catch {
793
+ /* no Codex hooks file, or Codex did not answer: the checks above stand */
794
+ }
692
795
  // Memory is per project: shown here, but kept out of the saved health that the daily background check overwrites.
693
796
  const mem = memoryCheck(scanMemory(memoryDir()));
694
797
  if (mem) checks.push(mem);
@@ -884,13 +987,22 @@ if (cmd === '_optimize-hook') {
884
987
  } else if (cmd === 'drift') {
885
988
  // SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
886
989
  const hook = args.includes('--hook');
990
+ const host = hookHost();
991
+ if (host === 'grok') settleGrokReceipts();
887
992
  try {
888
- const latest = await latestInteractiveTranscript(claudeRoot());
889
- const d = latest ? recordOverhead(snapshot(latest)) : null;
993
+ // Claude Code: the last interactive transcript. Codex and Grok (`--src`): the sizes their last interactive session logged.
994
+ const claudeLatest = host === 'claude' ? await latestInteractiveTranscript(claudeRoot()) : null;
995
+ const start = host === 'codex' ? await codexStartup() : host === 'grok' ? grokStartup() : null;
996
+ const latest = claudeLatest ?? start;
997
+ const d = claudeLatest
998
+ ? recordOverhead(snapshot(claudeLatest))
999
+ : start && host !== 'claude'
1000
+ ? recordOverhead(hostSnapshot(host, start), host)
1001
+ : null;
890
1002
  if (hook) {
891
- const lines = d?.alert ? [driftMessage(d)] : [];
1003
+ const lines = d?.alert ? [driftMessage(d, host)] : [];
892
1004
  // Claude Code may have rewritten the files `trim --apply` changed: put the cuts back for the next session.
893
- const re = reapplyTrim();
1005
+ const re = host === 'claude' ? reapplyTrim() : { reapplied: [] };
894
1006
  if (re.reapplied.length)
895
1007
  lines.push(
896
1008
  `limitcast: Claude Code had undone ${re.reapplied.length} of your trim cuts; they're back from your next session. (limitcast trim --undo to drop them)`,
@@ -898,7 +1010,7 @@ if (cmd === '_optimize-hook') {
898
1010
  // Once a week, what limitcast did: shown to the user at session start, never to the model.
899
1011
  if (weeklyDue(now)) {
900
1012
  const since = now - 7 * 86400_000;
901
- const samples = [...load(since), ...(await readCodex(since))];
1013
+ const samples = [...load(since), ...(await readCodex(since)), ...grokHistory(since, now)];
902
1014
  const s = loadOverhead();
903
1015
  // The daily rollup keeps the value record current; a session-start hook must not scan transcripts itself.
904
1016
  const week = valuePeriod(loadValue(), since, now);
@@ -907,9 +1019,9 @@ if (cmd === '_optimize-hook') {
907
1019
  );
908
1020
  }
909
1021
  if (lines.length) console.log(JSON.stringify({ systemMessage: lines.join('\n') }));
910
- } else if (!latest) console.log('No interactive Claude Code session found yet.');
1022
+ } else if (!latest) console.log(`No interactive ${host === 'claude' ? 'Claude Code' : host === 'codex' ? 'Codex' : 'Grok'} session found yet.`);
911
1023
  else if (!d) console.log('Starting context recorded. limitcast will tell you when it grows.');
912
- else console.log(d.alert ? forTerminal(driftMessage(d)) : 'No meaningful change in your starting context since the last session.');
1024
+ else console.log(d.alert ? forTerminal(driftMessage(d, host)) : 'No meaningful change in your starting context since the last session.');
913
1025
  } catch (e) {
914
1026
  if (!hook) throw e; // a hook must never break session start
915
1027
  }
@@ -939,7 +1051,7 @@ if (cmd === '_optimize-hook') {
939
1051
  ? savedSummary(s, 0).split('\n')[0] // the per-session drop; the value section above has the totals
940
1052
  : 'Run `limitcast trim` once to record your starting context, then check back here.';
941
1053
  }
942
- const samples = [...load(since), ...(await readCodex(since))];
1054
+ const samples = [...load(since), ...(await readCodex(since)), ...grokHistory(since, now)];
943
1055
  const blocks = loadBlocks(since);
944
1056
  const usage = await readUsage(Math.min(since - days() * 86400_000, now - KEEP_MS), {}); // one read feeds both below
945
1057
  const value = await refreshValue(usage);
@@ -958,7 +1070,7 @@ if (cmd === '_optimize-hook') {
958
1070
  );
959
1071
  else if (args.includes('--html')) {
960
1072
  // results, the current windows and the burn report on one page, opened in the browser.
961
- const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
1073
+ const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS)), ...grokSamples(now)]), now);
962
1074
  const burn = burnReport(
963
1075
  usage.filter((u) => u.t >= since),
964
1076
  { since, now },
@@ -1051,15 +1163,21 @@ if (cmd === '_optimize-hook') {
1051
1163
  const sep = args.indexOf('--');
1052
1164
  const command = sep >= 0 ? args.slice(sep + 1) : [];
1053
1165
  const src = flag('--src') ?? 'claude';
1054
- const win = flag('--window') ?? '5h';
1055
1166
  if (!command.length) {
1056
- console.log('Usage: limitcast after-reset [--src claude|codex] [--window 5h|7d] [--detach] -- <command...>');
1167
+ console.log('Usage: limitcast after-reset [--src claude|codex|grok] [--window 5h|7d] [--detach] -- <command...>');
1057
1168
  process.exit(1);
1058
1169
  }
1059
- const samples = src === 'codex' ? await readCodex(now - KEEP_MS) : oneClaudeAccount(load(now - KEEP_MS));
1060
- const f = forecastAll(samples, now).find((x) => x.src === src && x.win === win);
1170
+ const samples = src === 'codex' ? await readCodex(now - KEEP_MS) : src === 'grok' ? grokSamples(now) : oneClaudeAccount(load(now - KEEP_MS));
1171
+ const rows = forecastAll(samples, now).filter((x) => x.src === src);
1172
+ // Without --window, use the shortest window this tool reports: a Codex plan may report only a 7-day window.
1173
+ const f = flag('--window') ? rows.find((x) => x.win === flag('--window')) : (rows.find((x) => x.win === '5h') ?? rows.find((x) => x.win === '7d'));
1174
+ const win = f?.win ?? flag('--window') ?? '5h';
1061
1175
  if (!f) {
1062
- console.log(`No ${src} ${win} readings yet, so the reset time is unknown.`);
1176
+ console.log(
1177
+ src === 'grok'
1178
+ ? 'No grok readings yet, so the reset time is unknown. Set a dollar cap first: limitcast budget grok <usd>'
1179
+ : `No ${src} ${win} readings yet, so the reset time is unknown.`,
1180
+ );
1063
1181
  process.exit(1);
1064
1182
  }
1065
1183
  const at = resetTarget(f, now);
@@ -1154,7 +1272,12 @@ async function refreshValue(preread) {
1154
1272
  const o = loadOverhead();
1155
1273
  // limitcast started watching at its first status-line reading (or first measurement), not when Codex's logs begin.
1156
1274
  const start = Math.min(now, o?.first.at ?? now, ...claude.map((s) => s.t));
1157
- const v = foldEvents(loadValue(), { now, samples: [...claude, ...(await readCodex(since))], blocks: loadBlocks(since), start });
1275
+ const v = foldEvents(loadValue(), {
1276
+ now,
1277
+ samples: [...claude, ...(await readCodex(since)), ...grokHistory(since, now)],
1278
+ blocks: loadBlocks(since),
1279
+ start,
1280
+ });
1158
1281
  await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
1159
1282
  // Recalibrate from the last 8 days when there is enough data; keep the last good calibration otherwise.
1160
1283
  const usage = preread ? preread.filter((u) => u.t >= since) : await readUsage(since, {});
@@ -1235,18 +1358,37 @@ function undoMessage(e) {
1235
1358
  /**
1236
1359
  * Keep the latest feed's structure (key names and rate_limits only, no prompt or path content) for diagnosing parsing.
1237
1360
  * @param {any} feed
1361
+ * @param {string} [file]
1238
1362
  */
1239
- function saveFeedShape(feed) {
1363
+ function saveFeedShape(feed, file = 'last-feed.json') {
1240
1364
  const shape = { at: now, keys: Object.keys(feed ?? {}), session_id: feed?.session_id, rate_limits: feed?.rate_limits };
1241
- writeFileSync(join(stateDir(), 'last-feed.json'), JSON.stringify(shape, null, 2));
1365
+ writeFileSync(join(stateDir(), file), JSON.stringify(shape, null, 2));
1242
1366
  }
1243
1367
 
1368
+ /**
1369
+ * The whole of stdin. A host that pipes a large payload (a tool result can be 100 KB or more) may hand us a non-blocking pipe,
1370
+ * where readFileSync(0) throws EAGAIN once the pipe runs dry and the rest of the payload is lost. Wait for the writer instead,
1371
+ * for at most ten seconds.
1372
+ */
1244
1373
  function readStdin() {
1245
- try {
1246
- return readFileSync(0, 'utf8');
1247
- } catch {
1248
- return '';
1374
+ const chunks = [];
1375
+ const buf = Buffer.alloc(65536);
1376
+ const until = Date.now() + 10_000;
1377
+ for (;;) {
1378
+ let n = 0;
1379
+ try {
1380
+ n = readSync(0, buf, 0, buf.length, null);
1381
+ } catch (e) {
1382
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'EAGAIN' && Date.now() < until) {
1383
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
1384
+ continue;
1385
+ }
1386
+ break; // EOF on some platforms, or a closed or unreadable stdin: what arrived so far is what we have
1387
+ }
1388
+ if (n === 0) break;
1389
+ chunks.push(Buffer.from(buf.subarray(0, n)));
1249
1390
  }
1391
+ return Buffer.concat(chunks).toString('utf8');
1250
1392
  }
1251
1393
 
1252
1394
  /** @param {number|null} ms */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.19.2",
3
+ "version": "0.19.4",
4
4
  "description": "Claude Code usage limits: forecast Codex and Grok too.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,11 +1,48 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, unlinkSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
3
4
  import { dirname, join, relative, sep } from 'node:path';
5
+ import { codexConfigPath, codexServers } from './codex.mjs';
6
+ import { grokServers } from './grok.mjs';
4
7
  import { capabilityProposals, changeOptimization, digest, readOptimization, saveOptimization } from './optimize.mjs';
5
8
  import { writeAtomic } from './store.mjs';
6
9
 
7
10
  const KEYS = { collaboration: ['multi_agent'], goals: ['goals'], image_media: ['view_image'] };
8
- const configPath = (repo, host) => join(repo.root, host === 'codex' ? '.codex/config.toml' : '.claude/settings.local.json');
11
+ const CONFIG = { claude: '.claude/settings.local.json', codex: '.codex/config.toml', grok: '.grok/config.toml' };
12
+ const configPath = (repo, host) => join(repo.root, CONFIG[host]);
13
+
14
+ /** The MCP servers a host has configured in its own user-level config, which a project file can switch off. */
15
+ export function configuredServers(host) {
16
+ try {
17
+ if (host === 'codex') return existsSync(codexConfigPath()) ? codexServers(readFileSync(codexConfigPath(), 'utf8')) : [];
18
+ if (host === 'grok') return grokServers();
19
+ } catch {
20
+ /* an unreadable configuration proposes nothing */
21
+ }
22
+ return [];
23
+ }
24
+
25
+ /**
26
+ * Add `[mcp_servers.<name>] enabled = false` tables to a project config.toml. Refuses a server the file already configures.
27
+ * Codex merges the table into the user-level definition, which stays where it is (command, env). Grok replaces the server
28
+ * with the project's entry whole, and ignores one that has no command; `stub` writes a command that never runs, because the
29
+ * server is disabled, so nothing of the user's definition (arguments, tokens, headers) is copied into the repository.
30
+ * @param {string} text
31
+ * @param {string[]} names
32
+ * @param {boolean} [stub]
33
+ */
34
+ export function patchMcpServers(text, names, stub = false) {
35
+ const existing = codexServers(text);
36
+ for (const name of names) {
37
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) throw new Error(`unsupported MCP server name ${name}`);
38
+ if (existing.some((s) => s.name === name)) throw new Error(`preserve explicit ${name} server setting; change it yourself`);
39
+ }
40
+ const tables = names
41
+ .map((name) => `[mcp_servers.${name}]\n${stub ? 'command = "true" # never runs: the server is off\n' : ''}enabled = false # limitcast optimizer`)
42
+ .join('\n\n');
43
+ const body = text.trimEnd();
44
+ return `${body ? `${body}\n\n` : ''}${tables}\n`;
45
+ }
9
46
 
10
47
  function safePath(repo, file) {
11
48
  for (let path = file; path !== repo.root; path = dirname(path)) {
@@ -38,27 +75,60 @@ export function validateCodex(repo, disabled = []) {
38
75
  // `features list` ignores -C on Codex 0.167; its actual cwd decides which project config is loaded.
39
76
  const output = execFileSync('codex', ['features', 'list'], { cwd: repo.root, encoding: 'utf8', timeout: 5000, maxBuffer: 100_000 });
40
77
  for (const key of Object.values(KEYS).flat()) {
41
- if (!new RegExp(`^${key}\\s+(?:stable|experimental|under development)\\s+(?:true|false)$`, 'm').test(output))
78
+ // Codex 0.169 lists multi_agent as "deprecated" yet still honors it; a "removed" key has no control to switch.
79
+ if (!new RegExp(`^${key}\\s+(?:stable|experimental|under development|deprecated)\\s+(?:true|false)$`, 'm').test(output))
42
80
  throw new Error(`Codex does not expose supported ${key} control`);
43
81
  }
44
82
  for (const key of disabled.flatMap((name) => KEYS[name] ?? [])) {
45
83
  if (!new RegExp(`^${key}\\s+.*\\s+false$`, 'm').test(output)) throw new Error(`Codex ignored the project ${key} setting; check project trust`);
46
84
  }
85
+ const servers = disabled.filter((name) => !Object.hasOwn(KEYS, name));
86
+ if (servers.length) checkServersOff('codex', repo, servers, 'Codex');
87
+ }
88
+
89
+ /** Grok: the effective MCP server list, read from the real project directory, must show each named server off. */
90
+ export function validateGrok(repo, disabled = []) {
91
+ if (disabled.length) checkServersOff('grok', repo, disabled, 'Grok');
92
+ }
93
+
94
+ /** `<host> mcp list --json` reports the settings the host actually loads, so an untrusted project that ignores the file shows up here. */
95
+ function checkServersOff(command, repo, names, label) {
96
+ const list = JSON.parse(
97
+ execFileSync(command, ['mcp', 'list', '--json'], { cwd: repo.root, encoding: 'utf8', timeout: 10_000, maxBuffer: 1_000_000 }),
98
+ );
99
+ if (!Array.isArray(list)) throw new Error(`${label} returned an unexpected MCP server list`);
100
+ for (const name of names) {
101
+ if (list.find((s) => s?.name === name)?.enabled !== false)
102
+ throw new Error(`${label} ignored the project setting for ${name}; check project trust`);
103
+ }
47
104
  }
48
105
 
49
- export function applyCapabilities(repo, host, names, { validate = validateCodex } = {}) {
50
- if (!['claude', 'codex'].includes(host) || !names.length) throw new Error('choose proposed Claude tools or Codex capabilities');
106
+ export function applyCapabilities(repo, host, names, { validate = host === 'grok' ? validateGrok : validateCodex } = {}) {
107
+ if (!['claude', 'codex', 'grok'].includes(host) || !names.length)
108
+ throw new Error('choose proposed Claude tools, or Codex or Grok capabilities and MCP servers');
51
109
  const file = configPath(repo, host);
52
110
  safePath(repo, file);
111
+ if (host !== 'claude' && [homedir(), realpathSync(homedir())].includes(repo.root))
112
+ // In the home directory the "project" file is the user's own config, which already holds every server it could turn off.
113
+ throw new Error(
114
+ `this repository is your home directory, so ${CONFIG[host]} is your own ${host === 'codex' ? 'Codex' : 'Grok'} config; use \`limitcast trim --${host} --apply\` to turn servers off everywhere`,
115
+ );
53
116
  if (host === 'codex') validate(repo);
117
+ const servers = configuredServers(host);
54
118
  const result = changeOptimization(repo, (state) => {
55
- const proposal = capabilityProposals(state, host);
119
+ const proposal = capabilityProposals(state, host, servers);
56
120
  if (names.some((n) => !proposal.includes(n))) throw new Error('selection is protected, used, or lacks evidence; preview again');
57
121
  if (state.applied?.[host]) throw new Error('restore the previous capability change before applying another');
58
122
  if (existsSync(file) && statSync(file).size > 100_000) throw new Error('project configuration exceeds safe editing limit');
59
123
  const before = existsSync(file) ? readFileSync(file, 'utf8') : null;
60
124
  let after;
61
- if (host === 'codex') after = patchCodexCapabilities(before ?? '', names);
125
+ if (host === 'codex') {
126
+ const features = names.filter((n) => Object.hasOwn(KEYS, n));
127
+ const mcp = names.filter((n) => !Object.hasOwn(KEYS, n));
128
+ after = before ?? '';
129
+ if (features.length) after = patchCodexCapabilities(after, features);
130
+ if (mcp.length) after = patchMcpServers(after, mcp);
131
+ } else if (host === 'grok') after = patchMcpServers(before ?? '', names, true);
62
132
  else {
63
133
  const cfg = JSON.parse(before ?? '{}');
64
134
  if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw new Error('settings must be an object');
@@ -89,7 +159,7 @@ export function applyCapabilities(repo, host, names, { validate = validateCodex
89
159
  return { path: file, names, restart: true };
90
160
  });
91
161
  try {
92
- if (host === 'codex') validate(repo, names);
162
+ if (host === 'codex' || host === 'grok') validate(repo, names);
93
163
  } catch (error) {
94
164
  restoreCapabilities(repo, host, { protect: false });
95
165
  throw error;
@@ -121,5 +191,10 @@ export function restoreCapabilities(repo, host, { protect = true } = {}) {
121
191
  export function capabilityStatus(repo, host) {
122
192
  const state = readOptimization(repo);
123
193
  if (host === 'codex') validateCodex(repo);
124
- return { host, proposed: capabilityProposals(state, host), applied: state.applied?.[host]?.names ?? [], keep: state.config.keep };
194
+ return {
195
+ host,
196
+ proposed: capabilityProposals(state, host, configuredServers(host)),
197
+ applied: state.applied?.[host]?.names ?? [],
198
+ keep: state.config.keep,
199
+ };
125
200
  }