limitcast 0.6.2 → 0.8.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 +11 -8
- package/bin/limitcast.mjs +168 -16
- package/package.json +2 -2
- package/src/apply.mjs +249 -0
- package/src/forecast.mjs +63 -9
- package/src/guard.mjs +45 -16
- package/src/overhead.mjs +7 -1
- package/src/results.mjs +250 -0
- package/src/value.mjs +189 -0
package/README.md
CHANGED
|
@@ -11,8 +11,9 @@ Every Claude Code session starts at 102.7k tokens before your first message.
|
|
|
11
11
|
- Hide 66 skills from the model (~5.3k): dataviz, block-kit, ...
|
|
12
12
|
```
|
|
13
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.
|
|
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, and `trim --apply` makes the cuts for you (reversible).
|
|
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. Free installs get a preview that never blocks and shows what it would have stopped.
|
|
16
|
+
- **Results:** `limitcast results` shows the value since you installed it (tokens not re-sent, limits it warned you about and how far ahead, subagents stopped), then checks the last week against what actually happened.
|
|
16
17
|
- **Burn report (Pro):** Claude Code, Codex and Grok tokens by day, project, model and session.
|
|
17
18
|
- **Runout forecast (free):** burn rate and the clock time each window runs out.
|
|
18
19
|
- **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).
|
|
@@ -32,11 +33,11 @@ Requires Node 20+ on macOS or Linux.
|
|
|
32
33
|
npm install -g limitcast
|
|
33
34
|
limitcast install # free: status-line recorder
|
|
34
35
|
limitcast activate <key> # Pro
|
|
35
|
-
limitcast install --guard #
|
|
36
|
+
limitcast install --guard # also the subagent guard (free: preview only)
|
|
36
37
|
limitcast doctor
|
|
37
38
|
```
|
|
38
39
|
|
|
39
|
-
`install` backs up `~/.claude/settings.json` and wraps your existing status line (it looks exactly the same).
|
|
40
|
+
`install` backs up `~/.claude/settings.json` and wraps your existing status line (it looks exactly the same). `--guard` adds the subagent guard (without Pro it only records what it would block). Restart Claude Code to load it. `limitcast uninstall` puts everything back.
|
|
40
41
|
|
|
41
42
|
**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
|
|
|
@@ -52,22 +53,24 @@ limitcast doctor
|
|
|
52
53
|
| `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
|
|
53
54
|
| `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
55
|
| `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
|
-
| `
|
|
56
|
+
| `limitcast trim --apply` / `--undo` | **Pro.** Hide the unused skills from the model and turn off the unused MCP servers for that project, through Claude Code's own settings. Backed up; `--undo` reverses exactly what it changed |
|
|
57
|
+
| `limitcast results [--days N] [--share]` | Proof it works: each limit window that reached 100% and how far ahead limitcast warned, and what the guard blocked (free: what it would have blocked) and whether that window then ran out. **Pro** adds starting-context savings. `--share`: totals only |
|
|
58
|
+
| `install --alerts` | **Pro.** A SessionStart hook that tells you (never the model) when your starting context grew ~1k+ tokens, and what grew, plus a one-line weekly summary of what limitcast did |
|
|
56
59
|
| `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
60
|
| `limitcast deactivate` | Free this computer so the key can be used on another one |
|
|
58
61
|
| `limitcast license` | Show the license and re-check it with Polar now |
|
|
59
62
|
|
|
60
63
|
### Subagent guard (Pro)
|
|
61
64
|
|
|
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.
|
|
65
|
+
Without a valid license the guard runs as a preview: it allows everything and records what it would have blocked (`limitcast results` shows it), 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
66
|
|
|
64
67
|
## How the forecast works
|
|
65
68
|
|
|
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
|
|
69
|
+
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; **NEAR** means 95% or more is used. Claude sessions of the same account share one history (matched by window reset times, and usage that only rises), so two accounts used in parallel never mix.
|
|
67
70
|
|
|
68
71
|
## Pricing
|
|
69
72
|
|
|
70
|
-
Free: runout forecast, status-line readout,
|
|
73
|
+
Free: runout forecast with NEAR warnings, status-line readout, your starting-context total with how much you never use, `results`, and a guard preview. Pro ($79/year, or $149 lifetime): names what to cut and cuts it (`trim --apply`), subagent guard that blocks, burn report, starting-context alerts and a weekly summary. 14-day refund: email support@limitcast.dev. See https://limitcast.dev.
|
|
71
74
|
|
|
72
75
|
## License
|
|
73
76
|
|
package/bin/limitcast.mjs
CHANGED
|
@@ -4,36 +4,53 @@ import { spawn, spawnSync } from 'node:child_process';
|
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
applyTrim,
|
|
9
|
+
claudeJsonPath,
|
|
10
|
+
installedPlugins,
|
|
11
|
+
localSkillFolders,
|
|
12
|
+
planTrim,
|
|
13
|
+
projectMcpServers,
|
|
14
|
+
stillLoading,
|
|
15
|
+
transcriptCwd,
|
|
16
|
+
undoTrim,
|
|
17
|
+
} from '../src/apply.mjs';
|
|
18
|
+
import { forecastAll, oneClaudeAccount } from '../src/forecast.mjs';
|
|
8
19
|
import { formatChecks } from '../src/formats.mjs';
|
|
9
20
|
import { runGuard } from '../src/guard.mjs';
|
|
10
|
-
import { doctor, install, uninstall } from '../src/install.mjs';
|
|
21
|
+
import { doctor, install, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
11
22
|
import { activate, currentLicense, isPro, UPGRADE_URL } from '../src/license.mjs';
|
|
12
|
-
import { driftMessage, loadOverhead, recordOverhead, savedSummary, snapshot } from '../src/overhead.mjs';
|
|
23
|
+
import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
|
|
13
24
|
import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
|
|
14
25
|
import { burnReport } from '../src/report.mjs';
|
|
26
|
+
import { loadBlocks, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
|
|
15
27
|
import { claudeSamples, readCodex } from '../src/sources.mjs';
|
|
16
28
|
import { countInteractiveSince, latestInteractiveTranscript } from '../src/startup.mjs';
|
|
17
29
|
import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
|
|
18
|
-
import { baseline, contributors, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
30
|
+
import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
19
31
|
import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
|
|
32
|
+
import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valueSection, valueTotals } from '../src/value.mjs';
|
|
20
33
|
|
|
21
34
|
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
22
35
|
const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
|
|
23
36
|
|
|
24
37
|
limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex); backs up settings
|
|
38
|
+
(without Pro the guard is a preview: it records what it would block, never blocks)
|
|
25
39
|
limitcast uninstall remove it and restore your original status line
|
|
26
40
|
limitcast doctor check the setup
|
|
27
41
|
limitcast status [--json] used, burn rate, runout time and reset per limit window
|
|
28
42
|
limitcast trim [--share] tokens every session loads before you type, and how much you never use
|
|
43
|
+
limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
|
|
44
|
+
[--share] totals only, safe to post
|
|
29
45
|
limitcast license show the license and re-check it with Polar
|
|
30
46
|
|
|
31
47
|
Pro (${UPGRADE_URL})
|
|
32
48
|
limitcast trim [--days N] [--share] names what to cut and what each costs
|
|
33
49
|
(--share: totals only, no names, safe to post)
|
|
50
|
+
limitcast trim --apply / --undo hide those skills and turn off those MCP servers (backed up, reversible)
|
|
34
51
|
limitcast saved tokens saved since limitcast first measured you
|
|
35
52
|
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
|
|
53
|
+
limitcast install --alerts tell you when your starting context grows, plus a weekly summary
|
|
37
54
|
limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
|
|
38
55
|
limitcast activate <license-key> unlock Pro on this computer (online once; then a weekly check, offline up to 30 days)
|
|
39
56
|
limitcast deactivate free this computer's activation to use the key elsewhere
|
|
@@ -53,12 +70,12 @@ const flag = (/** @type {string} */ name) => {
|
|
|
53
70
|
const days = () => Math.max(1, Number(flag('--days') ?? 7));
|
|
54
71
|
|
|
55
72
|
// 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')) {
|
|
73
|
+
if (['report', 'trim', 'saved', 'results', 'drift', 'doctor', 'license'].includes(cmd) && !args.includes('--hook')) {
|
|
57
74
|
await refreshPolar({ force: cmd === 'license' }).catch(() => null);
|
|
58
75
|
}
|
|
59
76
|
|
|
60
77
|
if (cmd === 'status') {
|
|
61
|
-
const rows = forecastAll(
|
|
78
|
+
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
|
|
62
79
|
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
|
|
63
80
|
else {
|
|
64
81
|
console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, or run Codex once.');
|
|
@@ -74,6 +91,8 @@ if (cmd === 'status') {
|
|
|
74
91
|
saveFeedShape(feed);
|
|
75
92
|
// Hook-only Pro users never run an interactive command, so the weekly Polar check starts here, detached.
|
|
76
93
|
if (refreshDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'license'], { detached: true, stdio: 'ignore' }).unref();
|
|
94
|
+
// Readings are kept 8 days; the daily rollup folds what they showed into the long-term value record.
|
|
95
|
+
if (dailyDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'rollup'], { detached: true, stdio: 'ignore' }).unref();
|
|
77
96
|
} catch {
|
|
78
97
|
/* never break the status line */
|
|
79
98
|
}
|
|
@@ -83,12 +102,12 @@ if (cmd === 'status') {
|
|
|
83
102
|
const r = spawnSync(wrapped[0], wrapped.slice(1), { input, stdio: ['pipe', 'inherit', 'inherit'] });
|
|
84
103
|
process.exit(r.status ?? 1);
|
|
85
104
|
}
|
|
86
|
-
console.log(oneLine(forecastAll(
|
|
105
|
+
console.log(oneLine(forecastAll(oneClaudeAccount(load(now - KEEP_MS), sid), now)));
|
|
87
106
|
} else if (cmd === 'guard') {
|
|
88
|
-
//
|
|
89
|
-
if (process.env.LIMITCAST_ALLOW === '1'
|
|
107
|
+
// Blocking is Pro; without a valid license the guard only previews (logs what Pro would block) and allows everything.
|
|
108
|
+
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
90
109
|
try {
|
|
91
|
-
const reason = await runGuard(JSON.parse(readStdin()), now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30));
|
|
110
|
+
const reason = await runGuard(JSON.parse(readStdin()), now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30), { preview: !isPro() });
|
|
92
111
|
if (reason) {
|
|
93
112
|
console.log(
|
|
94
113
|
JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } }),
|
|
@@ -101,10 +120,13 @@ if (cmd === 'status') {
|
|
|
101
120
|
} else if (cmd === 'install') {
|
|
102
121
|
const wantGuard = args.includes('--guard');
|
|
103
122
|
const wantAlerts = args.includes('--alerts');
|
|
104
|
-
if (
|
|
105
|
-
console.log(
|
|
123
|
+
if (wantGuard && !isPro()) {
|
|
124
|
+
console.log(
|
|
125
|
+
`Without Pro the subagent guard runs as a preview: it never blocks, it records what Pro would have blocked (see \`limitcast results\`). Pro: ${UPGRADE_URL}`,
|
|
126
|
+
);
|
|
106
127
|
}
|
|
107
|
-
|
|
128
|
+
if (wantAlerts && !isPro()) console.log(`Alerts and the weekly summary are part of limitcast Pro (${UPGRADE_URL}). Skipping them.`);
|
|
129
|
+
for (const c of install({ guard: wantGuard, alerts: wantAlerts && isPro() })) console.log(`✓ ${c}`);
|
|
108
130
|
console.log('Restart Claude Code and Codex to load it. Then: limitcast doctor');
|
|
109
131
|
} else if (cmd === 'uninstall') {
|
|
110
132
|
const changes = uninstall();
|
|
@@ -141,10 +163,26 @@ if (cmd === 'status') {
|
|
|
141
163
|
console.log(`\`limitcast trim\` needs one Claude Code session first. Naming what to cut is Pro: ${UPGRADE_URL}`);
|
|
142
164
|
process.exit(2);
|
|
143
165
|
}
|
|
166
|
+
if (args.includes('--apply') || args.includes('--undo')) {
|
|
167
|
+
if (!pro) {
|
|
168
|
+
console.log(`\`limitcast trim --apply\` is part of limitcast Pro: ${UPGRADE_URL}\nAlready bought it? limitcast activate <license-key>`);
|
|
169
|
+
process.exit(2);
|
|
170
|
+
}
|
|
171
|
+
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
|
|
172
|
+
process.exit(0);
|
|
173
|
+
}
|
|
144
174
|
if (latest && (args.includes('--share') || !pro)) text = shareSummary(baseline(usage), latest, used, days());
|
|
145
175
|
else text = latest ? startupReport(baseline(usage), latest, used, days()) : trimReport(baseline(usage), contributors(), used, days());
|
|
146
176
|
if (!pro)
|
|
147
177
|
text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\nAlready bought it? limitcast activate <license-key>`;
|
|
178
|
+
else if (latest && !args.includes('--share')) {
|
|
179
|
+
const still = stillLoading(latest);
|
|
180
|
+
text += still.length
|
|
181
|
+
? `\n\nStill loading after \`trim --apply\`: ${still.join(', ')}. A Claude Code session that was running may have rewritten ~/.claude.json; quit Claude Code and run \`limitcast trim --apply\` again.`
|
|
182
|
+
: measuredSavings(latest.pieces, used).tokens > 0
|
|
183
|
+
? '\n\nApply these cuts: `limitcast trim --apply` (backed up; `limitcast trim --undo` reverses it).'
|
|
184
|
+
: '';
|
|
185
|
+
}
|
|
148
186
|
}
|
|
149
187
|
const out = flag('--out');
|
|
150
188
|
if (out) {
|
|
@@ -162,7 +200,23 @@ if (cmd === 'status') {
|
|
|
162
200
|
const latest = await latestInteractiveTranscript(claudeRoot());
|
|
163
201
|
const d = latest ? recordOverhead(snapshot(latest)) : null;
|
|
164
202
|
if (hook) {
|
|
165
|
-
|
|
203
|
+
const lines = d?.alert ? [driftMessage(d)] : [];
|
|
204
|
+
// Once a week, what limitcast did: shown to the user at session start, never to the model.
|
|
205
|
+
if (weeklyDue(now)) {
|
|
206
|
+
const since = now - 7 * 86400_000;
|
|
207
|
+
const samples = [...load(since), ...(await readCodex(since))];
|
|
208
|
+
const s = loadOverhead();
|
|
209
|
+
// The daily rollup keeps the value record current; a session-start hook must not scan transcripts itself.
|
|
210
|
+
const week = Object.values(loadValue().sessions).filter((x) => x.at >= since);
|
|
211
|
+
lines.push(
|
|
212
|
+
weeklyLine(
|
|
213
|
+
resultsStats({ now, days: 7, samples, blocks: loadBlocks(since), pro: true }),
|
|
214
|
+
s ? savedPerSession(s) : null,
|
|
215
|
+
week.reduce((a, x) => a + x.turns * x.savedPerTurn, 0),
|
|
216
|
+
),
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
if (lines.length) console.log(JSON.stringify({ systemMessage: lines.join('\n') }));
|
|
166
220
|
} else if (!latest) console.log('No interactive Claude Code session found yet.');
|
|
167
221
|
else if (!d) console.log('Starting context recorded. limitcast will tell you when it grows.');
|
|
168
222
|
else console.log(d.alert ? driftMessage(d) : 'No meaningful change in your starting context since the last session.');
|
|
@@ -178,6 +232,42 @@ if (cmd === 'status') {
|
|
|
178
232
|
if (latest) recordOverhead(snapshot(latest));
|
|
179
233
|
const s = loadOverhead();
|
|
180
234
|
console.log(s ? savedSummary(s, await countInteractiveSince(claudeRoot(), s.first.at)) : 'Nothing measured yet. Run `limitcast trim` first.');
|
|
235
|
+
} else if (cmd === 'results') {
|
|
236
|
+
// Free shows limits reached, how far ahead limitcast warned, and the guard preview; Pro adds real blocks and savings.
|
|
237
|
+
const pro = isPro();
|
|
238
|
+
const since = now - days() * 86400_000;
|
|
239
|
+
let saved = `Pro tracks how much your starting context shrinks and what that saves: ${UPGRADE_URL}`;
|
|
240
|
+
let perSession = null;
|
|
241
|
+
if (pro) {
|
|
242
|
+
const latest = await latestInteractiveTranscript(claudeRoot());
|
|
243
|
+
if (latest) recordOverhead(snapshot(latest));
|
|
244
|
+
const s = loadOverhead();
|
|
245
|
+
perSession = s ? savedPerSession(s) : null;
|
|
246
|
+
saved =
|
|
247
|
+
s && !args.includes('--share')
|
|
248
|
+
? savedSummary(s, 0).split('\n')[0] // the per-session drop; the value section above has the totals
|
|
249
|
+
: 'Run `limitcast trim` once to record your starting context, then check back here.';
|
|
250
|
+
}
|
|
251
|
+
const samples = [...load(since), ...(await readCodex(since))];
|
|
252
|
+
const blocks = loadBlocks(since);
|
|
253
|
+
const totals = valueTotals(await refreshValue());
|
|
254
|
+
if (args.includes('--share'))
|
|
255
|
+
console.log(
|
|
256
|
+
resultsShare(resultsStats({ now, days: days(), samples, blocks, pro }), {
|
|
257
|
+
days: days(),
|
|
258
|
+
pro,
|
|
259
|
+
savedPerSession: perSession,
|
|
260
|
+
notResent: totals.tokens,
|
|
261
|
+
}),
|
|
262
|
+
);
|
|
263
|
+
else console.log(resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }) }));
|
|
264
|
+
} else if (cmd === 'rollup') {
|
|
265
|
+
// Started daily in the background by the status line: keeps the value record current. Never prints.
|
|
266
|
+
try {
|
|
267
|
+
await refreshValue();
|
|
268
|
+
} catch {
|
|
269
|
+
/* next time */
|
|
270
|
+
}
|
|
181
271
|
} else if (cmd === 'activate') {
|
|
182
272
|
// Signed offline keys start with LC1.; anything else is a Polar license key.
|
|
183
273
|
const key = args[0] ?? '';
|
|
@@ -198,6 +288,65 @@ if (cmd === 'status') {
|
|
|
198
288
|
process.exit(cmd && !['help', '--help', '-h'].includes(cmd) ? 1 : 0);
|
|
199
289
|
}
|
|
200
290
|
|
|
291
|
+
/** Fold the last 8 days of readings and blocks, and any new sessions, into the long-term value record. */
|
|
292
|
+
async function refreshValue() {
|
|
293
|
+
const since = now - KEEP_MS;
|
|
294
|
+
const claude = load(since);
|
|
295
|
+
const o = loadOverhead();
|
|
296
|
+
// limitcast started watching at its first status-line reading (or first measurement), not when Codex's logs begin.
|
|
297
|
+
const start = Math.min(now, o?.first.at ?? now, ...claude.map((s) => s.t));
|
|
298
|
+
const v = foldEvents(loadValue(), { now, samples: [...claude, ...(await readCodex(since))], blocks: loadBlocks(since), start });
|
|
299
|
+
await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
|
|
300
|
+
saveValue(v);
|
|
301
|
+
return v;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* `trim --apply`: hide unused skills and turn off unused MCP servers for the project of the measured session.
|
|
306
|
+
* @param {Awaited<ReturnType<typeof latestInteractiveTranscript>>} latest
|
|
307
|
+
* @param {import('../src/trim.mjs').Activity} used
|
|
308
|
+
*/
|
|
309
|
+
function applyMessage(latest, used) {
|
|
310
|
+
if (!latest) return '`limitcast trim --apply` needs one Claude Code session first.';
|
|
311
|
+
const s = measuredSavings(latest.pieces, used);
|
|
312
|
+
const cwd = transcriptCwd(latest.file) ?? process.cwd();
|
|
313
|
+
const plan = planTrim({
|
|
314
|
+
skills: s.unusedSkills.map((k) => k.name),
|
|
315
|
+
mcp: s.unusedMcp.map((m) => m.name),
|
|
316
|
+
cwd,
|
|
317
|
+
settings: readSettings(settingsPath()),
|
|
318
|
+
claudeJson: readSettings(claudeJsonPath()),
|
|
319
|
+
plugins: installedPlugins(),
|
|
320
|
+
projectMcpJson: projectMcpServers(cwd),
|
|
321
|
+
localSkills: localSkillFolders(cwd),
|
|
322
|
+
});
|
|
323
|
+
const e = applyTrim(plan, { cwd, now });
|
|
324
|
+
const lines = [];
|
|
325
|
+
if (e.skills.length)
|
|
326
|
+
lines.push(`✓ Hid ${e.skills.length} skills from the model (\`/name\` still works): ${e.skills.map((k) => k.name).join(', ')}`);
|
|
327
|
+
if (e.mcp.length) lines.push(`✓ Turned off ${e.mcp.length} MCP servers for ${cwd}: ${e.mcp.join(', ')}`);
|
|
328
|
+
if (plan.pluginSkills.length) lines.push(`- Plugin skills can only be turned off with their plugin (\`/plugin\`): ${plan.pluginSkills.join(', ')}`);
|
|
329
|
+
if (plan.manualMcp.length) lines.push(`- Turn these off in \`/mcp\` (limitcast couldn't confirm their exact names): ${plan.manualMcp.join(', ')}`);
|
|
330
|
+
if (!e.skills.length && !e.mcp.length) lines.unshift('Nothing to change automatically.');
|
|
331
|
+
else
|
|
332
|
+
lines.push(
|
|
333
|
+
"Takes effect in your next Claude Code session; quit running sessions first so they don't write over ~/.claude.json. Undo: `limitcast trim --undo`",
|
|
334
|
+
);
|
|
335
|
+
return lines.join('\n');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** @param {ReturnType<typeof undoTrim>} e */
|
|
339
|
+
function undoMessage(e) {
|
|
340
|
+
if (!e) return 'Nothing to undo.';
|
|
341
|
+
return [
|
|
342
|
+
e.skills.length ? `✓ Skills visible to the model again: ${e.skills.map((k) => k.name).join(', ')}` : '',
|
|
343
|
+
e.mcp.length ? `✓ MCP servers back on for ${e.cwd}: ${e.mcp.join(', ')}` : '',
|
|
344
|
+
'Takes effect in your next Claude Code session.',
|
|
345
|
+
]
|
|
346
|
+
.filter(Boolean)
|
|
347
|
+
.join('\n');
|
|
348
|
+
}
|
|
349
|
+
|
|
201
350
|
/**
|
|
202
351
|
* Keep the latest feed's structure (key names and rate_limits only, no prompt or path content) for diagnosing parsing.
|
|
203
352
|
* @param {any} feed
|
|
@@ -250,7 +399,10 @@ function oneLine(rows) {
|
|
|
250
399
|
return (
|
|
251
400
|
rows
|
|
252
401
|
.filter((f) => f.src === 'claude')
|
|
253
|
-
.map(
|
|
402
|
+
.map(
|
|
403
|
+
(f) =>
|
|
404
|
+
`${f.win} ${Math.round(f.pct)}%${f.verdict === 'AT_RISK' ? ` ⚠ out ${clock(f.wall)}` : f.verdict === 'NEAR' ? ' ⚠ near limit' : f.verdict === 'HIT' ? ' ⛔' : ''}`,
|
|
405
|
+
)
|
|
254
406
|
.join(' · ') || 'limitcast: waiting for data'
|
|
255
407
|
);
|
|
256
408
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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": { "limitcast": "bin/limitcast.mjs" },
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"scripts": { "test": "node --test" },
|
|
11
11
|
"keywords": ["claude-code", "codex", "rate-limit", "usage-limit", "tokens", "hooks", "status-line", "ai-agents"],
|
|
12
12
|
"homepage": "https://limitcast.dev",
|
|
13
|
-
"repository": { "type": "git", "url": "git+https://github.com/
|
|
13
|
+
"repository": { "type": "git", "url": "git+https://github.com/SamStull9007/limitcast.git" },
|
|
14
14
|
"author": "Sam Stull",
|
|
15
15
|
"license": "Elastic-2.0"
|
|
16
16
|
}
|
package/src/apply.mjs
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import {
|
|
3
|
+
chmodSync,
|
|
4
|
+
closeSync,
|
|
5
|
+
copyFileSync,
|
|
6
|
+
existsSync,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
openSync,
|
|
9
|
+
readdirSync,
|
|
10
|
+
readFileSync,
|
|
11
|
+
readSync,
|
|
12
|
+
renameSync,
|
|
13
|
+
statSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
} from 'node:fs';
|
|
16
|
+
import { homedir } from 'node:os';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
import { readSettings, settingsPath } from './install.mjs';
|
|
19
|
+
import { stateDir } from './store.mjs';
|
|
20
|
+
|
|
21
|
+
// `trim --apply`: hide unused skills and turn off unused MCP servers through Claude Code's own settings.
|
|
22
|
+
// Skills: `skillOverrides` in ~/.claude/settings.json ("user-invocable-only": the model stops seeing it, /name still works).
|
|
23
|
+
// Plugin skills ignore skillOverrides, so they are listed for /plugin instead.
|
|
24
|
+
// MCP servers: the per-project `disabledMcpServers` list in ~/.claude.json, the same list the /mcp toggle writes.
|
|
25
|
+
// Only names that match a server Claude Code knows exactly are written; the rest are listed for /mcp.
|
|
26
|
+
|
|
27
|
+
const configDir = () => process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
|
|
28
|
+
export const claudeJsonPath = () => (process.env.CLAUDE_CONFIG_DIR ? join(configDir(), '.claude.json') : join(homedir(), '.claude.json'));
|
|
29
|
+
const ledgerPath = () => join(stateDir(), 'trim-applied.json');
|
|
30
|
+
|
|
31
|
+
/** MCP tool names keep the server name but normalize punctuation. @param {string} s */
|
|
32
|
+
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '_');
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Installed plugins and the MCP servers they register ("plugin:<plugin>:<server>").
|
|
36
|
+
* @returns {{names:Set<string>, servers:string[]}}
|
|
37
|
+
*/
|
|
38
|
+
export function installedPlugins(dir = configDir()) {
|
|
39
|
+
const names = new Set();
|
|
40
|
+
const servers = [];
|
|
41
|
+
try {
|
|
42
|
+
const reg = JSON.parse(readFileSync(join(dir, 'plugins', 'installed_plugins.json'), 'utf8'));
|
|
43
|
+
for (const [key, installs] of Object.entries(reg.plugins ?? {})) {
|
|
44
|
+
const name = key.split('@')[0];
|
|
45
|
+
names.add(name);
|
|
46
|
+
for (const i of /** @type {any[]} */ (installs)) {
|
|
47
|
+
for (const f of ['.mcp.json', join('.claude-plugin', 'plugin.json')]) {
|
|
48
|
+
try {
|
|
49
|
+
const j = JSON.parse(readFileSync(join(i.installPath, f), 'utf8'));
|
|
50
|
+
const defs = f === '.mcp.json' ? (j.mcpServers ?? j) : j.mcpServers;
|
|
51
|
+
if (defs && typeof defs === 'object') for (const s of Object.keys(defs)) servers.push(`plugin:${name}:${s}`);
|
|
52
|
+
} catch {
|
|
53
|
+
/* no MCP servers in this file */
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} catch {
|
|
59
|
+
/* no plugins */
|
|
60
|
+
}
|
|
61
|
+
return { names, servers };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* What `--apply` would change, from the unused items `trim` measured.
|
|
66
|
+
* @param {{skills:string[], mcp:string[], cwd:string, settings:any, claudeJson:any, plugins:{names:Set<string>, servers:string[]}, projectMcpJson:string[], localSkills:Set<string>}} r
|
|
67
|
+
* localSkills: folder names of personal and project skills
|
|
68
|
+
*/
|
|
69
|
+
export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, projectMcpJson, localSkills }) {
|
|
70
|
+
// "x:y" is a plugin skill (namespaced by its plugin) unless x is one of your own skill folders with nested skills.
|
|
71
|
+
// Plugins can load from places installed_plugins.json doesn't list, so the namespace alone decides.
|
|
72
|
+
const isPluginSkill = (/** @type {string} */ n) => n.includes(':') && !localSkills.has(n.split(':')[0]);
|
|
73
|
+
const overrides = settings.skillOverrides ?? {};
|
|
74
|
+
const hide = skills.filter((n) => !isPluginSkill(n) && (overrides[n] === undefined || overrides[n] === 'on'));
|
|
75
|
+
const pluginSkills = skills.filter(isPluginSkill);
|
|
76
|
+
|
|
77
|
+
// Exact server names Claude Code uses: configured servers, plugin servers, and names already toggled in /mcp anywhere.
|
|
78
|
+
const exact = new Set([
|
|
79
|
+
...Object.keys(claudeJson.mcpServers ?? {}),
|
|
80
|
+
...Object.keys(claudeJson.projects?.[cwd]?.mcpServers ?? {}),
|
|
81
|
+
...Object.keys(settings.mcpServers ?? {}),
|
|
82
|
+
...plugins.servers,
|
|
83
|
+
...Object.values(claudeJson.projects ?? {}).flatMap((p) => /** @type {any} */ (p).disabledMcpServers ?? []),
|
|
84
|
+
]);
|
|
85
|
+
const byNorm = new Map([...exact].map((n) => [norm(n), n]));
|
|
86
|
+
const already = new Set(claudeJson.projects?.[cwd]?.disabledMcpServers ?? []);
|
|
87
|
+
const projectServers = new Set(projectMcpJson.map(norm));
|
|
88
|
+
/** @type {string[]} */
|
|
89
|
+
const disable = [];
|
|
90
|
+
/** @type {string[]} */
|
|
91
|
+
const manualMcp = [];
|
|
92
|
+
for (const m of mcp) {
|
|
93
|
+
// .mcp.json servers are approved per project in settings, not toggled in disabledMcpServers.
|
|
94
|
+
const name = projectServers.has(norm(m)) ? null : (byNorm.get(norm(m)) ?? (m.startsWith('claude.ai ') ? m : null));
|
|
95
|
+
if (!name) manualMcp.push(m);
|
|
96
|
+
else if (!already.has(name)) disable.push(name);
|
|
97
|
+
}
|
|
98
|
+
return { hide, pluginSkills, disable, manualMcp };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** @param {string} path */
|
|
102
|
+
function backup(path) {
|
|
103
|
+
if (existsSync(path)) copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Write JSON through a temp file and rename, so a crash or a concurrent reader never sees half a file.
|
|
108
|
+
* @param {string} path @param {any} value
|
|
109
|
+
*/
|
|
110
|
+
function writeJson(path, value) {
|
|
111
|
+
const tmp = `${path}.limitcast-tmp`;
|
|
112
|
+
// ~/.claude.json can hold credentials: keep the file's own permissions (owner-only for a new file).
|
|
113
|
+
const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
|
|
114
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode });
|
|
115
|
+
chmodSync(tmp, mode); // a leftover tmp from a crash keeps its old mode otherwise
|
|
116
|
+
renameSync(tmp, path);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** @returns {{at:number, cwd:string, skills:{name:string, prev?:string}[], mcp:string[]}[]} */
|
|
120
|
+
export function loadLedger() {
|
|
121
|
+
try {
|
|
122
|
+
return JSON.parse(readFileSync(ledgerPath(), 'utf8'));
|
|
123
|
+
} catch {
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Apply a plan: back up both files, write the changes, and record exactly what changed so `--undo` can reverse it.
|
|
130
|
+
* @param {ReturnType<typeof planTrim>} plan
|
|
131
|
+
* @param {{cwd:string, now:number, settings?:string, claudeJson?:string}} o
|
|
132
|
+
*/
|
|
133
|
+
export function applyTrim(plan, { cwd, now, settings = settingsPath(), claudeJson = claudeJsonPath() }) {
|
|
134
|
+
const entry = { at: now, cwd, skills: /** @type {{name:string, prev?:string}[]} */ ([]), mcp: /** @type {string[]} */ ([]) };
|
|
135
|
+
if (plan.hide.length) {
|
|
136
|
+
const cfg = readSettings(settings);
|
|
137
|
+
backup(settings);
|
|
138
|
+
cfg.skillOverrides ??= {};
|
|
139
|
+
for (const name of plan.hide) {
|
|
140
|
+
entry.skills.push(name in cfg.skillOverrides ? { name, prev: cfg.skillOverrides[name] } : { name });
|
|
141
|
+
cfg.skillOverrides[name] = 'user-invocable-only';
|
|
142
|
+
}
|
|
143
|
+
writeJson(settings, cfg);
|
|
144
|
+
}
|
|
145
|
+
if (plan.disable.length) {
|
|
146
|
+
const cj = readSettings(claudeJson);
|
|
147
|
+
backup(claudeJson);
|
|
148
|
+
cj.projects ??= {};
|
|
149
|
+
cj.projects[cwd] ??= {};
|
|
150
|
+
const list = (cj.projects[cwd].disabledMcpServers ??= []);
|
|
151
|
+
for (const name of plan.disable) if (!list.includes(name)) list.push(name);
|
|
152
|
+
entry.mcp = [...plan.disable];
|
|
153
|
+
writeJson(claudeJson, cj);
|
|
154
|
+
}
|
|
155
|
+
if (entry.skills.length || entry.mcp.length) {
|
|
156
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
157
|
+
writeJson(ledgerPath(), [...loadLedger(), entry]);
|
|
158
|
+
}
|
|
159
|
+
return entry;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Reverse the last `--apply`: put back each skill's previous setting and re-enable the servers it turned off.
|
|
164
|
+
* Settings the user changed since are left alone.
|
|
165
|
+
* @param {{settings?:string, claudeJson?:string}} [o]
|
|
166
|
+
*/
|
|
167
|
+
export function undoTrim({ settings = settingsPath(), claudeJson = claudeJsonPath() } = {}) {
|
|
168
|
+
const ledger = loadLedger();
|
|
169
|
+
const last = ledger.pop();
|
|
170
|
+
if (!last) return null;
|
|
171
|
+
if (last.skills.length) {
|
|
172
|
+
const cfg = readSettings(settings);
|
|
173
|
+
backup(settings);
|
|
174
|
+
for (const s of last.skills) {
|
|
175
|
+
if (cfg.skillOverrides?.[s.name] !== 'user-invocable-only') continue;
|
|
176
|
+
if (s.prev === undefined) delete cfg.skillOverrides[s.name];
|
|
177
|
+
else cfg.skillOverrides[s.name] = s.prev;
|
|
178
|
+
}
|
|
179
|
+
writeJson(settings, cfg);
|
|
180
|
+
}
|
|
181
|
+
if (last.mcp.length) {
|
|
182
|
+
const cj = readSettings(claudeJson);
|
|
183
|
+
backup(claudeJson);
|
|
184
|
+
const p = cj.projects?.[last.cwd];
|
|
185
|
+
if (p?.disabledMcpServers) p.disabledMcpServers = p.disabledMcpServers.filter((/** @type {string} */ n) => !last.mcp.includes(n));
|
|
186
|
+
writeJson(claudeJson, cj);
|
|
187
|
+
}
|
|
188
|
+
writeJson(ledgerPath(), ledger);
|
|
189
|
+
return last;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Items an earlier --apply turned off that still loaded in a session started after it
|
|
194
|
+
* (for example, a running Claude Code session rewrote ~/.claude.json).
|
|
195
|
+
* @param {{pieces:{group:string, name:string}[], at:number}} b latest measured session
|
|
196
|
+
*/
|
|
197
|
+
export function stillLoading(b) {
|
|
198
|
+
const loaded = new Set(b.pieces.map((p) => norm(p.name)));
|
|
199
|
+
return loadLedger()
|
|
200
|
+
.filter((e) => b.at > e.at)
|
|
201
|
+
.flatMap((e) => [...e.skills.map((s) => s.name), ...e.mcp])
|
|
202
|
+
.filter((n) => loaded.has(norm(n)));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The working directory a transcript was recorded in (where its MCP toggles live).
|
|
207
|
+
* @param {string} file
|
|
208
|
+
*/
|
|
209
|
+
export function transcriptCwd(file) {
|
|
210
|
+
// The cwd is on the first entries; read only the head of what can be a multi-megabyte transcript.
|
|
211
|
+
const buf = Buffer.alloc(256 * 1024);
|
|
212
|
+
const fd = openSync(file, 'r');
|
|
213
|
+
const n = readSync(fd, buf, 0, buf.length, 0);
|
|
214
|
+
closeSync(fd);
|
|
215
|
+
for (const line of buf.subarray(0, n).toString('utf8').split('\n')) {
|
|
216
|
+
try {
|
|
217
|
+
const cwd = JSON.parse(line).cwd;
|
|
218
|
+
if (typeof cwd === 'string') return cwd;
|
|
219
|
+
} catch {
|
|
220
|
+
/* skip */
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Folder names of personal (~/.claude/skills) and project (<cwd>/.claude/skills) skills.
|
|
228
|
+
* @param {string} cwd
|
|
229
|
+
*/
|
|
230
|
+
export function localSkillFolders(cwd, dir = configDir()) {
|
|
231
|
+
const out = new Set();
|
|
232
|
+
for (const root of [join(dir, 'skills'), join(cwd, '.claude', 'skills')]) {
|
|
233
|
+
try {
|
|
234
|
+
for (const d of readdirSync(root, { withFileTypes: true })) if (d.isDirectory() || d.isSymbolicLink()) out.add(d.name);
|
|
235
|
+
} catch {
|
|
236
|
+
/* none */
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Server names in the project's .mcp.json. @param {string} cwd */
|
|
243
|
+
export function projectMcpServers(cwd) {
|
|
244
|
+
try {
|
|
245
|
+
return Object.keys(JSON.parse(readFileSync(join(cwd, '.mcp.json'), 'utf8')).mcpServers ?? {});
|
|
246
|
+
} catch {
|
|
247
|
+
return [];
|
|
248
|
+
}
|
|
249
|
+
}
|
package/src/forecast.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
const RESET_JITTER_S = 120; // Codex resets_at drifts by seconds between events
|
|
6
6
|
const RECENT_MS = 60 * 60 * 1000;
|
|
7
|
+
const NEAR_PCT = 95;
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Burn rate and limit forecast for one (src, win) series.
|
|
@@ -23,10 +24,12 @@ export function forecast(samples, now) {
|
|
|
23
24
|
const recent = window.filter((s) => s.t >= now - RECENT_MS);
|
|
24
25
|
const pts = recent.length >= 2 ? recent : window;
|
|
25
26
|
const rate = slopePerHour(pts);
|
|
26
|
-
|
|
27
|
+
// NEAR: so close to the limit that one heavy turn can finish it, even with no burn rate to go on yet.
|
|
28
|
+
const calm = last.pct >= NEAR_PCT ? 'NEAR' : 'OK';
|
|
29
|
+
if (rate === null || rate <= 0) return { ...base, rate, verdict: calm };
|
|
27
30
|
|
|
28
31
|
const wall = last.t + ((100 - last.pct) / rate) * 3600_000;
|
|
29
|
-
return { ...base, rate, wall, verdict: wall < resetMs ? 'AT_RISK' :
|
|
32
|
+
return { ...base, rate, wall, verdict: wall < resetMs ? 'AT_RISK' : calm };
|
|
30
33
|
}
|
|
31
34
|
|
|
32
35
|
/**
|
|
@@ -69,16 +72,67 @@ export function forecastAll(samples, now) {
|
|
|
69
72
|
|
|
70
73
|
/**
|
|
71
74
|
* Claude sessions can belong to different accounts with different limits, and the feed has no account id.
|
|
72
|
-
* Keep Claude samples
|
|
73
|
-
* Untagged Claude samples (recorded before 0.2) can't be attributed
|
|
75
|
+
* Keep the Claude samples of one account: the one `sid` belongs to if it has readings, else the most recently active one.
|
|
76
|
+
* Codex is untouched. Untagged Claude samples (recorded before 0.2) can't be attributed, so they're dropped once tagged ones exist.
|
|
74
77
|
* @param {Sample[]} samples
|
|
75
78
|
* @param {string} [sid]
|
|
76
79
|
*/
|
|
77
|
-
export function
|
|
78
|
-
const
|
|
79
|
-
if (!
|
|
80
|
-
const pick =
|
|
81
|
-
return samples.filter((s) => s.src !== 'claude'
|
|
80
|
+
export function oneClaudeAccount(samples, sid) {
|
|
81
|
+
const accounts = claudeAccounts(samples);
|
|
82
|
+
if (!accounts.length) return samples;
|
|
83
|
+
const pick = accounts.find((a) => a.some((s) => s.sid === sid)) ?? accounts[0];
|
|
84
|
+
return [...samples.filter((s) => s.src !== 'claude'), ...pick];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Tagged Claude samples grouped by account, most recently active account first.
|
|
89
|
+
* Each session reports the same account windows, and a session only records when a reading changes, so one
|
|
90
|
+
* session alone often holds too few readings to forecast from. Sessions are the same account when they share
|
|
91
|
+
* at least one window (same reset time) and their readings of every shared window never go down when merged:
|
|
92
|
+
* usage within a window only rises, so a second account's lower readings break the merge.
|
|
93
|
+
* shortcut: two accounts with identical reset times and near-identical usage could merge; split on a feed account id if Claude Code adds one.
|
|
94
|
+
* @param {Sample[]} samples
|
|
95
|
+
* @returns {Sample[][]}
|
|
96
|
+
*/
|
|
97
|
+
export function claudeAccounts(samples) {
|
|
98
|
+
/** @type {Map<string, Sample[]>} */
|
|
99
|
+
const sessions = new Map();
|
|
100
|
+
for (const s of samples) {
|
|
101
|
+
if (s.src !== 'claude' || !s.sid) continue;
|
|
102
|
+
sessions.set(s.sid, [...(sessions.get(s.sid) ?? []), s]);
|
|
103
|
+
}
|
|
104
|
+
const latest = (/** @type {Sample[]} */ g) => Math.max(...g.map((s) => s.t));
|
|
105
|
+
/** @type {Sample[][]} */
|
|
106
|
+
const accounts = [];
|
|
107
|
+
for (const g of [...sessions.values()].sort((a, b) => latest(b) - latest(a))) {
|
|
108
|
+
const a = accounts.find((acc) => sameAccount(acc, g));
|
|
109
|
+
if (a) a.push(...g);
|
|
110
|
+
else accounts.push([...g]);
|
|
111
|
+
}
|
|
112
|
+
return accounts;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* @param {Sample[]} a
|
|
117
|
+
* @param {Sample[]} b
|
|
118
|
+
*/
|
|
119
|
+
function sameAccount(a, b) {
|
|
120
|
+
let shared = false;
|
|
121
|
+
const same = (/** @type {Sample} */ x, /** @type {Sample} */ s) => x.win === s.win && Math.abs(x.reset - s.reset) <= RESET_JITTER_S;
|
|
122
|
+
// One representative reading per window of b; the status line runs this, so keep it to a few passes.
|
|
123
|
+
const windows = b.filter((s, i) => b.findIndex((x) => same(x, s)) === i);
|
|
124
|
+
for (const s of windows) {
|
|
125
|
+
const series = a.filter((x) => same(x, s));
|
|
126
|
+
if (!series.length) continue;
|
|
127
|
+
shared = true;
|
|
128
|
+
const merged = [...series, ...b.filter((x) => same(x, s))].sort((x, y) => x.t - y.t);
|
|
129
|
+
let top = Number.NEGATIVE_INFINITY;
|
|
130
|
+
for (const x of merged) {
|
|
131
|
+
if (x.pct < top - 0.5) return false;
|
|
132
|
+
top = Math.max(top, x.pct);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return shared;
|
|
82
136
|
}
|
|
83
137
|
|
|
84
138
|
/** @param {number} minutes */
|
package/src/guard.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import { forecastAll,
|
|
2
|
+
import { forecastAll, oneClaudeAccount } from './forecast.mjs';
|
|
3
|
+
import { logBlock } from './results.mjs';
|
|
3
4
|
import { readCodex } from './sources.mjs';
|
|
4
5
|
import { KEEP_MS, load } from './store.mjs';
|
|
5
6
|
|
|
@@ -29,19 +30,25 @@ export function spawnSource(tool) {
|
|
|
29
30
|
* @param {number} minutes
|
|
30
31
|
*/
|
|
31
32
|
export function guardDecision(tool, forecasts, now, minutes) {
|
|
33
|
+
const f = blockingForecast(tool, forecasts, now, minutes);
|
|
34
|
+
if (!f || f.wall === null) return null;
|
|
35
|
+
const left = Math.max(0, Math.round((f.wall - now) / 60_000));
|
|
36
|
+
return (
|
|
37
|
+
`limitcast: ${NAMES[/** @type {'claude'} */ (f.src)]} ${f.win} limit is ${f.pct}% used and on pace to run out in ~${left} min, before it resets. ` +
|
|
38
|
+
'Finish with the agents already running, or set LIMITCAST_ALLOW=1 to spawn anyway.'
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The forecast that blocks this spawn, or undefined. See guardDecision.
|
|
44
|
+
* @param {string} tool
|
|
45
|
+
* @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
|
|
46
|
+
* @param {number} now epoch ms
|
|
47
|
+
* @param {number} minutes
|
|
48
|
+
*/
|
|
49
|
+
function blockingForecast(tool, forecasts, now, minutes) {
|
|
32
50
|
const src = spawnSource(tool);
|
|
33
|
-
|
|
34
|
-
for (const f of forecasts) {
|
|
35
|
-
if (f.src !== src) continue;
|
|
36
|
-
if (f.verdict === 'AT_RISK' && f.wall !== null && f.wall - now <= minutes * 60_000) {
|
|
37
|
-
const left = Math.max(0, Math.round((f.wall - now) / 60_000));
|
|
38
|
-
return (
|
|
39
|
-
`limitcast: ${NAMES[src]} ${f.win} limit is ${f.pct}% used and on pace to run out in ~${left} min, before it resets. ` +
|
|
40
|
-
'Finish with the agents already running, or set LIMITCAST_ALLOW=1 to spawn anyway.'
|
|
41
|
-
);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return null;
|
|
51
|
+
return forecasts.find((f) => f.src === src && f.verdict === 'AT_RISK' && f.wall !== null && f.wall - now <= minutes * 60_000);
|
|
45
52
|
}
|
|
46
53
|
|
|
47
54
|
/**
|
|
@@ -50,16 +57,38 @@ export function guardDecision(tool, forecasts, now, minutes) {
|
|
|
50
57
|
* @param {any} hook parsed hook input
|
|
51
58
|
* @param {number} now epoch ms
|
|
52
59
|
* @param {number} minutes
|
|
60
|
+
* @param {{preview?:boolean}} [opts] preview: a free install; log what Pro would block, never block
|
|
53
61
|
*/
|
|
54
|
-
export async function runGuard(hook, now, minutes) {
|
|
62
|
+
export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
55
63
|
const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
|
|
56
64
|
const src = spawnSource(tool);
|
|
57
65
|
// Codex: only the last two hours of rollouts, so the hook stays fast; Grok has no readings to judge by.
|
|
58
66
|
const samples =
|
|
59
67
|
src === 'claude'
|
|
60
|
-
?
|
|
68
|
+
? oneClaudeAccount(load(now - KEEP_MS), hook.session_id ?? hook.sessionId)
|
|
61
69
|
: src === 'codex'
|
|
62
70
|
? await readCodex(now - 2 * 3600_000)
|
|
63
71
|
: [];
|
|
64
|
-
|
|
72
|
+
const forecasts = forecastAll(samples, now);
|
|
73
|
+
const reason = guardDecision(tool, forecasts, now, minutes);
|
|
74
|
+
const f = reason ? blockingForecast(tool, forecasts, now, minutes) : undefined;
|
|
75
|
+
if (f?.wall) {
|
|
76
|
+
// Any session of the blocking account identifies it for `results`.
|
|
77
|
+
const sid = f.src === 'claude' ? samples.find((s) => s.src === 'claude' && s.sid)?.sid : undefined;
|
|
78
|
+
try {
|
|
79
|
+
logBlock({
|
|
80
|
+
t: now,
|
|
81
|
+
src: f.src,
|
|
82
|
+
win: f.win,
|
|
83
|
+
pct: f.pct,
|
|
84
|
+
wall: f.wall,
|
|
85
|
+
reset: f.reset,
|
|
86
|
+
...(sid ? { sid } : {}),
|
|
87
|
+
...(preview ? { shadow: true } : {}),
|
|
88
|
+
});
|
|
89
|
+
} catch {
|
|
90
|
+
/* a failed log must not change the decision */
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return preview ? null : reason;
|
|
65
94
|
}
|
package/src/overhead.mjs
CHANGED
|
@@ -86,7 +86,7 @@ export function driftMessage(d) {
|
|
|
86
86
|
* @param {number} sessions interactive sessions since s.first.at
|
|
87
87
|
*/
|
|
88
88
|
export function savedSummary(s, sessions) {
|
|
89
|
-
const perSession =
|
|
89
|
+
const perSession = savedPerSession(s);
|
|
90
90
|
const since = new Date(s.first.at).toLocaleDateString();
|
|
91
91
|
if (perSession <= 0) {
|
|
92
92
|
return `Since ${since}, the part of your starting context you control (hooks, MCP servers, skills, agents, instruction files) went from ~${fmtK(tok(s.first.chars))} to ~${fmtK(tok(s.last.chars))} tokens (${perSession === 0 ? 'no change' : `+${fmtK(-perSession)}`}). Run \`limitcast trim\` to find cuts.`;
|
|
@@ -97,5 +97,11 @@ export function savedSummary(s, sessions) {
|
|
|
97
97
|
].join('\n');
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
+
/**
|
|
101
|
+
* Tokens per session the controllable starting context dropped since limitcast first measured it (negative: it grew).
|
|
102
|
+
* @param {{first:Snapshot, last:Snapshot}} s
|
|
103
|
+
*/
|
|
104
|
+
export const savedPerSession = (s) => tok(s.first.chars - s.last.chars);
|
|
105
|
+
|
|
100
106
|
/** @param {number} n */
|
|
101
107
|
const fmtK = (n) => (Math.abs(n) >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : Math.abs(n) >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : `${n}`);
|
package/src/results.mjs
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { claudeAccounts, forecast } from './forecast.mjs';
|
|
5
|
+
import { stateDir } from './store.mjs';
|
|
6
|
+
|
|
7
|
+
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
8
|
+
/** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, shadow?:boolean}} Block t, wall, reset: epoch ms; shadow: a free install's preview, not blocked */
|
|
9
|
+
|
|
10
|
+
const JITTER_MS = 120_000; // Codex resets_at drifts by seconds between events
|
|
11
|
+
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
12
|
+
|
|
13
|
+
const blockFile = () => join(stateDir(), 'guard.jsonl');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Remember a guard block so `limitcast results` can check it later against what the window actually did.
|
|
17
|
+
* shortcut: never pruned; one short line per block, so it stays small for years of normal use.
|
|
18
|
+
* @param {Block} b
|
|
19
|
+
*/
|
|
20
|
+
export function logBlock(b) {
|
|
21
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
22
|
+
appendFileSync(blockFile(), `${JSON.stringify(b)}\n`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @param {number} since epoch ms @returns {Block[]} */
|
|
26
|
+
export function loadBlocks(since) {
|
|
27
|
+
if (!existsSync(blockFile())) return [];
|
|
28
|
+
return readFileSync(blockFile(), 'utf8')
|
|
29
|
+
.split('\n')
|
|
30
|
+
.flatMap((line) => {
|
|
31
|
+
try {
|
|
32
|
+
const b = JSON.parse(line);
|
|
33
|
+
return b.t >= since ? [b] : [];
|
|
34
|
+
} catch {
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The readings that belong together: each Claude account, then everything else (Codex), as `status` sees them.
|
|
42
|
+
* @param {Sample[]} samples
|
|
43
|
+
*/
|
|
44
|
+
function pools(samples) {
|
|
45
|
+
const accounts = claudeAccounts(samples);
|
|
46
|
+
const rest = samples.filter((s) => s.src !== 'claude' || (!accounts.length && !s.sid));
|
|
47
|
+
return [...accounts, rest];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Samples of one limit window (same pool, tool, window and reset time).
|
|
52
|
+
* @param {Sample[]} samples
|
|
53
|
+
*/
|
|
54
|
+
function windows(samples) {
|
|
55
|
+
/** @type {Sample[][]} */
|
|
56
|
+
const groups = [];
|
|
57
|
+
for (const pool of pools(samples)) {
|
|
58
|
+
/** @type {Sample[][]} */
|
|
59
|
+
const local = [];
|
|
60
|
+
for (const s of [...pool].sort((a, b) => a.t - b.t)) {
|
|
61
|
+
const g = local.find(([f]) => f.src === s.src && f.win === s.win && Math.abs(f.reset - s.reset) * 1000 <= JITTER_MS);
|
|
62
|
+
if (g) g.push(s);
|
|
63
|
+
else local.push([s]);
|
|
64
|
+
}
|
|
65
|
+
groups.push(...local);
|
|
66
|
+
}
|
|
67
|
+
return groups;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Each window that reached 100%, and how far ahead limitcast's forecast first said AT_RISK.
|
|
72
|
+
* The forecast is replayed with only the readings known at each moment, exactly as `status` would have shown it.
|
|
73
|
+
* @param {Sample[]} samples
|
|
74
|
+
*/
|
|
75
|
+
export function limitHits(samples) {
|
|
76
|
+
const hits = [];
|
|
77
|
+
for (const g of windows(samples)) {
|
|
78
|
+
const hitIdx = g.findIndex((s) => s.pct >= 100);
|
|
79
|
+
if (hitIdx < 0) continue;
|
|
80
|
+
const at = g[hitIdx].t;
|
|
81
|
+
// Earliest moment the forecast warned (AT_RISK or NEAR), counting only warnings it kept until the hit.
|
|
82
|
+
let warnedAt = null;
|
|
83
|
+
for (let i = hitIdx - 1; i >= 0; i--) {
|
|
84
|
+
const f = forecast(g.slice(0, i + 1), g[i].t);
|
|
85
|
+
if (f?.verdict !== 'AT_RISK' && f?.verdict !== 'NEAR') break;
|
|
86
|
+
warnedAt = g[i].t;
|
|
87
|
+
}
|
|
88
|
+
// unseen: already at 100% in its first reading, so there was nothing to forecast from.
|
|
89
|
+
hits.push({ src: g[0].src, win: g[0].win, at, reset: g[0].reset * 1000, warnedAt, unseen: hitIdx === 0 });
|
|
90
|
+
}
|
|
91
|
+
return hits.sort((a, b) => a.at - b.at);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* What happened to the window after each guard block.
|
|
96
|
+
* @param {Block[]} blocks
|
|
97
|
+
* @param {Sample[]} samples
|
|
98
|
+
* @param {number} now epoch ms
|
|
99
|
+
*/
|
|
100
|
+
export function blockOutcomes(blocks, samples, now) {
|
|
101
|
+
const accounts = claudeAccounts(samples);
|
|
102
|
+
return blocks.map((b) => {
|
|
103
|
+
// A Claude block is judged by the readings of the account its session belongs to.
|
|
104
|
+
const pool = b.src === 'claude' && b.sid ? (accounts.find((a) => a.some((s) => s.sid === b.sid)) ?? []) : samples;
|
|
105
|
+
const after = pool.filter((s) => s.src === b.src && s.win === b.win && s.t >= b.t && Math.abs(s.reset * 1000 - b.reset) <= JITTER_MS);
|
|
106
|
+
const peak = Math.max(b.pct, ...after.map((s) => s.pct));
|
|
107
|
+
const hit = after.find((s) => s.pct >= 100);
|
|
108
|
+
const outcome = hit ? 'hit' : b.reset > now ? 'open' : 'under';
|
|
109
|
+
return { ...b, peak, hitAt: hit?.t ?? null, outcome };
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The numbers behind `results`, its --share summary and the weekly line.
|
|
115
|
+
* Pro sees the blocks the guard made; free sees the preview: what Pro would have blocked (shadow blocks).
|
|
116
|
+
* @param {{now:number, days:number, samples:Sample[], blocks:Block[], pro:boolean}} r
|
|
117
|
+
*/
|
|
118
|
+
export function resultsStats({ now, days, samples, blocks, pro }) {
|
|
119
|
+
const since = now - days * 86400_000;
|
|
120
|
+
const readings = samples.filter((s) => s.t >= since).length;
|
|
121
|
+
const hits = limitHits(samples.filter((s) => s.t >= since));
|
|
122
|
+
const watched = hits.filter((h) => !h.unseen);
|
|
123
|
+
const leads = hits.flatMap((h) => (h.warnedAt === null ? [] : [Math.round((h.at - h.warnedAt) / 60_000)]));
|
|
124
|
+
const mine = blocks.filter((b) => b.t >= since && Boolean(b.shadow) === !pro);
|
|
125
|
+
const outcomes = blockOutcomes(mine, samples, now);
|
|
126
|
+
return { readings, hits, watched: watched.length, leads, outcomes };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Totals only, no project, file or session names: safe to post.
|
|
131
|
+
* @param {ReturnType<typeof resultsStats>} st
|
|
132
|
+
* @param {{days:number, pro:boolean, savedPerSession:number|null, notResent?:number}} o
|
|
133
|
+
* notResent: tokens not re-sent since install (the value record)
|
|
134
|
+
*/
|
|
135
|
+
export function resultsShare(st, { days, pro, savedPerSession, notResent = 0 }) {
|
|
136
|
+
const parts = [`limitcast, last ${days} days:`, `${st.hits.length} usage limit${st.hits.length === 1 ? '' : 's'} reached`];
|
|
137
|
+
if (st.watched)
|
|
138
|
+
parts.push(`forecast ${st.leads.length} of the ${st.watched} it watched in advance${st.leads.length ? ` (avg ${avg(st.leads)} min ahead)` : ''}`);
|
|
139
|
+
if (st.outcomes.length)
|
|
140
|
+
parts.push(`${pro ? 'blocked' : 'would have blocked'} ${st.outcomes.length} runaway subagent${st.outcomes.length === 1 ? '' : 's'}`);
|
|
141
|
+
if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller per session`);
|
|
142
|
+
if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent since install`);
|
|
143
|
+
return `${parts[0]} ${parts.slice(1).join('; ')}. https://limitcast.dev`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* One line for the weekly SessionStart summary (shown to the user, never the model).
|
|
148
|
+
* @param {ReturnType<typeof resultsStats>} st
|
|
149
|
+
* @param {number|null} savedPerSession
|
|
150
|
+
* @param {number} [notResent] tokens not re-sent this week
|
|
151
|
+
*/
|
|
152
|
+
export function weeklyLine(st, savedPerSession, notResent = 0) {
|
|
153
|
+
const parts = [`${st.hits.length} limit${st.hits.length === 1 ? '' : 's'} reached`];
|
|
154
|
+
if (st.leads.length) parts.push(`warned ahead on ${st.leads.length} (avg ${avg(st.leads)} min)`);
|
|
155
|
+
parts.push(`guard blocked ${st.outcomes.length} subagent${st.outcomes.length === 1 ? '' : 's'}`);
|
|
156
|
+
if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller`);
|
|
157
|
+
if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent`);
|
|
158
|
+
return `limitcast this week: ${parts.join(', ')}. Details: limitcast results`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* True once every 7 days. The first call only starts the clock, so the first summary covers a full week.
|
|
163
|
+
* @param {number} now epoch ms
|
|
164
|
+
*/
|
|
165
|
+
export function weeklyDue(now) {
|
|
166
|
+
const mark = join(stateDir(), 'weekly.at');
|
|
167
|
+
let last = null;
|
|
168
|
+
try {
|
|
169
|
+
last = Number(readFileSync(mark, 'utf8'));
|
|
170
|
+
} catch {
|
|
171
|
+
/* never shown */
|
|
172
|
+
}
|
|
173
|
+
if (last !== null && now - last < 7 * 86400_000) return false;
|
|
174
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
175
|
+
writeFileSync(mark, String(now));
|
|
176
|
+
return last !== null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const avg = (/** @type {number[]} */ xs) => Math.round(xs.reduce((a, b) => a + b, 0) / xs.length);
|
|
180
|
+
const fmtK = (/** @type {number} */ n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* @param {{now:number, days:number, samples:Sample[], blocks:Block[], pro:boolean, saved:string|null, value?:string}} r
|
|
184
|
+
* blocks: every logged block (Pro blocks and free previews); saved: the starting-context text, if any;
|
|
185
|
+
* value: the "since you installed" section, shown first
|
|
186
|
+
*/
|
|
187
|
+
export function resultsReport({ now, days, samples, blocks, pro, saved, value = '' }) {
|
|
188
|
+
const when = (/** @type {number} */ ms) =>
|
|
189
|
+
new Date(ms).toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false });
|
|
190
|
+
const name = (/** @type {{src:string, win:string}} */ x) => `${NAMES[/** @type {'claude'} */ (x.src)] ?? x.src} ${x.win}`;
|
|
191
|
+
const out = value
|
|
192
|
+
? ['# limitcast results', '', value, '', `# Last ${days} day${days === 1 ? '' : 's'} in detail`]
|
|
193
|
+
: [`# limitcast results, last ${days} day${days === 1 ? '' : 's'}`];
|
|
194
|
+
|
|
195
|
+
const st = resultsStats({ now, days, samples, blocks, pro });
|
|
196
|
+
const { hits } = st;
|
|
197
|
+
out.push('', '## Limits reached');
|
|
198
|
+
if (!st.readings) out.push('No limit readings in this period. Is the status-line recorder installed? Run `limitcast doctor`.');
|
|
199
|
+
else if (!hits.length) out.push('None: no window reached 100%.');
|
|
200
|
+
else {
|
|
201
|
+
const watched = hits.filter((h) => !h.unseen);
|
|
202
|
+
const warned = hits.filter((h) => h.warnedAt !== null);
|
|
203
|
+
out.push(
|
|
204
|
+
`${hits.length} window${hits.length === 1 ? '' : 's'} reached 100%. ` +
|
|
205
|
+
(watched.length
|
|
206
|
+
? `Of the ${watched.length} limitcast watched on the way up, it forecast ${warned.length} in advance.`
|
|
207
|
+
: 'limitcast had no readings before any of them.'),
|
|
208
|
+
);
|
|
209
|
+
for (const h of hits) {
|
|
210
|
+
const lead = h.unseen
|
|
211
|
+
? 'already at 100% in the first reading limitcast saw'
|
|
212
|
+
: h.warnedAt === null
|
|
213
|
+
? 'no advance warning'
|
|
214
|
+
: `warned ${Math.round((h.at - h.warnedAt) / 60_000)} min ahead`;
|
|
215
|
+
out.push(`- ${name(h)}: hit ${when(h.at)}, ${lead}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
out.push('', pro ? '## Subagent guard' : '## Subagent guard (preview)');
|
|
220
|
+
const { outcomes } = st;
|
|
221
|
+
if (!outcomes.length)
|
|
222
|
+
out.push(
|
|
223
|
+
pro
|
|
224
|
+
? 'No subagents blocked in this period.'
|
|
225
|
+
: 'Nothing Pro would have blocked in this period. (`limitcast install --guard` records it; without Pro the guard never blocks.)',
|
|
226
|
+
);
|
|
227
|
+
else {
|
|
228
|
+
const n = (/** @type {string} */ o) => outcomes.filter((x) => x.outcome === o).length;
|
|
229
|
+
const count = `${outcomes.length} subagent spawn${outcomes.length === 1 ? '' : 's'}`;
|
|
230
|
+
out.push(
|
|
231
|
+
`${pro ? `${count} blocked` : `Pro would have blocked ${count} (your free install let them run)`}. Afterwards: ${n('hit')} window(s) reached 100% (the forecast was right), ` +
|
|
232
|
+
`${n('under')} reset without reaching 100% (${pro ? 'the block may have saved them, or' : 'here'} the forecast ran high), ${n('open')} still open.`,
|
|
233
|
+
);
|
|
234
|
+
for (const o of outcomes) {
|
|
235
|
+
const what =
|
|
236
|
+
o.outcome === 'hit'
|
|
237
|
+
? `reached 100% at ${when(/** @type {number} */ (o.hitAt))}`
|
|
238
|
+
: o.outcome === 'under'
|
|
239
|
+
? `reset at ${o.peak}%`
|
|
240
|
+
: `now at ${o.peak}%, resets ${when(o.reset)}`;
|
|
241
|
+
out.push(`- ${when(o.t)}: ${name(o)} at ${o.pct}%, forecast out in ~${Math.max(0, Math.round((o.wall - o.t) / 60_000))} min; ${what}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
out.push('', '## Starting context');
|
|
246
|
+
out.push(saved ?? 'Run `limitcast trim` once to record your starting context, then check back here.');
|
|
247
|
+
if (!pro && outcomes.length) out.push('', `Pro blocks those subagents before they use up your window: https://limitcast.dev/#pricing`);
|
|
248
|
+
if (days > 8) out.push('', 'Limit readings are kept for 8 days, so the first two sections cover at most the last 8 days.');
|
|
249
|
+
return out.join('\n');
|
|
250
|
+
}
|
package/src/value.mjs
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createReadStream, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
import { blockOutcomes, limitHits } from './results.mjs';
|
|
6
|
+
import { startupBreakdown } from './startup.mjs';
|
|
7
|
+
import { stateDir } from './store.mjs';
|
|
8
|
+
import { claudeUsage } from './usage.mjs';
|
|
9
|
+
|
|
10
|
+
// The value record: what limitcast did for you since you installed it, kept beyond the 8 days of raw readings.
|
|
11
|
+
// `results` shows it; a daily background rollup (started by the status line) keeps it current.
|
|
12
|
+
|
|
13
|
+
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
14
|
+
/** @typedef {import('./results.mjs').Block} Block */
|
|
15
|
+
/** @typedef {{at:number, turns:number, savedPerTurn:number}} SessionValue savedPerTurn: tokens below the first measured start */
|
|
16
|
+
/** @typedef {{src:string, win:string, at:number, lead:number|null, unseen:boolean}} HitValue lead: minutes of warning */
|
|
17
|
+
/** @typedef {{t:number, src:string, win:string, shadow:boolean, outcome:string}} BlockValue */
|
|
18
|
+
/** @typedef {{since:number, scanned:number, sessions:Record<string, SessionValue>, hits:Record<string, HitValue>, blocks:Record<string, BlockValue>}} Value */
|
|
19
|
+
|
|
20
|
+
const file = () => join(stateDir(), 'value.json');
|
|
21
|
+
const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
22
|
+
|
|
23
|
+
/** @returns {Value} */
|
|
24
|
+
export function loadValue() {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(readFileSync(file(), 'utf8'));
|
|
27
|
+
} catch {
|
|
28
|
+
return { since: 0, scanned: 0, sessions: {}, hits: {}, blocks: {} };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* True at most once a day (the status line uses it to start the rollup in the background).
|
|
34
|
+
* @param {number} now epoch ms
|
|
35
|
+
*/
|
|
36
|
+
export function dailyDue(now) {
|
|
37
|
+
const mark = join(stateDir(), 'value.at');
|
|
38
|
+
try {
|
|
39
|
+
if (now - Number(readFileSync(mark, 'utf8')) < 86400_000) return false;
|
|
40
|
+
} catch {
|
|
41
|
+
/* never rolled up */
|
|
42
|
+
}
|
|
43
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
44
|
+
writeFileSync(mark, String(now));
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** @param {Value} v */
|
|
49
|
+
export function saveValue(v) {
|
|
50
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
51
|
+
writeFileSync(file(), JSON.stringify(v));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Fold what the recent readings show into the record. Recent entries overwrite older ones: a block's
|
|
56
|
+
* outcome is "open" until its window resets, and a hit's warning only gets more complete.
|
|
57
|
+
* @param {Value} v
|
|
58
|
+
* @param {{now:number, samples:Sample[], blocks:Block[], start?:number}} r
|
|
59
|
+
* start: when limitcast started watching (the first status-line reading); defaults to the earliest sample
|
|
60
|
+
*/
|
|
61
|
+
export function foldEvents(v, { now, samples, blocks, start }) {
|
|
62
|
+
v.since ||= start ?? Math.min(now, ...samples.map((s) => s.t));
|
|
63
|
+
// As readings age out (8 days), a later look sees less: keep what was recorded while they all existed.
|
|
64
|
+
// Limits before limitcast was watching (Codex logs reach back further) are replays, not warnings you got.
|
|
65
|
+
for (const h of limitHits(samples).filter((x) => x.at >= v.since)) {
|
|
66
|
+
const key = `${h.src}|${h.win}|${Math.round(h.reset / 120_000)}`;
|
|
67
|
+
const prev = v.hits[key];
|
|
68
|
+
const lead = h.warnedAt === null ? null : Math.round((h.at - h.warnedAt) / 60_000);
|
|
69
|
+
v.hits[key] = {
|
|
70
|
+
src: h.src,
|
|
71
|
+
win: h.win,
|
|
72
|
+
at: prev?.at ?? h.at,
|
|
73
|
+
lead: prev && prev.lead !== null && (lead === null || prev.lead > lead) ? prev.lead : lead,
|
|
74
|
+
unseen: prev ? prev.unseen && h.unseen : h.unseen,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
for (const o of blockOutcomes(blocks, samples, now)) {
|
|
78
|
+
const prev = v.blocks[String(o.t)];
|
|
79
|
+
if (prev && prev.outcome !== 'open') continue; // final once the window reset
|
|
80
|
+
v.blocks[String(o.t)] = { t: o.t, src: o.src, win: o.win, shadow: Boolean(o.shadow), outcome: o.outcome };
|
|
81
|
+
}
|
|
82
|
+
return v;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* One interactive session's value: how many model calls it made on the main thread (each re-sends the whole
|
|
87
|
+
* starting context) and how much smaller its starting context was than the first one limitcast measured.
|
|
88
|
+
* @param {string} path transcript
|
|
89
|
+
* @param {number} baselineChars
|
|
90
|
+
* @returns {Promise<SessionValue|null>}
|
|
91
|
+
*/
|
|
92
|
+
export async function sessionValue(path, baselineChars) {
|
|
93
|
+
const b = await startupBreakdown(path);
|
|
94
|
+
if (b.entry !== 'cli' || !b.pieces.length) return null;
|
|
95
|
+
const chars = b.pieces.reduce((a, p) => a + p.chars, 0);
|
|
96
|
+
const seen = new Set();
|
|
97
|
+
let turns = 0;
|
|
98
|
+
const rl = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
|
|
99
|
+
for await (const line of rl) {
|
|
100
|
+
const u = claudeUsage(line, seen, '');
|
|
101
|
+
if (u && !u.sidechain) turns++;
|
|
102
|
+
}
|
|
103
|
+
return { at: b.at, turns, savedPerTurn: Math.max(0, tok(baselineChars - chars)) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Add sessions whose transcripts changed since the last scan (a session still running is re-read next time).
|
|
108
|
+
* @param {Value} v
|
|
109
|
+
* @param {{root:string, baseline:{at:number, chars:number}|null, now:number}} r
|
|
110
|
+
*/
|
|
111
|
+
export async function scanSessions(v, { root, baseline, now }) {
|
|
112
|
+
if (!baseline) return v;
|
|
113
|
+
try {
|
|
114
|
+
for (const proj of readdirSync(root, { withFileTypes: true })) {
|
|
115
|
+
if (!proj.isDirectory()) continue;
|
|
116
|
+
for (const f of readdirSync(join(root, proj.name), { withFileTypes: true })) {
|
|
117
|
+
if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
|
|
118
|
+
const p = join(root, proj.name, f.name);
|
|
119
|
+
const st = statSync(p);
|
|
120
|
+
if (st.mtimeMs < Math.max(baseline.at, v.scanned) || (st.birthtimeMs || st.mtimeMs) < baseline.at - 86400_000) continue;
|
|
121
|
+
const s = await sessionValue(p, baseline.chars);
|
|
122
|
+
if (s && s.at >= baseline.at) v.sessions[f.name.replace(/\.jsonl$/, '')] = s;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} catch {
|
|
126
|
+
/* unreadable root: keep what we have */
|
|
127
|
+
}
|
|
128
|
+
v.scanned = now;
|
|
129
|
+
return v;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @param {Value} v */
|
|
133
|
+
export function valueTotals(v) {
|
|
134
|
+
const sessions = Object.values(v.sessions);
|
|
135
|
+
const hits = Object.values(v.hits);
|
|
136
|
+
const leads = hits.flatMap((h) => (h.lead === null ? [] : [h.lead]));
|
|
137
|
+
const blocks = Object.values(v.blocks);
|
|
138
|
+
return {
|
|
139
|
+
since: v.since,
|
|
140
|
+
sessions: sessions.length,
|
|
141
|
+
turns: sessions.reduce((a, s) => a + s.turns, 0),
|
|
142
|
+
tokens: sessions.reduce((a, s) => a + s.turns * s.savedPerTurn, 0),
|
|
143
|
+
hits: hits.length,
|
|
144
|
+
watched: hits.filter((h) => !h.unseen).length,
|
|
145
|
+
leads,
|
|
146
|
+
blocked: blocks.filter((b) => !b.shadow).length,
|
|
147
|
+
previewed: blocks.filter((b) => b.shadow).length,
|
|
148
|
+
confirmed: blocks.filter((b) => b.outcome === 'hit').length,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The "since you installed" section at the top of `limitcast results`.
|
|
154
|
+
* @param {ReturnType<typeof valueTotals>} t
|
|
155
|
+
* @param {{now:number, pro:boolean}} o
|
|
156
|
+
*/
|
|
157
|
+
export function valueSection(t, { now, pro }) {
|
|
158
|
+
if (!t.since) return '';
|
|
159
|
+
const days = Math.max(1, Math.round((now - t.since) / 86400_000));
|
|
160
|
+
const out = [`## Since limitcast started watching (${new Date(t.since).toLocaleDateString()}, ${days} day${days === 1 ? '' : 's'})`];
|
|
161
|
+
if (t.tokens > 0) {
|
|
162
|
+
out.push(
|
|
163
|
+
`- **${fmtBig(t.tokens)} tokens not re-sent.** Your sessions now start smaller than the first one limitcast measured, and Claude Code re-sends the starting context on every model call: ${t.turns.toLocaleString()} calls across ${t.sessions} sessions. (Most of it would have been cached input.)`,
|
|
164
|
+
);
|
|
165
|
+
} else if (t.sessions) {
|
|
166
|
+
out.push(`- Starting context: no smaller than when limitcast first measured it. \`limitcast trim\` shows what to cut.`);
|
|
167
|
+
}
|
|
168
|
+
if (t.hits) {
|
|
169
|
+
const avg = t.leads.length ? `, on average ${fmtMin(t.leads.reduce((a, b) => a + b, 0) / t.leads.length)} ahead` : '';
|
|
170
|
+
out.push(
|
|
171
|
+
`- **Warned you before ${t.leads.length} of the ${t.watched} limits it watched you approach**${avg}. (${t.hits} limits reached in all.)`,
|
|
172
|
+
);
|
|
173
|
+
} else out.push('- No limit reached yet.');
|
|
174
|
+
if (pro) {
|
|
175
|
+
out.push(
|
|
176
|
+
t.blocked
|
|
177
|
+
? `- **Stopped ${t.blocked} subagent${t.blocked === 1 ? '' : 's'}** while a window was about to run out${t.confirmed ? ` (${t.confirmed} of those windows hit 100% anyway, so the forecast was right)` : ''}.`
|
|
178
|
+
: "- The guard hasn't needed to stop a subagent yet.",
|
|
179
|
+
);
|
|
180
|
+
} else if (t.previewed) {
|
|
181
|
+
out.push(`- **Pro would have stopped ${t.previewed} subagent${t.previewed === 1 ? '' : 's'}** while a window was about to run out.`);
|
|
182
|
+
}
|
|
183
|
+
return out.join('\n');
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** @param {number} n */
|
|
187
|
+
export const fmtBig = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : `${n}`);
|
|
188
|
+
/** @param {number} m minutes */
|
|
189
|
+
const fmtMin = (m) => (m >= 90 ? `${(m / 60).toFixed(1)} h` : `${Math.round(m)} min`);
|