limitcast 0.13.0 → 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 +6 -4
- package/bin/limitcast.mjs +73 -16
- package/package.json +1 -1
- package/src/apply.mjs +33 -5
- package/src/codex.mjs +9 -5
- package/src/grok.mjs +53 -7
- package/src/guard.mjs +82 -4
- package/src/hints.mjs +24 -0
- package/src/notify.mjs +15 -2
- package/src/prices.mjs +17 -6
- package/src/report.mjs +4 -4
- package/src/results.mjs +8 -1
- package/src/subagents.mjs +35 -2
- package/src/trim.mjs +17 -10
- package/src/where.mjs +3 -1
package/README.md
CHANGED
|
@@ -51,19 +51,20 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
51
51
|
|
|
52
52
|
**Codex:** forecasts and reports need no setup (`~/.codex/sessions`, or `$CODEX_HOME/sessions`). With `--guard`, `install` also appends the guard to `~/.codex/hooks.json`, after your existing hooks so the ones you've already trusted keep their trust. Codex runs a new hook only once you approve it: start Codex and accept it. `limitcast doctor` shows whether it's trusted.
|
|
53
53
|
|
|
54
|
-
**Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json
|
|
54
|
+
**Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json` and prices Grok models at xAI list prices (the same API-equivalent column as Claude). `install` wraps `[ui.status_line]` in `~/.grok/config.toml` (session model, context % and cost on one line; the limitcast forecast under it). `--guard` writes `~/.grok/hooks/limitcast.json` matching `spawn_subagent`. Grok stores spend, not a % used, so the status line shows `grok 5h $X · 7d $Y` until you set a dollar cap (`limitcast budget grok <usd>`); then `status` forecasts that window and the guard blocks new spawns when it is on pace to run out. `limitcast subagent-model explore grok-4.3` writes `[subagents.models]` (restart Grok). Restart Grok to load the status line and hook.
|
|
55
55
|
|
|
56
56
|
## Commands
|
|
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
|
|
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`) |
|
|
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` |
|
|
69
70
|
| `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
|
|
@@ -71,12 +72,13 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
71
72
|
| `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
|
|
72
73
|
| `limitcast doctor [--fix]` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads. Also runs daily in the background and flags problems in the status line. `--fix` re-installs with the current Node (after a Node upgrade) |
|
|
73
74
|
| `limitcast trial` | Pro free for 7 days on this computer, no card, once |
|
|
74
|
-
| `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share; and the API-equivalent cost: what the tokens would cost at the API's list prices (Claude models
|
|
75
|
+
| `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share; and the API-equivalent cost: what the tokens would cost at the API's list prices (Claude and Grok models; a subscription is not billed this way). Prices are in the code as of 2026-10-26; add or change a model in `~/.local/state/limitcast/prices.json` (`{"models": {"claude-opus-4-1": {"input": 15, "output": 75}}}`, dollars per million tokens) |
|
|
75
76
|
| `limitcast report --why [--days N]` | **Pro.** Where your new tokens went: subagents, session starts, cache rebuilds after idle, tool results by tool, model output, and the largest single steps (Claude Code only) |
|
|
76
77
|
| `limitcast report --jobs [--days N]` | **Pro.** The scheduled (headless) jobs that spend the most tokens just starting: runs, average start, share of all new tokens, and how to launch a job leaner (Claude Code only) |
|
|
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,
|
|
@@ -22,6 +25,7 @@ import { coldCost, coldMessage, firstWarning } from '../src/cold.mjs';
|
|
|
22
25
|
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
23
26
|
import { formatChecks } from '../src/formats.mjs';
|
|
24
27
|
import {
|
|
28
|
+
applyGrokSubagentModel,
|
|
25
29
|
applyGrokTrim,
|
|
26
30
|
getGrokBudget,
|
|
27
31
|
grokConfigPath,
|
|
@@ -37,7 +41,7 @@ import {
|
|
|
37
41
|
undoGrokTrim,
|
|
38
42
|
} from '../src/grok.mjs';
|
|
39
43
|
import { runGuard } from '../src/guard.mjs';
|
|
40
|
-
import { accountForecasts, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
44
|
+
import { accountForecasts, bindingLine, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
41
45
|
import { htmlPage } from '../src/html.mjs';
|
|
42
46
|
import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
43
47
|
import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
|
|
@@ -55,11 +59,13 @@ import {
|
|
|
55
59
|
budgetSpent,
|
|
56
60
|
getBudget,
|
|
57
61
|
getSubagentModels,
|
|
62
|
+
getTodayHold,
|
|
58
63
|
loadSubagents,
|
|
59
64
|
logSubagent,
|
|
60
65
|
receiptMessage,
|
|
61
66
|
setBudget,
|
|
62
67
|
setSubagentModel,
|
|
68
|
+
setTodayHold,
|
|
63
69
|
subagentUsage,
|
|
64
70
|
validModel,
|
|
65
71
|
windowStart,
|
|
@@ -93,6 +99,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
93
99
|
limitcast trim --apply / --undo hide those skills and turn off those MCP servers (backed up, reversible)
|
|
94
100
|
limitcast trim --codex --apply / --undo turn off unused Codex MCP servers (enabled = false; reversible)
|
|
95
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
|
|
96
103
|
limitcast saved tokens saved since limitcast first measured you
|
|
97
104
|
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
98
105
|
them on Sonnet while a window is tight (NEAR or AT_RISK); show what
|
|
@@ -100,11 +107,13 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
100
107
|
one starts; hold the first message after the prompt
|
|
101
108
|
cache expired (idle over 60 min, LIMITCAST_CACHE_MINUTES) and say what it costs
|
|
102
109
|
limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
|
|
103
|
-
limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku or a model id
|
|
110
|
+
limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku, grok-… or a model id
|
|
104
111
|
limitcast plan [--days N] does your Claude plan fit your use? Hit-limit and headroom evidence, and the monthly price difference
|
|
105
112
|
limitcast plan set <pro|max5|max20>|off tell limitcast which Claude plan you are on
|
|
106
113
|
limitcast budget grok <usd>|off Grok 5-hour dollar cap (Grok stores spend, not a % used; the guard
|
|
107
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)
|
|
108
117
|
limitcast install --alerts tell you when your starting context grows, plus a weekly summary, and
|
|
109
118
|
when one tool result is very large (about 20k tokens), with what to ask for instead
|
|
110
119
|
limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
|
|
@@ -147,6 +156,8 @@ if (cmd === 'status') {
|
|
|
147
156
|
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
|
|
148
157
|
else {
|
|
149
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}`);
|
|
150
161
|
// Pro: the other Claude accounts limitcast has current readings for (the table shows the latest one).
|
|
151
162
|
if (isPro())
|
|
152
163
|
for (const a of accountForecasts(load(now - KEEP_MS), now).slice(1))
|
|
@@ -361,10 +372,16 @@ if (cmd === 'status') {
|
|
|
361
372
|
}
|
|
362
373
|
const [type, model] = args;
|
|
363
374
|
if (type && (model === undefined || (model !== 'off' && !validModel(model)))) {
|
|
364
|
-
console.log(
|
|
375
|
+
console.log(
|
|
376
|
+
'Usage: limitcast subagent-model <type> <sonnet|opus|haiku|claude-id|grok-id>|off\n limitcast subagent-model list them',
|
|
377
|
+
);
|
|
365
378
|
process.exit(1);
|
|
366
379
|
}
|
|
367
|
-
if (type)
|
|
380
|
+
if (type) {
|
|
381
|
+
const next = model === 'off' ? null : model;
|
|
382
|
+
setSubagentModel(type, next);
|
|
383
|
+
applyGrokSubagentModel(type, next);
|
|
384
|
+
}
|
|
368
385
|
const pinned = Object.entries(getSubagentModels());
|
|
369
386
|
console.log(pinned.length ? pinned.map(([t, m]) => `${t}: ${m}`).join('\n') : 'No subagent type is pinned to a model.');
|
|
370
387
|
const ran = new Map();
|
|
@@ -376,11 +393,12 @@ if (cmd === 'status') {
|
|
|
376
393
|
.map(([t, n]) => `${t} (${n})`)
|
|
377
394
|
.join(', ')}`,
|
|
378
395
|
);
|
|
379
|
-
if (pinned.length)
|
|
396
|
+
if (pinned.length) {
|
|
380
397
|
console.log(
|
|
381
398
|
'\nNew subagents of these types run on that model unless the spawn names one itself. Needs the guard: limitcast install --guard, then restart Claude Code.',
|
|
382
399
|
);
|
|
383
|
-
|
|
400
|
+
if (pinned.some(([, m]) => /^grok-/i.test(m))) console.log('Grok also writes [subagents.models] in ~/.grok/config.toml; restart Grok.');
|
|
401
|
+
} else console.log('\nExample: limitcast subagent-model Explore haiku');
|
|
384
402
|
process.exit(0);
|
|
385
403
|
} else if (cmd === 'budget') {
|
|
386
404
|
if (!isPro()) {
|
|
@@ -408,9 +426,25 @@ if (cmd === 'status') {
|
|
|
408
426
|
console.log('The budget is enforced by the guard: limitcast install --guard (then restart Grok).');
|
|
409
427
|
process.exit(0);
|
|
410
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
|
+
}
|
|
411
443
|
const value = args[1];
|
|
412
444
|
if (args[0] !== 'subagents' || (value !== undefined && value !== 'off' && !(Number(value) > 0 && Number(value) <= 100))) {
|
|
413
|
-
console.log(
|
|
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
|
+
);
|
|
414
448
|
process.exit(1);
|
|
415
449
|
}
|
|
416
450
|
if (value !== undefined) setBudget(value === 'off' ? null : Number(value));
|
|
@@ -493,6 +527,20 @@ if (cmd === 'status') {
|
|
|
493
527
|
process.exit(2);
|
|
494
528
|
}
|
|
495
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
|
+
}
|
|
496
544
|
if (cmd === 'trim' && args.includes('--codex')) {
|
|
497
545
|
// Codex: AGENTS.md and the MCP servers in ~/.codex/config.toml. Free counts them; Pro names them and turns them off.
|
|
498
546
|
if ((args.includes('--apply') || args.includes('--undo')) && !pro) {
|
|
@@ -511,13 +559,13 @@ if (cmd === 'status') {
|
|
|
511
559
|
process.exit(0);
|
|
512
560
|
}
|
|
513
561
|
const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
|
|
514
|
-
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() });
|
|
515
563
|
if (args.includes('--apply')) {
|
|
516
564
|
const changed = applyCodexTrim(r.unused);
|
|
517
565
|
console.log(
|
|
518
|
-
changed.length
|
|
566
|
+
(changed.length
|
|
519
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`
|
|
520
|
-
: '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),
|
|
521
569
|
);
|
|
522
570
|
} else console.log(forTerminal(r.text));
|
|
523
571
|
process.exit(0);
|
|
@@ -544,13 +592,14 @@ if (cmd === 'status') {
|
|
|
544
592
|
startup: grokStartup(),
|
|
545
593
|
days: days(),
|
|
546
594
|
pro,
|
|
595
|
+
keep: getKeep(),
|
|
547
596
|
});
|
|
548
597
|
if (args.includes('--apply')) {
|
|
549
598
|
const changed = applyGrokTrim(r.unused);
|
|
550
599
|
console.log(
|
|
551
|
-
changed.length
|
|
600
|
+
(changed.length
|
|
552
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`
|
|
553
|
-
: '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),
|
|
554
603
|
);
|
|
555
604
|
} else console.log(forTerminal(r.text));
|
|
556
605
|
process.exit(0);
|
|
@@ -584,15 +633,16 @@ if (cmd === 'status') {
|
|
|
584
633
|
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
|
|
585
634
|
process.exit(0);
|
|
586
635
|
}
|
|
587
|
-
|
|
588
|
-
|
|
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());
|
|
589
639
|
if (!pro)
|
|
590
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>`;
|
|
591
641
|
else if (latest && !args.includes('--share')) {
|
|
592
642
|
const still = stillLoading(latest);
|
|
593
643
|
text += still.length
|
|
594
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.`
|
|
595
|
-
: measuredSavings(latest.pieces, used).tokens > 0
|
|
645
|
+
: measuredSavings(latest.pieces, used, keep).tokens > 0
|
|
596
646
|
? '\n\nApply these cuts: `limitcast trim --apply` (backed up; `limitcast trim --undo` reverses it).'
|
|
597
647
|
: '';
|
|
598
648
|
}
|
|
@@ -902,7 +952,7 @@ function freeWeeklyHint(t) {
|
|
|
902
952
|
}
|
|
903
953
|
if (t < from) return null;
|
|
904
954
|
const preview = loadBlocks(t - WEEK).filter((b) => b.shadow);
|
|
905
|
-
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;
|
|
906
956
|
const moved = preview.filter((b) => b.kind === 'switch').length;
|
|
907
957
|
const cold = preview.filter((b) => b.kind === 'cold').length;
|
|
908
958
|
if (!stopped && !moved && !cold) return null;
|
|
@@ -984,6 +1034,7 @@ function applyMessage(latest, used) {
|
|
|
984
1034
|
plugins: installedPlugins(),
|
|
985
1035
|
projectMcpJson: projectMcpServers(cwd),
|
|
986
1036
|
localSkills: localSkillFolders(cwd),
|
|
1037
|
+
keep: getKeep(),
|
|
987
1038
|
});
|
|
988
1039
|
const e = applyTrim(plan, { cwd, now });
|
|
989
1040
|
const lines = [];
|
|
@@ -992,6 +1043,7 @@ function applyMessage(latest, used) {
|
|
|
992
1043
|
if (e.mcp.length) lines.push(`✓ Turned off ${e.mcp.length} MCP servers for ${cwd}: ${e.mcp.join(', ')}`);
|
|
993
1044
|
if (plan.pluginSkills.length) lines.push(`- Plugin skills can only be turned off with their plugin (\`/plugin\`): ${plan.pluginSkills.join(', ')}`);
|
|
994
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(', ')}`);
|
|
995
1047
|
if (!e.skills.length && !e.mcp.length) lines.unshift('Nothing to change automatically.');
|
|
996
1048
|
else
|
|
997
1049
|
lines.push(
|
|
@@ -1000,6 +1052,11 @@ function applyMessage(latest, used) {
|
|
|
1000
1052
|
return lines.join('\n');
|
|
1001
1053
|
}
|
|
1002
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
|
+
|
|
1003
1060
|
/** @param {ReturnType<typeof undoTrim>} e */
|
|
1004
1061
|
function undoMessage(e) {
|
|
1005
1062
|
if (!e) return 'Nothing to undo.';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
/**
|
|
@@ -395,6 +399,48 @@ export function restoreStatusLine(toml, previous) {
|
|
|
395
399
|
* A one-line session summary from Grok's status-line JSON (model, context %, session cost).
|
|
396
400
|
* @param {any} feed
|
|
397
401
|
*/
|
|
402
|
+
/**
|
|
403
|
+
* Set or clear a Grok `[subagents.models]` pin. A non-grok model (or null) removes that type's key.
|
|
404
|
+
* @param {string} type
|
|
405
|
+
* @param {string|null} model
|
|
406
|
+
* @param {{path?:string}} [opts]
|
|
407
|
+
*/
|
|
408
|
+
export function applyGrokSubagentModel(type, model, { path = grokConfigPath() } = {}) {
|
|
409
|
+
if (!existsSync(path)) return false;
|
|
410
|
+
const grokId = typeof model === 'string' && /^grok-[a-z0-9.-]+$/i.test(model) ? model : null;
|
|
411
|
+
const prev = readFileSync(path, 'utf8');
|
|
412
|
+
const next = patchGrokSubagentModel(prev, type, grokId);
|
|
413
|
+
if (next === prev) return false;
|
|
414
|
+
backup(path);
|
|
415
|
+
writeText(path, next);
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Pure TOML patch for `[subagents.models.<type>]`. `model` null deletes the key; an empty table is removed.
|
|
421
|
+
* @param {string} toml
|
|
422
|
+
* @param {string} type
|
|
423
|
+
* @param {string|null} model
|
|
424
|
+
*/
|
|
425
|
+
export function patchGrokSubagentModel(toml, type, model) {
|
|
426
|
+
const key = type.toLowerCase().replace(/[^a-z0-9_-]/g, '');
|
|
427
|
+
if (!key) return toml;
|
|
428
|
+
const range = tableRange(toml, 'subagents.models');
|
|
429
|
+
if (!range) {
|
|
430
|
+
if (!model) return toml;
|
|
431
|
+
return `${toml.trimEnd()}\n\n[subagents.models]\n${key} = ${tomlString(model)}\n`;
|
|
432
|
+
}
|
|
433
|
+
const keys = parseTable(range.body);
|
|
434
|
+
if (model) keys[key] = model;
|
|
435
|
+
else delete keys[key];
|
|
436
|
+
if (!Object.keys(keys).length) {
|
|
437
|
+
const before = toml.slice(0, range.start).trimEnd();
|
|
438
|
+
const after = toml.slice(range.end).replace(/^\n+/, '');
|
|
439
|
+
return after ? `${before}\n\n${after}` : `${before}\n`;
|
|
440
|
+
}
|
|
441
|
+
return toml.slice(0, range.start) + renderTable('subagents.models', keys, range.body) + toml.slice(range.end);
|
|
442
|
+
}
|
|
443
|
+
|
|
398
444
|
export function grokSessionLine(feed) {
|
|
399
445
|
if (!feed || typeof feed !== 'object') return '';
|
|
400
446
|
if (feed.rate_limits) return ''; // Claude Code feed
|
|
@@ -548,7 +594,7 @@ function parseTable(body) {
|
|
|
548
594
|
/** @type {Record<string, string>} */
|
|
549
595
|
const keys = {};
|
|
550
596
|
for (const line of body.split('\n').slice(1)) {
|
|
551
|
-
const m = /^\s*([A-Za-z0-9_]+)\s*=\s*(.*)$/.exec(line);
|
|
597
|
+
const m = /^\s*([A-Za-z0-9_-]+)\s*=\s*(.*)$/.exec(line);
|
|
552
598
|
if (!m) continue;
|
|
553
599
|
keys[m[1]] = unquote(m[2].trim());
|
|
554
600
|
}
|
|
@@ -572,7 +618,7 @@ function unquote(v) {
|
|
|
572
618
|
function renderTable(name, keys, previousBody) {
|
|
573
619
|
const order = [];
|
|
574
620
|
for (const line of previousBody.split('\n').slice(1)) {
|
|
575
|
-
const m = /^\s*([A-Za-z0-9_]+)\s*=/.exec(line);
|
|
621
|
+
const m = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line);
|
|
576
622
|
if (m && keys[m[1]] !== undefined && !order.includes(m[1])) order.push(m[1]);
|
|
577
623
|
}
|
|
578
624
|
for (const k of Object.keys(keys)) if (!order.includes(k)) order.push(k);
|
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,
|
|
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) {
|
|
@@ -124,10 +145,10 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
124
145
|
// Not blocked, but a window is tight: run a new Claude subagent on Sonnet instead of the main (usually Opus) model.
|
|
125
146
|
const input = hook?.tool_input ?? hook?.toolInput;
|
|
126
147
|
const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
|
|
148
|
+
const type = String(input?.subagent_type ?? input?.subagentType ?? '');
|
|
149
|
+
const pinned = isUnset(input?.model) && type ? pinnedModel(type) : undefined;
|
|
150
|
+
if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview);
|
|
127
151
|
if (src !== 'claude') return null;
|
|
128
|
-
// A subagent type pinned to a model (`limitcast subagent-model Explore haiku`) runs on it unless the spawn names a model itself.
|
|
129
|
-
const type = String(input?.subagent_type ?? '');
|
|
130
|
-
const pinned = isUnset(input?.model) && type ? getSubagentModels()[type] : undefined;
|
|
131
152
|
const model = pinned ?? input?.model;
|
|
132
153
|
if (!tight || !switchable(model)) {
|
|
133
154
|
if (pinned) {
|
|
@@ -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
|
/**
|
|
@@ -193,3 +228,46 @@ export const switchable = (model) => model === undefined || model === null || mo
|
|
|
193
228
|
|
|
194
229
|
/** Whether a spawn names no model of its own, so a pinned one may apply. @param {unknown} model */
|
|
195
230
|
const isUnset = (model) => model === undefined || model === null || model === '' || model === 'inherit';
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Grok: pin via updatedInput only when the spawn already has a `model` field (adding one fails the tool schema and
|
|
234
|
+
* denies the call). [subagents.models] in config.toml covers the rest after restart. Spawn notice when a cap exists.
|
|
235
|
+
* @param {any} input
|
|
236
|
+
* @param {string} type
|
|
237
|
+
* @param {string|undefined} pinned
|
|
238
|
+
* @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
|
|
239
|
+
* @param {number} now
|
|
240
|
+
* @param {boolean} preview
|
|
241
|
+
*/
|
|
242
|
+
function grokPinOrNotice(input, type, pinned, forecasts, now, preview) {
|
|
243
|
+
const grokPin = pinned && /^grok-/i.test(pinned) ? pinned : undefined;
|
|
244
|
+
const hasModelField = input && typeof input === 'object' && Object.hasOwn(input, 'model');
|
|
245
|
+
if (grokPin && hasModelField) {
|
|
246
|
+
try {
|
|
247
|
+
logBlock({
|
|
248
|
+
t: now,
|
|
249
|
+
kind: 'default',
|
|
250
|
+
src: 'grok',
|
|
251
|
+
win: '5h',
|
|
252
|
+
pct: 0,
|
|
253
|
+
wall: now,
|
|
254
|
+
reset: now,
|
|
255
|
+
from: input?.model ?? 'default',
|
|
256
|
+
to: grokPin,
|
|
257
|
+
type,
|
|
258
|
+
...(preview ? { shadow: true } : {}),
|
|
259
|
+
});
|
|
260
|
+
} catch {
|
|
261
|
+
/* a failed log must not change the decision */
|
|
262
|
+
}
|
|
263
|
+
if (preview) return null;
|
|
264
|
+
return {
|
|
265
|
+
updatedInput: { ...input, model: grokPin },
|
|
266
|
+
reason: `limitcast: ${type} subagents run on ${grokPin}, the model you set for them. Set LIMITCAST_ALLOW=1 to keep the main model.`,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
if (preview) return null;
|
|
270
|
+
const win = forecasts.find((x) => x.src === 'grok' && x.win === '5h' && x.verdict !== 'RESET');
|
|
271
|
+
const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, win);
|
|
272
|
+
return notice ? { notice } : null;
|
|
273
|
+
}
|
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
|
-
*
|
|
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/prices.mjs
CHANGED
|
@@ -4,14 +4,16 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { stateDir } from './store.mjs';
|
|
5
5
|
|
|
6
6
|
// What your tokens would cost at the API's list prices ("API-equivalent cost"). A subscription is not billed this way:
|
|
7
|
-
// it is a yardstick for what the plan covers. Claude models
|
|
7
|
+
// it is a yardstick for what the plan covers. Claude and Grok models; any other model is left out, never priced at 0.
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* USD per million tokens. input/output: base prices; readX: cache read as a multiple of input; over: the prices that
|
|
11
|
-
* apply to a call whose whole prompt is above `above` tokens. Cache writes
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* apply to a call whose whole prompt is above `above` tokens. Cache writes default to 1.25x input (5 minutes) or 2x
|
|
12
|
+
* (1 hour) for Claude; Grok sets writeX 1 (xAI lists cached input, not a write multiplier).
|
|
13
|
+
* Sources: platform.claude.com/docs/en/about-claude/pricing and docs.x.ai/developers/models, read 2026-10-26.
|
|
14
|
+
* Override or add models in ~/.local/state/limitcast/prices.json:
|
|
15
|
+
* {"models": {"claude-opus-4-1": {"input": 15, "output": 75, "readX": 0.1}}}.
|
|
16
|
+
* @typedef {{input:number, output:number, readX:number, writeX?:number, write1hX?:number, over?:{above:number, input:number, output:number, readX?:number}}} Price
|
|
15
17
|
* @type {Record<string, Price>}
|
|
16
18
|
*/
|
|
17
19
|
export const PRICES = {
|
|
@@ -19,6 +21,13 @@ export const PRICES = {
|
|
|
19
21
|
'claude-opus-5-5': { input: 4, output: 20, readX: 0.05 },
|
|
20
22
|
'claude-sonnet-5-5': { input: 2, output: 10, readX: 0.05 },
|
|
21
23
|
'claude-haiku-5-5': { input: 0.1, output: 0.5, readX: 0.1, over: { above: 100_000, input: 0.5, output: 2.5 } },
|
|
24
|
+
// xAI: cache read is listed in $/1M; writeX 1 = cache creation billed as input. Long-context at 200k prompt tokens.
|
|
25
|
+
'grok-4.7': { input: 2, output: 6, readX: 0.25, writeX: 1, write1hX: 1, over: { above: 200_000, input: 4, output: 12 } },
|
|
26
|
+
'grok-4.6': { input: 2, output: 6, readX: 0.25, writeX: 1, write1hX: 1, over: { above: 200_000, input: 4, output: 12 } },
|
|
27
|
+
'grok-4.5': { input: 2, output: 6, readX: 0.15, writeX: 1, write1hX: 1, over: { above: 200_000, input: 4, output: 12 } },
|
|
28
|
+
'grok-4.3': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
|
|
29
|
+
'grok-4.20': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
|
|
30
|
+
'grok-build-0.1': { input: 1, output: 2, readX: 0.2, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2, output: 4 } },
|
|
22
31
|
};
|
|
23
32
|
|
|
24
33
|
const WRITE_5M = 1.25;
|
|
@@ -63,7 +72,9 @@ export function callCost(u, table = priceTable()) {
|
|
|
63
72
|
const p = base.over && u.input + u.cacheWrite + u.cacheRead > base.over.above ? { ...base, ...base.over } : base;
|
|
64
73
|
const w1h = Math.min(u.cacheWrite1h ?? 0, u.cacheWrite);
|
|
65
74
|
const w5m = u.cacheWrite - w1h;
|
|
66
|
-
|
|
75
|
+
const write5 = p.writeX ?? WRITE_5M;
|
|
76
|
+
const write1h = p.write1hX ?? WRITE_1H;
|
|
77
|
+
return (u.input * p.input + (w5m * write5 + w1h * write1h) * p.input + u.cacheRead * p.readX * p.input + u.output * p.output) / 1e6;
|
|
67
78
|
}
|
|
68
79
|
|
|
69
80
|
/**
|
package/src/report.mjs
CHANGED
|
@@ -14,9 +14,9 @@ export function burnReport(usage, { since, now }) {
|
|
|
14
14
|
const sum = (/** @type {Usage[]} */ xs) => xs.reduce((a, u) => a + total(u), 0);
|
|
15
15
|
const all = sum(usage);
|
|
16
16
|
const lines = [`# limitcast burn report`, '', `${day(since)} to ${day(now)} · ${fmt(all)} tokens`, ''];
|
|
17
|
-
if (!usage.length) return [...lines, 'No Claude Code or
|
|
17
|
+
if (!usage.length) return [...lines, 'No Claude Code, Codex or Grok usage in this period.'].join('\n');
|
|
18
18
|
|
|
19
|
-
// API-equivalent dollars: what the tokens would cost at list prices.
|
|
19
|
+
// API-equivalent dollars: what the tokens would cost at list prices. Claude and Grok models are priced; others show "-".
|
|
20
20
|
const cost = (/** @type {Usage[]} */ xs) => {
|
|
21
21
|
const c = costOf(xs);
|
|
22
22
|
return c.priced ? c.total : null;
|
|
@@ -36,7 +36,7 @@ export function burnReport(usage, { since, now }) {
|
|
|
36
36
|
if (all$.priced)
|
|
37
37
|
lines.push(
|
|
38
38
|
'',
|
|
39
|
-
`**API-equivalent cost: ${fmtUsd(all$.total)}** at list prices for Claude models, not what a subscription charges.` +
|
|
39
|
+
`**API-equivalent cost: ${fmtUsd(all$.total)}** at list prices for Claude and Grok models, not what a subscription charges.` +
|
|
40
40
|
(all$.unpriced ? ` ${fmt(all$.unpriced)} tokens on other models are not counted.` : ''),
|
|
41
41
|
);
|
|
42
42
|
|
|
@@ -93,7 +93,7 @@ export function burnReport(usage, { since, now }) {
|
|
|
93
93
|
'new tokens',
|
|
94
94
|
cost,
|
|
95
95
|
);
|
|
96
|
-
lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code and
|
|
96
|
+
lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code, Codex and Grok logs._`);
|
|
97
97
|
return lines.join('\n');
|
|
98
98
|
}
|
|
99
99
|
|
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,8 +131,41 @@ export function setBudget(pct) {
|
|
|
131
131
|
writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
-
/**
|
|
135
|
-
export
|
|
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
|
+
|
|
155
|
+
/** A model a subagent type can be pinned to: sonnet, opus, haiku, a claude-... id, or a grok-... id. */
|
|
156
|
+
export const validModel = (/** @type {unknown} */ m) => typeof m === 'string' && /^(sonnet|opus|haiku|claude-[a-z0-9.-]+|grok-[a-z0-9.-]+)$/i.test(m);
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The pinned model for a subagent type, matching the stored name case-insensitively (Claude "Explore" vs Grok "explore").
|
|
160
|
+
* @param {unknown} type
|
|
161
|
+
*/
|
|
162
|
+
export function pinnedModel(type) {
|
|
163
|
+
if (typeof type !== 'string' || !type) return undefined;
|
|
164
|
+
const models = getSubagentModels();
|
|
165
|
+
if (models[type]) return models[type];
|
|
166
|
+
const want = type.toLowerCase();
|
|
167
|
+
return Object.entries(models).find(([t]) => t.toLowerCase() === want)?.[1];
|
|
168
|
+
}
|
|
136
169
|
|
|
137
170
|
/** @returns {Record<string, string>} the model each subagent type runs on by default, e.g. {Explore: 'haiku'} */
|
|
138
171
|
export function getSubagentModels() {
|
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
|
|
216
|
-
const
|
|
217
|
-
|
|
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 (
|
|
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
|
];
|
package/src/where.mjs
CHANGED
|
@@ -395,7 +395,9 @@ export function jobsReport(r, { since, now }) {
|
|
|
395
395
|
'',
|
|
396
396
|
`Every run loads your settings, plugins, hooks, MCP servers, skills and instruction files before it reads its prompt. "New tokens at start" is what counts against your limit; "starting prompt" is the whole context, cached or not. The smallest starting prompt among these jobs averages ${avg(lean.size, lean)} (${leanJob.replace(/\|/g, '/')}); the heaviest job's averages ${avg(ranked[0][1].size, ranked[0][1])}.`,
|
|
397
397
|
'',
|
|
398
|
-
'A job that does not need
|
|
398
|
+
'A job that does not need your hooks can leave them out and keep its claude.ai connectors: launch it with `claude -p --settings \'{"disableAllHooks": true}\'`. In a test on one scheduled job that cut each start from about 16k new tokens to about 5k.',
|
|
399
|
+
'',
|
|
400
|
+
'To leave out everything else too, add `--setting-sources "" --strict-mcp-config` (and `--mcp-config` for the servers it uses). That also drops the claude.ai connectors, plugins and permission rules, so a job that reads from one (HubSpot, Slack) cannot use it. Pass `--model` and `--permission-mode`, and check the job still does what it should.',
|
|
399
401
|
'',
|
|
400
402
|
'_Estimated from your local transcripts. A job is its first 45 characters of prompt, so runs of the same job group together._',
|
|
401
403
|
);
|