limitcast 0.11.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,95 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Sam Stull
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Copyright 2026 Sam Stull
2
+
3
+ Elastic License 2.0
4
+
5
+ URL: https://www.elastic.co/licensing/elastic-license
6
+
7
+ ## Acceptance
8
+
9
+ By using the software, you agree to all of the terms and conditions below.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
14
+ non-sublicensable, non-transferable license to use, copy, distribute, make
15
+ available, and prepare derivative works of the software, in each case subject to
16
+ the limitations and conditions below.
17
+
18
+ ## Limitations
19
+
20
+ You may not provide the software to third parties as a hosted or managed
21
+ service, where the service provides users with access to any substantial set of
22
+ the features or functionality of the software.
23
+
24
+ You may not move, change, disable, or circumvent the license key functionality
25
+ in the software, and you may not remove or obscure any functionality in the
26
+ software that is protected by the license key.
27
+
28
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
29
+ of the licensor in the software. Any use of the licensor’s trademarks is subject
30
+ to applicable law.
31
+
32
+ ## Patents
33
+
34
+ The licensor grants you a license, under any patent claims the licensor can
35
+ license, or becomes able to license, to make, have made, use, sell, offer for
36
+ sale, import and have imported the software, in each case subject to the
37
+ limitations and conditions in this license. This license does not cover any
38
+ patent claims that you cause to be infringed by modifications or additions to
39
+ the software. If you or your company make any written claim that the software
40
+ infringes or contributes to infringement of any patent, your patent license for
41
+ the software granted under these terms ends immediately. If your company makes
42
+ such a claim, your patent license ends immediately for work on behalf of your
43
+ company.
44
+
45
+ ## Notices
46
+
47
+ You must ensure that anyone who gets a copy of any part of the software from you
48
+ also gets a copy of these terms.
49
+
50
+ If you modify the software, you must include in any modified copies of the
51
+ software prominent notices stating that you have modified the software.
52
+
53
+ ## No Other Rights
54
+
55
+ These terms do not imply any licenses other than those expressly granted in
56
+ these terms.
57
+
58
+ ## Termination
59
+
60
+ If you use the software in violation of these terms, such use is not licensed,
61
+ and your licenses will automatically terminate. If the licensor provides you
62
+ with a notice of your violation, and you cease all violation of this license no
63
+ later than 30 days after you receive that notice, your licenses will be
64
+ reinstated retroactively. However, if you violate these terms after such
65
+ reinstatement, any additional violation of these terms will cause your licenses
66
+ to terminate automatically and permanently.
67
+
68
+ ## No Liability
69
+
70
+ *As far as the law allows, the software comes as is, without any warranty or
71
+ condition, and the licensor will not be liable to you for any damages arising
72
+ out of these terms or the use or nature of the software, under any kind of
73
+ legal claim.*
74
+
75
+ ## Definitions
76
+
77
+ The **licensor** is the entity offering these terms, and the **software** is the
78
+ software the licensor makes available under these terms, including any portion
79
+ of it.
80
+
81
+ **you** refers to the individual or entity agreeing to these terms.
82
+
83
+ **your company** is any legal entity, sole proprietorship, or other kind of
84
+ organization that you work for, plus all organizations that have control over,
85
+ are under the control of, or are under common control with that
86
+ organization. **control** means ownership of substantially all the assets of an
87
+ entity, or the power to direct its management and policies by vote, contract, or
88
+ otherwise. Control can be direct or indirect.
89
+
90
+ **your licenses** are all the licenses granted to you for the software under
91
+ these terms.
92
+
93
+ **use** means anything you do with the software requiring one of your licenses.
94
+
95
+ **trademark** means trademarks, service marks, and similar rights.
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 | no: Grok keeps no limit readings on disk |
31
- | Subagent guard | ✓ `Task`/`Agent` | ✓ `spawn_agent` | never blocks (nothing to judge by) |
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`. Grok also loads hooks from `~/.claude/settings.json`; the guard's `Task|Agent` matcher doesn't match Grok's `spawn_subagent`, and the guard never blocks Grok spawns anyway.
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,19 @@ 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 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
67
  | `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
65
68
  | `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
66
69
  | `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
67
70
  | `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
71
  | `limitcast trial` | Pro free for 7 days on this computer, no card, once |
69
72
  | `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
73
+ | `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) |
74
+ | `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
75
  | `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
76
  | `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
77
  | `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 |
@@ -92,4 +97,4 @@ Free: runout forecast with NEAR warnings and the daily allowance, status-line re
92
97
 
93
98
  ## License
94
99
 
95
- [MIT](LICENSE). Versions up to 0.11.3 were released under the Elastic License 2.0 and stay under it.
100
+ [Elastic License 2.0](LICENSE): free to use; you may not remove or circumvent the license-key checks or offer limitcast as a hosted service.
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';
@@ -36,14 +51,16 @@ import { countInteractiveSince, latestInteractiveTranscript } from '../src/start
36
51
  import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
37
52
  import { budgetSpent, getBudget, loadSubagents, logSubagent, receiptMessage, setBudget, subagentUsage, windowStart } from '../src/subagents.mjs';
38
53
  import { forTerminal } from '../src/term.mjs';
54
+ import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
39
55
  import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
40
56
  import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
41
57
  import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valueSection, valueTotals } from '../src/value.mjs';
58
+ import { attribute, jobsReport, whyReport, whySessions } from '../src/where.mjs';
42
59
 
43
60
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
44
- const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
61
+ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok plans
45
62
 
46
- limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex); backs up settings
63
+ limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex and Grok); backs up settings
47
64
  (without Pro the guard is a preview: it records what it would block, never blocks)
48
65
  limitcast uninstall remove it and restore your original status line
49
66
  limitcast doctor [--fix] check the setup (--fix: re-install with this Node, e.g. after a Node upgrade)
@@ -51,6 +68,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
51
68
  limitcast status [--json] used, burn rate, runout time, reset, and today's share of each weekly window
52
69
  limitcast trim [--share] tokens every session loads before you type, and how much you never use
53
70
  limitcast trim --codex the same for Codex: AGENTS.md size and MCP servers you haven't used
71
+ limitcast trim --grok the same for Grok: system prompt size and MCP servers you haven't used
54
72
  limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
55
73
  [--share] totals only, safe to post
56
74
  limitcast license show the license and re-check it with Polar
@@ -60,13 +78,18 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
60
78
  (--share: totals only, no names, safe to post)
61
79
  limitcast trim --apply / --undo hide those skills and turn off those MCP servers (backed up, reversible)
62
80
  limitcast trim --codex --apply / --undo turn off unused Codex MCP servers (enabled = false; reversible)
81
+ limitcast trim --grok --apply / --undo turn off unused Grok MCP servers (enabled = false; reversible)
63
82
  limitcast saved tokens saved since limitcast first measured you
64
83
  limitcast install --guard block new subagents when a window is on pace to run out, and run
65
84
  them on Sonnet while a window is tight (NEAR or AT_RISK); show what
66
- each finished subagent cost; hold the first message after the prompt
85
+ each finished subagent cost, and what that kind has cost before a new
86
+ one starts; hold the first message after the prompt
67
87
  cache expired (idle over 60 min, LIMITCAST_CACHE_MINUTES) and say what it costs
68
88
  limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
69
- limitcast install --alerts tell you when your starting context grows, plus a weekly summary
89
+ limitcast budget grok <usd>|off Grok 5-hour dollar cap (Grok stores spend, not a % used; the guard
90
+ needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
91
+ limitcast install --alerts tell you when your starting context grows, plus a weekly summary, and
92
+ when one tool result is very large (about 20k tokens), with what to ask for instead
70
93
  limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
71
94
  and when your Claude limit itself changes
72
95
  limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
@@ -75,11 +98,13 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
75
98
  run a heavy job once the window has reset
76
99
  limitcast results --html [--out FILE] results, current windows and the burn report as one page
77
100
  limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
101
+ limitcast report --why [--days N] where the new tokens went: subagents, session starts, cache rebuilds, tool results
102
+ limitcast report --jobs [--days N] the scheduled (headless) jobs that spend the most tokens just starting
78
103
  (status line, Pro: points to another account with room, and suggests /compact past ~150k tokens a call)
79
104
  limitcast activate <license-key> unlock Pro on this computer (online once; then a weekly check, offline up to 30 days)
80
105
  limitcast deactivate free this computer's activation to use the key elsewhere
81
106
 
82
- Used by Claude Code and Codex (set up by install)
107
+ Used by Claude Code, Codex and Grok (set up by install)
83
108
  limitcast statusline [-- <cmd...>] record limit readings, then run your status-line command
84
109
  limitcast guard PreToolUse hook (Pro)
85
110
  limitcast prompt-check UserPromptSubmit hook: the cold-cache warning (Pro)
@@ -101,25 +126,30 @@ if (['report', 'trim', 'saved', 'results', 'drift', 'doctor', 'license'].include
101
126
  }
102
127
 
103
128
  if (cmd === 'status') {
104
- const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
129
+ const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS)), ...grokSamples(now)]), now);
105
130
  if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
106
131
  else {
107
- console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, or run Codex once.');
132
+ console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, Codex or Grok.');
108
133
  // Pro: the other Claude accounts limitcast has current readings for (the table shows the latest one).
109
134
  if (isPro())
110
135
  for (const a of accountForecasts(load(now - KEEP_MS), now).slice(1))
111
136
  console.log(
112
137
  `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
138
  );
114
- if (existsSync(grokRoot())) console.log('grok: no limit readings (Grok keeps none on disk); its token use is in `limitcast report`');
139
+ const spend = grokSpendLine(now);
140
+ if (spend) console.log(spend);
141
+ else if (existsSync(grokRoot()) && !rows.some((f) => f.src === 'grok'))
142
+ console.log('grok: spent $0 in the current windows. Set a cap to forecast runout: limitcast budget grok <usd>');
115
143
  }
116
144
  } else if (cmd === 'statusline') {
117
145
  const input = readStdin();
118
146
  let sid;
147
+ /** @type {any} */
148
+ let feed;
119
149
  /** @type {string[]} */
120
150
  const hints = [];
121
151
  try {
122
- const feed = JSON.parse(input);
152
+ feed = JSON.parse(input);
123
153
  sid = feed?.session_id;
124
154
  record(claudeSamples(feed, now));
125
155
  saveFeedShape(feed);
@@ -131,11 +161,15 @@ if (cmd === 'status') {
131
161
  if (health) hints.push(health);
132
162
  if (isPro()) {
133
163
  const samples = load(now - KEEP_MS);
134
- if (notifyEnabled()) notifyChanges(forecastAll(oneClaudeAccount(samples, sid), now), clock);
164
+ if (notifyEnabled()) notifyChanges(forecastAll(oneClaudeAccount([...samples, ...grokSamples(now)], sid), now), clock);
135
165
  const room = headroom(samples, sid, now);
136
166
  if (room) hints.push(room);
137
- const ctx = typeof feed?.transcript_path === 'string' ? compactHint(lastCallTokens(feed.transcript_path)) : null;
138
- if (ctx) hints.push(ctx);
167
+ const ctxPct = Number(feed?.context_window?.used_percentage);
168
+ if (Number.isFinite(ctxPct) && ctxPct >= 80) hints.push(`${ctxPct}% ctx`);
169
+ else if (typeof feed?.transcript_path === 'string') {
170
+ const ctx = compactHint(lastCallTokens(feed.transcript_path));
171
+ if (ctx) hints.push(ctx);
172
+ }
139
173
  } else {
140
174
  const week = freeWeeklyHint(now);
141
175
  if (week) hints.push(week);
@@ -145,21 +179,26 @@ if (cmd === 'status') {
145
179
  }
146
180
  const sep = args.indexOf('--');
147
181
  const wrapped = sep >= 0 ? args.slice(sep + 1) : [];
182
+ const grokOwn = grokSessionLine(feed);
183
+ let line = 'waiting for data';
184
+ try {
185
+ // Grok spend/forecast stays on the Grok status line. Claude's feed has rate_limits; mixing the two
186
+ // would print grok $ on Claude Code and break "waiting for data" when there are no Claude readings.
187
+ const grokExtra = grokOwn ? grokSamples(now) : [];
188
+ line = statusBits(forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...grokExtra], sid), now), grokOwn ? grokSpendLine(now) : '', hints);
189
+ } catch {
190
+ /* never break the status line */
191
+ }
148
192
  if (wrapped.length) {
149
193
  const r = spawnSync(wrapped[0], wrapped.slice(1), { input, stdio: ['pipe', 'pipe', 'inherit'] });
150
194
  // Your status line stays as it was; limitcast adds its own line under it (status scripts often printf without a newline).
151
195
  const yours = r.stdout?.toString() ?? '';
152
196
  process.stdout.write(yours && !yours.endsWith('\n') ? `${yours}\n` : yours);
153
- let line = 'waiting for data';
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(' · ')}`);
197
+ console.log(`limitcast: ${line}`);
160
198
  process.exit(r.status ?? 1);
161
199
  }
162
- console.log([oneLine(forecastAll(oneClaudeAccount(load(now - KEEP_MS), sid), now)), ...hints].join(' · '));
200
+ if (grokOwn) console.log(grokOwn);
201
+ console.log(`limitcast: ${line}`);
163
202
  } else if (cmd === 'guard') {
164
203
  // Blocking is Pro; without a valid license the guard only previews (logs what Pro would block) and allows everything.
165
204
  if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
@@ -167,6 +206,9 @@ if (cmd === 'status') {
167
206
  const d = await runGuard(JSON.parse(readStdin()), now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30), { preview: !isPro() });
168
207
  if (typeof d === 'string') {
169
208
  console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d } }));
209
+ } else if (d && 'notice' in d) {
210
+ // Allowed as is, with what this kind of subagent has cost so far (shown to the user, never the model).
211
+ console.log(JSON.stringify({ systemMessage: d.notice }));
170
212
  } else if (d) {
171
213
  // Model switch: allow the spawn with the same input and model "sonnet" (updatedInput replaces the whole input).
172
214
  console.log(
@@ -211,6 +253,19 @@ if (cmd === 'status') {
211
253
  } catch {
212
254
  /* a hook must never stop a prompt by failing */
213
255
  }
256
+ } else if (cmd === 'tool-check') {
257
+ // PostToolUse hook (Pro, installed with --alerts): tell the user, once per tool per session, about a very large tool
258
+ // result and what to ask for next time. Never reaches the model.
259
+ try {
260
+ if (isPro()) {
261
+ const hook = JSON.parse(readStdin());
262
+ const name = String(hook?.tool_name ?? '');
263
+ const notice = name ? toolNotice(name, hook?.tool_response, loadValue().calib, Number(process.env.LIMITCAST_TOOL_TOKENS) || undefined) : null;
264
+ if (notice && firstFlag(String(hook.session_id), toolKey(name))) console.log(JSON.stringify({ systemMessage: notice }));
265
+ }
266
+ } catch {
267
+ /* a hook must never break the session */
268
+ }
214
269
  } else if (cmd === 'subagent-receipt') {
215
270
  // SubagentStop hook: price the finished subagent against the 5-hour window and log it (for budgets and results).
216
271
  // Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
@@ -240,12 +295,33 @@ if (cmd === 'status') {
240
295
  }
241
296
  } else if (cmd === 'budget') {
242
297
  if (!isPro()) {
243
- console.log(`Subagent budgets are part of limitcast Pro: ${UPGRADE_URL}`);
298
+ console.log(`Budgets are part of limitcast Pro: ${UPGRADE_URL}`);
244
299
  process.exit(2);
245
300
  }
301
+ if (args[0] === 'grok') {
302
+ const win = args[1] === '7d' || args[1] === '5h' ? args[1] : '5h';
303
+ const value = args[1] === '7d' || args[1] === '5h' ? args[2] : args[1];
304
+ if (value !== undefined && value !== 'off' && !(Number(value) > 0)) {
305
+ console.log('Usage: limitcast budget grok <usd>|off (5-hour dollar cap)\n limitcast budget grok 7d <usd>|off');
306
+ process.exit(1);
307
+ }
308
+ if (value !== undefined) setGrokBudget(value === 'off' ? null : Number(value), win);
309
+ const budget = getGrokBudget();
310
+ const spend = grokSpend(now);
311
+ const cap = budget?.[win];
312
+ const used = spend?.[win];
313
+ console.log(
314
+ cap
315
+ ? `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.`
316
+ : `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`,
317
+ );
318
+ if (getGrokBudget() && !installedFeatures().guard && grokPresent())
319
+ console.log('The budget is enforced by the guard: limitcast install --guard (then restart Grok).');
320
+ process.exit(0);
321
+ }
246
322
  const value = args[1];
247
323
  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');
324
+ console.log('Usage: limitcast budget subagents <percent of the 5-hour window, 1-100>|off\n limitcast budget grok <usd>|off');
249
325
  process.exit(1);
250
326
  }
251
327
  if (value !== undefined) setBudget(value === 'off' ? null : Number(value));
@@ -273,7 +349,9 @@ if (cmd === 'status') {
273
349
  }
274
350
  if (wantAlerts && !isPro()) console.log(`Alerts and the weekly summary are part of limitcast Pro (${UPGRADE_URL}). Skipping them.`);
275
351
  for (const c of install({ guard: wantGuard, alerts: wantAlerts && isPro() })) console.log(`✓ ${c}`);
276
- console.log('Restart Claude Code and Codex to load it. Then: limitcast doctor');
352
+ console.log('Restart Claude Code, Codex and Grok to load it. Then: limitcast doctor');
353
+ if (wantGuard && grokPresent() && !getGrokBudget())
354
+ console.log('Grok stores spend, not a % used. Set a 5-hour dollar cap so the guard can block: limitcast budget grok <usd>');
277
355
  // First run: show the number that matters right away, and what comes next.
278
356
  try {
279
357
  const latest = await latestInteractiveTranscript(claudeRoot());
@@ -310,7 +388,7 @@ if (cmd === 'status') {
310
388
  if (!f.statusLine) console.log('limitcast is not installed. Run `limitcast install` first.');
311
389
  else {
312
390
  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.');
391
+ 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
392
  }
315
393
  }
316
394
  const checks = await healthChecks();
@@ -355,11 +433,49 @@ if (cmd === 'status') {
355
433
  } else console.log(forTerminal(r.text));
356
434
  process.exit(0);
357
435
  }
436
+ if (cmd === 'trim' && args.includes('--grok')) {
437
+ if ((args.includes('--apply') || args.includes('--undo')) && !pro) {
438
+ console.log(`\`limitcast trim --grok --apply\` is part of limitcast Pro: ${UPGRADE_URL}`);
439
+ process.exit(2);
440
+ }
441
+ if (args.includes('--undo')) {
442
+ const e = undoGrokTrim();
443
+ console.log(
444
+ e ? `✓ Back to how they were: ${e.servers.map((s) => s.name).join(', ')}. Takes effect in your next Grok session.` : 'Nothing to undo.',
445
+ );
446
+ process.exit(0);
447
+ }
448
+ if (!existsSync(grokConfigPath())) {
449
+ console.log(`No Grok setup found (${grokConfigPath()}). Set GROK_HOME if Grok keeps it elsewhere.`);
450
+ process.exit(0);
451
+ }
452
+ const r = grokTrimReport({
453
+ servers: grokServers(),
454
+ used: grokUsedServers(since),
455
+ startup: grokStartup(),
456
+ days: days(),
457
+ pro,
458
+ });
459
+ if (args.includes('--apply')) {
460
+ const changed = applyGrokTrim(r.unused);
461
+ console.log(
462
+ changed.length
463
+ ? `✓ 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`
464
+ : 'Nothing to turn off: every server that is on was used.',
465
+ );
466
+ } else console.log(forTerminal(r.text));
467
+ process.exit(0);
468
+ }
358
469
  /** @type {import('../src/trim.mjs').Activity} */
359
470
  const used = { skills: new Set(), mcp: new Set() };
360
- const usage = await readUsage(since, {}, cmd === 'trim' ? used : undefined);
471
+ const jobs = cmd === 'report' && args.includes('--jobs');
472
+ const why = cmd === 'report' && args.includes('--why');
473
+ const usage = why || jobs ? [] : await readUsage(since, {}, cmd === 'trim' ? used : undefined);
361
474
  let text;
362
- if (cmd === 'report') text = burnReport(usage, { since, now });
475
+ if (why || jobs) {
476
+ const r = attribute(await whySessions(claudeRoot(), since), since);
477
+ text = jobs ? jobsReport(r, { since, now }) : whyReport(r, { since, now, calib: loadValue().calib });
478
+ } else if (cmd === 'report') text = burnReport(usage, { since, now });
363
479
  else {
364
480
  // Prefer the measured starting context of the latest interactive session; older Claude Code logs fall back to estimates.
365
481
  const latest = await latestInteractiveTranscript(claudeRoot());
@@ -856,16 +972,35 @@ function table(rows) {
856
972
 
857
973
  /** @param {ReturnType<typeof forecastAll>} rows */
858
974
  function oneLine(rows) {
859
- return (
860
- rows
861
- .filter((f) => f.src === 'claude')
862
- .map(
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'
975
+ const bits = rows.map(
976
+ (f) =>
977
+ `${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' ? ' ⛔' : ''}` +
978
+ (f.today && f.verdict !== 'HIT' ? ` · today ${todayLabel(f.today)}` : ''),
868
979
  );
980
+ return bits.join(' · ') || 'limitcast: waiting for data';
981
+ }
982
+
983
+ /**
984
+ * Status-line body: forecasts, Grok spend when there is no cap, then hints. No "waiting for data" when spend is known.
985
+ * @param {ReturnType<typeof forecastAll>} rows
986
+ * @param {string} spend
987
+ * @param {string[]} hints
988
+ */
989
+ function statusBits(rows, spend, hints) {
990
+ const core = oneLine(rows);
991
+ const parts = [];
992
+ if (core !== 'limitcast: waiting for data') parts.push(core.replace(/^limitcast: /, ''));
993
+ if (spend) parts.push(spend);
994
+ parts.push(...hints);
995
+ return parts.join(' · ') || 'waiting for data';
996
+ }
997
+
998
+ /** Grok spend line when no dollar cap is set (a cap becomes a forecast row instead). */
999
+ function grokSpendLine(t) {
1000
+ if (getGrokBudget()) return '';
1001
+ const s = grokSpend(t);
1002
+ if (!s) return '';
1003
+ return `grok 5h $${s['5h'].toFixed(2)} · 7d $${s['7d'].toFixed(2)}`;
869
1004
  }
870
1005
 
871
1006
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.11.4",
3
+ "version": "0.12.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": {
@@ -36,5 +36,5 @@
36
36
  "url": "git+https://github.com/SamStull9007/limitcast.git"
37
37
  },
38
38
  "author": "Sam Stull",
39
- "license": "MIT"
39
+ "license": "Elastic-2.0"
40
40
  }