limitcast 0.11.5 → 0.13.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 +13 -6
- package/bin/limitcast.mjs +261 -36
- package/package.json +1 -1
- package/src/grok.mjs +585 -0
- package/src/guard.mjs +47 -6
- package/src/install.mjs +17 -4
- package/src/plan.mjs +196 -0
- package/src/prices.mjs +96 -0
- package/src/report.mjs +46 -12
- package/src/results.mjs +9 -1
- package/src/subagents.mjs +59 -0
- package/src/toolcheck.mjs +83 -0
- package/src/usage.mjs +7 -3
- package/src/where.mjs +445 -0
package/README.md
CHANGED
|
@@ -15,8 +15,9 @@ Every Claude Code session starts at 102.7k tokens before your first message.
|
|
|
15
15
|
|
|
16
16
|
- **Trim advisor:** measures your latest session's starting context from its transcript (SessionStart hook output, MCP server instructions and tool names, skills, agents, instruction files). Free shows the total and how much of it you haven't used; Pro names each item and what it costs, and `trim --apply` makes the cuts for you (reversible). `trim --codex` does the same for Codex (AGENTS.md, MCP servers).
|
|
17
17
|
- **Subagent guard (Pro)** for Claude Code and Codex: blocks a new subagent when that tool's own window is on pace to run out before it resets, and while a Claude window is tight runs new subagents on Sonnet instead of your main model. Free installs get a preview that never acts and shows what it would have done.
|
|
18
|
-
- **Subagent receipts and budgets (Pro):** when a subagent finishes you see what it cost: "that Explore subagent used ≈2.1% of your 5-hour window (34 calls)". `limitcast budget subagents 15` holds new subagents once they have used 15% of the current window.
|
|
18
|
+
- **Subagent receipts and budgets (Pro):** when a subagent finishes you see what it cost: "that Explore subagent used ≈2.1% of your 5-hour window (34 calls)". Before a new one starts you see what that kind has cost you so far: "Explore subagents have cost you a median ≈1.2% (max ≈3.6%) of a 5-hour window over 7 runs" (once there are 3 priced runs, and only when a typical run is over 1% of a window or the window is NEAR). `limitcast budget subagents 15` holds new subagents once they have used 15% of the current window.
|
|
19
19
|
- **Cold-cache warning (Pro):** after a long pause (60 min, `LIMITCAST_CACHE_MINUTES`) the prompt cache has expired and your next message re-sends the whole context as new tokens. limitcast holds that first message once and tells you what it will cost; send it again to go ahead, or `/compact` first.
|
|
20
|
+
- **Large tool-output notice (Pro, with `install --alerts`):** when one tool result is very large (about 20k tokens or more; `LIMITCAST_TOOL_TOKENS` changes that), you see it once per tool per session with what to ask for next time: "that HubSpot get_crm_objects result was ≈25k tokens. Next time: ask for fewer fields and a smaller limit". It is shown to you, never to the model, and `limitcast report --why` lists the same advice for the sources that cost you most.
|
|
20
21
|
- **Limit-change alert (Pro):** limitcast re-measures how many tokens move your meter by 1% every day and notifies you when that shifts by 15% or more, so you know when the limit itself changed.
|
|
21
22
|
- **Daily allowance (free):** today's even share of each weekly window, so you can pace the week: `7d 41% · today 6% left`.
|
|
22
23
|
- **Pro extras:** desktop notifications (`limitcast notify on`), also to your phone (`notify ntfy <topic>`) or a Slack/Discord webhook (`notify webhook <url>`), run a job after the reset (`limitcast after-reset -- …`), a pointer to your other account when this one is near its limit, a `/compact` nudge in long sessions, and an HTML dashboard (`limitcast results --html`).
|
|
@@ -27,10 +28,10 @@ Every Claude Code session starts at 102.7k tokens before your first message.
|
|
|
27
28
|
|
|
28
29
|
| | Claude Code | Codex | Grok |
|
|
29
30
|
|---|---|---|---|
|
|
30
|
-
| Limit forecast (`status`) | ✓ status-line feed | ✓ session logs |
|
|
31
|
-
| Subagent guard | ✓ `Task`/`Agent` | ✓ `spawn_agent` |
|
|
31
|
+
| Limit forecast (`status`) | ✓ status-line feed | ✓ session logs | spend from `usage.json`; % / runout after `limitcast budget grok <usd>` |
|
|
32
|
+
| Subagent guard | ✓ `Task`/`Agent` | ✓ `spawn_agent` | ✓ `spawn_subagent` (blocks once a dollar cap is set) |
|
|
32
33
|
| Token report (`report`) | ✓ | ✓ | ✓ per-turn ledger |
|
|
33
|
-
| Trim advisor (`trim`) | ✓ |
|
|
34
|
+
| Trim advisor (`trim`) | ✓ | `--codex` | `--grok` |
|
|
34
35
|
|
|
35
36
|
Requires Node 20+ on macOS or Linux.
|
|
36
37
|
|
|
@@ -50,7 +51,7 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
50
51
|
|
|
51
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.
|
|
52
53
|
|
|
53
|
-
**Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json`.
|
|
54
|
+
**Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json`. `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. Restart Grok to load the status line and hook.
|
|
54
55
|
|
|
55
56
|
## Commands
|
|
56
57
|
|
|
@@ -58,15 +59,21 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
58
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
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
|
+
| `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) |
|
|
61
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 |
|
|
62
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 |
|
|
63
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 subagent-model <type> <sonnet\|opus\|haiku\|model-id>` / `off` | **Pro.** Run new subagents of that type (for example `Explore`) on that model, unless the spawn names a model itself. 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
|
+
| `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
|
+
| `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` |
|
|
64
69
|
| `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
|
|
65
70
|
| `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
|
|
66
71
|
| `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
|
|
67
72
|
| `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) |
|
|
68
73
|
| `limitcast trial` | Pro free for 7 days on this computer, no card, once |
|
|
69
|
-
| `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
|
|
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 only; 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
|
+
| `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
|
+
| `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) |
|
|
70
77
|
| `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 |
|
|
71
78
|
| `limitcast saved` | **Pro.** How much the part of your starting context you control has dropped since limitcast first measured it, times your sessions since |
|
|
72
79
|
| `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 |
|
package/bin/limitcast.mjs
CHANGED
|
@@ -21,6 +21,21 @@ import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimR
|
|
|
21
21
|
import { coldCost, coldMessage, firstWarning } from '../src/cold.mjs';
|
|
22
22
|
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
23
23
|
import { formatChecks } from '../src/formats.mjs';
|
|
24
|
+
import {
|
|
25
|
+
applyGrokTrim,
|
|
26
|
+
getGrokBudget,
|
|
27
|
+
grokConfigPath,
|
|
28
|
+
grokPresent,
|
|
29
|
+
grokSamples,
|
|
30
|
+
grokServers,
|
|
31
|
+
grokSessionLine,
|
|
32
|
+
grokSpend,
|
|
33
|
+
grokStartup,
|
|
34
|
+
grokTrimReport,
|
|
35
|
+
grokUsedServers,
|
|
36
|
+
setGrokBudget,
|
|
37
|
+
undoGrokTrim,
|
|
38
|
+
} from '../src/grok.mjs';
|
|
24
39
|
import { runGuard } from '../src/guard.mjs';
|
|
25
40
|
import { accountForecasts, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
26
41
|
import { htmlPage } from '../src/html.mjs';
|
|
@@ -28,22 +43,38 @@ import { doctor, install, installedFeatures, readSettings, settingsPath, uninsta
|
|
|
28
43
|
import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
|
|
29
44
|
import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
|
|
30
45
|
import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
|
|
46
|
+
import { advise, getPlan, loadPeaks, PLANS, planPrices, planStats, recordPeaks, setPlan } from '../src/plan.mjs';
|
|
31
47
|
import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
|
|
48
|
+
import { costOf, fmtUsd } from '../src/prices.mjs';
|
|
32
49
|
import { burnReport } from '../src/report.mjs';
|
|
33
50
|
import { loadBlocks, logBlock, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
|
|
34
51
|
import { claudeSamples, readCodex } from '../src/sources.mjs';
|
|
35
52
|
import { countInteractiveSince, latestInteractiveTranscript } from '../src/startup.mjs';
|
|
36
53
|
import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
|
|
37
|
-
import {
|
|
54
|
+
import {
|
|
55
|
+
budgetSpent,
|
|
56
|
+
getBudget,
|
|
57
|
+
getSubagentModels,
|
|
58
|
+
loadSubagents,
|
|
59
|
+
logSubagent,
|
|
60
|
+
receiptMessage,
|
|
61
|
+
setBudget,
|
|
62
|
+
setSubagentModel,
|
|
63
|
+
subagentUsage,
|
|
64
|
+
validModel,
|
|
65
|
+
windowStart,
|
|
66
|
+
} from '../src/subagents.mjs';
|
|
38
67
|
import { forTerminal } from '../src/term.mjs';
|
|
68
|
+
import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
|
|
39
69
|
import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
40
70
|
import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
|
|
41
71
|
import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valueSection, valueTotals } from '../src/value.mjs';
|
|
72
|
+
import { attribute, jobsReport, whyReport, whySessions } from '../src/where.mjs';
|
|
42
73
|
|
|
43
74
|
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
44
|
-
const HELP = `limitcast ${VERSION}: stretch your Claude Code and
|
|
75
|
+
const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok plans
|
|
45
76
|
|
|
46
|
-
limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex); backs up settings
|
|
77
|
+
limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex and Grok); backs up settings
|
|
47
78
|
(without Pro the guard is a preview: it records what it would block, never blocks)
|
|
48
79
|
limitcast uninstall remove it and restore your original status line
|
|
49
80
|
limitcast doctor [--fix] check the setup (--fix: re-install with this Node, e.g. after a Node upgrade)
|
|
@@ -51,6 +82,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
|
|
|
51
82
|
limitcast status [--json] used, burn rate, runout time, reset, and today's share of each weekly window
|
|
52
83
|
limitcast trim [--share] tokens every session loads before you type, and how much you never use
|
|
53
84
|
limitcast trim --codex the same for Codex: AGENTS.md size and MCP servers you haven't used
|
|
85
|
+
limitcast trim --grok the same for Grok: system prompt size and MCP servers you haven't used
|
|
54
86
|
limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
|
|
55
87
|
[--share] totals only, safe to post
|
|
56
88
|
limitcast license show the license and re-check it with Polar
|
|
@@ -60,13 +92,21 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
|
|
|
60
92
|
(--share: totals only, no names, safe to post)
|
|
61
93
|
limitcast trim --apply / --undo hide those skills and turn off those MCP servers (backed up, reversible)
|
|
62
94
|
limitcast trim --codex --apply / --undo turn off unused Codex MCP servers (enabled = false; reversible)
|
|
95
|
+
limitcast trim --grok --apply / --undo turn off unused Grok MCP servers (enabled = false; reversible)
|
|
63
96
|
limitcast saved tokens saved since limitcast first measured you
|
|
64
97
|
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
65
98
|
them on Sonnet while a window is tight (NEAR or AT_RISK); show what
|
|
66
|
-
each finished subagent cost
|
|
99
|
+
each finished subagent cost, and what that kind has cost before a new
|
|
100
|
+
one starts; hold the first message after the prompt
|
|
67
101
|
cache expired (idle over 60 min, LIMITCAST_CACHE_MINUTES) and say what it costs
|
|
68
102
|
limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
|
|
69
|
-
limitcast
|
|
103
|
+
limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku or a model id
|
|
104
|
+
limitcast plan [--days N] does your Claude plan fit your use? Hit-limit and headroom evidence, and the monthly price difference
|
|
105
|
+
limitcast plan set <pro|max5|max20>|off tell limitcast which Claude plan you are on
|
|
106
|
+
limitcast budget grok <usd>|off Grok 5-hour dollar cap (Grok stores spend, not a % used; the guard
|
|
107
|
+
needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
|
|
108
|
+
limitcast install --alerts tell you when your starting context grows, plus a weekly summary, and
|
|
109
|
+
when one tool result is very large (about 20k tokens), with what to ask for instead
|
|
70
110
|
limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
|
|
71
111
|
and when your Claude limit itself changes
|
|
72
112
|
limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
|
|
@@ -75,11 +115,13 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
|
|
|
75
115
|
run a heavy job once the window has reset
|
|
76
116
|
limitcast results --html [--out FILE] results, current windows and the burn report as one page
|
|
77
117
|
limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
|
|
118
|
+
limitcast report --why [--days N] where the new tokens went: subagents, session starts, cache rebuilds, tool results
|
|
119
|
+
limitcast report --jobs [--days N] the scheduled (headless) jobs that spend the most tokens just starting
|
|
78
120
|
(status line, Pro: points to another account with room, and suggests /compact past ~150k tokens a call)
|
|
79
121
|
limitcast activate <license-key> unlock Pro on this computer (online once; then a weekly check, offline up to 30 days)
|
|
80
122
|
limitcast deactivate free this computer's activation to use the key elsewhere
|
|
81
123
|
|
|
82
|
-
Used by Claude Code and
|
|
124
|
+
Used by Claude Code, Codex and Grok (set up by install)
|
|
83
125
|
limitcast statusline [-- <cmd...>] record limit readings, then run your status-line command
|
|
84
126
|
limitcast guard PreToolUse hook (Pro)
|
|
85
127
|
limitcast prompt-check UserPromptSubmit hook: the cold-cache warning (Pro)
|
|
@@ -101,25 +143,30 @@ if (['report', 'trim', 'saved', 'results', 'drift', 'doctor', 'license'].include
|
|
|
101
143
|
}
|
|
102
144
|
|
|
103
145
|
if (cmd === 'status') {
|
|
104
|
-
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
|
|
146
|
+
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS)), ...grokSamples(now)]), now);
|
|
105
147
|
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
|
|
106
148
|
else {
|
|
107
|
-
console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, or
|
|
149
|
+
console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, Codex or Grok.');
|
|
108
150
|
// Pro: the other Claude accounts limitcast has current readings for (the table shows the latest one).
|
|
109
151
|
if (isPro())
|
|
110
152
|
for (const a of accountForecasts(load(now - KEEP_MS), now).slice(1))
|
|
111
153
|
console.log(
|
|
112
154
|
`other Claude account (last used ${clock(a.lastSeen)}): ${a.rows.map((f) => `${f.win} ${f.verdict === 'RESET' ? 0 : Math.round(f.pct)}%${f.verdict === 'OK' || f.verdict === 'RESET' ? '' : ` ${f.verdict}`}`).join(' · ')}`,
|
|
113
155
|
);
|
|
114
|
-
|
|
156
|
+
const spend = grokSpendLine(now);
|
|
157
|
+
if (spend) console.log(spend);
|
|
158
|
+
else if (existsSync(grokRoot()) && !rows.some((f) => f.src === 'grok'))
|
|
159
|
+
console.log('grok: spent $0 in the current windows. Set a cap to forecast runout: limitcast budget grok <usd>');
|
|
115
160
|
}
|
|
116
161
|
} else if (cmd === 'statusline') {
|
|
117
162
|
const input = readStdin();
|
|
118
163
|
let sid;
|
|
164
|
+
/** @type {any} */
|
|
165
|
+
let feed;
|
|
119
166
|
/** @type {string[]} */
|
|
120
167
|
const hints = [];
|
|
121
168
|
try {
|
|
122
|
-
|
|
169
|
+
feed = JSON.parse(input);
|
|
123
170
|
sid = feed?.session_id;
|
|
124
171
|
record(claudeSamples(feed, now));
|
|
125
172
|
saveFeedShape(feed);
|
|
@@ -131,11 +178,15 @@ if (cmd === 'status') {
|
|
|
131
178
|
if (health) hints.push(health);
|
|
132
179
|
if (isPro()) {
|
|
133
180
|
const samples = load(now - KEEP_MS);
|
|
134
|
-
if (notifyEnabled()) notifyChanges(forecastAll(oneClaudeAccount(samples, sid), now), clock);
|
|
181
|
+
if (notifyEnabled()) notifyChanges(forecastAll(oneClaudeAccount([...samples, ...grokSamples(now)], sid), now), clock);
|
|
135
182
|
const room = headroom(samples, sid, now);
|
|
136
183
|
if (room) hints.push(room);
|
|
137
|
-
const
|
|
138
|
-
if (
|
|
184
|
+
const ctxPct = Number(feed?.context_window?.used_percentage);
|
|
185
|
+
if (Number.isFinite(ctxPct) && ctxPct >= 80) hints.push(`${ctxPct}% ctx`);
|
|
186
|
+
else if (typeof feed?.transcript_path === 'string') {
|
|
187
|
+
const ctx = compactHint(lastCallTokens(feed.transcript_path));
|
|
188
|
+
if (ctx) hints.push(ctx);
|
|
189
|
+
}
|
|
139
190
|
} else {
|
|
140
191
|
const week = freeWeeklyHint(now);
|
|
141
192
|
if (week) hints.push(week);
|
|
@@ -145,21 +196,26 @@ if (cmd === 'status') {
|
|
|
145
196
|
}
|
|
146
197
|
const sep = args.indexOf('--');
|
|
147
198
|
const wrapped = sep >= 0 ? args.slice(sep + 1) : [];
|
|
199
|
+
const grokOwn = grokSessionLine(feed);
|
|
200
|
+
let line = 'waiting for data';
|
|
201
|
+
try {
|
|
202
|
+
// Grok spend/forecast stays on the Grok status line. Claude's feed has rate_limits; mixing the two
|
|
203
|
+
// would print grok $ on Claude Code and break "waiting for data" when there are no Claude readings.
|
|
204
|
+
const grokExtra = grokOwn ? grokSamples(now) : [];
|
|
205
|
+
line = statusBits(forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...grokExtra], sid), now), grokOwn ? grokSpendLine(now) : '', hints);
|
|
206
|
+
} catch {
|
|
207
|
+
/* never break the status line */
|
|
208
|
+
}
|
|
148
209
|
if (wrapped.length) {
|
|
149
210
|
const r = spawnSync(wrapped[0], wrapped.slice(1), { input, stdio: ['pipe', 'pipe', 'inherit'] });
|
|
150
211
|
// Your status line stays as it was; limitcast adds its own line under it (status scripts often printf without a newline).
|
|
151
212
|
const yours = r.stdout?.toString() ?? '';
|
|
152
213
|
process.stdout.write(yours && !yours.endsWith('\n') ? `${yours}\n` : yours);
|
|
153
|
-
|
|
154
|
-
try {
|
|
155
|
-
line = oneLine(forecastAll(oneClaudeAccount(load(now - KEEP_MS), sid), now)).replace(/^limitcast: /, '');
|
|
156
|
-
} catch {
|
|
157
|
-
/* never break the status line */
|
|
158
|
-
}
|
|
159
|
-
console.log(`limitcast: ${[line, ...hints].join(' · ')}`);
|
|
214
|
+
console.log(`limitcast: ${line}`);
|
|
160
215
|
process.exit(r.status ?? 1);
|
|
161
216
|
}
|
|
162
|
-
|
|
217
|
+
if (grokOwn) console.log(grokOwn);
|
|
218
|
+
console.log(`limitcast: ${line}`);
|
|
163
219
|
} else if (cmd === 'guard') {
|
|
164
220
|
// Blocking is Pro; without a valid license the guard only previews (logs what Pro would block) and allows everything.
|
|
165
221
|
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
@@ -167,6 +223,9 @@ if (cmd === 'status') {
|
|
|
167
223
|
const d = await runGuard(JSON.parse(readStdin()), now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30), { preview: !isPro() });
|
|
168
224
|
if (typeof d === 'string') {
|
|
169
225
|
console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d } }));
|
|
226
|
+
} else if (d && 'notice' in d) {
|
|
227
|
+
// Allowed as is, with what this kind of subagent has cost so far (shown to the user, never the model).
|
|
228
|
+
console.log(JSON.stringify({ systemMessage: d.notice }));
|
|
170
229
|
} else if (d) {
|
|
171
230
|
// Model switch: allow the spawn with the same input and model "sonnet" (updatedInput replaces the whole input).
|
|
172
231
|
console.log(
|
|
@@ -211,6 +270,19 @@ if (cmd === 'status') {
|
|
|
211
270
|
} catch {
|
|
212
271
|
/* a hook must never stop a prompt by failing */
|
|
213
272
|
}
|
|
273
|
+
} else if (cmd === 'tool-check') {
|
|
274
|
+
// PostToolUse hook (Pro, installed with --alerts): tell the user, once per tool per session, about a very large tool
|
|
275
|
+
// result and what to ask for next time. Never reaches the model.
|
|
276
|
+
try {
|
|
277
|
+
if (isPro()) {
|
|
278
|
+
const hook = JSON.parse(readStdin());
|
|
279
|
+
const name = String(hook?.tool_name ?? '');
|
|
280
|
+
const notice = name ? toolNotice(name, hook?.tool_response, loadValue().calib, Number(process.env.LIMITCAST_TOOL_TOKENS) || undefined) : null;
|
|
281
|
+
if (notice && firstFlag(String(hook.session_id), toolKey(name))) console.log(JSON.stringify({ systemMessage: notice }));
|
|
282
|
+
}
|
|
283
|
+
} catch {
|
|
284
|
+
/* a hook must never break the session */
|
|
285
|
+
}
|
|
214
286
|
} else if (cmd === 'subagent-receipt') {
|
|
215
287
|
// SubagentStop hook: price the finished subagent against the 5-hour window and log it (for budgets and results).
|
|
216
288
|
// Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
|
|
@@ -238,14 +310,107 @@ if (cmd === 'status') {
|
|
|
238
310
|
} catch {
|
|
239
311
|
/* a hook must never break the session */
|
|
240
312
|
}
|
|
313
|
+
} else if (cmd === 'plan') {
|
|
314
|
+
if (!isPro()) {
|
|
315
|
+
console.log(
|
|
316
|
+
`\`limitcast plan\` is part of limitcast Pro: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`,
|
|
317
|
+
);
|
|
318
|
+
process.exit(2);
|
|
319
|
+
}
|
|
320
|
+
if (args[0] === 'set') {
|
|
321
|
+
const id = args[1];
|
|
322
|
+
if (id !== 'off' && !(id in PLANS)) {
|
|
323
|
+
console.log('Usage: limitcast plan set <pro|max5|max20>|off');
|
|
324
|
+
process.exit(1);
|
|
325
|
+
}
|
|
326
|
+
setPlan(id === 'off' ? null : /** @type {keyof typeof PLANS} */ (id));
|
|
327
|
+
console.log(id === 'off' ? 'Plan forgotten.' : `Plan set to Claude ${PLANS[/** @type {keyof typeof PLANS} */ (id)].name}. Run: limitcast plan`);
|
|
328
|
+
process.exit(0);
|
|
329
|
+
}
|
|
330
|
+
const planDays = Math.max(1, Number(flag('--days') ?? 28));
|
|
331
|
+
recordPeaks(load(now - KEEP_MS), now);
|
|
332
|
+
const plan = getPlan();
|
|
333
|
+
const prices = planPrices();
|
|
334
|
+
const advice = advise(plan, planStats(loadPeaks(), now, planDays), prices);
|
|
335
|
+
const out = [
|
|
336
|
+
'# limitcast plan',
|
|
337
|
+
'',
|
|
338
|
+
`Claude plan: ${plan ? `${PLANS[plan].name}, ${fmtUsd(prices[plan])} a month` : 'not set'}`,
|
|
339
|
+
'',
|
|
340
|
+
...advice.lines,
|
|
341
|
+
];
|
|
342
|
+
const used = (await readUsage(now - planDays * 86400_000, {})).filter((u) => u.src === 'claude');
|
|
343
|
+
const cost = costOf(used);
|
|
344
|
+
if (plan && cost.priced) {
|
|
345
|
+
const span = Math.min(planDays, Math.max(1, (now - Math.min(...used.map((u) => u.t))) / 86400_000));
|
|
346
|
+
out.push(
|
|
347
|
+
'',
|
|
348
|
+
`At API list prices your Claude Code tokens of the last ${Math.round(span)} days would have cost ${fmtUsd(cost.total)} (about ${fmtUsd((cost.total * 30) / span)} a month at this pace), against ${fmtUsd(prices[plan])} for your plan.`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
out.push(
|
|
352
|
+
'',
|
|
353
|
+
'_From the peak of every 5-hour and weekly window limitcast has seen; plan prices and multipliers from claude.com/pricing, 2026-10-26._',
|
|
354
|
+
);
|
|
355
|
+
console.log(forTerminal(out.join('\n')));
|
|
356
|
+
process.exit(0);
|
|
357
|
+
} else if (cmd === 'subagent-model') {
|
|
358
|
+
if (!isPro()) {
|
|
359
|
+
console.log(`Per-type subagent models are part of limitcast Pro: ${UPGRADE_URL}`);
|
|
360
|
+
process.exit(2);
|
|
361
|
+
}
|
|
362
|
+
const [type, model] = args;
|
|
363
|
+
if (type && (model === undefined || (model !== 'off' && !validModel(model)))) {
|
|
364
|
+
console.log('Usage: limitcast subagent-model <type> <sonnet|opus|haiku|claude-id>|off\n limitcast subagent-model list them');
|
|
365
|
+
process.exit(1);
|
|
366
|
+
}
|
|
367
|
+
if (type) setSubagentModel(type, model === 'off' ? null : model);
|
|
368
|
+
const pinned = Object.entries(getSubagentModels());
|
|
369
|
+
console.log(pinned.length ? pinned.map(([t, m]) => `${t}: ${m}`).join('\n') : 'No subagent type is pinned to a model.');
|
|
370
|
+
const ran = new Map();
|
|
371
|
+
for (const e of loadSubagents(now - 30 * 86400_000)) if (e.type) ran.set(e.type, (ran.get(e.type) ?? 0) + 1);
|
|
372
|
+
if (ran.size)
|
|
373
|
+
console.log(
|
|
374
|
+
`\nTypes you ran in the last 30 days: ${[...ran]
|
|
375
|
+
.sort((a, b) => b[1] - a[1])
|
|
376
|
+
.map(([t, n]) => `${t} (${n})`)
|
|
377
|
+
.join(', ')}`,
|
|
378
|
+
);
|
|
379
|
+
if (pinned.length)
|
|
380
|
+
console.log(
|
|
381
|
+
'\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
|
+
);
|
|
383
|
+
else console.log('\nExample: limitcast subagent-model Explore haiku');
|
|
384
|
+
process.exit(0);
|
|
241
385
|
} else if (cmd === 'budget') {
|
|
242
386
|
if (!isPro()) {
|
|
243
|
-
console.log(`
|
|
387
|
+
console.log(`Budgets are part of limitcast Pro: ${UPGRADE_URL}`);
|
|
244
388
|
process.exit(2);
|
|
245
389
|
}
|
|
390
|
+
if (args[0] === 'grok') {
|
|
391
|
+
const win = args[1] === '7d' || args[1] === '5h' ? args[1] : '5h';
|
|
392
|
+
const value = args[1] === '7d' || args[1] === '5h' ? args[2] : args[1];
|
|
393
|
+
if (value !== undefined && value !== 'off' && !(Number(value) > 0)) {
|
|
394
|
+
console.log('Usage: limitcast budget grok <usd>|off (5-hour dollar cap)\n limitcast budget grok 7d <usd>|off');
|
|
395
|
+
process.exit(1);
|
|
396
|
+
}
|
|
397
|
+
if (value !== undefined) setGrokBudget(value === 'off' ? null : Number(value), win);
|
|
398
|
+
const budget = getGrokBudget();
|
|
399
|
+
const spend = grokSpend(now);
|
|
400
|
+
const cap = budget?.[win];
|
|
401
|
+
const used = spend?.[win];
|
|
402
|
+
console.log(
|
|
403
|
+
cap
|
|
404
|
+
? `Grok ${win} budget: $${cap}. Spent this window: $${(used ?? 0).toFixed(2)} (${Math.min(100, ((used ?? 0) / cap) * 100).toFixed(0)}%). The guard holds new spawn_subagent calls when this window is on pace to run out.`
|
|
405
|
+
: `No Grok ${win} dollar cap. Spent this window: $${(used ?? 0).toFixed(2)}. Grok stores spend, not a % used; set a cap so the guard can block: limitcast budget grok 5`,
|
|
406
|
+
);
|
|
407
|
+
if (getGrokBudget() && !installedFeatures().guard && grokPresent())
|
|
408
|
+
console.log('The budget is enforced by the guard: limitcast install --guard (then restart Grok).');
|
|
409
|
+
process.exit(0);
|
|
410
|
+
}
|
|
246
411
|
const value = args[1];
|
|
247
412
|
if (args[0] !== 'subagents' || (value !== undefined && value !== 'off' && !(Number(value) > 0 && Number(value) <= 100))) {
|
|
248
|
-
console.log('Usage: limitcast budget subagents <percent of the 5-hour window, 1-100>|off');
|
|
413
|
+
console.log('Usage: limitcast budget subagents <percent of the 5-hour window, 1-100>|off\n limitcast budget grok <usd>|off');
|
|
249
414
|
process.exit(1);
|
|
250
415
|
}
|
|
251
416
|
if (value !== undefined) setBudget(value === 'off' ? null : Number(value));
|
|
@@ -273,7 +438,9 @@ if (cmd === 'status') {
|
|
|
273
438
|
}
|
|
274
439
|
if (wantAlerts && !isPro()) console.log(`Alerts and the weekly summary are part of limitcast Pro (${UPGRADE_URL}). Skipping them.`);
|
|
275
440
|
for (const c of install({ guard: wantGuard, alerts: wantAlerts && isPro() })) console.log(`✓ ${c}`);
|
|
276
|
-
console.log('Restart Claude Code and
|
|
441
|
+
console.log('Restart Claude Code, Codex and Grok to load it. Then: limitcast doctor');
|
|
442
|
+
if (wantGuard && grokPresent() && !getGrokBudget())
|
|
443
|
+
console.log('Grok stores spend, not a % used. Set a 5-hour dollar cap so the guard can block: limitcast budget grok <usd>');
|
|
277
444
|
// First run: show the number that matters right away, and what comes next.
|
|
278
445
|
try {
|
|
279
446
|
const latest = await latestInteractiveTranscript(claudeRoot());
|
|
@@ -310,7 +477,7 @@ if (cmd === 'status') {
|
|
|
310
477
|
if (!f.statusLine) console.log('limitcast is not installed. Run `limitcast install` first.');
|
|
311
478
|
else {
|
|
312
479
|
for (const c of install({ guard: f.guard && isPro(), alerts: f.alerts && isPro() })) console.log(`✓ ${c}`);
|
|
313
|
-
console.log('Restart Claude Code to load it. Codex asks you to approve the guard again: start Codex and accept it.');
|
|
480
|
+
console.log('Restart Claude Code, Codex and Grok to load it. Codex asks you to approve the guard again: start Codex and accept it.');
|
|
314
481
|
}
|
|
315
482
|
}
|
|
316
483
|
const checks = await healthChecks();
|
|
@@ -355,11 +522,49 @@ if (cmd === 'status') {
|
|
|
355
522
|
} else console.log(forTerminal(r.text));
|
|
356
523
|
process.exit(0);
|
|
357
524
|
}
|
|
525
|
+
if (cmd === 'trim' && args.includes('--grok')) {
|
|
526
|
+
if ((args.includes('--apply') || args.includes('--undo')) && !pro) {
|
|
527
|
+
console.log(`\`limitcast trim --grok --apply\` is part of limitcast Pro: ${UPGRADE_URL}`);
|
|
528
|
+
process.exit(2);
|
|
529
|
+
}
|
|
530
|
+
if (args.includes('--undo')) {
|
|
531
|
+
const e = undoGrokTrim();
|
|
532
|
+
console.log(
|
|
533
|
+
e ? `✓ Back to how they were: ${e.servers.map((s) => s.name).join(', ')}. Takes effect in your next Grok session.` : 'Nothing to undo.',
|
|
534
|
+
);
|
|
535
|
+
process.exit(0);
|
|
536
|
+
}
|
|
537
|
+
if (!existsSync(grokConfigPath())) {
|
|
538
|
+
console.log(`No Grok setup found (${grokConfigPath()}). Set GROK_HOME if Grok keeps it elsewhere.`);
|
|
539
|
+
process.exit(0);
|
|
540
|
+
}
|
|
541
|
+
const r = grokTrimReport({
|
|
542
|
+
servers: grokServers(),
|
|
543
|
+
used: grokUsedServers(since),
|
|
544
|
+
startup: grokStartup(),
|
|
545
|
+
days: days(),
|
|
546
|
+
pro,
|
|
547
|
+
});
|
|
548
|
+
if (args.includes('--apply')) {
|
|
549
|
+
const changed = applyGrokTrim(r.unused);
|
|
550
|
+
console.log(
|
|
551
|
+
changed.length
|
|
552
|
+
? `✓ 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.',
|
|
554
|
+
);
|
|
555
|
+
} else console.log(forTerminal(r.text));
|
|
556
|
+
process.exit(0);
|
|
557
|
+
}
|
|
358
558
|
/** @type {import('../src/trim.mjs').Activity} */
|
|
359
559
|
const used = { skills: new Set(), mcp: new Set() };
|
|
360
|
-
const
|
|
560
|
+
const jobs = cmd === 'report' && args.includes('--jobs');
|
|
561
|
+
const why = cmd === 'report' && args.includes('--why');
|
|
562
|
+
const usage = why || jobs ? [] : await readUsage(since, {}, cmd === 'trim' ? used : undefined);
|
|
361
563
|
let text;
|
|
362
|
-
if (
|
|
564
|
+
if (why || jobs) {
|
|
565
|
+
const r = attribute(await whySessions(claudeRoot(), since), since);
|
|
566
|
+
text = jobs ? jobsReport(r, { since, now }) : whyReport(r, { since, now, calib: loadValue().calib });
|
|
567
|
+
} else if (cmd === 'report') text = burnReport(usage, { since, now });
|
|
363
568
|
else {
|
|
364
569
|
// Prefer the measured starting context of the latest interactive session; older Claude Code logs fall back to estimates.
|
|
365
570
|
const latest = await latestInteractiveTranscript(claudeRoot());
|
|
@@ -732,6 +937,7 @@ function healthHint() {
|
|
|
732
937
|
async function refreshValue() {
|
|
733
938
|
const since = now - KEEP_MS;
|
|
734
939
|
const claude = load(since);
|
|
940
|
+
recordPeaks(claude, now); // the long-lived record of window peaks behind `limitcast plan`
|
|
735
941
|
const o = loadOverhead();
|
|
736
942
|
// limitcast started watching at its first status-line reading (or first measurement), not when Codex's logs begin.
|
|
737
943
|
const start = Math.min(now, o?.first.at ?? now, ...claude.map((s) => s.t));
|
|
@@ -856,16 +1062,35 @@ function table(rows) {
|
|
|
856
1062
|
|
|
857
1063
|
/** @param {ReturnType<typeof forecastAll>} rows */
|
|
858
1064
|
function oneLine(rows) {
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
.
|
|
862
|
-
.
|
|
863
|
-
(f) =>
|
|
864
|
-
`${f.win} ${Math.round(f.pct)}%${f.verdict === 'AT_RISK' ? ` ⚠ out ${clock(f.wall)}` : f.verdict === 'NEAR' ? ' ⚠ near limit' : f.verdict === 'HIT' ? ' ⛔' : ''}` +
|
|
865
|
-
(f.today && f.verdict !== 'HIT' ? ` · today ${todayLabel(f.today)}` : ''),
|
|
866
|
-
)
|
|
867
|
-
.join(' · ') || 'limitcast: waiting for data'
|
|
1065
|
+
const bits = rows.map(
|
|
1066
|
+
(f) =>
|
|
1067
|
+
`${f.src === 'claude' ? '' : `${f.src} `}${f.win} ${Math.round(f.pct)}%${f.verdict === 'AT_RISK' ? ` ⚠ out ${clock(f.wall)}` : f.verdict === 'NEAR' ? ' ⚠ near limit' : f.verdict === 'HIT' ? ' ⛔' : ''}` +
|
|
1068
|
+
(f.today && f.verdict !== 'HIT' ? ` · today ${todayLabel(f.today)}` : ''),
|
|
868
1069
|
);
|
|
1070
|
+
return bits.join(' · ') || 'limitcast: waiting for data';
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* Status-line body: forecasts, Grok spend when there is no cap, then hints. No "waiting for data" when spend is known.
|
|
1075
|
+
* @param {ReturnType<typeof forecastAll>} rows
|
|
1076
|
+
* @param {string} spend
|
|
1077
|
+
* @param {string[]} hints
|
|
1078
|
+
*/
|
|
1079
|
+
function statusBits(rows, spend, hints) {
|
|
1080
|
+
const core = oneLine(rows);
|
|
1081
|
+
const parts = [];
|
|
1082
|
+
if (core !== 'limitcast: waiting for data') parts.push(core.replace(/^limitcast: /, ''));
|
|
1083
|
+
if (spend) parts.push(spend);
|
|
1084
|
+
parts.push(...hints);
|
|
1085
|
+
return parts.join(' · ') || 'waiting for data';
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
/** Grok spend line when no dollar cap is set (a cap becomes a forecast row instead). */
|
|
1089
|
+
function grokSpendLine(t) {
|
|
1090
|
+
if (getGrokBudget()) return '';
|
|
1091
|
+
const s = grokSpend(t);
|
|
1092
|
+
if (!s) return '';
|
|
1093
|
+
return `grok 5h $${s['5h'].toFixed(2)} · 7d $${s['7d'].toFixed(2)}`;
|
|
869
1094
|
}
|
|
870
1095
|
|
|
871
1096
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.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": {
|