limitcast 0.13.1 → 0.14.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/README.md CHANGED
@@ -57,12 +57,13 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
57
57
 
58
58
  | Command | |
59
59
  |---|---|
60
- | `limitcast status [--json]` | Used, burn rate, runout time and reset for each window, and today's share of each weekly one. **Pro** also lists your other Claude accounts |
60
+ | `limitcast status [--json]` | Used, burn rate, runout time and reset for each window, and today's share of each weekly one. When a window is on pace to run out, one line names the one that binds first and where else there is room ("You'll hit Claude 7d first (Thu 14:00). Grok 5h still has $38."). **Pro** also lists your other Claude accounts |
61
61
  | `limitcast trim --codex [--apply / --undo]` | Codex: AGENTS.md size and MCP servers in `~/.codex/config.toml` you haven't used. **Pro** names them and turns them off (`enabled = false`; `--undo` restores the file exactly) |
62
62
  | `limitcast trim --grok [--apply / --undo]` | Grok: system prompt and tool-definition size, and MCP servers in `~/.grok/config.toml` you haven't used. **Pro** names them and turns them off (`enabled = false`; `--undo` restores the file exactly) |
63
63
  | `limitcast notify on/off/test` | **Pro.** A desktop notification when a Claude window turns NEAR, AT_RISK or HIT, and when it resets after a HIT. On macOS they come from a tiny limitcast notifier app, listed as "limitcast" in System Settings → Notifications |
64
64
  | `limitcast notify ntfy <topic or https URL>` / `notify webhook <https URL>` | **Pro.** Also send every notification to your phone through [ntfy](https://ntfy.sh) (install the app, subscribe to the topic) or to a Slack or Discord incoming webhook. `off` removes it. Sent in the background, so no hook waits on the network |
65
65
  | `limitcast budget subagents <percent>` / `off` | **Pro.** Once subagents have used that share of the current 5-hour window, the guard holds new ones until it resets. Priced from your own readings (needs about a day of use first) |
66
+ | `limitcast budget today on` / `off` | **Pro.** The `today N% left` pace of a weekly window becomes an action. With `notify on` you get one notification a day at 80% of today's share. With `budget today on` the guard also holds new subagents once today's share is used up, until local midnight. Off by default; a window already at 100% is left to the tool; `LIMITCAST_ALLOW=1` overrides. Free installs record what it would have held (`results`) |
66
67
  | `limitcast subagent-model <type> <sonnet\|opus\|haiku\|claude-id\|grok-id>` / `off` | **Pro.** Run new subagents of that type (for example `Explore` or `explore`) on that model, unless the spawn names a model itself. Grok ids also write `[subagents.models]` in `~/.grok/config.toml` (restart Grok). Without arguments it lists what is pinned and the types you ran in the last 30 days. Needs `install --guard`; `results` counts the subagents it moved |
67
68
  | `limitcast plan [--days N]`, `limitcast plan set <pro\|max5\|max20>` / `off` | **Pro.** Does your Claude plan fit how much you use? From a long-lived record of the peak of every 5-hour and weekly window (kept 120 days; it starts when you install this version) it says whether you reached your limits often enough to look at the next plan, or used so little that a smaller one would have fit, with the monthly price difference, and shows what your Claude Code tokens would cost at API list prices. Tell it your plan first with `plan set`. Plan prices (Pro $20, Max 5x $100, Max 20x $200) and the 5x / 20x multipliers are from claude.com/pricing (2026-10-26; the Max 20x price was not on that page: change any price in `prices.json`, `{"plans": {"max20": 200}}`). It assumes weekly limits scale like the 5-hour limit, and it cannot see extra-usage spend |
68
69
  | `limitcast budget grok <usd>` / `off` / `7d <usd>` | **Pro.** Dollar cap for Grok's aligned 5-hour window (optional 7-day cap). Turns Grok spend into a % so `status` can forecast runout and the guard can block `spawn_subagent` |
@@ -77,6 +78,7 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
77
78
  | `limitcast trim [--days N] [--share]` | Measured starting context of your latest session and how much you haven't used in N days (default 7). **Pro** names each item. `--share`: totals only, no names, safe to post |
78
79
  | `limitcast saved` | **Pro.** How much the part of your starting context you control has dropped since limitcast first measured it, times your sessions since |
79
80
  | `limitcast trim --apply` / `--undo` | **Pro.** Hide the unused skills from the model and turn off the unused MCP servers for that project, through Claude Code's own settings. Backed up; `--undo` reverses exactly what it changed |
81
+ | `limitcast trim keep <name>[,<name>]` | Servers or skills no `trim --apply` (Claude, Codex or Grok) ever turns off or hides, e.g. `trim keep ego-browser`. `--remove <name>` drops one; no name lists them. Free to set; `trim` shows what it would keep |
80
82
  | `limitcast results [--days N] [--share]` | Proof it works: each limit window that reached 100% and how far ahead limitcast warned, and what the guard blocked (free: what it would have blocked) and whether that window then ran out. **Pro** adds starting-context savings. `--share`: totals only |
81
83
  | `install --alerts` | **Pro.** A SessionStart hook that tells you (never the model) when your starting context grew ~1k+ tokens, and what grew, plus a one-line weekly summary of what limitcast did |
82
84
  | `limitcast activate <key>` | Unlock Pro: registers this computer with Polar (3 computers per key). Polar re-checks it weekly in the background; it keeps working up to 30 days offline |
package/bin/limitcast.mjs CHANGED
@@ -7,11 +7,14 @@ import { fileURLToPath } from 'node:url';
7
7
  import {
8
8
  applyTrim,
9
9
  claudeJsonPath,
10
+ getKeep,
10
11
  installedPlugins,
12
+ isKept,
11
13
  localSkillFolders,
12
14
  planTrim,
13
15
  projectMcpServers,
14
16
  reapplyTrim,
17
+ setKeep,
15
18
  stillLoading,
16
19
  transcriptCwd,
17
20
  undoTrim,
@@ -38,7 +41,7 @@ import {
38
41
  undoGrokTrim,
39
42
  } from '../src/grok.mjs';
40
43
  import { runGuard } from '../src/guard.mjs';
41
- import { accountForecasts, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
44
+ import { accountForecasts, bindingLine, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
42
45
  import { htmlPage } from '../src/html.mjs';
43
46
  import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
44
47
  import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
@@ -56,11 +59,13 @@ import {
56
59
  budgetSpent,
57
60
  getBudget,
58
61
  getSubagentModels,
62
+ getTodayHold,
59
63
  loadSubagents,
60
64
  logSubagent,
61
65
  receiptMessage,
62
66
  setBudget,
63
67
  setSubagentModel,
68
+ setTodayHold,
64
69
  subagentUsage,
65
70
  validModel,
66
71
  windowStart,
@@ -94,6 +99,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
94
99
  limitcast trim --apply / --undo hide those skills and turn off those MCP servers (backed up, reversible)
95
100
  limitcast trim --codex --apply / --undo turn off unused Codex MCP servers (enabled = false; reversible)
96
101
  limitcast trim --grok --apply / --undo turn off unused Grok MCP servers (enabled = false; reversible)
102
+ limitcast trim keep <name>[,<name>…] never hide or turn off these (any --apply); --remove <name> drops one, no name lists them
97
103
  limitcast saved tokens saved since limitcast first measured you
98
104
  limitcast install --guard block new subagents when a window is on pace to run out, and run
99
105
  them on Sonnet while a window is tight (NEAR or AT_RISK); show what
@@ -106,6 +112,8 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
106
112
  limitcast plan set <pro|max5|max20>|off tell limitcast which Claude plan you are on
107
113
  limitcast budget grok <usd>|off Grok 5-hour dollar cap (Grok stores spend, not a % used; the guard
108
114
  needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
115
+ limitcast budget today on|off hold new subagents once today's share of a weekly window is used up, until
116
+ midnight (off: you only get a notification at 80% of the share; notify on)
109
117
  limitcast install --alerts tell you when your starting context grows, plus a weekly summary, and
110
118
  when one tool result is very large (about 20k tokens), with what to ask for instead
111
119
  limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
@@ -148,6 +156,8 @@ if (cmd === 'status') {
148
156
  if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
149
157
  else {
150
158
  console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, Codex or Grok.');
159
+ const binds = bindingLine(rows, getGrokBudget(), clock);
160
+ if (binds) console.log(`\n${binds}`);
151
161
  // Pro: the other Claude accounts limitcast has current readings for (the table shows the latest one).
152
162
  if (isPro())
153
163
  for (const a of accountForecasts(load(now - KEEP_MS), now).slice(1))
@@ -416,9 +426,25 @@ if (cmd === 'status') {
416
426
  console.log('The budget is enforced by the guard: limitcast install --guard (then restart Grok).');
417
427
  process.exit(0);
418
428
  }
429
+ if (args[0] === 'today') {
430
+ if (args[1] !== undefined && args[1] !== 'on' && args[1] !== 'off') {
431
+ console.log('Usage: limitcast budget today on|off');
432
+ process.exit(1);
433
+ }
434
+ if (args[1]) setTodayHold(args[1] === 'on');
435
+ console.log(
436
+ getTodayHold()
437
+ ? "Daily hold is on: the guard holds new subagents once today's share of a weekly window is used up, until midnight. Turn it off: limitcast budget today off"
438
+ : "Daily hold is off: you get a notification at 80% of today's share (limitcast notify on), nothing is held. Hold new subagents past it: limitcast budget today on",
439
+ );
440
+ if (getTodayHold() && !installedFeatures().guard) console.log('The hold is enforced by the guard: limitcast install --guard');
441
+ process.exit(0);
442
+ }
419
443
  const value = args[1];
420
444
  if (args[0] !== 'subagents' || (value !== undefined && value !== 'off' && !(Number(value) > 0 && Number(value) <= 100))) {
421
- console.log('Usage: limitcast budget subagents <percent of the 5-hour window, 1-100>|off\n limitcast budget grok <usd>|off');
445
+ console.log(
446
+ 'Usage: limitcast budget subagents <percent of the 5-hour window, 1-100>|off\n limitcast budget grok <usd>|off\n limitcast budget today on|off',
447
+ );
422
448
  process.exit(1);
423
449
  }
424
450
  if (value !== undefined) setBudget(value === 'off' ? null : Number(value));
@@ -501,6 +527,20 @@ if (cmd === 'status') {
501
527
  process.exit(2);
502
528
  }
503
529
  const since = now - days() * 86400_000;
530
+ if (cmd === 'trim' && args[0] === 'keep') {
531
+ // The keep-list: servers and skills `trim --apply` never touches (Claude, Codex and Grok). Free to manage; apply is Pro.
532
+ const drop = args[1] === '--remove';
533
+ const names = args
534
+ .slice(drop ? 2 : 1)
535
+ .join(',')
536
+ .split(',')
537
+ .map((n) => n.trim())
538
+ .filter(Boolean);
539
+ if (names.length) setKeep(drop ? getKeep().filter((k) => !isKept(names, k)) : [...getKeep(), ...names]);
540
+ const keep = getKeep();
541
+ console.log(keep.length ? `Kept by \`trim --apply\`: ${keep.join(', ')}` : 'Nothing on the keep-list. Example: limitcast trim keep ego-browser');
542
+ process.exit(0);
543
+ }
504
544
  if (cmd === 'trim' && args.includes('--codex')) {
505
545
  // Codex: AGENTS.md and the MCP servers in ~/.codex/config.toml. Free counts them; Pro names them and turns them off.
506
546
  if ((args.includes('--apply') || args.includes('--undo')) && !pro) {
@@ -519,13 +559,13 @@ if (cmd === 'status') {
519
559
  process.exit(0);
520
560
  }
521
561
  const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
522
- const r = codexTrimReport({ servers, used: await codexUsedServers(since), startup: await codexStartup(), days: days(), pro });
562
+ const r = codexTrimReport({ servers, used: await codexUsedServers(since), startup: await codexStartup(), days: days(), pro, keep: getKeep() });
523
563
  if (args.includes('--apply')) {
524
564
  const changed = applyCodexTrim(r.unused);
525
565
  console.log(
526
- changed.length
566
+ (changed.length
527
567
  ? `✓ Turned off ${changed.length} Codex MCP servers (enabled = false in ${codexConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Codex session. Undo: limitcast trim --codex --undo`
528
- : 'Nothing to turn off: every server that is on was used.',
568
+ : 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
529
569
  );
530
570
  } else console.log(forTerminal(r.text));
531
571
  process.exit(0);
@@ -552,13 +592,14 @@ if (cmd === 'status') {
552
592
  startup: grokStartup(),
553
593
  days: days(),
554
594
  pro,
595
+ keep: getKeep(),
555
596
  });
556
597
  if (args.includes('--apply')) {
557
598
  const changed = applyGrokTrim(r.unused);
558
599
  console.log(
559
- changed.length
600
+ (changed.length
560
601
  ? `✓ Turned off ${changed.length} Grok MCP servers (enabled = false in ${grokConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Grok session. Undo: limitcast trim --grok --undo`
561
- : 'Nothing to turn off: every server that is on was used.',
602
+ : 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
562
603
  );
563
604
  } else console.log(forTerminal(r.text));
564
605
  process.exit(0);
@@ -592,15 +633,16 @@ if (cmd === 'status') {
592
633
  console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
593
634
  process.exit(0);
594
635
  }
595
- if (latest && (args.includes('--share') || !pro)) text = shareSummary(baseline(usage), latest, used, days());
596
- else text = latest ? startupReport(baseline(usage), latest, used, days()) : trimReport(baseline(usage), contributors(), used, days());
636
+ const keep = getKeep();
637
+ if (latest && (args.includes('--share') || !pro)) text = shareSummary(baseline(usage), latest, used, days(), keep);
638
+ else text = latest ? startupReport(baseline(usage), latest, used, days(), keep) : trimReport(baseline(usage), contributors(), used, days());
597
639
  if (!pro)
598
640
  text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`;
599
641
  else if (latest && !args.includes('--share')) {
600
642
  const still = stillLoading(latest);
601
643
  text += still.length
602
644
  ? `\n\nStill loading after \`trim --apply\`: ${still.join(', ')}. A Claude Code session that was running may have rewritten ~/.claude.json; quit Claude Code and run \`limitcast trim --apply\` again.`
603
- : measuredSavings(latest.pieces, used).tokens > 0
645
+ : measuredSavings(latest.pieces, used, keep).tokens > 0
604
646
  ? '\n\nApply these cuts: `limitcast trim --apply` (backed up; `limitcast trim --undo` reverses it).'
605
647
  : '';
606
648
  }
@@ -910,7 +952,7 @@ function freeWeeklyHint(t) {
910
952
  }
911
953
  if (t < from) return null;
912
954
  const preview = loadBlocks(t - WEEK).filter((b) => b.shadow);
913
- const stopped = preview.filter((b) => !b.kind || b.kind === 'budget').length;
955
+ const stopped = preview.filter((b) => !b.kind || b.kind === 'budget' || b.kind === 'today').length;
914
956
  const moved = preview.filter((b) => b.kind === 'switch').length;
915
957
  const cold = preview.filter((b) => b.kind === 'cold').length;
916
958
  if (!stopped && !moved && !cold) return null;
@@ -992,6 +1034,7 @@ function applyMessage(latest, used) {
992
1034
  plugins: installedPlugins(),
993
1035
  projectMcpJson: projectMcpServers(cwd),
994
1036
  localSkills: localSkillFolders(cwd),
1037
+ keep: getKeep(),
995
1038
  });
996
1039
  const e = applyTrim(plan, { cwd, now });
997
1040
  const lines = [];
@@ -1000,6 +1043,7 @@ function applyMessage(latest, used) {
1000
1043
  if (e.mcp.length) lines.push(`✓ Turned off ${e.mcp.length} MCP servers for ${cwd}: ${e.mcp.join(', ')}`);
1001
1044
  if (plan.pluginSkills.length) lines.push(`- Plugin skills can only be turned off with their plugin (\`/plugin\`): ${plan.pluginSkills.join(', ')}`);
1002
1045
  if (plan.manualMcp.length) lines.push(`- Turn these off in \`/mcp\` (limitcast couldn't confirm their exact names): ${plan.manualMcp.join(', ')}`);
1046
+ if (plan.kept.length) lines.push(`- Kept, as on your keep-list: ${[...new Set(plan.kept)].join(', ')}`);
1003
1047
  if (!e.skills.length && !e.mcp.length) lines.unshift('Nothing to change automatically.');
1004
1048
  else
1005
1049
  lines.push(
@@ -1008,6 +1052,11 @@ function applyMessage(latest, used) {
1008
1052
  return lines.join('\n');
1009
1053
  }
1010
1054
 
1055
+ /** The keep-list servers a Codex or Grok `trim --apply` left on. @param {string[]} kept */
1056
+ function keptNote(kept) {
1057
+ return kept.length ? `\nKept, as on your keep-list: ${kept.join(', ')}` : '';
1058
+ }
1059
+
1011
1060
  /** @param {ReturnType<typeof undoTrim>} e */
1012
1061
  function undoMessage(e) {
1013
1062
  if (!e) return 'Nothing to undo.';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "description": "Stretch your Claude Code plan: measure what every session loads before you type, cut what you never use, and stop runaway subagents before they burn your window.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/apply.mjs CHANGED
@@ -30,6 +30,32 @@ const ledgerPath = () => join(stateDir(), 'trim-applied.json');
30
30
 
31
31
  /** MCP tool names keep the server name but normalize punctuation. @param {string} s */
32
32
  const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '_');
33
+ const configFile = () => join(stateDir(), 'config.json');
34
+
35
+ /** Names `trim --apply` never turns off or hides, from `limitcast trim keep`. @returns {string[]} */
36
+ export function getKeep() {
37
+ try {
38
+ const k = JSON.parse(readFileSync(configFile(), 'utf8')).trimKeep;
39
+ return Array.isArray(k) ? k.filter((n) => typeof n === 'string') : [];
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ /** @param {string[]} names */
46
+ export function setKeep(names) {
47
+ let cfg = {};
48
+ try {
49
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
50
+ } catch {
51
+ /* new */
52
+ }
53
+ mkdirSync(stateDir(), { recursive: true });
54
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, trimKeep: [...new Set(names)] }));
55
+ }
56
+
57
+ /** Same server or skill under another spelling ("ego-browser" / "ego_browser") counts. @param {string[]} keep @param {string} name */
58
+ export const isKept = (keep, name) => keep.some((k) => norm(k) === norm(name));
33
59
 
34
60
  /**
35
61
  * Installed plugins and the MCP servers they register ("plugin:<plugin>:<server>").
@@ -63,15 +89,15 @@ export function installedPlugins(dir = configDir()) {
63
89
 
64
90
  /**
65
91
  * What `--apply` would change, from the unused items `trim` measured.
66
- * @param {{skills:string[], mcp:string[], cwd:string, settings:any, claudeJson:any, plugins:{names:Set<string>, servers:string[]}, projectMcpJson:string[], localSkills:Set<string>}} r
67
- * localSkills: folder names of personal and project skills
92
+ * @param {{skills:string[], mcp:string[], cwd:string, settings:any, claudeJson:any, plugins:{names:Set<string>, servers:string[]}, projectMcpJson:string[], localSkills:Set<string>, keep?:string[]}} r
93
+ * localSkills: folder names of personal and project skills; keep: the `trim keep` list, never hidden or disabled
68
94
  */
69
- export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, projectMcpJson, localSkills }) {
95
+ export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, projectMcpJson, localSkills, keep = [] }) {
70
96
  // "x:y" is a plugin skill (namespaced by its plugin) unless x is one of your own skill folders with nested skills.
71
97
  // Plugins can load from places installed_plugins.json doesn't list, so the namespace alone decides.
72
98
  const isPluginSkill = (/** @type {string} */ n) => n.includes(':') && !localSkills.has(n.split(':')[0]);
73
99
  const overrides = settings.skillOverrides ?? {};
74
- const hide = skills.filter((n) => !isPluginSkill(n) && (overrides[n] === undefined || overrides[n] === 'on'));
100
+ const hide = skills.filter((n) => !isPluginSkill(n) && (overrides[n] === undefined || overrides[n] === 'on') && !isKept(keep, n));
75
101
  const pluginSkills = skills.filter(isPluginSkill);
76
102
 
77
103
  // Exact server names Claude Code uses: configured servers, plugin servers, and names already toggled in /mcp anywhere.
@@ -90,12 +116,14 @@ export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, proj
90
116
  /** @type {string[]} */
91
117
  const manualMcp = [];
92
118
  for (const m of mcp) {
119
+ if (isKept(keep, m)) continue;
93
120
  // .mcp.json servers are approved per project in settings, not toggled in disabledMcpServers.
94
121
  const name = projectServers.has(norm(m)) ? null : (byNorm.get(norm(m)) ?? (m.startsWith('claude.ai ') ? m : null));
95
122
  if (!name) manualMcp.push(m);
96
123
  else if (!already.has(name)) disable.push(name);
97
124
  }
98
- return { hide, pluginSkills, disable, manualMcp };
125
+ const kept = [...skills, ...mcp].filter((n) => isKept(keep, n));
126
+ return { hide, pluginSkills, disable, manualMcp, kept };
99
127
  }
100
128
 
101
129
  /** @param {string} path */
package/src/codex.mjs CHANGED
@@ -118,11 +118,14 @@ export async function codexStartup(root = join(codexHome(), 'sessions')) {
118
118
  }
119
119
 
120
120
  /**
121
- * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean}} r
121
+ * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean, keep?:string[]}} r
122
+ * keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`
122
123
  */
123
- export function codexTrimReport({ servers, used, startup, days, pro }) {
124
+ export function codexTrimReport({ servers, used, startup, days, pro, keep = [] }) {
124
125
  const on = servers.filter((s) => s.enabled !== false);
125
- const unused = on.filter((s) => !used.has(norm(s.name)));
126
+ const idle = on.filter((s) => !used.has(norm(s.name)));
127
+ const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
128
+ const unused = idle.filter((s) => !kept.includes(s));
126
129
  const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
127
130
  const out = ['# limitcast trim --codex', ''];
128
131
  if (startup)
@@ -131,15 +134,16 @@ export function codexTrimReport({ servers, used, startup, days, pro }) {
131
134
  '',
132
135
  );
133
136
  out.push(`## MCP servers: ${on.length} on, ${unused.length} not used in ${days} days`);
134
- if (!unused.length) out.push('Every server that is on was used.');
137
+ if (!unused.length) out.push(kept.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
135
138
  else if (pro)
136
139
  out.push(...unused.map((s) => `- ${s.name}`), '', 'Turn them off: `limitcast trim --codex --apply` (backed up; `--undo` reverses it).');
137
140
  else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
141
+ if (kept.length) out.push('', `Would keep (your keep-list): ${kept.map((s) => s.name).join(', ')}.`);
138
142
  out.push(
139
143
  '',
140
144
  'Each server that is on starts with every Codex session and adds its tool list to the context. AGENTS.md: every 1k tokens you move into files read on demand saves 1k per turn.',
141
145
  );
142
- return { text: out.join('\n'), unused: unused.map((s) => s.name) };
146
+ return { text: out.join('\n'), unused: unused.map((s) => s.name), kept: kept.map((s) => s.name) };
143
147
  }
144
148
 
145
149
  /** @param {string} path @param {string} text */
package/src/grok.mjs CHANGED
@@ -73,11 +73,14 @@ export function grokStartup(root = grokRoot()) {
73
73
  }
74
74
 
75
75
  /**
76
- * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{prompt:number, tools:number}|null, days:number, pro:boolean}} r
76
+ * @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{prompt:number, tools:number}|null, days:number, pro:boolean, keep?:string[]}} r
77
+ * keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`
77
78
  */
78
- export function grokTrimReport({ servers, used, startup, days, pro }) {
79
+ export function grokTrimReport({ servers, used, startup, days, pro, keep = [] }) {
79
80
  const on = servers.filter((s) => s.enabled !== false);
80
- const unused = on.filter((s) => !used.has(norm(s.name)));
81
+ const idle = on.filter((s) => !used.has(norm(s.name)));
82
+ const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
83
+ const unused = idle.filter((s) => !kept.includes(s));
81
84
  const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
82
85
  const out = ['# limitcast trim --grok', ''];
83
86
  if (startup)
@@ -86,15 +89,16 @@ export function grokTrimReport({ servers, used, startup, days, pro }) {
86
89
  '',
87
90
  );
88
91
  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.');
92
+ if (!unused.length) out.push(kept.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
90
93
  else if (pro)
91
94
  out.push(...unused.map((s) => `- ${s.name}`), '', 'Turn them off: `limitcast trim --grok --apply` (backed up; `--undo` reverses it).');
92
95
  else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
96
+ if (kept.length) out.push('', `Would keep (your keep-list): ${kept.map((s) => s.name).join(', ')}.`);
93
97
  out.push(
94
98
  '',
95
99
  '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
100
  );
97
- return { text: out.join('\n'), unused: unused.map((s) => s.name) };
101
+ return { text: out.join('\n'), unused: unused.map((s) => s.name), kept: kept.map((s) => s.name) };
98
102
  }
99
103
 
100
104
  /**
package/src/guard.mjs CHANGED
@@ -4,7 +4,7 @@ import { grokSamples } from './grok.mjs';
4
4
  import { logBlock } from './results.mjs';
5
5
  import { readCodex } from './sources.mjs';
6
6
  import { KEEP_MS, load } from './store.mjs';
7
- import { budgetMessage, budgetSpent, getBudget, loadSubagents, pinnedModel, spawnNotice, windowStart } from './subagents.mjs';
7
+ import { budgetMessage, budgetSpent, getBudget, getTodayHold, loadSubagents, pinnedModel, spawnNotice, windowStart } from './subagents.mjs';
8
8
 
9
9
  const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
10
10
 
@@ -95,6 +95,27 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
95
95
  }
96
96
  }
97
97
  if (reason) return preview ? null : reason;
98
+ // Today's share of a weekly window is used up: hold new subagents until local midnight, when the share starts over.
99
+ // Opt-in for Pro (`limitcast budget today on`; the default is a notification at 80%); a free preview records it either way.
100
+ // A window already at 100% is left to the tool. shortcut: Codex readings here span only 2 hours, so its share reads low.
101
+ const day = todayOver(src, forecasts);
102
+ if (day && (preview || getTodayHold())) {
103
+ try {
104
+ logBlock({
105
+ t: now,
106
+ kind: 'today',
107
+ src: day.src,
108
+ win: day.win,
109
+ pct: Math.round(day.today.used),
110
+ wall: now,
111
+ reset: new Date(now).setHours(24, 0, 0, 0),
112
+ ...(preview ? { shadow: true } : {}),
113
+ });
114
+ } catch {
115
+ /* a failed log must not change the decision */
116
+ }
117
+ if (!preview) return todayMessage(day);
118
+ }
98
119
  // Pro: hold new Claude subagents once those of this account have used their budget of the current 5-hour window.
99
120
  const budget = src === 'claude' ? getBudget() : null;
100
121
  if (budget) {
@@ -182,6 +203,20 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
182
203
  };
183
204
  }
184
205
 
206
+ /**
207
+ * The spawning tool's weekly window when today's even share of it is used up (and the window itself is not at 100%).
208
+ * @param {'claude'|'codex'|'grok'|null} src
209
+ * @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
210
+ */
211
+ function todayOver(src, forecasts) {
212
+ return forecasts.find((f) => f.src === src && f.today && f.today.left < 0 && f.verdict !== 'HIT' && f.verdict !== 'RESET');
213
+ }
214
+
215
+ /** @param {NonNullable<ReturnType<typeof todayOver>>} f */
216
+ const todayMessage = (f) =>
217
+ `limitcast: today's share of your ${NAMES[/** @type {'claude'} */ (f.src)]} ${f.win} limit is used up (${Math.round(f.today?.used ?? 0)}% of ${Math.round(f.today?.budget ?? 0)}%). ` +
218
+ 'New subagents are held until midnight. Turn this off: `limitcast budget today off`, or set LIMITCAST_ALLOW=1 to spawn anyway.';
219
+
185
220
  const SWITCH_TO = 'sonnet';
186
221
 
187
222
  /**
package/src/hints.mjs CHANGED
@@ -42,6 +42,30 @@ export function headroom(samples, sid, now) {
42
42
  return `⇄ other account ${parts.join(' · ')}`;
43
43
  }
44
44
 
45
+ const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
46
+
47
+ /**
48
+ * One sentence naming the window that runs out first at the current pace, and where else there is room:
49
+ * "You'll hit Claude 7d first (Thu 14:00). Grok 5h still has $38." Null when no window is on pace to run out.
50
+ * @param {ReturnType<typeof forecastAll>} rows
51
+ * @param {{'5h'?:number, '7d'?:number}|null} grokCap the Grok dollar caps; a Grok row holds a % of its cap
52
+ * @param {(ms:number)=>string} clock
53
+ */
54
+ export function bindingLine(rows, grokCap, clock) {
55
+ const first = rows.filter((f) => f.verdict === 'AT_RISK' && f.wall !== null).sort((a, b) => (a.wall ?? 0) - (b.wall ?? 0))[0];
56
+ if (!first) return null;
57
+ const name = (/** @type {{src:string, win:string}} */ f) => `${NAMES[/** @type {'claude'} */ (f.src)] ?? f.src} ${f.win}`;
58
+ // Room: the least-used window of another tool that is not itself in trouble.
59
+ const room = rows.filter((f) => f.src !== first.src && f.verdict === 'OK').sort((a, b) => a.pct - b.pct)[0];
60
+ const cap = room?.src === 'grok' ? grokCap?.[/** @type {'5h'} */ (room.win)] : undefined;
61
+ const left = !room
62
+ ? ''
63
+ : cap
64
+ ? ` ${name(room)} still has $${Math.round((cap * (100 - room.pct)) / 100)}.`
65
+ : ` ${name(room)} has ${Math.round(100 - room.pct)}% left.`;
66
+ return `You'll hit ${name(first)} first (${clock(first.wall ?? first.reset)}).${left}`;
67
+ }
68
+
45
69
  const COMPACT_AT = 150_000; // tokens re-sent per model call worth a /compact
46
70
 
47
71
  /**
package/src/notify.mjs CHANGED
@@ -25,11 +25,14 @@ export function setNotify(on) {
25
25
  /**
26
26
  * Messages for windows that got worse since the last notification, or reset after reaching their limit.
27
27
  * Within one window the state only ratchets up, so a pace that wobbles around a threshold notifies once.
28
- * @param {{src:string, win:string, pct:number, reset:number, wall:number|null, verdict:string}[]} rows
28
+ * A weekly window's daily share also notifies once a day, at 80% of today's share used (key "<src>|<win>|today",
29
+ * reset = that day's midnight).
30
+ * @param {{src:string, win:string, pct:number, reset:number, wall:number|null, verdict:string, today?:{budget:number, used:number, left:number}|null}[]} rows
29
31
  * @param {Record<string, {reset:number, verdict:string}>} prev
30
32
  * @param {(ms:number)=>string} clock
33
+ * @param {number} [now] epoch ms
31
34
  */
32
- export function transitions(rows, prev, clock) {
35
+ export function transitions(rows, prev, clock, now = Date.now()) {
33
36
  const messages = [];
34
37
  const next = { ...prev };
35
38
  for (const f of rows) {
@@ -50,6 +53,16 @@ export function transitions(rows, prev, clock) {
50
53
  messages.push(`${name} limit is on pace to run out at ${clock(f.wall)}, before it resets at ${clock(f.reset)}.`);
51
54
  if (f.verdict === 'HIT') messages.push(`${name} limit reached. Resets ${clock(f.reset)}.`);
52
55
  }
56
+ const midnight = new Date(now).setHours(0, 0, 0, 0);
57
+ for (const f of rows) {
58
+ const t = f.today;
59
+ const key = `${f.src}|${f.win}|today`;
60
+ if (!t || t.budget <= 0 || t.used < 0.8 * t.budget || f.verdict === 'HIT' || next[key]?.reset === midnight) continue;
61
+ next[key] = { reset: midnight, verdict: 'NEAR' };
62
+ messages.push(
63
+ `${NAMES[/** @type {'claude'} */ (f.src)] ?? f.src} ${f.win}: ${Math.round((t.used / t.budget) * 100)}% of today's share used, ${Math.max(0, Math.round(t.left))}% left today.`,
64
+ );
65
+ }
53
66
  return { messages, next };
54
67
  }
55
68
 
package/src/results.mjs CHANGED
@@ -5,7 +5,7 @@ import { claudeAccounts, forecast } from './forecast.mjs';
5
5
  import { stateDir } from './store.mjs';
6
6
 
7
7
  /** @typedef {import('./forecast.mjs').Sample} Sample */
8
- /** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, shadow?:boolean, kind?:string, from?:string, to?:string, type?:string, tokens?:number}} Block t, wall, reset: epoch ms; shadow: a free install's preview, not acted on; kind "switch": a subagent moved to Sonnet instead of blocked, "budget": a subagent held over the budget, "cold": a message held after the prompt cache expired (pct: its cost, tokens: context re-sent); no kind: a forecast block */
8
+ /** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, shadow?:boolean, kind?:string, from?:string, to?:string, type?:string, tokens?:number}} Block t, wall, reset: epoch ms; shadow: a free install's preview, not acted on; kind "switch": a subagent moved to Sonnet instead of blocked, "budget": a subagent held over the budget, "cold": a message held after the prompt cache expired (pct: its cost, tokens: context re-sent), "today": a subagent held once today's share of a weekly window was used up (pct: used today); no kind: a forecast block */
9
9
 
10
10
  const JITTER_MS = 120_000; // Codex resets_at drifts by seconds between events
11
11
  const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
@@ -131,6 +131,7 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
131
131
  const defaults = mine.filter((b) => b.kind === 'default').length;
132
132
  const colds = mine.filter((b) => b.kind === 'cold');
133
133
  const budgets = mine.filter((b) => b.kind === 'budget').length;
134
+ const todays = mine.filter((b) => b.kind === 'today').length;
134
135
  return {
135
136
  readings,
136
137
  hits,
@@ -142,6 +143,7 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
142
143
  colds: colds.length,
143
144
  coldPct: colds.reduce((a, b) => a + b.pct, 0),
144
145
  budgets,
146
+ todays,
145
147
  };
146
148
  }
147
149
 
@@ -177,6 +179,7 @@ export function weeklyLine(st, savedPerSession, notResent = 0) {
177
179
  if (st.switches) parts.push(`moved ${st.switches} to Sonnet`);
178
180
  if (st.defaults) parts.push(`ran ${st.defaults} on their set model`);
179
181
  if (st.budgets) parts.push(`held ${st.budgets} over budget`);
182
+ if (st.todays) parts.push(`held ${st.todays} once today's share was used`);
180
183
  if (st.colds) parts.push(`caught ${st.colds} cold-cache message${st.colds === 1 ? '' : 's'}`);
181
184
  if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller`);
182
185
  if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent`);
@@ -276,6 +279,10 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
276
279
  `${pro ? 'Ran' : 'Pro would have run'} ${st.defaults} subagent${st.defaults === 1 ? '' : 's'} on the model you set for their type (limitcast subagent-model).`,
277
280
  );
278
281
  if (st.budgets) out.push(`Held ${st.budgets} subagent${st.budgets === 1 ? '' : 's'} once subagents had used their budget of the 5-hour window.`);
282
+ if (st.todays)
283
+ out.push(
284
+ `${pro ? 'Held' : 'Pro could have held'} ${st.todays} subagent${st.todays === 1 ? '' : 's'} once today's share of a weekly window was used up (limitcast budget today on).`,
285
+ );
279
286
 
280
287
  const recent = subagents.filter((e) => e.t >= now - days * 86400_000);
281
288
  if (recent.length || st.colds) {
package/src/subagents.mjs CHANGED
@@ -131,6 +131,27 @@ export function setBudget(pct) {
131
131
  writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
132
132
  }
133
133
 
134
+ /** Whether the guard holds new subagents once today's share of a weekly window is used up (`limitcast budget today on`). */
135
+ export function getTodayHold() {
136
+ try {
137
+ return JSON.parse(readFileSync(configFile(), 'utf8')).todayHold === true;
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
142
+
143
+ /** @param {boolean} on */
144
+ export function setTodayHold(on) {
145
+ let cfg = {};
146
+ try {
147
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
148
+ } catch {
149
+ /* new */
150
+ }
151
+ mkdirSync(stateDir(), { recursive: true });
152
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, todayHold: on }));
153
+ }
154
+
134
155
  /** A model a subagent type can be pinned to: sonnet, opus, haiku, a claude-... id, or a grok-... id. */
135
156
  export const validModel = (/** @type {unknown} */ m) => typeof m === 'string' && /^(sonnet|opus|haiku|claude-[a-z0-9.-]+|grok-[a-z0-9.-]+)$/i.test(m);
136
157
 
package/src/trim.mjs CHANGED
@@ -196,8 +196,9 @@ const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
196
196
  * From a measured startup breakdown: MCP servers and listed skills unused in the period, with their exact size.
197
197
  * @param {import('./startup.mjs').Piece[]} pieces
198
198
  * @param {Activity} used
199
+ * @param {string[]} [keep] the `trim keep` list: unused, but never counted as a cut; named in `kept`
199
200
  */
200
- export function measuredSavings(pieces, used) {
201
+ export function measuredSavings(pieces, used, keep = []) {
201
202
  const usedMcp = new Set([...used.mcp].map(norm));
202
203
  // Instructions and tool names spell a server differently ("claude.ai Postman" / "claude_ai_Postman"): merge by normalized name.
203
204
  /** @type {Map<string, {name:string, chars:number}>} */
@@ -212,9 +213,12 @@ export function measuredSavings(pieces, used) {
212
213
  }
213
214
  }
214
215
  const skills = pieces.filter((p) => p.group === 'Skill listing' && !skillUsed(p.name, used.skills)).sort((a, b) => b.chars - a.chars);
215
- const unusedMcp = [...mcp.values()].sort((a, b) => b.chars - a.chars);
216
- const chars = unusedMcp.reduce((a, m) => a + m.chars, 0) + skills.reduce((a, s) => a + s.chars, 0);
217
- return { unusedMcp, unusedSkills: skills, tokens: tok(chars) };
216
+ const kept = [...mcp.values(), ...skills].filter((x) => keep.some((k) => norm(k) === norm(x.name))).map((x) => x.name);
217
+ const isKept = (/** @type {{name:string}} */ x) => kept.includes(x.name);
218
+ const unusedMcp = [...mcp.values()].filter((m) => !isKept(m)).sort((a, b) => b.chars - a.chars);
219
+ const unusedSkills = skills.filter((s) => !isKept(s));
220
+ const chars = unusedMcp.reduce((a, m) => a + m.chars, 0) + unusedSkills.reduce((a, s) => a + s.chars, 0);
221
+ return { unusedMcp, unusedSkills, tokens: tok(chars), kept };
218
222
  }
219
223
 
220
224
  /**
@@ -223,9 +227,10 @@ export function measuredSavings(pieces, used) {
223
227
  * @param {{pieces:import('./startup.mjs').Piece[], at:number}} b
224
228
  * @param {Activity} used
225
229
  * @param {number} days
230
+ * @param {string[]} [keep] the `trim keep` list
226
231
  */
227
- export function startupReport(base, b, used, days) {
228
- const s = measuredSavings(b.pieces, used);
232
+ export function startupReport(base, b, used, days, keep = []) {
233
+ const s = measuredSavings(b.pieces, used, keep);
229
234
  const median = base?.median ?? 0;
230
235
  const lines = ['# limitcast trim', ''];
231
236
  if (base) {
@@ -257,7 +262,8 @@ export function startupReport(base, b, used, days) {
257
262
  ' Set each to `"user-invocable-only"` under `skillOverrides` in `~/.claude/settings.json`: `/name` still works.',
258
263
  );
259
264
  }
260
- if (!s.unusedMcp.length && !s.unusedSkills.length) lines.push('- Nothing unused. Everything that loads was used in the period.');
265
+ if (s.kept.length) lines.push(`- **Would keep ${s.kept.length} on your keep-list** (\`trim --apply\` never touches them): ${s.kept.join(', ')}.`);
266
+ else if (!s.unusedMcp.length && !s.unusedSkills.length) lines.push('- Nothing unused. Everything that loads was used in the period.');
261
267
 
262
268
  /** @type {Map<string, number>} */
263
269
  const groups = new Map();
@@ -293,16 +299,17 @@ export function startupReport(base, b, used, days) {
293
299
  * @param {{pieces:import('./startup.mjs').Piece[]}} b
294
300
  * @param {Activity} used
295
301
  * @param {number} days
302
+ * @param {string[]} [keep] the `trim keep` list; only its count is shown
296
303
  */
297
- export function shareSummary(base, b, used, days) {
298
- const s = measuredSavings(b.pieces, used);
304
+ export function shareSummary(base, b, used, days, keep = []) {
305
+ const s = measuredSavings(b.pieces, used, keep);
299
306
  /** @type {Map<string, number>} */
300
307
  const groups = new Map();
301
308
  for (const p of b.pieces) groups.set(p.group, (groups.get(p.group) ?? 0) + p.chars);
302
309
  const median = base?.median ?? 0;
303
310
  const lines = [
304
311
  `My Claude Code sessions start at ${fmt(median)} tokens before I type.`,
305
- `limitcast found ~${fmt(s.tokens)} per session${median ? ` (${Math.round((s.tokens / median) * 100)}%)` : ''} I haven't used in ${days} days: ${s.unusedMcp.length} MCP servers, ${s.unusedSkills.length} skills.`,
312
+ `limitcast found ~${fmt(s.tokens)} per session${median ? ` (${Math.round((s.tokens / median) * 100)}%)` : ''} I haven't used in ${days} days: ${s.unusedMcp.length} MCP servers, ${s.unusedSkills.length} skills${s.kept.length ? ` (${s.kept.length} more kept on my keep-list)` : ''}.`,
306
313
  'Where it comes from:',
307
314
  ...[...groups].sort((x, y) => y[1] - x[1]).map(([g, c]) => ` ${g}: ${fmt(tok(c))}`),
308
315
  ];