limitcast 0.17.3 → 0.18.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 +147 -84
- package/bin/limitcast.mjs +169 -32
- package/package.json +1 -1
- package/src/cold.mjs +47 -10
- package/src/inflight.mjs +99 -0
- package/src/install.mjs +9 -0
- package/src/results.mjs +21 -1
- package/src/startup.mjs +28 -0
- package/src/toollimit.mjs +137 -0
- package/src/trim.mjs +10 -1
- package/src/where.mjs +53 -3
package/README.md
CHANGED
|
@@ -1,118 +1,181 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/assets/emblem.png" alt="Limitcast forecast gauge connected to Claude Code, Codex, and Grok provider badges" width="420">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<p align="center">
|
|
6
|
+
<a href="https://www.npmjs.com/package/limitcast"><code>npm · limitcast</code></a>
|
|
7
|
+
<a href="https://github.com/SamStull9007/limitcast/actions/workflows/ci.yml"><img src="https://github.com/SamStull9007/limitcast/actions/workflows/ci.yml/badge.svg" alt="CI status"></a>
|
|
8
|
+
<a href="LICENSE"><code>MIT license</code></a>
|
|
9
|
+
<a href="https://nodejs.org"><code>Node.js 20+</code></a>
|
|
10
|
+
</p>
|
|
4
11
|
|
|
5
|
-
|
|
12
|
+
<p align="center">
|
|
13
|
+
<strong>See the limit. Stay ahead.</strong><br>
|
|
14
|
+
See when your usage window will run out, control subagent burn,<br>
|
|
15
|
+
and remove starting context you never use.
|
|
16
|
+
</p>
|
|
6
17
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
18
|
+
<p align="center"><code>npm install -g limitcast</code></p>
|
|
19
|
+
|
|
20
|
+
> **Follow Limitcast:** select **Watch → Custom → Releases** for updates. Enable email delivery in your GitHub notification settings to get release emails. [How to subscribe](docs/community.md#get-release-emails) · [Join Discussions](https://github.com/SamStull9007/limitcast/discussions)
|
|
21
|
+
|
|
22
|
+
<p align="center">
|
|
23
|
+
<a href="#quick-start">Quick start</a> ·
|
|
24
|
+
<a href="#see-it-in-action">Demo</a> ·
|
|
25
|
+
<a href="docs/tour.md">Visual tour</a> ·
|
|
26
|
+
<a href="docs/usage.md">Full guide</a> ·
|
|
27
|
+
<a href="https://limitcast.dev">Website</a> ·
|
|
28
|
+
<a href="CHANGELOG.md">Changelog</a>
|
|
29
|
+
</p>
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Less overhead. More room to build.
|
|
34
|
+
|
|
35
|
+
- **Forecast your windows.** See what's likely to run out first and pace your weekly allowance. `limitcast status`
|
|
36
|
+
|
|
37
|
+
- **Keep agents in check.** Hold new subagents when capacity is tight, with receipts and optional budgets. The guard also holds a second subagent of the same type and prompt while the first is still running. `limitcast install --guard`
|
|
38
|
+
|
|
39
|
+
- **Start lighter.** Inspect unused skills and MCP servers, then trim with backups and undo. `limitcast trim`
|
|
40
|
+
|
|
41
|
+
<a id="free-and-open-source"></a>
|
|
42
|
+
|
|
43
|
+
**Free and open source.** All features are included. No Limitcast account, license key, or subscription required. Runs locally on **macOS and Linux** with **Node.js 20+**.
|
|
10
44
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
45
|
+
<a id="install"></a>
|
|
46
|
+
|
|
47
|
+
## Quick start
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
npm install -g limitcast
|
|
51
|
+
limitcast onboard # Read-only setup checks and a first useful result
|
|
52
|
+
limitcast install # Add the status-line recorder
|
|
53
|
+
limitcast doctor # Check the integration
|
|
14
54
|
```
|
|
15
55
|
|
|
16
|
-
|
|
17
|
-
- **Subagent guard** 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:** 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
|
-
- **Cold-cache warning:** 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 (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.
|
|
21
|
-
- **Limit-change alert:** 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.
|
|
22
|
-
- **Daily allowance (free):** today's even share of each weekly window, so you can pace the week: `7d 41% · today 6% left`.
|
|
23
|
-
- **More controls:** 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`).
|
|
24
|
-
- **Capacity report:** `limitcast results` separates recorded consumption by provider, applied protection decisions and historical previews, and estimated Claude context tokens not re-sent relative to a recorded baseline. Calls crossing a week boundary are counted in the period they happened. It also shows lifetime context estimates, forecast replay and next steps. Unknown evidence stays unavailable; controls are not converted into invented saved tokens.
|
|
25
|
-
- **Burn report:** Claude Code, Codex and Grok tokens by day, project, model and session.
|
|
26
|
-
- **Runout forecast (free):** burn rate and the clock time each window runs out.
|
|
27
|
-
- **Local only.** Reads the limit readings Claude Code passes to your status line and the logs Claude Code, Codex and Grok already write. No logins, and your usage data never leaves your machine. No license validation or payment-service connection is required. If you turn on phone or webhook notifications (off by default), each notification's text goes to the service you chose (ntfy.sh or your webhook) and nothing else. The one other exception is also off by default: `limitcast grok-usage on` reads the login Grok keeps in `~/.grok/auth.json` and sends it to grok.com, and nowhere else, to ask for your weekly Grok usage (details under Grok below).
|
|
56
|
+
Restart Claude Code after installing. Your existing status line stays in place, with the Limitcast line underneath. Installation backs up your settings; `limitcast uninstall` restores them.
|
|
28
57
|
|
|
29
|
-
|
|
30
|
-
|---|---|---|---|
|
|
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) |
|
|
33
|
-
| Token report (`report`) | ✓ | ✓ | ✓ per-turn ledger |
|
|
34
|
-
| Trim advisor (`trim`) | ✓ | `--codex` | `--grok` |
|
|
58
|
+
Want protection as well as visibility? Enable the optional guard:
|
|
35
59
|
|
|
36
|
-
|
|
60
|
+
```sh
|
|
61
|
+
limitcast install --guard
|
|
62
|
+
```
|
|
37
63
|
|
|
38
|
-
|
|
64
|
+
The guard holds **new** subagents when a usage window is on pace to run out; existing agents continue. `LIMITCAST_ALLOW=1` overrides a hold. [Guard behavior and thresholds →](docs/usage.md#subagent-guard)
|
|
39
65
|
|
|
40
|
-
|
|
66
|
+
<details>
|
|
67
|
+
<summary><strong>Homebrew or Claude Code plugin</strong></summary>
|
|
41
68
|
|
|
42
|
-
|
|
69
|
+
Install with Homebrew:
|
|
43
70
|
|
|
44
71
|
```sh
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
limitcast install # free: status-line recorder
|
|
48
|
-
limitcast install --guard # also the subagent guard (free; holds new subagents when a limit is on pace to run out)
|
|
49
|
-
limitcast doctor
|
|
72
|
+
brew trust samstull9007/limitcast
|
|
73
|
+
brew install samstull9007/limitcast/limitcast
|
|
50
74
|
```
|
|
51
75
|
|
|
52
|
-
|
|
76
|
+
Or add the Claude Code plugin for `/limitcast:status`, `/limitcast:results`, `/limitcast:trim`, `/limitcast:memory-audit`, and `/limitcast:memory-split`:
|
|
77
|
+
|
|
78
|
+
```text
|
|
79
|
+
/plugin marketplace add SamStull9007/limitcast
|
|
80
|
+
/plugin install limitcast@limitcast
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The status-line recorder still comes from `limitcast install`.
|
|
84
|
+
|
|
85
|
+
</details>
|
|
86
|
+
|
|
87
|
+
## See it in action
|
|
53
88
|
|
|
54
|
-
|
|
89
|
+
**[Take the illustrated tour →](docs/tour.md)** Forecast your windows, give subagents a budget, and inspect what you load.
|
|
55
90
|
|
|
56
|
-
|
|
91
|
+

|
|
57
92
|
|
|
58
|
-
|
|
93
|
+
<p align="center"><sub>Actual CLI output, arranged for readability · synthetic demo data · estimates are not measured financial savings</sub></p>
|
|
59
94
|
|
|
60
|
-
|
|
95
|
+
<details>
|
|
96
|
+
<summary><strong>Watch the recorded terminal walkthrough</strong></summary>
|
|
61
97
|
|
|
62
|
-
|
|
63
|
-
|---|---|
|
|
64
|
-
| `limitcast onboard` | Read-only guided setup: local tools, readiness, free feature availability, personal context finding, keep/undo/override controls and next commands. Never changes settings |
|
|
65
|
-
| `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."). also lists your other Claude accounts |
|
|
66
|
-
| `limitcast trim --codex [--apply / --undo]` | Codex: AGENTS.md size and MCP servers in `~/.codex/config.toml` you haven't used. names them and turns them off (`enabled = false`; `--undo` restores the file exactly) |
|
|
67
|
-
| `limitcast trim --grok [--apply / --undo]` | Grok: system prompt and tool-definition size, and MCP servers in `~/.grok/config.toml` you haven't used. names them and turns them off (`enabled = false`; `--undo` restores the file exactly) |
|
|
68
|
-
| `limitcast notify on/off/test` | 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 |
|
|
69
|
-
| `limitcast notify ntfy <topic or https URL>` / `notify webhook <https URL>` | 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 |
|
|
70
|
-
| `limitcast budget subagents <percent>` / `off` | 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) |
|
|
71
|
-
| `limitcast budget today on` / `off` | 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. Applied holds appear in `results` |
|
|
72
|
-
| `limitcast subagent-model <type> <sonnet\|opus\|haiku\|claude-id\|grok-id>` / `off` | 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 |
|
|
73
|
-
| `limitcast plan [--days N]`, `limitcast plan set <pro\|max5\|max20>` / `off` | 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 |
|
|
74
|
-
| `limitcast budget grok <usd>` / `off` / `7d <usd>` | 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` |
|
|
75
|
-
| `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | Wait for the window to reset, then run the command |
|
|
76
|
-
| `limitcast results --html [--out FILE]` | Results, current windows and the burn report on one page, opened in your browser |
|
|
77
|
-
| `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
|
|
78
|
-
| `limitcast doctor [--fix]` | Check the setup, data freshness, this project's auto-memory index (see `memory`), 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 (the memory line only shows when you run `doctor` yourself). `--fix` re-installs with the current Node (after a Node upgrade) |
|
|
79
|
-
| `limitcast grok-usage [on\|off]` | Grok's real weekly % used, from grok.com with the login Grok already holds (off by default; see Grok above for exactly what it reads and sends). With no argument it shows the current reading |
|
|
80
|
-
| `limitcast memory [dir]` | Check this project's auto-memory folder (`~/.claude/projects/<project>/memory`): how much of `MEMORY.md` fits in what Claude Code loads each session (the first 200 lines or 25 KB; anything past that is never read), broken links, topic files nothing links to, and files over 150 lines. Read-only. In Claude Code, `/limitcast:memory-audit` takes it from there (stale, contradictory and unlinked notes) and `/limitcast:memory-split` splits an oversized file into a short hub plus topic files |
|
|
81
|
-
| `limitcast report [--days N] [--out FILE]` | 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) |
|
|
82
|
-
| `limitcast report --why [--days N]` | 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) |
|
|
83
|
-
| `limitcast report --jobs [--days N]` | 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) |
|
|
84
|
-
| `limitcast trim [--days N] [--share]` | Measured starting context of your latest session and how much you haven't used in N days (default 7). names each item. `--share`: totals only, no names, safe to post |
|
|
85
|
-
| `limitcast saved` | How much the part of your starting context you control has dropped since limitcast first measured it, times your sessions since |
|
|
86
|
-
| `limitcast trim --apply` / `--undo` | 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 |
|
|
87
|
-
| `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 |
|
|
88
|
-
| `limitcast results [--days N] [--share]` | Capacity report plus forecast evidence: each limit window that reached 100% and how far ahead limitcast warned, and what the guard blocked and whether that window then ran out. adds baseline context estimates. `--share`: voluntary totals only; nothing uploads automatically |
|
|
89
|
-
| `install --alerts` | 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 |
|
|
90
|
-
| `limitcast license` | Show the free MIT license status; no network call |
|
|
98
|
+

|
|
91
99
|
|
|
92
|
-
|
|
100
|
+
</details>
|
|
93
101
|
|
|
94
|
-
|
|
102
|
+
### Find the context you carry into every session
|
|
95
103
|
|
|
96
|
-
|
|
104
|
+
Run `limitcast trim` to inspect what your sessions load. It names unused skills and servers and estimates their starting-context cost.
|
|
97
105
|
|
|
98
|
-
|
|
106
|
+
Your findings depend on your local sessions. `trim` inspects first. Use `trim keep <name>` to protect essentials, `trim --apply` to make the changes, and `trim --undo` to reverse them.
|
|
99
107
|
|
|
100
|
-
|
|
108
|
+
## Three tools. One place to understand usage.
|
|
101
109
|
|
|
102
|
-
|
|
110
|
+
| Capability | Claude Code | Codex | Grok |
|
|
111
|
+
| --- | --- | --- | --- |
|
|
112
|
+
| Usage forecast | Status-line readings | Session logs | Dollar budget or opt-in weekly readings |
|
|
113
|
+
| Subagent guard | `Task` / `Agent` | `spawn_agent` | `spawn_subagent` |
|
|
114
|
+
| Token report | Supported | Supported | Per-turn ledger |
|
|
115
|
+
| Context trim | `trim` | `trim --codex` | `trim --grok` |
|
|
103
116
|
|
|
104
|
-
|
|
117
|
+
**Codex:** forecasts and reports read your existing logs without setup. `install --guard` adds the hook; approve it in Codex before it runs.
|
|
105
118
|
|
|
106
|
-
|
|
119
|
+
**Grok:** reports read local spend. Set a dollar cap with `limitcast budget grok <usd>` for forecasts and guarding, or opt into real weekly usage with `limitcast grok-usage on`. [Provider setup and qualifications →](docs/usage.md#install)
|
|
107
120
|
|
|
108
|
-
|
|
121
|
+
<a id="commands"></a>
|
|
109
122
|
|
|
110
|
-
|
|
123
|
+
## Pick your next move
|
|
111
124
|
|
|
112
|
-
|
|
125
|
+
| I want to… | Run |
|
|
126
|
+
| --- | --- |
|
|
127
|
+
| See usage, burn rate, and reset times | `limitcast status` |
|
|
128
|
+
| Find what's consuming tokens | `limitcast report --why` |
|
|
129
|
+
| Limit subagent spend to 15% of a window | `limitcast budget subagents 15` |
|
|
130
|
+
| Pace the weekly allowance day by day | `limitcast budget today on` |
|
|
131
|
+
| Get a desktop alert | `limitcast notify on` |
|
|
132
|
+
| Review activity and protection decisions | `limitcast results` |
|
|
133
|
+
| Check the project's memory index | `limitcast memory` |
|
|
113
134
|
|
|
114
|
-
|
|
135
|
+
[All commands, notification options, model controls, and setup details →](docs/usage.md#commands)
|
|
136
|
+
|
|
137
|
+
## Your data stays yours
|
|
138
|
+
|
|
139
|
+
Limitcast reads usage readings and session logs already on your machine. Reports remain local, sharing totals is voluntary, and no billing-service connection is required.
|
|
140
|
+
|
|
141
|
+
Two optional features make network requests, both **off by default**:
|
|
142
|
+
|
|
143
|
+
- **Phone or webhook notifications** send notification text to the service you choose.
|
|
144
|
+
- **Grok weekly usage** reads Grok's existing login and sends it only to grok.com to retrieve your usage. Redirects are refused; the login is never stored or logged by Limitcast.
|
|
145
|
+
|
|
146
|
+
Context reductions are estimates against a recorded baseline, not measured causal savings or a lower subscription bill. Forecasts depend on observed usage. [How forecasting and measurement work →](docs/usage.md#how-the-forecast-works)
|
|
147
|
+
|
|
148
|
+
<details>
|
|
149
|
+
<summary><strong>Technical reference and upgrade notes</strong></summary>
|
|
150
|
+
|
|
151
|
+
<a id="subagent-guard"></a>
|
|
152
|
+
|
|
153
|
+
**Subagent guard:** [Thresholds, overrides, receipts, and cold-cache behavior](docs/usage.md#subagent-guard).
|
|
154
|
+
|
|
155
|
+
<a id="how-the-forecast-works"></a>
|
|
156
|
+
|
|
157
|
+
**How the forecast works:** [Sampling, burn rates, weekly pacing, and account separation](docs/usage.md#how-the-forecast-works).
|
|
158
|
+
|
|
159
|
+
<a id="measuring-recurring-value"></a>
|
|
160
|
+
|
|
161
|
+
**Measuring recurring value:** [Baselines, time windows, and what the evidence can establish](docs/usage.md#measuring-recurring-value).
|
|
162
|
+
|
|
163
|
+
<a id="upgrading-to-0150"></a>
|
|
164
|
+
|
|
165
|
+
**Upgrading from before 0.15.0:** All features are free. Previously preview-only guards enforce after upgrading. [Behavior changes and opt-out](docs/usage.md#upgrading-to-0150).
|
|
166
|
+
|
|
167
|
+
</details>
|
|
168
|
+
|
|
169
|
+
## Build with us
|
|
170
|
+
|
|
171
|
+
Found a rough edge? [Report a bug](https://github.com/SamStull9007/limitcast/issues/new/choose). Ask questions in [Q&A](https://github.com/SamStull9007/limitcast/discussions/categories/q-a), propose improvements in [Ideas](https://github.com/SamStull9007/limitcast/discussions/categories/ideas), or [try it for a week](docs/community.md#try-it-for-a-week) and share a reviewed check-in. [Contributions are welcome](CONTRIBUTING.md).
|
|
172
|
+
|
|
173
|
+
```sh
|
|
174
|
+
git clone https://github.com/SamStull9007/limitcast.git
|
|
175
|
+
cd limitcast
|
|
176
|
+
npm test
|
|
177
|
+
```
|
|
115
178
|
|
|
116
|
-
|
|
179
|
+
<a id="license"></a>
|
|
117
180
|
|
|
118
|
-
[MIT License](LICENSE)
|
|
181
|
+
Created by **Sam Stull** · [MIT License](LICENSE) · [Release history](CHANGELOG.md)
|
package/bin/limitcast.mjs
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from '../src/apply.mjs';
|
|
22
22
|
import { calibrate, limitChange, limitChangeMessage, windowPct } from '../src/calibrate.mjs';
|
|
23
23
|
import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
|
|
24
|
-
import { coldCost, coldMessage, firstWarning } from '../src/cold.mjs';
|
|
24
|
+
import { coldCost, coldMessage, coldNotice, firstNotice, firstWarning } from '../src/cold.mjs';
|
|
25
25
|
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
26
26
|
import { formatChecks } from '../src/formats.mjs';
|
|
27
27
|
import {
|
|
@@ -49,6 +49,16 @@ import {
|
|
|
49
49
|
import { runGuard } from '../src/guard.mjs';
|
|
50
50
|
import { accountForecasts, bindingLine, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
51
51
|
import { htmlPage } from '../src/html.mjs';
|
|
52
|
+
import {
|
|
53
|
+
duplicateReason,
|
|
54
|
+
findDuplicate,
|
|
55
|
+
forgetInflight,
|
|
56
|
+
loadInflight,
|
|
57
|
+
pruneInflight,
|
|
58
|
+
rememberInflight,
|
|
59
|
+
saveInflight,
|
|
60
|
+
spawnIdentity,
|
|
61
|
+
} from '../src/inflight.mjs';
|
|
52
62
|
import { insightsReport, insightsShare, periodInsights } from '../src/insights.mjs';
|
|
53
63
|
import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
54
64
|
import { memoryCheck, memoryDir, memoryReport, scanMemory } from '../src/memory.mjs';
|
|
@@ -79,6 +89,7 @@ import {
|
|
|
79
89
|
} from '../src/subagents.mjs';
|
|
80
90
|
import { forTerminal } from '../src/term.mjs';
|
|
81
91
|
import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
|
|
92
|
+
import { loadToolStats, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
|
|
82
93
|
import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
83
94
|
import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
|
|
84
95
|
import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valuePeriod, valueSection, valueTotals } from '../src/value.mjs';
|
|
@@ -112,8 +123,10 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
112
123
|
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
113
124
|
them on Sonnet while a window is tight (NEAR or AT_RISK); show what
|
|
114
125
|
each finished subagent cost, and what that kind has cost before a new
|
|
115
|
-
one starts; hold
|
|
116
|
-
|
|
126
|
+
one starts; hold a second spawn of the same type and prompt
|
|
127
|
+
while the first is still running; announce a message after the
|
|
128
|
+
cheap cache expires (idle over 5 min, LIMITCAST_CACHE_NOTICE_MINUTES)
|
|
129
|
+
and hold the first one after 60 min (LIMITCAST_CACHE_MINUTES)
|
|
117
130
|
limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
|
|
118
131
|
limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku, grok-… or a model id
|
|
119
132
|
limitcast plan [--days N] does your Claude plan fit your use? Hit-limit and headroom evidence, and the monthly price difference
|
|
@@ -122,8 +135,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
122
135
|
needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
|
|
123
136
|
limitcast budget today on|off hold new subagents once today's share of a weekly window is used up, until
|
|
124
137
|
midnight (off: you only get a notification at 80% of the share; notify on)
|
|
125
|
-
limitcast install --alerts tell you when your starting context grows, plus a weekly summary,
|
|
126
|
-
when one tool result is very large (about 20k tokens),
|
|
138
|
+
limitcast install --alerts tell you when your starting context grows, plus a weekly summary,
|
|
139
|
+
when one tool result is very large (about 20k tokens), and, before it
|
|
140
|
+
runs, when a tool report --why has shown to be fat sets no limit
|
|
127
141
|
limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
|
|
128
142
|
and when your Claude limit itself changes
|
|
129
143
|
limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
|
|
@@ -133,13 +147,15 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
133
147
|
limitcast results --html [--out FILE] results, current windows and the burn report as one page
|
|
134
148
|
limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
|
|
135
149
|
limitcast report --why [--days N] where the new tokens went: subagents, session starts, cache rebuilds, tool results
|
|
136
|
-
limitcast report --jobs [--days N] the scheduled (headless) jobs that spend the most tokens just starting
|
|
150
|
+
limitcast report --jobs [--days N] the scheduled (headless) jobs that spend the most tokens just starting,
|
|
151
|
+
and which startup piece changed between two runs of the same job
|
|
137
152
|
(status line: points to another account with room, and suggests /compact past ~150k tokens a call)
|
|
138
153
|
|
|
139
154
|
Used by Claude Code, Codex and Grok (set up by install)
|
|
140
155
|
limitcast statusline [-- <cmd...>] record limit readings, then run your status-line command
|
|
141
156
|
limitcast guard PreToolUse hook
|
|
142
|
-
limitcast prompt-check UserPromptSubmit hook: the cold-cache
|
|
157
|
+
limitcast prompt-check UserPromptSubmit hook: the cold-cache notice and hold
|
|
158
|
+
limitcast tool-limit PreToolUse hook: a fat tool call that sets no limit
|
|
143
159
|
limitcast subagent-receipt SubagentStop hook: what the subagent cost
|
|
144
160
|
limitcast drift [--hook] SessionStart hook: compare starting context with the last session
|
|
145
161
|
`;
|
|
@@ -252,24 +268,53 @@ if (cmd === 'status') {
|
|
|
252
268
|
// The installed guard protects all users; LIMITCAST_ALLOW=1 remains the explicit override.
|
|
253
269
|
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
254
270
|
try {
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
271
|
+
const hook = JSON.parse(readStdin());
|
|
272
|
+
const id = spawnIdentity(hook);
|
|
273
|
+
const live = pruneInflight(loadInflight(), now);
|
|
274
|
+
const dup = id ? findDuplicate(live, id) : null;
|
|
275
|
+
if (id && dup) {
|
|
276
|
+
saveInflight(live);
|
|
277
|
+
logBlock({
|
|
278
|
+
t: now,
|
|
279
|
+
kind: 'duplicate',
|
|
280
|
+
src: id.src,
|
|
281
|
+
win: '5h',
|
|
282
|
+
pct: 0,
|
|
283
|
+
wall: now,
|
|
284
|
+
reset: now,
|
|
285
|
+
type: id.type,
|
|
286
|
+
sid: id.sid,
|
|
287
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
288
|
+
});
|
|
263
289
|
console.log(
|
|
264
290
|
JSON.stringify({
|
|
265
|
-
hookSpecificOutput: {
|
|
266
|
-
hookEventName: 'PreToolUse',
|
|
267
|
-
permissionDecision: 'allow',
|
|
268
|
-
permissionDecisionReason: d.reason,
|
|
269
|
-
updatedInput: d.updatedInput,
|
|
270
|
-
},
|
|
291
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: duplicateReason(id) },
|
|
271
292
|
}),
|
|
272
293
|
);
|
|
294
|
+
} else {
|
|
295
|
+
const d = await runGuard(hook, now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30), { preview: false });
|
|
296
|
+
if (typeof d === 'string') {
|
|
297
|
+
saveInflight(live);
|
|
298
|
+
console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d } }));
|
|
299
|
+
} else {
|
|
300
|
+
if (id) saveInflight(rememberInflight(live, id, now));
|
|
301
|
+
if (d && 'notice' in d) {
|
|
302
|
+
// Allowed as is, with what this kind of subagent has cost so far (shown to the user, never the model).
|
|
303
|
+
console.log(JSON.stringify({ systemMessage: d.notice }));
|
|
304
|
+
} else if (d) {
|
|
305
|
+
// Model switch: allow the spawn with the same input and model "sonnet" (updatedInput replaces the whole input).
|
|
306
|
+
console.log(
|
|
307
|
+
JSON.stringify({
|
|
308
|
+
hookSpecificOutput: {
|
|
309
|
+
hookEventName: 'PreToolUse',
|
|
310
|
+
permissionDecision: 'allow',
|
|
311
|
+
permissionDecisionReason: d.reason,
|
|
312
|
+
updatedInput: d.updatedInput,
|
|
313
|
+
},
|
|
314
|
+
}),
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
273
318
|
}
|
|
274
319
|
} catch (e) {
|
|
275
320
|
// Fail open: a broken governor must not stop the agent.
|
|
@@ -282,9 +327,13 @@ if (cmd === 'status') {
|
|
|
282
327
|
const hook = JSON.parse(readStdin());
|
|
283
328
|
const path = hook?.transcript_path;
|
|
284
329
|
const last = process.env.LIMITCAST_ALLOW !== '1' && typeof path === 'string' && existsSync(path) ? lastCall(path) : null;
|
|
285
|
-
const c = coldCost(hook?.prompt, last, now, {
|
|
286
|
-
|
|
287
|
-
|
|
330
|
+
const c = coldCost(hook?.prompt, last, now, {
|
|
331
|
+
minutes: Number(process.env.LIMITCAST_CACHE_MINUTES ?? 60),
|
|
332
|
+
noticeMinutes: Number(process.env.LIMITCAST_CACHE_NOTICE_MINUTES ?? 5),
|
|
333
|
+
calib: loadValue().calib,
|
|
334
|
+
});
|
|
335
|
+
const sid = String(hook.session_id ?? '');
|
|
336
|
+
if (c && last && c.hold && firstWarning(sid, last.t)) {
|
|
288
337
|
logBlock({
|
|
289
338
|
t: now,
|
|
290
339
|
kind: 'cold',
|
|
@@ -295,13 +344,74 @@ if (cmd === 'status') {
|
|
|
295
344
|
reset: now,
|
|
296
345
|
tokens: c.tokens,
|
|
297
346
|
sid: hook.session_id,
|
|
298
|
-
...(pro ? {} : { shadow: true }),
|
|
299
347
|
});
|
|
300
|
-
|
|
348
|
+
console.log(JSON.stringify({ decision: 'block', reason: coldMessage(c) }));
|
|
349
|
+
} else if (c && last && !c.hold && firstNotice(sid, last.t)) {
|
|
350
|
+
logBlock({
|
|
351
|
+
t: now,
|
|
352
|
+
kind: 'cold-notice',
|
|
353
|
+
src: 'claude',
|
|
354
|
+
win: '5h',
|
|
355
|
+
pct: c.pct ?? 0,
|
|
356
|
+
wall: now,
|
|
357
|
+
reset: now,
|
|
358
|
+
tokens: c.tokens,
|
|
359
|
+
sid: hook.session_id,
|
|
360
|
+
});
|
|
361
|
+
console.log(JSON.stringify({ systemMessage: coldNotice(c) }));
|
|
301
362
|
}
|
|
302
363
|
} catch {
|
|
303
364
|
/* a hook must never stop a prompt by failing */
|
|
304
365
|
}
|
|
366
|
+
} else if (cmd === 'tool-limit') {
|
|
367
|
+
// PreToolUse hook (installed with --alerts). A fat tool with no limit is denied so the model can retry smaller.
|
|
368
|
+
// A limit that is only too large is lowered. Fail open, and LIMITCAST_ALLOW=1 skips it.
|
|
369
|
+
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
370
|
+
try {
|
|
371
|
+
const hook = JSON.parse(readStdin());
|
|
372
|
+
const name = String(hook?.tool_name ?? hook?.toolName ?? '');
|
|
373
|
+
const d = name ? toolLimitDecision(name, hook?.tool_input ?? hook?.toolInput, loadToolStats()) : null;
|
|
374
|
+
if (d && 'deny' in d) {
|
|
375
|
+
logBlock({
|
|
376
|
+
t: now,
|
|
377
|
+
kind: 'tool-limit',
|
|
378
|
+
src: 'claude',
|
|
379
|
+
win: '5h',
|
|
380
|
+
pct: 0,
|
|
381
|
+
wall: now,
|
|
382
|
+
reset: now,
|
|
383
|
+
sid: hook.session_id,
|
|
384
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
385
|
+
});
|
|
386
|
+
console.log(
|
|
387
|
+
JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d.deny } }),
|
|
388
|
+
);
|
|
389
|
+
} else if (d) {
|
|
390
|
+
logBlock({
|
|
391
|
+
t: now,
|
|
392
|
+
kind: 'tool-cap',
|
|
393
|
+
src: 'claude',
|
|
394
|
+
win: '5h',
|
|
395
|
+
pct: 0,
|
|
396
|
+
wall: now,
|
|
397
|
+
reset: now,
|
|
398
|
+
sid: hook.session_id,
|
|
399
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
400
|
+
});
|
|
401
|
+
console.log(
|
|
402
|
+
JSON.stringify({
|
|
403
|
+
hookSpecificOutput: {
|
|
404
|
+
hookEventName: 'PreToolUse',
|
|
405
|
+
permissionDecision: 'allow',
|
|
406
|
+
permissionDecisionReason: d.reason,
|
|
407
|
+
updatedInput: d.updatedInput,
|
|
408
|
+
},
|
|
409
|
+
}),
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
} catch {
|
|
413
|
+
/* a hook must never break the session */
|
|
414
|
+
}
|
|
305
415
|
} else if (cmd === 'tool-check') {
|
|
306
416
|
// PostToolUse hook (installed with --alerts): tell the user, once per tool per session, about a very large tool
|
|
307
417
|
// result and what to ask for next time. Never reaches the model.
|
|
@@ -320,6 +430,7 @@ if (cmd === 'status') {
|
|
|
320
430
|
// Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
|
|
321
431
|
try {
|
|
322
432
|
const hook = JSON.parse(readStdin());
|
|
433
|
+
saveInflight(forgetInflight(loadInflight(), String(hook?.session_id ?? ''), String(hook?.agent_type ?? ''), now));
|
|
323
434
|
const path = hook?.agent_transcript_path;
|
|
324
435
|
if (hook?.agent_type && typeof path === 'string') {
|
|
325
436
|
const u = subagentUsage(path);
|
|
@@ -576,6 +687,10 @@ if (cmd === 'status') {
|
|
|
576
687
|
} else if (cmd === 'report' || cmd === 'trim') {
|
|
577
688
|
const pro = true;
|
|
578
689
|
const since = now - days() * 86400_000;
|
|
690
|
+
if (cmd === 'trim' && args.includes('--share') && (args[0] === 'keep' || args.includes('--apply') || args.includes('--undo'))) {
|
|
691
|
+
console.error('--share is read-only; run keep, --apply, or --undo separately.');
|
|
692
|
+
process.exit(1);
|
|
693
|
+
}
|
|
579
694
|
if (cmd === 'trim' && args[0] === 'keep') {
|
|
580
695
|
// The keep-list: servers and skills `trim --apply` never touches (Claude, Codex and Grok). Free to manage; apply is Pro.
|
|
581
696
|
const drop = args[1] === '--remove';
|
|
@@ -600,7 +715,11 @@ if (cmd === 'status') {
|
|
|
600
715
|
process.exit(0);
|
|
601
716
|
}
|
|
602
717
|
if (!existsSync(codexConfigPath())) {
|
|
603
|
-
console.log(
|
|
718
|
+
console.log(
|
|
719
|
+
args.includes('--share')
|
|
720
|
+
? 'Codex context summary: unavailable (no setup found).'
|
|
721
|
+
: `No Codex setup found (${codexConfigPath()}). Set CODEX_HOME if Codex keeps it elsewhere.`,
|
|
722
|
+
);
|
|
604
723
|
process.exit(0);
|
|
605
724
|
}
|
|
606
725
|
const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
|
|
@@ -612,7 +731,12 @@ if (cmd === 'status') {
|
|
|
612
731
|
? `✓ 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`
|
|
613
732
|
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
614
733
|
);
|
|
615
|
-
} else
|
|
734
|
+
} else
|
|
735
|
+
console.log(
|
|
736
|
+
args.includes('--share')
|
|
737
|
+
? `Codex trim: ${r.unused.length} unused MCP servers, ${r.kept.length} kept. Totals only; no names or paths. https://limitcast.dev`
|
|
738
|
+
: forTerminal(r.text),
|
|
739
|
+
);
|
|
616
740
|
process.exit(0);
|
|
617
741
|
}
|
|
618
742
|
if (cmd === 'trim' && args.includes('--grok')) {
|
|
@@ -624,7 +748,11 @@ if (cmd === 'status') {
|
|
|
624
748
|
process.exit(0);
|
|
625
749
|
}
|
|
626
750
|
if (!existsSync(grokConfigPath())) {
|
|
627
|
-
console.log(
|
|
751
|
+
console.log(
|
|
752
|
+
args.includes('--share')
|
|
753
|
+
? 'Grok context summary: unavailable (no setup found).'
|
|
754
|
+
: `No Grok setup found (${grokConfigPath()}). Set GROK_HOME if Grok keeps it elsewhere.`,
|
|
755
|
+
);
|
|
628
756
|
process.exit(0);
|
|
629
757
|
}
|
|
630
758
|
const r = grokTrimReport({
|
|
@@ -642,7 +770,12 @@ if (cmd === 'status') {
|
|
|
642
770
|
? `✓ 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`
|
|
643
771
|
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
644
772
|
);
|
|
645
|
-
} else
|
|
773
|
+
} else
|
|
774
|
+
console.log(
|
|
775
|
+
args.includes('--share')
|
|
776
|
+
? `Grok trim: ${r.unused.length} unused MCP servers, ${r.kept.length} kept. Totals only; no names or paths. https://limitcast.dev`
|
|
777
|
+
: forTerminal(r.text),
|
|
778
|
+
);
|
|
646
779
|
process.exit(0);
|
|
647
780
|
}
|
|
648
781
|
/** @type {import('../src/trim.mjs').Activity} */
|
|
@@ -653,6 +786,7 @@ if (cmd === 'status') {
|
|
|
653
786
|
let text;
|
|
654
787
|
if (why || jobs) {
|
|
655
788
|
const r = attribute(await whySessions(claudeRoot(), since), since);
|
|
789
|
+
saveToolStats(toolStats(r.tools));
|
|
656
790
|
text = jobs ? jobsReport(r, { since, now }) : whyReport(r, { since, now, calib: loadValue().calib });
|
|
657
791
|
} else if (cmd === 'report') text = burnReport(usage, { since, now });
|
|
658
792
|
else {
|
|
@@ -666,7 +800,10 @@ if (cmd === 'status') {
|
|
|
666
800
|
}
|
|
667
801
|
const keep = getKeep();
|
|
668
802
|
if (latest && args.includes('--share')) text = shareSummary(baseline(usage), latest, used, days(), keep);
|
|
669
|
-
else
|
|
803
|
+
else
|
|
804
|
+
text = latest
|
|
805
|
+
? startupReport(baseline(usage), latest, used, days(), keep)
|
|
806
|
+
: trimReport(baseline(usage), contributors(), used, days(), args.includes('--share'));
|
|
670
807
|
if (latest && !args.includes('--share')) {
|
|
671
808
|
const still = stillLoading(latest);
|
|
672
809
|
text += still.length
|
|
@@ -679,7 +816,7 @@ if (cmd === 'status') {
|
|
|
679
816
|
const out = flag('--out');
|
|
680
817
|
if (out) {
|
|
681
818
|
writeFileSync(out, `${text}\n`);
|
|
682
|
-
console.log(`Wrote ${out}`);
|
|
819
|
+
console.log(cmd === 'trim' && args.includes('--share') ? 'Wrote shared summary.' : `Wrote ${out}`);
|
|
683
820
|
} else console.log(forTerminal(text));
|
|
684
821
|
} else if (cmd === 'drift') {
|
|
685
822
|
// SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.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/cold.mjs
CHANGED
|
@@ -3,9 +3,10 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { stateDir } from './store.mjs';
|
|
5
5
|
|
|
6
|
-
// Cold-cache warning (
|
|
7
|
-
//
|
|
8
|
-
//
|
|
6
|
+
// Cold-cache warning (UserPromptSubmit hook). After a pause the prompt cache has expired, so the next message
|
|
7
|
+
// re-sends the whole context as new tokens, which count against the limit far more than cached ones.
|
|
8
|
+
// From 5 minutes (the cheap cache) the first message is announced and still sent. From 60 minutes it is held
|
|
9
|
+
// once with its cost; sending it again goes through.
|
|
9
10
|
|
|
10
11
|
const MIN_TOKENS = 100_000;
|
|
11
12
|
const stateFile = () => join(stateDir(), 'cold.json');
|
|
@@ -15,18 +16,21 @@ const stateFile = () => join(stateDir(), 'cold.json');
|
|
|
15
16
|
* @param {unknown} prompt
|
|
16
17
|
* @param {{tokens:number, t:number}|null} last the session's latest model call
|
|
17
18
|
* @param {number} now epoch ms
|
|
18
|
-
* @param {{minutes:number, calib?:{fresh:number, read:number}|null}} o
|
|
19
|
-
*
|
|
19
|
+
* @param {{minutes:number, noticeMinutes?:number, calib?:{fresh:number, read:number}|null}} o
|
|
20
|
+
* minutes: idle time that holds the message. noticeMinutes: idle time that only announces it (default: the hold).
|
|
21
|
+
* @returns {{tokens:number, idle:number, pct:number|null, warm:number|null, hold:boolean}|null} pct/warm: % of the 5h window cold/warm
|
|
20
22
|
*/
|
|
21
|
-
export function coldCost(prompt, last, now, { minutes, calib }) {
|
|
23
|
+
export function coldCost(prompt, last, now, { minutes, noticeMinutes, calib }) {
|
|
22
24
|
if (!last?.t || last.tokens < MIN_TOKENS) return null;
|
|
23
25
|
const p = String(prompt ?? '').trimStart();
|
|
24
26
|
// Background agents and other sessions report back as prompts; /compact and /clear are what the warning suggests.
|
|
25
27
|
if (p.startsWith('<') || /^\/(compact|clear)\b/.test(p)) return null;
|
|
26
28
|
const idle = Math.round((now - last.t) / 60_000);
|
|
27
|
-
|
|
29
|
+
// A notice threshold past the hold would skip the hold entirely. Keep the notice at or before it.
|
|
30
|
+
const noticeAt = Math.min(noticeMinutes ?? minutes, minutes);
|
|
31
|
+
if (idle < noticeAt) return null;
|
|
28
32
|
const m = last.tokens / 1e6;
|
|
29
|
-
return { tokens: last.tokens, idle, pct: calib ? m * calib.fresh : null, warm: calib ? m * calib.read : null };
|
|
33
|
+
return { tokens: last.tokens, idle, pct: calib ? m * calib.fresh : null, warm: calib ? m * calib.read : null, hold: idle >= minutes };
|
|
30
34
|
}
|
|
31
35
|
|
|
32
36
|
/** @param {NonNullable<ReturnType<typeof coldCost>>} c */
|
|
@@ -42,6 +46,22 @@ export function coldMessage(c) {
|
|
|
42
46
|
);
|
|
43
47
|
}
|
|
44
48
|
|
|
49
|
+
/**
|
|
50
|
+
* The short-idle announcement. The message is not held.
|
|
51
|
+
* @param {NonNullable<ReturnType<typeof coldCost>>} c
|
|
52
|
+
*/
|
|
53
|
+
export function coldNotice(c) {
|
|
54
|
+
const idle = c.idle >= 120 ? `${Math.round(c.idle / 60)} hours` : `${c.idle} minutes`;
|
|
55
|
+
const cost =
|
|
56
|
+
c.pct !== null && c.warm !== null
|
|
57
|
+
? `≈${pct(c.pct)} of your 5-hour window (≈${pct(c.warm)} if the cache were still warm)`
|
|
58
|
+
: 'all at the new-token rate instead of the much cheaper cached one';
|
|
59
|
+
return (
|
|
60
|
+
`limitcast: this session sat idle for ${idle}, so its cheap prompt cache may have expired. Your message re-sends ${Math.round(c.tokens / 1000)}k tokens of context: ${cost}. ` +
|
|
61
|
+
'It is going through. Run /compact before a longer pause to shrink the next one.'
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
45
65
|
const pct = (/** @type {number} */ x) => `${x < 1 ? x.toFixed(2) : x.toFixed(1)}%`;
|
|
46
66
|
|
|
47
67
|
/**
|
|
@@ -51,6 +71,23 @@ const pct = (/** @type {number} */ x) => `${x < 1 ? x.toFixed(2) : x.toFixed(1)}
|
|
|
51
71
|
* @param {number} lastT the latest model call's time
|
|
52
72
|
*/
|
|
53
73
|
export function firstWarning(sid, lastT) {
|
|
74
|
+
return claim(lastT, sid);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* True the first time this pause is announced (the message still goes through). Independent of the hold.
|
|
79
|
+
* @param {string} sid
|
|
80
|
+
* @param {number} lastT
|
|
81
|
+
*/
|
|
82
|
+
export function firstNotice(sid, lastT) {
|
|
83
|
+
return claim(lastT, `n:${sid}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @param {number} lastT
|
|
88
|
+
* @param {string} key session id, or `n:` plus the session id for the idle notice
|
|
89
|
+
*/
|
|
90
|
+
function claim(lastT, key) {
|
|
54
91
|
/** @type {Record<string, number>} */
|
|
55
92
|
let seen = {};
|
|
56
93
|
try {
|
|
@@ -58,9 +95,9 @@ export function firstWarning(sid, lastT) {
|
|
|
58
95
|
} catch {
|
|
59
96
|
/* first warning */
|
|
60
97
|
}
|
|
61
|
-
if (seen[
|
|
98
|
+
if (seen[key] === lastT) return false;
|
|
62
99
|
const keep = Object.entries(seen).slice(-49); // the 49 most recent other sessions
|
|
63
100
|
mkdirSync(stateDir(), { recursive: true });
|
|
64
|
-
writeFileSync(stateFile(), JSON.stringify(Object.fromEntries([...keep.filter(([k]) => k !==
|
|
101
|
+
writeFileSync(stateFile(), JSON.stringify(Object.fromEntries([...keep.filter(([k]) => k !== key), [key, lastT]])));
|
|
65
102
|
return true;
|
|
66
103
|
}
|
package/src/inflight.mjs
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { spawnSource } from './guard.mjs';
|
|
6
|
+
import { stateDir } from './store.mjs';
|
|
7
|
+
|
|
8
|
+
// A second spawn of the same type and prompt, in the same session, while the first has not finished.
|
|
9
|
+
// SubagentStop clears the Claude one. Codex and Grok have no stop event here, so a record older than
|
|
10
|
+
// 30 minutes is forgotten: a missed stop must not hold the same prompt for the rest of the day.
|
|
11
|
+
|
|
12
|
+
export const INFLIGHT_MS = 30 * 60_000;
|
|
13
|
+
|
|
14
|
+
/** @typedef {{sid:string, type:string, hash:string, t:number}} Inflight */
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Identity of a spawn the duplicate hold can see, or null when the call is not one.
|
|
18
|
+
* An empty prompt or type is not tracked: those retries are how a host re-sends, and they are not the same request.
|
|
19
|
+
* @param {any} hook
|
|
20
|
+
*/
|
|
21
|
+
export function spawnIdentity(hook) {
|
|
22
|
+
const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
|
|
23
|
+
const src = spawnSource(tool);
|
|
24
|
+
if (!src) return null;
|
|
25
|
+
const input = hook?.tool_input ?? hook?.toolInput ?? {};
|
|
26
|
+
const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '').trim();
|
|
27
|
+
const prompt = String(input?.prompt ?? input?.description ?? input?.task ?? '')
|
|
28
|
+
.replace(/\s+/g, ' ')
|
|
29
|
+
.trim();
|
|
30
|
+
const sid = String(hook?.session_id ?? hook?.sessionId ?? '').trim();
|
|
31
|
+
if (!type || !prompt || !sid) return null;
|
|
32
|
+
const hash = createHash('sha256').update(`${type.toLowerCase()}\0${prompt}`).digest('hex').slice(0, 16);
|
|
33
|
+
return { src, type, prompt, hash, sid };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param {Inflight[]} entries @param {number} now @param {number} [maxAge] */
|
|
37
|
+
export function pruneInflight(entries, now, maxAge = INFLIGHT_MS) {
|
|
38
|
+
return entries.filter((e) => now - e.t >= 0 && now - e.t < maxAge);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The still-running spawn with this session, type and prompt, if any.
|
|
43
|
+
* @param {Inflight[]} entries already pruned
|
|
44
|
+
* @param {{sid:string, type:string, hash:string}} id
|
|
45
|
+
*/
|
|
46
|
+
export function findDuplicate(entries, id) {
|
|
47
|
+
return entries.find((e) => e.sid === id.sid && e.hash === id.hash) ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {Inflight[]} entries already pruned
|
|
52
|
+
* @param {{sid:string, type:string, hash:string}} id
|
|
53
|
+
* @param {number} now
|
|
54
|
+
*/
|
|
55
|
+
export function rememberInflight(entries, id, now) {
|
|
56
|
+
return [...entries, { sid: id.sid, type: id.type, hash: id.hash, t: now }];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Drop the oldest still-running spawn of this type in this session (SubagentStop does not carry the prompt).
|
|
61
|
+
* Clearing the oldest fails open: the spawn that is still running may be a different prompt, and that one is then allowed again.
|
|
62
|
+
* @param {Inflight[]} entries
|
|
63
|
+
* @param {string} sid
|
|
64
|
+
* @param {string} type
|
|
65
|
+
* @param {number} now
|
|
66
|
+
*/
|
|
67
|
+
export function forgetInflight(entries, sid, type, now) {
|
|
68
|
+
const live = pruneInflight(entries, now);
|
|
69
|
+
if (!sid || !type) return live;
|
|
70
|
+
const i = live.findIndex((e) => e.sid === sid && e.type.toLowerCase() === type.toLowerCase());
|
|
71
|
+
if (i >= 0) live.splice(i, 1);
|
|
72
|
+
return live;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @param {{type:string}} id */
|
|
76
|
+
export function duplicateReason(id) {
|
|
77
|
+
return (
|
|
78
|
+
`limitcast: a ${id.type} subagent with this same prompt is already running in this session. ` +
|
|
79
|
+
'Wait for it to finish, or set LIMITCAST_ALLOW=1 to spawn another.'
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const file = () => join(stateDir(), 'inflight.json');
|
|
84
|
+
|
|
85
|
+
/** @returns {Inflight[]} */
|
|
86
|
+
export function loadInflight() {
|
|
87
|
+
try {
|
|
88
|
+
const parsed = JSON.parse(readFileSync(file(), 'utf8'));
|
|
89
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
90
|
+
} catch {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {Inflight[]} entries */
|
|
96
|
+
export function saveInflight(entries) {
|
|
97
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
98
|
+
writeFileSync(file(), JSON.stringify(entries.slice(-100)));
|
|
99
|
+
}
|
package/src/install.mjs
CHANGED
|
@@ -112,6 +112,13 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
|
|
|
112
112
|
isToolCheck,
|
|
113
113
|
);
|
|
114
114
|
changes.push('added the large tool-output notice');
|
|
115
|
+
upsertHook(
|
|
116
|
+
cfg,
|
|
117
|
+
'PreToolUse',
|
|
118
|
+
{ matcher: 'Bash|Read|Grep|WebFetch|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-limit`, timeout: 10 }] },
|
|
119
|
+
isToolLimit,
|
|
120
|
+
);
|
|
121
|
+
changes.push('added the fat-tool limit check');
|
|
115
122
|
}
|
|
116
123
|
writeSettings(path, cfg);
|
|
117
124
|
if (guard && existsSync(join(codexPath, '..'))) {
|
|
@@ -174,6 +181,7 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(),
|
|
|
174
181
|
['UserPromptSubmit', isPromptCheck, 'the cold-cache warning'],
|
|
175
182
|
['SubagentStop', isReceipt, 'subagent receipts'],
|
|
176
183
|
['PostToolUse', isToolCheck, 'the large tool-output notice'],
|
|
184
|
+
['PreToolUse', isToolLimit, 'the fat-tool limit check'],
|
|
177
185
|
])) {
|
|
178
186
|
const n = cfg.hooks?.[event]?.length ?? 0;
|
|
179
187
|
if (!n) continue;
|
|
@@ -231,6 +239,7 @@ const isAlert = runs(/\bdrift --hook\b/);
|
|
|
231
239
|
const isPromptCheck = runs(/\bprompt-check\b/);
|
|
232
240
|
const isReceipt = runs(/\bsubagent-receipt\b/);
|
|
233
241
|
const isToolCheck = runs(/\btool-check\b/);
|
|
242
|
+
const isToolLimit = runs(/\btool-limit\b/);
|
|
234
243
|
|
|
235
244
|
/** @param {string} path */
|
|
236
245
|
export function readSettings(path) {
|
package/src/results.mjs
CHANGED
|
@@ -146,8 +146,12 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
|
|
|
146
146
|
const switches = mine.filter((b) => b.kind === 'switch').length;
|
|
147
147
|
const defaults = mine.filter((b) => b.kind === 'default').length;
|
|
148
148
|
const colds = mine.filter((b) => b.kind === 'cold');
|
|
149
|
+
const coldNotices = mine.filter((b) => b.kind === 'cold-notice').length;
|
|
149
150
|
const budgets = mine.filter((b) => b.kind === 'budget').length;
|
|
150
151
|
const todays = mine.filter((b) => b.kind === 'today').length;
|
|
152
|
+
const duplicates = mine.filter((b) => b.kind === 'duplicate').length;
|
|
153
|
+
const toolLimits = mine.filter((b) => b.kind === 'tool-limit').length;
|
|
154
|
+
const toolCaps = mine.filter((b) => b.kind === 'tool-cap').length;
|
|
151
155
|
return {
|
|
152
156
|
readings,
|
|
153
157
|
hits,
|
|
@@ -160,6 +164,10 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
|
|
|
160
164
|
coldPct: colds.reduce((a, b) => a + b.pct, 0),
|
|
161
165
|
budgets,
|
|
162
166
|
todays,
|
|
167
|
+
coldNotices,
|
|
168
|
+
duplicates,
|
|
169
|
+
toolLimits,
|
|
170
|
+
toolCaps,
|
|
163
171
|
};
|
|
164
172
|
}
|
|
165
173
|
|
|
@@ -295,13 +303,15 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
|
|
|
295
303
|
`${pro ? 'Ran' : 'Pro would have run'} ${st.defaults} subagent${st.defaults === 1 ? '' : 's'} on the model you set for their type (limitcast subagent-model).`,
|
|
296
304
|
);
|
|
297
305
|
if (st.budgets) out.push(`Held ${st.budgets} subagent${st.budgets === 1 ? '' : 's'} once subagents had used their budget of the 5-hour window.`);
|
|
306
|
+
if (st.duplicates)
|
|
307
|
+
out.push(`Held ${st.duplicates} duplicate subagent${st.duplicates === 1 ? '' : 's'} that repeated a prompt already running in that session.`);
|
|
298
308
|
if (st.todays)
|
|
299
309
|
out.push(
|
|
300
310
|
`${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).`,
|
|
301
311
|
);
|
|
302
312
|
|
|
303
313
|
const recent = subagents.filter((e) => e.t >= now - days * 86400_000);
|
|
304
|
-
if (recent.length || st.colds) {
|
|
314
|
+
if (recent.length || st.colds || st.coldNotices) {
|
|
305
315
|
out.push('', '## Subagents and cold caches');
|
|
306
316
|
const priced = recent.filter((e) => e.pct !== undefined).map((e) => /** @type {number} */ (e.pct));
|
|
307
317
|
if (recent.length)
|
|
@@ -316,6 +326,16 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
|
|
|
316
326
|
`${pro ? 'Held' : 'Pro would have held'} ${st.colds} message${st.colds === 1 ? '' : 's'} sent after the prompt cache had expired` +
|
|
317
327
|
(st.coldPct ? `, each re-sending the whole context (≈${pctText(st.coldPct)} of a 5-hour window in all).` : '.'),
|
|
318
328
|
);
|
|
329
|
+
if (st.coldNotices)
|
|
330
|
+
out.push(
|
|
331
|
+
`Noted ${st.coldNotices} message${st.coldNotices === 1 ? '' : 's'} sent after a shorter idle, while the cheap prompt cache may already have expired.`,
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
if (st.toolLimits || st.toolCaps) {
|
|
335
|
+
out.push('', '## Fat tool calls');
|
|
336
|
+
if (st.toolLimits)
|
|
337
|
+
out.push(`Held ${st.toolLimits} call${st.toolLimits === 1 ? '' : 's'} that set no limit on a tool whose recent results were large.`);
|
|
338
|
+
if (st.toolCaps) out.push(`Lowered the limit on ${st.toolCaps} call${st.toolCaps === 1 ? '' : 's'} whose recent results were large.`);
|
|
319
339
|
}
|
|
320
340
|
|
|
321
341
|
out.push('', '## Starting context');
|
package/src/startup.mjs
CHANGED
|
@@ -115,6 +115,34 @@ export function skillPieces(content) {
|
|
|
115
115
|
});
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Pieces whose size changed between two runs of the same job. Char counts are summed per group and name.
|
|
120
|
+
* @param {Piece[]} earlier
|
|
121
|
+
* @param {Piece[]} later
|
|
122
|
+
*/
|
|
123
|
+
export function pieceDiff(earlier, later) {
|
|
124
|
+
const sum = (/** @type {Piece[]} */ list) => {
|
|
125
|
+
/** @type {Map<string, number>} */
|
|
126
|
+
const m = new Map();
|
|
127
|
+
for (const p of list ?? []) {
|
|
128
|
+
const k = `${p.group}|${p.name}`;
|
|
129
|
+
m.set(k, (m.get(k) ?? 0) + p.chars);
|
|
130
|
+
}
|
|
131
|
+
return m;
|
|
132
|
+
};
|
|
133
|
+
const a = sum(earlier);
|
|
134
|
+
const b = sum(later);
|
|
135
|
+
return [...new Set([...a.keys(), ...b.keys()])]
|
|
136
|
+
.map((k) => {
|
|
137
|
+
const split = k.indexOf('|');
|
|
138
|
+
const from = a.get(k) ?? 0;
|
|
139
|
+
const to = b.get(k) ?? 0;
|
|
140
|
+
return { group: k.slice(0, split), name: k.slice(split + 1), from, to, delta: to - from };
|
|
141
|
+
})
|
|
142
|
+
.filter((x) => x.delta !== 0)
|
|
143
|
+
.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta));
|
|
144
|
+
}
|
|
145
|
+
|
|
118
146
|
/** @param {unknown} v */
|
|
119
147
|
const text = (v) => (typeof v === 'string' ? v : v == null ? '' : JSON.stringify(v));
|
|
120
148
|
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { stateDir } from './store.mjs';
|
|
5
|
+
import { toolKey } from './toolcheck.mjs';
|
|
6
|
+
|
|
7
|
+
// PreToolUse: a tool whose recent results are fat, and whose call sets no limit, is denied before it runs.
|
|
8
|
+
// Rewriting a limit that is already present but huge keeps the call and caps it. Bash and WebFetch are left
|
|
9
|
+
// alone: they have no limit argument, so a missing one is every call. Stats come from `report --why` / `--jobs`.
|
|
10
|
+
|
|
11
|
+
export const FAT_AVG = 5_000;
|
|
12
|
+
export const MIN_CALLS = 3;
|
|
13
|
+
const MCP_CAP = 100;
|
|
14
|
+
const READ_CAP = 400;
|
|
15
|
+
const LIMIT_KEYS = new Set(['limit', 'max_results', 'maxresults', 'page_size', 'pagesize', 'top_k', 'topk', 'first']);
|
|
16
|
+
|
|
17
|
+
/** @typedef {{avg:number, calls:number}} ToolStat */
|
|
18
|
+
/** @typedef {{path:string[], value:number}} LimitField */
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {Map<string, {tokens:number, calls:number}>} tools attribution totals, keyed the way reports key them
|
|
22
|
+
*/
|
|
23
|
+
export function toolStats(tools) {
|
|
24
|
+
/** @type {Record<string, ToolStat>} */
|
|
25
|
+
const stats = {};
|
|
26
|
+
for (const [key, e] of tools) {
|
|
27
|
+
if (e.calls > 0) stats[key] = { avg: Math.round(e.tokens / e.calls), calls: e.calls };
|
|
28
|
+
}
|
|
29
|
+
return stats;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const statsFile = () => join(stateDir(), 'tool-stats.json');
|
|
33
|
+
|
|
34
|
+
/** @param {Record<string, ToolStat>} stats */
|
|
35
|
+
export function saveToolStats(stats) {
|
|
36
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
37
|
+
writeFileSync(statsFile(), JSON.stringify(stats));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** @returns {Record<string, ToolStat>} */
|
|
41
|
+
export function loadToolStats() {
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(readFileSync(statsFile(), 'utf8'));
|
|
44
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
45
|
+
} catch {
|
|
46
|
+
return {};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Limit-shaped numbers anywhere in the arguments, a few levels down (MCP tools nest them).
|
|
52
|
+
* @param {unknown} input
|
|
53
|
+
* @returns {LimitField[]}
|
|
54
|
+
*/
|
|
55
|
+
export function findLimits(input) {
|
|
56
|
+
/** @type {LimitField[]} */
|
|
57
|
+
const found = [];
|
|
58
|
+
const walk = (/** @type {any} */ node, /** @type {string[]} */ path, /** @type {number} */ depth) => {
|
|
59
|
+
if (!node || typeof node !== 'object' || depth > 4) return;
|
|
60
|
+
for (const [key, value] of Object.entries(node)) {
|
|
61
|
+
const here = [...path, key];
|
|
62
|
+
if (LIMIT_KEYS.has(key.toLowerCase())) {
|
|
63
|
+
const n = typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : NaN;
|
|
64
|
+
if (Number.isFinite(n)) found.push({ path: here, value: n });
|
|
65
|
+
} else walk(value, here, depth + 1);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
walk(input, [], 0);
|
|
69
|
+
return found;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @param {any} input
|
|
74
|
+
* @param {string[]} path
|
|
75
|
+
* @param {number} value
|
|
76
|
+
*/
|
|
77
|
+
function setAt(input, path, value) {
|
|
78
|
+
const copy = structuredClone(input);
|
|
79
|
+
let node = copy;
|
|
80
|
+
for (let i = 0; i < path.length - 1; i++) node = node[path[i]];
|
|
81
|
+
node[path[path.length - 1]] = value;
|
|
82
|
+
return copy;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const k = (/** @type {number} */ n) => `${Math.max(1, Math.round(n / 1000))}k`;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* What to do with one tool call, or null to leave it alone.
|
|
89
|
+
* Deny reaches the model as the hook reason so it can retry with a limit. A cap rewrites the arguments in place.
|
|
90
|
+
* @param {string} toolName
|
|
91
|
+
* @param {unknown} input
|
|
92
|
+
* @param {Record<string, ToolStat>} stats
|
|
93
|
+
* @returns {{deny:string}|{updatedInput:any, reason:string}|null}
|
|
94
|
+
*/
|
|
95
|
+
export function toolLimitDecision(toolName, input, stats) {
|
|
96
|
+
const key = toolKey(toolName);
|
|
97
|
+
const stat = stats?.[key];
|
|
98
|
+
if (!stat || stat.calls < MIN_CALLS || stat.avg < FAT_AVG) return null;
|
|
99
|
+
const args = typeof input === 'string' ? tryJson(input) : input;
|
|
100
|
+
const obj = args && typeof args === 'object' ? args : {};
|
|
101
|
+
if (toolName === 'Grep' || key === 'Grep') {
|
|
102
|
+
const path = /** @type {any} */ (obj).path ?? /** @type {any} */ (obj).file_path;
|
|
103
|
+
const glob = /** @type {any} */ (obj).glob;
|
|
104
|
+
if ((typeof path === 'string' && path.trim()) || (typeof glob === 'string' && glob.trim())) return null;
|
|
105
|
+
return {
|
|
106
|
+
deny: `limitcast: Grep results average ≈${k(stat.avg)} tokens a call over ${stat.calls} calls. Add a path or a glob, then retry. Set LIMITCAST_ALLOW=1 to run it as written.`,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
if (toolName !== 'Read' && key !== 'Read' && !toolName.startsWith('mcp__') && !key.startsWith('mcp:')) return null;
|
|
110
|
+
const cap = toolName === 'Read' || key === 'Read' ? READ_CAP : MCP_CAP;
|
|
111
|
+
const limits = findLimits(obj);
|
|
112
|
+
if (limits.some((f) => f.value > 0 && f.value <= cap)) return null;
|
|
113
|
+
const big = limits.find((f) => f.value > cap);
|
|
114
|
+
const label = toolName === 'Read' || key === 'Read' ? 'Read' : key.replace(/^mcp:/, '');
|
|
115
|
+
if (big) {
|
|
116
|
+
return {
|
|
117
|
+
updatedInput: setAt(obj, big.path, cap),
|
|
118
|
+
reason: `limitcast: ${label} results average ≈${k(stat.avg)} tokens a call, so this limit was lowered to ${cap}. Set LIMITCAST_ALLOW=1 to keep ${big.value}.`,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
const what =
|
|
122
|
+
toolName === 'Read' || key === 'Read'
|
|
123
|
+
? `Pass offset and limit (${cap} lines or fewer)`
|
|
124
|
+
: `Add a limit of ${cap} or fewer, and ask for fewer fields`;
|
|
125
|
+
return {
|
|
126
|
+
deny: `limitcast: ${label} results average ≈${k(stat.avg)} tokens a call over ${stat.calls} calls. This call sets no limit. ${what}, then retry. Set LIMITCAST_ALLOW=1 to run it as written.`,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** @param {string} text */
|
|
131
|
+
function tryJson(text) {
|
|
132
|
+
try {
|
|
133
|
+
return JSON.parse(text);
|
|
134
|
+
} catch {
|
|
135
|
+
return {};
|
|
136
|
+
}
|
|
137
|
+
}
|
package/src/trim.mjs
CHANGED
|
@@ -140,12 +140,21 @@ export function savings(c, used) {
|
|
|
140
140
|
* @param {ReturnType<typeof contributors>} c
|
|
141
141
|
* @param {Activity} used
|
|
142
142
|
* @param {number} days
|
|
143
|
+
* @param {boolean} [share] totals only, including when no startup transcript is available
|
|
143
144
|
*/
|
|
144
|
-
export function trimReport(base, c, used, days) {
|
|
145
|
+
export function trimReport(base, c, used, days, share = false) {
|
|
145
146
|
const s = savings(c, used);
|
|
146
147
|
const fileTokens = c.files.reduce((a, f) => a + f.tokens, 0);
|
|
147
148
|
const visible = c.skills.filter((k) => !k.hidden);
|
|
148
149
|
const listing = visible.reduce((a, k) => a + k.tokens, 0);
|
|
150
|
+
if (share)
|
|
151
|
+
return [
|
|
152
|
+
base ? `Claude starting context: ${fmt(base.median)} tokens across ${base.sessions} sessions.` : 'Claude starting context: unavailable.',
|
|
153
|
+
`Estimated removable skill listings: ~${fmt(s.skillTokens)} tokens per session.`,
|
|
154
|
+
`Unused in ${days} days: ${s.unusedSkills.length} skills, ${s.unusedMcp.length} MCP servers (server sizes unavailable).`,
|
|
155
|
+
`Instruction files: ${c.files.length}, ~${fmt(fileTokens)} tokens. Visible skill listings: ~${fmt(listing)} tokens.`,
|
|
156
|
+
'Totals only; no configuration names or paths. https://limitcast.dev',
|
|
157
|
+
].join('\n');
|
|
149
158
|
const lines = ['# limitcast trim', ''];
|
|
150
159
|
if (base) {
|
|
151
160
|
lines.push(
|
package/src/where.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline';
|
|
6
6
|
import { fmt } from './report.mjs';
|
|
7
|
+
import { attachmentPieces, pieceDiff } from './startup.mjs';
|
|
7
8
|
import { stateDir } from './store.mjs';
|
|
8
9
|
import { BIG_RESULT, tipFor, toolKey } from './toolcheck.mjs';
|
|
9
10
|
import { jsonlFiles } from './usage.mjs';
|
|
@@ -13,8 +14,8 @@ import { jsonlFiles } from './usage.mjs';
|
|
|
13
14
|
// call i-1: its own output (written to the cache) plus the tool results it asked for plus your messages. So the input
|
|
14
15
|
// of call i, less call i-1's output, is attributed to the tools call i-1 used. Claude Code transcripts only.
|
|
15
16
|
|
|
16
|
-
/** @typedef {{t:number, input:number, cacheWrite:number, cacheRead:number, output:number, tools:string[], side:boolean, entry:string, project:string, model?:string, prompt?:string, agentType?:string}} Call
|
|
17
|
-
* prompt: first words of the session's first message, on its first main-thread call; agentType: a subagent transcript's type, on its first call */
|
|
17
|
+
/** @typedef {{t:number, input:number, cacheWrite:number, cacheRead:number, output:number, tools:string[], side:boolean, entry:string, project:string, model?:string, prompt?:string, agentType?:string, startup?:import('./startup.mjs').Piece[]}} Call
|
|
18
|
+
* prompt: first words of the session's first message, on its first main-thread call; agentType: a subagent transcript's type, on its first call; startup: context loaded before the first response */
|
|
18
19
|
|
|
19
20
|
const COLD_MIN = 100_000; // prompt size from which a missed cache is called a rebuild after idle
|
|
20
21
|
const NO_TOOL = '(your messages)';
|
|
@@ -48,7 +49,18 @@ export async function readCalls(file) {
|
|
|
48
49
|
const calls = new Map();
|
|
49
50
|
/** @type {string|undefined} */
|
|
50
51
|
let prompt;
|
|
52
|
+
/** @type {import('./startup.mjs').Piece[]} */
|
|
53
|
+
const startup = [];
|
|
54
|
+
let startupOpen = true;
|
|
51
55
|
for await (const line of createInterface({ input: createReadStream(file), crlfDelay: Infinity })) {
|
|
56
|
+
if (startupOpen && line.includes('"type":"attachment"')) {
|
|
57
|
+
try {
|
|
58
|
+
const ev = JSON.parse(line);
|
|
59
|
+
if (ev?.type === 'attachment') startup.push(...attachmentPieces(ev.attachment));
|
|
60
|
+
} catch {
|
|
61
|
+
/* a torn line: the call list is what matters */
|
|
62
|
+
}
|
|
63
|
+
}
|
|
52
64
|
if (prompt === undefined && line.includes('"type":"user"')) prompt = firstPrompt(line);
|
|
53
65
|
if (!line.includes('"usage"')) continue;
|
|
54
66
|
let ev;
|
|
@@ -61,6 +73,7 @@ export async function readCalls(file) {
|
|
|
61
73
|
const u = m?.usage;
|
|
62
74
|
const t = Date.parse(ev?.timestamp);
|
|
63
75
|
if (ev?.type !== 'assistant' || !u || !Number.isFinite(t)) continue;
|
|
76
|
+
startupOpen = false;
|
|
64
77
|
const id = `${m.id ?? ''}:${ev.requestId ?? ''}`;
|
|
65
78
|
let c = calls.get(id);
|
|
66
79
|
if (!c || id === ':') {
|
|
@@ -85,6 +98,7 @@ export async function readCalls(file) {
|
|
|
85
98
|
const all = [...calls.values()];
|
|
86
99
|
const first = all.find((c) => !c.side);
|
|
87
100
|
if (first && prompt) first.prompt = prompt;
|
|
101
|
+
if (first && startup.length) first.startup = startup;
|
|
88
102
|
// A subagent's transcript has its type in a file next to it: agent-<id>.jsonl and agent-<id>.meta.json.
|
|
89
103
|
if (all.length && file.includes('/subagents/')) {
|
|
90
104
|
try {
|
|
@@ -117,7 +131,7 @@ export function attribute(sessions, since = 0) {
|
|
|
117
131
|
tools: new Map(),
|
|
118
132
|
/** @type {{tokens:number, tool:string, t:number, project:string}[]} */
|
|
119
133
|
steps: [],
|
|
120
|
-
/** @type {{t:number, tokens:number, size:number, calls:number, prompt:string, project:string, entry:string}[]} headless session starts: when, new tokens, and the whole starting prompt (cached or not) */
|
|
134
|
+
/** @type {{t:number, tokens:number, size:number, calls:number, prompt:string, project:string, entry:string, startup?:import('./startup.mjs').Piece[]}[]} headless session starts: when, new tokens, and the whole starting prompt (cached or not) */
|
|
121
135
|
starts: [],
|
|
122
136
|
/** @type {Map<string, number>} every new token, by model */
|
|
123
137
|
byModel: new Map(),
|
|
@@ -165,6 +179,7 @@ export function attribute(sessions, since = 0) {
|
|
|
165
179
|
prompt: c.prompt ?? '',
|
|
166
180
|
project: c.project,
|
|
167
181
|
entry: c.entry,
|
|
182
|
+
...(c.startup?.length ? { startup: c.startup } : {}),
|
|
168
183
|
});
|
|
169
184
|
}
|
|
170
185
|
return;
|
|
@@ -340,6 +355,40 @@ function coldSection(runs, jobs) {
|
|
|
340
355
|
return lines;
|
|
341
356
|
}
|
|
342
357
|
|
|
358
|
+
const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Which startup piece changed between the earliest and latest recorded run of a job.
|
|
362
|
+
* Only jobs with two startup breakdowns are named. A stable prefix is omitted.
|
|
363
|
+
* @param {[string, {starts:{startup?:import('./startup.mjs').Piece[]}[]} ][]} ranked
|
|
364
|
+
*/
|
|
365
|
+
function driftSection(ranked) {
|
|
366
|
+
/** @type {string[]} */
|
|
367
|
+
const rows = [];
|
|
368
|
+
for (const [name, job] of ranked) {
|
|
369
|
+
const marked = job.starts.filter((s) => s.startup?.length);
|
|
370
|
+
if (marked.length < 2) continue;
|
|
371
|
+
const diff = pieceDiff(
|
|
372
|
+
/** @type {import('./startup.mjs').Piece[]} */ (marked[0].startup),
|
|
373
|
+
/** @type {import('./startup.mjs').Piece[]} */ (marked[marked.length - 1].startup),
|
|
374
|
+
);
|
|
375
|
+
for (const d of diff.slice(0, 5)) {
|
|
376
|
+
rows.push(`| ${name.replace(/\|/g, '/').slice(0, 45)} | ${d.group}: ${d.name} | ${fmt(tok(d.from))} | ${fmt(tok(d.to))} |`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (!rows.length) return [];
|
|
380
|
+
return [
|
|
381
|
+
'',
|
|
382
|
+
'## What changed between runs',
|
|
383
|
+
'',
|
|
384
|
+
'The earliest and latest run of each job that recorded its startup. A piece that changes every run (a hook that prints a date or a count) keeps the prompt cache from being reused, so running the job again sooner does not warm it.',
|
|
385
|
+
'',
|
|
386
|
+
'| job | piece | earlier | later |',
|
|
387
|
+
'|---|---|---:|---:|',
|
|
388
|
+
...rows,
|
|
389
|
+
];
|
|
390
|
+
}
|
|
391
|
+
|
|
343
392
|
/**
|
|
344
393
|
* Markdown: the scheduled (headless) jobs whose runs spent the most new tokens just starting. A run's start is what
|
|
345
394
|
* it loads before reading its prompt: settings, plugins, hooks, MCP servers, skills and instruction files.
|
|
@@ -388,6 +437,7 @@ export function jobsReport(r, { since, now }) {
|
|
|
388
437
|
);
|
|
389
438
|
}
|
|
390
439
|
lines.push(...coldSection(r.starts.length, [...jobs.values()]));
|
|
440
|
+
lines.push(...driftSection(ranked));
|
|
391
441
|
const [leanJob, lean] = [...jobs].sort((a, b) => a[1].size / a[1].runs - b[1].size / b[1].runs)[0];
|
|
392
442
|
lines.push(
|
|
393
443
|
'',
|