limitcast 0.0.0-stage → 0.6.1

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 ADDED
@@ -0,0 +1,95 @@
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
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # limitcast
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stretch your Claude Code plan. Every session starts with ~100k tokens of context before you type, re-sent on every turn and to every subagent. limitcast measures what's in it, names what you never use, and stops runaway subagents before they burn the rest of your window.
4
+
5
+ ```
6
+ $ limitcast trim
7
+ Every Claude Code session starts at 102.7k tokens before your first message.
8
+
9
+ ## Measured savings: ~6.2k tokens per session (6% of your starting context)
10
+ - Disable 9 MCP servers you haven't used in 14 days (~0.9k): postman, context7, ...
11
+ - Hide 66 skills from the model (~5.3k): dataviz, block-kit, ...
12
+ ```
13
+
14
+ - **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.
15
+ - **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.
16
+ - **Burn report (Pro):** Claude Code, Codex and Grok tokens by day, project, model and session.
17
+ - **Runout forecast (free):** burn rate and the clock time each window runs out.
18
+ - **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. The free tier makes no network calls; a Pro license key talks to Polar only to activate, to re-check weekly, and to deactivate (it sends the key and your computer's name).
19
+
20
+ | | Claude Code | Codex | Grok |
21
+ |---|---|---|---|
22
+ | Limit forecast (`status`) | ✓ status-line feed | ✓ session logs | no: Grok keeps no limit readings on disk |
23
+ | Subagent guard | ✓ `Task`/`Agent` | ✓ `spawn_agent` | never blocks (nothing to judge by) |
24
+ | Token report (`report`) | ✓ | ✓ | ✓ per-turn ledger |
25
+ | Trim advisor (`trim`) | ✓ | - | - |
26
+
27
+ Requires Node 20+ on macOS or Linux.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ npm install -g limitcast
33
+ limitcast install # free: status-line recorder
34
+ limitcast activate <key> # Pro
35
+ limitcast install --guard # Pro: also the subagent guard
36
+ limitcast doctor
37
+ ```
38
+
39
+ `install` backs up `~/.claude/settings.json` and wraps your existing status line (it looks exactly the same). With Pro, `--guard` adds the subagent guard. Restart Claude Code to load it. `limitcast uninstall` puts everything back.
40
+
41
+ **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.
42
+
43
+ **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.
44
+
45
+ ## Commands
46
+
47
+ | Command | |
48
+ |---|---|
49
+ | `limitcast status [--json]` | Used, burn rate, runout time and reset for each window |
50
+ | `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
51
+ | `limitcast doctor` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads |
52
+ | `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
53
+ | `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 |
54
+ | `limitcast saved` | **Pro.** How much the part of your starting context you control has dropped since limitcast first measured it, times your sessions since |
55
+ | `install --alerts` | **Pro.** A SessionStart hook that tells you (never the model) when your starting context grew ~1k+ tokens, and what grew |
56
+ | `limitcast activate <key>` | Unlock Pro: registers this computer with Polar (3 computers per key). Polar re-checks it weekly in the background; it keeps working up to 30 days offline |
57
+ | `limitcast deactivate` | Free this computer so the key can be used on another one |
58
+ | `limitcast license` | Show the license and re-check it with Polar now |
59
+
60
+ ### Subagent guard (Pro)
61
+
62
+ Without a valid license the guard allows everything, so an expired license never blocks your work. Blocks a new subagent only when the spawning tool's window is on pace to run out before it resets, within 30 minutes (`LIMITCAST_GUARD_MINUTES`). A window already at 100% is left to Claude Code, so extra usage keeps working. `LIMITCAST_ALLOW=1` overrides. If the guard itself fails, it allows the call.
63
+
64
+ ## How the forecast works
65
+
66
+ Each limit reading is saved to `~/.local/state/limitcast/samples.jsonl` when it changes (kept 8 days). The burn rate is the least-squares slope of percent used over the last hour of the current window, and the runout time is where that line reaches 100%. **AT_RISK** means that happens before the reset. Each Claude session is forecast from its own readings, so two accounts used in parallel never mix.
67
+
68
+ ## Pricing
69
+
70
+ Free: runout forecast, status-line readout, and your starting-context total with how much you never use. Pro ($79/year, or $149 lifetime for the first 100 buyers): names what to cut, subagent guard, burn report, starting-context alerts. 14-day refund: email support@limitcast.dev. See https://limitcast.dev.
71
+
72
+ ## License
73
+
74
+ [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.
@@ -0,0 +1,256 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ import { spawn, spawnSync } from 'node:child_process';
4
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { forecastAll, oneClaudeSession } from '../src/forecast.mjs';
8
+ import { formatChecks } from '../src/formats.mjs';
9
+ import { runGuard } from '../src/guard.mjs';
10
+ import { doctor, install, uninstall } from '../src/install.mjs';
11
+ import { activate, currentLicense, isPro, UPGRADE_URL } from '../src/license.mjs';
12
+ import { driftMessage, loadOverhead, recordOverhead, savedSummary, snapshot } from '../src/overhead.mjs';
13
+ import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
14
+ import { burnReport } from '../src/report.mjs';
15
+ import { claudeSamples, readCodex } from '../src/sources.mjs';
16
+ import { countInteractiveSince, latestInteractiveTranscript } from '../src/startup.mjs';
17
+ import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
18
+ import { baseline, contributors, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
19
+ import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
20
+
21
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
22
+ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
23
+
24
+ limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex); backs up settings
25
+ limitcast uninstall remove it and restore your original status line
26
+ limitcast doctor check the setup
27
+ limitcast status [--json] used, burn rate, runout time and reset per limit window
28
+ limitcast trim [--share] tokens every session loads before you type, and how much you never use
29
+ limitcast license show the license and re-check it with Polar
30
+
31
+ Pro (${UPGRADE_URL})
32
+ limitcast trim [--days N] [--share] names what to cut and what each costs
33
+ (--share: totals only, no names, safe to post)
34
+ limitcast saved tokens saved since limitcast first measured you
35
+ limitcast install --guard block new subagents when a window is on pace to run out
36
+ limitcast install --alerts tell you when your starting context grows
37
+ limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
38
+ limitcast activate <license-key> unlock Pro on this computer (online once; then a weekly check, offline up to 30 days)
39
+ limitcast deactivate free this computer's activation to use the key elsewhere
40
+
41
+ Used by Claude Code and Codex (set up by install)
42
+ limitcast statusline [-- <cmd...>] record limit readings, then run your status-line command
43
+ limitcast guard PreToolUse hook (Pro)
44
+ limitcast drift [--hook] SessionStart hook: compare starting context with the last session (Pro)
45
+ `;
46
+
47
+ const [cmd, ...args] = process.argv.slice(2);
48
+ const now = Date.now();
49
+ const flag = (/** @type {string} */ name) => {
50
+ const i = args.indexOf(name);
51
+ return i >= 0 ? args[i + 1] : undefined;
52
+ };
53
+ const days = () => Math.max(1, Number(flag('--days') ?? 7));
54
+
55
+ // Interactive commands re-check a Polar license weekly; hooks (statusline, guard, drift --hook) never touch the network.
56
+ if (['report', 'trim', 'saved', 'drift', 'doctor', 'license'].includes(cmd) && !args.includes('--hook')) {
57
+ await refreshPolar({ force: cmd === 'license' }).catch(() => null);
58
+ }
59
+
60
+ if (cmd === 'status') {
61
+ const rows = forecastAll(oneClaudeSession([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
62
+ if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
63
+ else {
64
+ console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, or run Codex once.');
65
+ if (existsSync(grokRoot())) console.log('grok: no limit readings (Grok keeps none on disk); its token use is in `limitcast report`');
66
+ }
67
+ } else if (cmd === 'statusline') {
68
+ const input = readStdin();
69
+ let sid;
70
+ try {
71
+ const feed = JSON.parse(input);
72
+ sid = feed?.session_id;
73
+ record(claudeSamples(feed, now));
74
+ saveFeedShape(feed);
75
+ // Hook-only Pro users never run an interactive command, so the weekly Polar check starts here, detached.
76
+ if (refreshDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'license'], { detached: true, stdio: 'ignore' }).unref();
77
+ } catch {
78
+ /* never break the status line */
79
+ }
80
+ const sep = args.indexOf('--');
81
+ const wrapped = sep >= 0 ? args.slice(sep + 1) : [];
82
+ if (wrapped.length) {
83
+ const r = spawnSync(wrapped[0], wrapped.slice(1), { input, stdio: ['pipe', 'inherit', 'inherit'] });
84
+ process.exit(r.status ?? 1);
85
+ }
86
+ console.log(oneLine(forecastAll(oneClaudeSession(load(now - KEEP_MS), sid), now)));
87
+ } else if (cmd === 'guard') {
88
+ // The guard is Pro; without a valid license it allows everything (an expired license must never block work).
89
+ if (process.env.LIMITCAST_ALLOW === '1' || !isPro()) process.exit(0);
90
+ try {
91
+ const reason = await runGuard(JSON.parse(readStdin()), now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30));
92
+ if (reason) {
93
+ console.log(
94
+ JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } }),
95
+ );
96
+ }
97
+ } catch (e) {
98
+ // Fail open: a broken governor must not stop the agent.
99
+ console.error(`limitcast guard skipped: ${e instanceof Error ? e.message : e}`);
100
+ }
101
+ } else if (cmd === 'install') {
102
+ const wantGuard = args.includes('--guard');
103
+ const wantAlerts = args.includes('--alerts');
104
+ if ((wantGuard || wantAlerts) && !isPro()) {
105
+ console.log(`The subagent guard and alerts are part of limitcast Pro (${UPGRADE_URL}). Installing the free features.`);
106
+ }
107
+ for (const c of install({ guard: wantGuard && isPro(), alerts: wantAlerts && isPro() })) console.log(`✓ ${c}`);
108
+ console.log('Restart Claude Code and Codex to load it. Then: limitcast doctor');
109
+ } else if (cmd === 'uninstall') {
110
+ const changes = uninstall();
111
+ console.log(changes.length ? changes.map((c) => `✓ ${c}`).join('\n') : 'Nothing to remove.');
112
+ } else if (cmd === 'doctor') {
113
+ // Readings are only stored when they change, so freshness comes from the last feed the status line saw.
114
+ let latest = 0;
115
+ try {
116
+ latest = JSON.parse(readFileSync(join(stateDir(), 'last-feed.json'), 'utf8')).at ?? 0;
117
+ } catch {
118
+ /* never fed */
119
+ }
120
+ const checks = [...doctor({ samplesAgeMs: latest ? now - latest : null, license: currentLicense() }), ...(await formatChecks())];
121
+ for (const c of checks) console.log(`${c.ok ? '✓' : '✗'} ${c.line}`);
122
+ process.exit(checks.every((c) => c.ok) ? 0 : 1);
123
+ } else if (cmd === 'report' || cmd === 'trim') {
124
+ const pro = isPro();
125
+ if (!pro && cmd === 'report') {
126
+ console.log(`\`limitcast ${cmd}\` is part of limitcast Pro: ${UPGRADE_URL}\nAlready bought it? limitcast activate <license-key>`);
127
+ process.exit(2);
128
+ }
129
+ const since = now - days() * 86400_000;
130
+ /** @type {import('../src/trim.mjs').Activity} */
131
+ const used = { skills: new Set(), mcp: new Set() };
132
+ const usage = await readUsage(since, {}, cmd === 'trim' ? used : undefined);
133
+ let text;
134
+ if (cmd === 'report') text = burnReport(usage, { since, now });
135
+ else {
136
+ // Prefer the measured starting context of the latest interactive session; older Claude Code logs fall back to estimates.
137
+ const latest = await latestInteractiveTranscript(claudeRoot());
138
+ if (latest) recordOverhead(snapshot(latest));
139
+ // Free: the measured totals without names (the --share view); Pro names what to cut.
140
+ if (!pro && !latest) {
141
+ console.log(`\`limitcast trim\` needs one Claude Code session first. Naming what to cut is Pro: ${UPGRADE_URL}`);
142
+ process.exit(2);
143
+ }
144
+ if (latest && (args.includes('--share') || !pro)) text = shareSummary(baseline(usage), latest, used, days());
145
+ else text = latest ? startupReport(baseline(usage), latest, used, days()) : trimReport(baseline(usage), contributors(), used, days());
146
+ if (!pro)
147
+ text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\nAlready bought it? limitcast activate <license-key>`;
148
+ }
149
+ const out = flag('--out');
150
+ if (out) {
151
+ writeFileSync(out, `${text}\n`);
152
+ console.log(`Wrote ${out}`);
153
+ } else console.log(text);
154
+ } else if (cmd === 'drift') {
155
+ // SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
156
+ const hook = args.includes('--hook');
157
+ if (!isPro()) {
158
+ if (!hook) console.log(`\`limitcast drift\` is part of limitcast Pro: ${UPGRADE_URL}`);
159
+ process.exit(hook ? 0 : 2);
160
+ }
161
+ try {
162
+ const latest = await latestInteractiveTranscript(claudeRoot());
163
+ const d = latest ? recordOverhead(snapshot(latest)) : null;
164
+ if (hook) {
165
+ if (d?.alert) console.log(JSON.stringify({ systemMessage: driftMessage(d) }));
166
+ } else if (!latest) console.log('No interactive Claude Code session found yet.');
167
+ else if (!d) console.log('Starting context recorded. limitcast will tell you when it grows.');
168
+ else console.log(d.alert ? driftMessage(d) : 'No meaningful change in your starting context since the last session.');
169
+ } catch (e) {
170
+ if (!hook) throw e; // a hook must never break session start
171
+ }
172
+ } else if (cmd === 'saved') {
173
+ if (!isPro()) {
174
+ console.log(`\`limitcast saved\` is part of limitcast Pro: ${UPGRADE_URL}`);
175
+ process.exit(2);
176
+ }
177
+ const latest = await latestInteractiveTranscript(claudeRoot());
178
+ if (latest) recordOverhead(snapshot(latest));
179
+ const s = loadOverhead();
180
+ console.log(s ? savedSummary(s, await countInteractiveSince(claudeRoot(), s.first.at)) : 'Nothing measured yet. Run `limitcast trim` first.');
181
+ } else if (cmd === 'activate') {
182
+ // Signed offline keys start with LC1.; anything else is a Polar license key.
183
+ const key = args[0] ?? '';
184
+ const res = key.startsWith('LC1.') ? activate(key) : await activatePolar(key);
185
+ console.log(res.ok ? `✓ limitcast Pro activated${res.claims.e ? ` for ${res.claims.e}` : ''}` : `✗ ${res.reason}`);
186
+ process.exit(res.ok ? 0 : 1);
187
+ } else if (cmd === 'deactivate') {
188
+ const res = await deactivatePolar();
189
+ console.log(res.ok ? '✓ This machine is deactivated; the key can be used on another computer.' : `✗ ${res.reason}`);
190
+ process.exit(res.ok ? 0 : 1);
191
+ } else if (cmd === 'license') {
192
+ const l = currentLicense();
193
+ console.log(l === null ? `Free tier. Pro: ${UPGRADE_URL}` : l.ok ? `Pro: ${l.claims.e}` : `License problem: ${l.reason}`);
194
+ } else if (cmd === '--version' || cmd === '-v') {
195
+ console.log(VERSION);
196
+ } else {
197
+ console.log(HELP);
198
+ process.exit(cmd && !['help', '--help', '-h'].includes(cmd) ? 1 : 0);
199
+ }
200
+
201
+ /**
202
+ * Keep the latest feed's structure (key names and rate_limits only, no prompt or path content) for diagnosing parsing.
203
+ * @param {any} feed
204
+ */
205
+ function saveFeedShape(feed) {
206
+ const shape = { at: now, keys: Object.keys(feed ?? {}), session_id: feed?.session_id, rate_limits: feed?.rate_limits };
207
+ writeFileSync(join(stateDir(), 'last-feed.json'), JSON.stringify(shape, null, 2));
208
+ }
209
+
210
+ function readStdin() {
211
+ try {
212
+ return readFileSync(0, 'utf8');
213
+ } catch {
214
+ return '';
215
+ }
216
+ }
217
+
218
+ /** @param {number|null} ms */
219
+ function clock(ms) {
220
+ if (ms === null) return '-';
221
+ const d = new Date(ms);
222
+ const hm = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
223
+ return d.toDateString() === new Date(now).toDateString() ? hm : `${d.toLocaleDateString([], { weekday: 'short' })} ${hm}`;
224
+ }
225
+
226
+ /** @param {ReturnType<typeof forecastAll>} rows */
227
+ function table(rows) {
228
+ const lines = rows.map((f) => [
229
+ `${f.src} ${f.win}`,
230
+ `${Math.round(f.pct)}%`,
231
+ f.rate === null ? '-' : `${f.rate >= 0 ? '+' : ''}${f.rate.toFixed(1)}%/h`,
232
+ f.verdict === 'AT_RISK' ? clock(f.wall) : '-',
233
+ clock(f.reset),
234
+ f.verdict,
235
+ ]);
236
+ const head = ['window', 'used', 'burn', 'runs out', 'resets', 'status'];
237
+ const w = head.map((h, i) => Math.max(h.length, ...lines.map((l) => l[i].length)));
238
+ return [head, ...lines]
239
+ .map((l) =>
240
+ l
241
+ .map((c, i) => c.padEnd(w[i]))
242
+ .join(' ')
243
+ .trimEnd(),
244
+ )
245
+ .join('\n');
246
+ }
247
+
248
+ /** @param {ReturnType<typeof forecastAll>} rows */
249
+ function oneLine(rows) {
250
+ return (
251
+ rows
252
+ .filter((f) => f.src === 'claude')
253
+ .map((f) => `${f.win} ${Math.round(f.pct)}%${f.verdict === 'AT_RISK' ? ` ⚠ out ${clock(f.wall)}` : f.verdict === 'HIT' ? ' ⛔' : ''}`)
254
+ .join(' · ') || 'limitcast: waiting for data'
255
+ );
256
+ }
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.1",
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
+ "type": "module",
6
+ "bin": { "limitcast": "bin/limitcast.mjs" },
7
+ "files": ["bin", "src"],
8
+ "engines": { "node": ">=20" },
9
+ "os": ["darwin", "linux"],
10
+ "scripts": { "test": "node --test" },
11
+ "keywords": ["claude-code", "codex", "rate-limit", "usage-limit", "tokens", "hooks", "status-line", "ai-agents"],
12
+ "homepage": "https://limitcast.dev",
13
+ "repository": { "type": "git", "url": "git+https://github.com/Taste4458/limitcast.git" },
14
+ "author": "Sam Stull",
15
+ "license": "Elastic-2.0"
16
+ }
@@ -0,0 +1,89 @@
1
+ // @ts-check
2
+
3
+ /** @typedef {{t:number, src:string, win:string, pct:number, reset:number, sid?:string}} Sample t: epoch ms, reset: epoch s, sid: Claude session */
4
+
5
+ const RESET_JITTER_S = 120; // Codex resets_at drifts by seconds between events
6
+ const RECENT_MS = 60 * 60 * 1000;
7
+
8
+ /**
9
+ * Burn rate and limit forecast for one (src, win) series.
10
+ * @param {Sample[]} samples
11
+ * @param {number} now epoch ms
12
+ */
13
+ export function forecast(samples, now) {
14
+ if (!samples.length) return null;
15
+ const sorted = [...samples].sort((a, b) => a.t - b.t);
16
+ const last = sorted[sorted.length - 1];
17
+ const resetMs = last.reset * 1000;
18
+ const base = { src: last.src, win: last.win, pct: last.pct, reset: resetMs, rate: null, wall: null };
19
+ if (resetMs <= now) return { ...base, pct: 0, verdict: 'RESET' };
20
+ if (last.pct >= 100) return { ...base, verdict: 'HIT' };
21
+
22
+ const window = sorted.filter((s) => Math.abs(s.reset - last.reset) <= RESET_JITTER_S);
23
+ const recent = window.filter((s) => s.t >= now - RECENT_MS);
24
+ const pts = recent.length >= 2 ? recent : window;
25
+ const rate = slopePerHour(pts);
26
+ if (rate === null || rate <= 0) return { ...base, rate, verdict: 'OK' };
27
+
28
+ const wall = last.t + ((100 - last.pct) / rate) * 3600_000;
29
+ return { ...base, rate, wall, verdict: wall < resetMs ? 'AT_RISK' : 'OK' };
30
+ }
31
+
32
+ /**
33
+ * Least-squares slope of pct over time, in % per hour.
34
+ * Needs 2+ distinct timestamps spanning at least 5 minutes, or the coarse integer percents are noise.
35
+ * @param {Sample[]} pts
36
+ */
37
+ export function slopePerHour(pts) {
38
+ if (pts.length < 2) return null;
39
+ const t0 = pts[0].t;
40
+ const xs = pts.map((p) => (p.t - t0) / 3600_000);
41
+ if (xs[xs.length - 1] - xs[0] < 5 / 60) return null;
42
+ const n = xs.length;
43
+ const mx = xs.reduce((a, b) => a + b, 0) / n;
44
+ const my = pts.reduce((a, p) => a + p.pct, 0) / n;
45
+ let num = 0,
46
+ den = 0;
47
+ for (let i = 0; i < n; i++) {
48
+ num += (xs[i] - mx) * (pts[i].pct - my);
49
+ den += (xs[i] - mx) ** 2;
50
+ }
51
+ return den === 0 ? null : num / den;
52
+ }
53
+
54
+ /**
55
+ * Group samples by src+win and forecast each.
56
+ * @param {Sample[]} samples
57
+ * @param {number} now
58
+ */
59
+ export function forecastAll(samples, now) {
60
+ /** @type {Map<string, Sample[]>} */
61
+ const groups = new Map();
62
+ for (const s of samples) {
63
+ const k = `${s.src}:${s.win}`;
64
+ if (!groups.has(k)) groups.set(k, []);
65
+ groups.get(k)?.push(s);
66
+ }
67
+ return [...groups.values()].map((g) => forecast(g, now)).filter((f) => f !== null);
68
+ }
69
+
70
+ /**
71
+ * Claude sessions can belong to different accounts with different limits, and the feed has no account id.
72
+ * Keep Claude samples from one session: `sid` if it has any, else the most recently active one. Codex is untouched.
73
+ * Untagged Claude samples (recorded before 0.2) can't be attributed to an account, so they're dropped once tagged ones exist.
74
+ * @param {Sample[]} samples
75
+ * @param {string} [sid]
76
+ */
77
+ export function oneClaudeSession(samples, sid) {
78
+ const claude = samples.filter((s) => s.src === 'claude' && s.sid);
79
+ if (!claude.length) return samples;
80
+ const pick = sid && claude.some((s) => s.sid === sid) ? sid : claude.reduce((a, b) => (b.t > a.t ? b : a)).sid;
81
+ return samples.filter((s) => s.src !== 'claude' || s.sid === pick);
82
+ }
83
+
84
+ /** @param {number} minutes */
85
+ export function windowName(minutes) {
86
+ if (minutes === 300) return '5h';
87
+ if (minutes === 10080) return '7d';
88
+ return minutes % 1440 === 0 ? `${minutes / 1440}d` : minutes % 60 === 0 ? `${minutes / 60}h` : `${minutes}m`;
89
+ }
@@ -0,0 +1,115 @@
1
+ // @ts-check
2
+ import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { stateDir } from './store.mjs';
6
+ import { claudeRoot, codexRoot, grokRoot } from './usage.mjs';
7
+
8
+ /**
9
+ * limitcast reads Claude Code's, Codex's and Grok's own log formats, which can change in any release.
10
+ * These checks look at your latest real logs and say plainly when the fields limitcast needs are gone.
11
+ * @returns {Promise<{ok:boolean, line:string}[]>}
12
+ */
13
+ export async function formatChecks() {
14
+ /** @type {{ok:boolean, line:string}[]} */
15
+ const out = [];
16
+
17
+ const feedPath = join(stateDir(), 'last-feed.json');
18
+ if (existsSync(feedPath)) {
19
+ let rl = null;
20
+ try {
21
+ rl = JSON.parse(readFileSync(feedPath, 'utf8')).rate_limits;
22
+ } catch {
23
+ /* unreadable: reported below */
24
+ }
25
+ out.push(
26
+ Number.isFinite(rl?.five_hour?.used_percentage ?? rl?.seven_day?.used_percentage)
27
+ ? { ok: true, line: 'Claude Code status-line feed: limit readings present' }
28
+ : { ok: false, line: 'Claude Code status-line feed has no rate_limits: the format may have changed, update limitcast' },
29
+ );
30
+ }
31
+
32
+ const claude = newest(claudeRoot(), (n) => n.endsWith('.jsonl'));
33
+ if (claude) {
34
+ const found = await findLine(claude, '"usage"', (ev) => ev?.type === 'assistant' && Number.isFinite(ev?.message?.usage?.output_tokens));
35
+ out.push(
36
+ found
37
+ ? { ok: true, line: 'Claude Code transcripts: usage records readable' }
38
+ : { ok: false, line: `Claude Code transcript has no readable usage records (${claude}): the format may have changed, update limitcast` },
39
+ );
40
+ }
41
+
42
+ const codex = newest(codexRoot(), (n) => n.startsWith('rollout-') && n.endsWith('.jsonl'));
43
+ if (codex) {
44
+ const found = await findLine(codex, '"rate_limits"', (ev) => Number.isFinite(ev?.payload?.rate_limits?.primary?.used_percent));
45
+ out.push(
46
+ found
47
+ ? { ok: true, line: 'Codex session logs: limit readings readable' }
48
+ : { ok: true, line: 'Codex: latest session has no limit readings yet (normal for a very short session)' },
49
+ );
50
+ }
51
+
52
+ const grok = newest(grokRoot(), (n) => n === 'usage.json');
53
+ if (grok) {
54
+ let ok = false;
55
+ try {
56
+ const turns = JSON.parse(readFileSync(grok, 'utf8')).turns;
57
+ ok = Array.isArray(turns) && (turns.length === 0 || (Number.isFinite(turns[0].inputTokens) && !!turns[0].endedAt));
58
+ } catch {
59
+ ok = false;
60
+ }
61
+ out.push(
62
+ ok
63
+ ? { ok: true, line: 'Grok usage ledger: readable' }
64
+ : { ok: false, line: `Grok usage ledger is not in the expected format (${grok}): update limitcast` },
65
+ );
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /**
71
+ * Most recently modified file under `dir` (recursive) whose name passes `keep`.
72
+ * @param {string} dir
73
+ * @param {(name:string)=>boolean} keep
74
+ * @returns {string|null}
75
+ */
76
+ export function newest(dir, keep) {
77
+ if (!existsSync(dir)) return null;
78
+ let best = null;
79
+ let bestM = -1;
80
+ /** @param {string} d */
81
+ const walk = (d) => {
82
+ for (const e of readdirSync(d, { withFileTypes: true })) {
83
+ const p = join(d, e.name);
84
+ if (e.isDirectory()) walk(p);
85
+ else if (keep(e.name)) {
86
+ const m = statSync(p).mtimeMs;
87
+ if (m > bestM) [best, bestM] = [p, m];
88
+ }
89
+ }
90
+ };
91
+ walk(dir);
92
+ return best;
93
+ }
94
+
95
+ /**
96
+ * Does any line containing `needle` parse to something `test` accepts?
97
+ * @param {string} file
98
+ * @param {string} needle
99
+ * @param {(ev:any)=>boolean} test
100
+ */
101
+ async function findLine(file, needle, test) {
102
+ const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
103
+ for await (const line of rl) {
104
+ if (!line.includes(needle)) continue;
105
+ try {
106
+ if (test(JSON.parse(line))) {
107
+ rl.close();
108
+ return true;
109
+ }
110
+ } catch {
111
+ /* torn line */
112
+ }
113
+ }
114
+ return false;
115
+ }