limitcast 0.9.2 → 0.10.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 +7 -4
- package/bin/limitcast.mjs +179 -17
- package/package.json +32 -8
- package/src/apply.mjs +46 -0
- package/src/calibrate.mjs +69 -0
- package/src/install.mjs +88 -8
- package/src/license.mjs +41 -2
- package/src/usage.mjs +71 -14
- package/src/value.mjs +14 -1
package/README.md
CHANGED
|
@@ -32,13 +32,15 @@ Requires Node 20+ on macOS or Linux.
|
|
|
32
32
|
## Install
|
|
33
33
|
|
|
34
34
|
```sh
|
|
35
|
-
npm install -g limitcast
|
|
35
|
+
npm install -g limitcast # or: brew install samstull9007/limitcast/limitcast
|
|
36
36
|
limitcast install # free: status-line recorder
|
|
37
|
-
limitcast activate <key>
|
|
37
|
+
limitcast trial # Pro free for 7 days, no card (or: limitcast activate <key>)
|
|
38
38
|
limitcast install --guard # also the subagent guard (free: preview only)
|
|
39
39
|
limitcast doctor
|
|
40
40
|
```
|
|
41
41
|
|
|
42
|
+
In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast:results` and `/limitcast:trim`: `/plugin marketplace add SamStull9007/limitcast`, then `/plugin install limitcast@limitcast`. The status-line recorder still comes from `limitcast install`.
|
|
43
|
+
|
|
42
44
|
`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.
|
|
43
45
|
|
|
44
46
|
**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.
|
|
@@ -55,7 +57,8 @@ limitcast doctor
|
|
|
55
57
|
| `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
|
|
56
58
|
| `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
|
|
57
59
|
| `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
|
|
58
|
-
| `limitcast doctor` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads |
|
|
60
|
+
| `limitcast doctor [--fix]` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads. Also runs daily in the background and flags problems in the status line. `--fix` re-installs with the current Node (after a Node upgrade) |
|
|
61
|
+
| `limitcast trial` | Pro free for 7 days on this computer, no card, once |
|
|
59
62
|
| `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
|
|
60
63
|
| `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 |
|
|
61
64
|
| `limitcast saved` | **Pro.** How much the part of your starting context you control has dropped since limitcast first measured it, times your sessions since |
|
|
@@ -76,7 +79,7 @@ Each limit reading is saved to `~/.local/state/limitcast/samples.jsonl` when it
|
|
|
76
79
|
|
|
77
80
|
## Pricing
|
|
78
81
|
|
|
79
|
-
Free: runout forecast with NEAR warnings and the daily allowance, status-line readout, your starting-context total with how much you never use (Claude Code and Codex), `results`, and a preview of the guard. Pro ($79/year or $9/month, 14 days free): names what to cut and cuts it (`trim --apply`, also for Codex), a subagent guard that blocks and switches to Sonnet, burn report, alerts, a weekly summary, notifications, after-reset jobs, account headroom, the `/compact` nudge and the HTML dashboard. Cancel anytime; 14-day refund on any charge: email support@limitcast.dev. See https://limitcast.dev.
|
|
82
|
+
Free: runout forecast with NEAR warnings and the daily allowance, status-line readout, your starting-context total with how much you never use (Claude Code and Codex), `results`, and a preview of the guard. Pro ($79/year or $9/month, 14 days free; or `limitcast trial` for 7 days, no card; Team $69/seat/year, 3 seats minimum): names what to cut and cuts it (`trim --apply`, also for Codex), a subagent guard that blocks and switches to Sonnet, burn report, alerts, a weekly summary, notifications, after-reset jobs, account headroom, the `/compact` nudge and the HTML dashboard. Cancel anytime; 14-day refund on any charge: email support@limitcast.dev. See https://limitcast.dev.
|
|
80
83
|
|
|
81
84
|
## License
|
|
82
85
|
|
package/bin/limitcast.mjs
CHANGED
|
@@ -11,18 +11,20 @@ import {
|
|
|
11
11
|
localSkillFolders,
|
|
12
12
|
planTrim,
|
|
13
13
|
projectMcpServers,
|
|
14
|
+
reapplyTrim,
|
|
14
15
|
stillLoading,
|
|
15
16
|
transcriptCwd,
|
|
16
17
|
undoTrim,
|
|
17
18
|
} from '../src/apply.mjs';
|
|
19
|
+
import { calibrate } from '../src/calibrate.mjs';
|
|
18
20
|
import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
|
|
19
21
|
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
20
22
|
import { formatChecks } from '../src/formats.mjs';
|
|
21
23
|
import { runGuard } from '../src/guard.mjs';
|
|
22
24
|
import { accountForecasts, compactHint, headroom, lastCallTokens } from '../src/hints.mjs';
|
|
23
25
|
import { htmlPage } from '../src/html.mjs';
|
|
24
|
-
import { doctor, install, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
25
|
-
import { activate, currentLicense, isPro, UPGRADE_URL } from '../src/license.mjs';
|
|
26
|
+
import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
27
|
+
import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
|
|
26
28
|
import { buildNotifierApp, notifierApp, notifyChanges, notifyEnabled, send, setNotify } from '../src/notify.mjs';
|
|
27
29
|
import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
|
|
28
30
|
import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
|
|
@@ -41,8 +43,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
|
|
|
41
43
|
limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex); backs up settings
|
|
42
44
|
(without Pro the guard is a preview: it records what it would block, never blocks)
|
|
43
45
|
limitcast uninstall remove it and restore your original status line
|
|
44
|
-
limitcast doctor
|
|
45
|
-
limitcast
|
|
46
|
+
limitcast doctor [--fix] check the setup (--fix: re-install with this Node, e.g. after a Node upgrade)
|
|
47
|
+
limitcast trial Pro free for 7 days on this computer, no card
|
|
48
|
+
limitcast status [--json] used, burn rate, runout time, reset, and today's share of each weekly window
|
|
46
49
|
limitcast trim [--share] tokens every session loads before you type, and how much you never use
|
|
47
50
|
limitcast trim --codex the same for Codex: AGENTS.md size and MCP servers you haven't used
|
|
48
51
|
limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
|
|
@@ -113,6 +116,8 @@ if (cmd === 'status') {
|
|
|
113
116
|
if (refreshDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'license'], { detached: true, stdio: 'ignore' }).unref();
|
|
114
117
|
// Readings are kept 8 days; the daily rollup folds what they showed into the long-term value record.
|
|
115
118
|
if (dailyDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'rollup'], { detached: true, stdio: 'ignore' }).unref();
|
|
119
|
+
const health = healthHint();
|
|
120
|
+
if (health) hints.push(health);
|
|
116
121
|
if (isPro()) {
|
|
117
122
|
const samples = load(now - KEEP_MS);
|
|
118
123
|
if (notifyEnabled()) notifyChanges(forecastAll(oneClaudeAccount(samples, sid), now), clock);
|
|
@@ -120,6 +125,9 @@ if (cmd === 'status') {
|
|
|
120
125
|
if (room) hints.push(room);
|
|
121
126
|
const ctx = typeof feed?.transcript_path === 'string' ? compactHint(lastCallTokens(feed.transcript_path)) : null;
|
|
122
127
|
if (ctx) hints.push(ctx);
|
|
128
|
+
} else {
|
|
129
|
+
const week = freeWeeklyHint(now);
|
|
130
|
+
if (week) hints.push(week);
|
|
123
131
|
}
|
|
124
132
|
} catch {
|
|
125
133
|
/* never break the status line */
|
|
@@ -128,7 +136,7 @@ if (cmd === 'status') {
|
|
|
128
136
|
const wrapped = sep >= 0 ? args.slice(sep + 1) : [];
|
|
129
137
|
if (wrapped.length) {
|
|
130
138
|
const r = spawnSync(wrapped[0], wrapped.slice(1), { input, stdio: ['pipe', 'inherit', 'inherit'] });
|
|
131
|
-
// Your status line stays as it was;
|
|
139
|
+
// Your status line stays as it was; limitcast adds a second line only when there is something to act on.
|
|
132
140
|
if (hints.length) console.log(`limitcast: ${hints.join(' · ')}`);
|
|
133
141
|
process.exit(r.status ?? 1);
|
|
134
142
|
}
|
|
@@ -168,24 +176,55 @@ if (cmd === 'status') {
|
|
|
168
176
|
if (wantAlerts && !isPro()) console.log(`Alerts and the weekly summary are part of limitcast Pro (${UPGRADE_URL}). Skipping them.`);
|
|
169
177
|
for (const c of install({ guard: wantGuard, alerts: wantAlerts && isPro() })) console.log(`✓ ${c}`);
|
|
170
178
|
console.log('Restart Claude Code and Codex to load it. Then: limitcast doctor');
|
|
179
|
+
// First run: show the number that matters right away, and what comes next.
|
|
180
|
+
try {
|
|
181
|
+
const latest = await latestInteractiveTranscript(claudeRoot());
|
|
182
|
+
if (latest) {
|
|
183
|
+
recordOverhead(snapshot(latest));
|
|
184
|
+
/** @type {Map<string, number>} */
|
|
185
|
+
const groups = new Map();
|
|
186
|
+
for (const p of latest.pieces) groups.set(p.group, (groups.get(p.group) ?? 0) + p.chars);
|
|
187
|
+
const k = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
188
|
+
const total = [...groups.values()].reduce((a, c) => a + c, 0);
|
|
189
|
+
const top = [...groups].sort((a, b) => b[1] - a[1]).slice(0, 3);
|
|
190
|
+
console.log(
|
|
191
|
+
[
|
|
192
|
+
'',
|
|
193
|
+
`Your last Claude Code session loaded ~${k(total)} tokens of hooks, MCP servers, skills and instruction files before you typed`,
|
|
194
|
+
`(biggest: ${top.map(([g, c]) => `${g} ${k(c)}`).join(', ')}). It's re-sent on every turn and to every subagent.`,
|
|
195
|
+
'See what you never use: limitcast trim',
|
|
196
|
+
].join('\n'),
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
} catch {
|
|
200
|
+
/* no transcripts yet */
|
|
201
|
+
}
|
|
202
|
+
console.log(
|
|
203
|
+
`In a week, \`limitcast results\` shows every limit you hit and how far ahead limitcast warned you.${isPro() ? '' : ' Try Pro free for 7 days, no card: limitcast trial'}`,
|
|
204
|
+
);
|
|
171
205
|
} else if (cmd === 'uninstall') {
|
|
172
206
|
const changes = uninstall();
|
|
173
207
|
console.log(changes.length ? changes.map((c) => `✓ ${c}`).join('\n') : 'Nothing to remove.');
|
|
174
208
|
} else if (cmd === 'doctor') {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
209
|
+
if (args.includes('--fix')) {
|
|
210
|
+
// Re-install what is installed, with this Node and this copy of limitcast (after a Node upgrade, say).
|
|
211
|
+
const f = installedFeatures();
|
|
212
|
+
if (!f.statusLine) console.log('limitcast is not installed. Run `limitcast install` first.');
|
|
213
|
+
else {
|
|
214
|
+
for (const c of install({ guard: f.guard && isPro(), alerts: f.alerts && isPro() })) console.log(`✓ ${c}`);
|
|
215
|
+
console.log('Restart Claude Code to load it. Codex asks you to approve the guard again: start Codex and accept it.');
|
|
216
|
+
}
|
|
181
217
|
}
|
|
182
|
-
const checks =
|
|
218
|
+
const checks = await healthChecks();
|
|
219
|
+
saveHealth(checks);
|
|
183
220
|
for (const c of checks) console.log(`${c.ok ? '✓' : '✗'} ${c.line}`);
|
|
184
221
|
process.exit(checks.every((c) => c.ok) ? 0 : 1);
|
|
185
222
|
} else if (cmd === 'report' || cmd === 'trim') {
|
|
186
223
|
const pro = isPro();
|
|
187
224
|
if (!pro && cmd === 'report') {
|
|
188
|
-
console.log(
|
|
225
|
+
console.log(
|
|
226
|
+
`\`limitcast ${cmd}\` is part of limitcast Pro: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`,
|
|
227
|
+
);
|
|
189
228
|
process.exit(2);
|
|
190
229
|
}
|
|
191
230
|
const since = now - days() * 86400_000;
|
|
@@ -234,7 +273,9 @@ if (cmd === 'status') {
|
|
|
234
273
|
}
|
|
235
274
|
if (args.includes('--apply') || args.includes('--undo')) {
|
|
236
275
|
if (!pro) {
|
|
237
|
-
console.log(
|
|
276
|
+
console.log(
|
|
277
|
+
`\`limitcast trim --apply\` is part of limitcast Pro: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`,
|
|
278
|
+
);
|
|
238
279
|
process.exit(2);
|
|
239
280
|
}
|
|
240
281
|
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
|
|
@@ -243,7 +284,7 @@ if (cmd === 'status') {
|
|
|
243
284
|
if (latest && (args.includes('--share') || !pro)) text = shareSummary(baseline(usage), latest, used, days());
|
|
244
285
|
else text = latest ? startupReport(baseline(usage), latest, used, days()) : trimReport(baseline(usage), contributors(), used, days());
|
|
245
286
|
if (!pro)
|
|
246
|
-
text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\
|
|
287
|
+
text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`;
|
|
247
288
|
else if (latest && !args.includes('--share')) {
|
|
248
289
|
const still = stillLoading(latest);
|
|
249
290
|
text += still.length
|
|
@@ -270,6 +311,12 @@ if (cmd === 'status') {
|
|
|
270
311
|
const d = latest ? recordOverhead(snapshot(latest)) : null;
|
|
271
312
|
if (hook) {
|
|
272
313
|
const lines = d?.alert ? [driftMessage(d)] : [];
|
|
314
|
+
// Claude Code may have rewritten the files `trim --apply` changed: put the cuts back for the next session.
|
|
315
|
+
const re = reapplyTrim();
|
|
316
|
+
if (re.reapplied.length)
|
|
317
|
+
lines.push(
|
|
318
|
+
`limitcast: Claude Code had undone ${re.reapplied.length} of your trim cuts; they're back from your next session. (limitcast trim --undo to drop them)`,
|
|
319
|
+
);
|
|
273
320
|
// Once a week, what limitcast did: shown to the user at session start, never to the model.
|
|
274
321
|
if (weeklyDue(now)) {
|
|
275
322
|
const since = now - 7 * 86400_000;
|
|
@@ -414,7 +461,13 @@ if (cmd === 'status') {
|
|
|
414
461
|
const r = spawnSync(command[0], command.slice(1), { stdio: 'inherit' });
|
|
415
462
|
process.exit(r.status ?? 1);
|
|
416
463
|
} else if (cmd === 'rollup') {
|
|
417
|
-
// Started daily in the background by the status line: keeps the value record current
|
|
464
|
+
// Started daily in the background by the status line: keeps the value record current and checks the setup.
|
|
465
|
+
// Never prints.
|
|
466
|
+
try {
|
|
467
|
+
saveHealth(await healthChecks());
|
|
468
|
+
} catch {
|
|
469
|
+
/* next time */
|
|
470
|
+
}
|
|
418
471
|
try {
|
|
419
472
|
await refreshValue();
|
|
420
473
|
} catch {
|
|
@@ -432,7 +485,29 @@ if (cmd === 'status') {
|
|
|
432
485
|
process.exit(res.ok ? 0 : 1);
|
|
433
486
|
} else if (cmd === 'license') {
|
|
434
487
|
const l = currentLicense();
|
|
435
|
-
console.log(l === null ?
|
|
488
|
+
console.log(l === null ? trialLine() : l.ok ? `Pro: ${l.claims.e}` : `License problem: ${l.reason}`);
|
|
489
|
+
} else if (cmd === 'trial') {
|
|
490
|
+
// Pro for 7 days on this machine, no card, once.
|
|
491
|
+
if (currentLicense()?.ok) {
|
|
492
|
+
console.log('You already have Pro.');
|
|
493
|
+
process.exit(0);
|
|
494
|
+
}
|
|
495
|
+
const t = startTrial(now);
|
|
496
|
+
if (!t.ok) {
|
|
497
|
+
console.log(t.active ? `Your Pro trial is already running, until ${clock(t.ends)}.` : trialLine());
|
|
498
|
+
process.exit(t.active ? 0 : 2);
|
|
499
|
+
}
|
|
500
|
+
console.log(
|
|
501
|
+
[
|
|
502
|
+
`✓ Pro trial on: 7 days, until ${new Date(t.ends).toLocaleDateString()}. No card, nothing to cancel.`,
|
|
503
|
+
'Try it:',
|
|
504
|
+
' limitcast install --guard --alerts block runaway subagents, move them to Sonnet when a window is tight',
|
|
505
|
+
' limitcast trim --apply cut the context you never use (limitcast trim --undo reverses it)',
|
|
506
|
+
' limitcast notify on a desktop notification before you hit a limit',
|
|
507
|
+
' limitcast results what it did for you, any time',
|
|
508
|
+
`Keep Pro after the trial: ${UPGRADE_URL}`,
|
|
509
|
+
].join('\n'),
|
|
510
|
+
);
|
|
436
511
|
} else if (cmd === '--version' || cmd === '-v') {
|
|
437
512
|
console.log(VERSION);
|
|
438
513
|
} else {
|
|
@@ -440,6 +515,90 @@ if (cmd === 'status') {
|
|
|
440
515
|
process.exit(cmd && !['help', '--help', '-h'].includes(cmd) ? 1 : 0);
|
|
441
516
|
}
|
|
442
517
|
|
|
518
|
+
/** Everything `doctor` checks: setup, data freshness, license, and whether each tool's logs still parse. */
|
|
519
|
+
async function healthChecks() {
|
|
520
|
+
// Readings are only stored when they change, so freshness comes from the last feed the status line saw.
|
|
521
|
+
let latest = 0;
|
|
522
|
+
try {
|
|
523
|
+
latest = JSON.parse(readFileSync(join(stateDir(), 'last-feed.json'), 'utf8')).at ?? 0;
|
|
524
|
+
} catch {
|
|
525
|
+
/* never fed */
|
|
526
|
+
}
|
|
527
|
+
const license = currentLicense();
|
|
528
|
+
const checks = doctor({ samplesAgeMs: latest ? now - latest : null, license });
|
|
529
|
+
if (license === null && trialStatus(now)) checks.push({ ok: true, line: trialLine() });
|
|
530
|
+
return [...checks, ...(await formatChecks())];
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Remember the failing checks that need the user (not just "no reading yet": that fixes itself), for the
|
|
535
|
+
* status-line hint, and notify once when a new one appears.
|
|
536
|
+
* @param {{ok:boolean, line:string}[]} checks
|
|
537
|
+
*/
|
|
538
|
+
function saveHealth(checks) {
|
|
539
|
+
const file = join(stateDir(), 'health.json');
|
|
540
|
+
const failed = checks.filter((c) => !c.ok && !/^(No Claude limit readings|Last Claude reading)/.test(c.line)).map((c) => c.line);
|
|
541
|
+
let before = [];
|
|
542
|
+
try {
|
|
543
|
+
before = JSON.parse(readFileSync(file, 'utf8')).failed ?? [];
|
|
544
|
+
} catch {
|
|
545
|
+
/* first check */
|
|
546
|
+
}
|
|
547
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
548
|
+
writeFileSync(file, JSON.stringify({ at: now, failed }));
|
|
549
|
+
const fresh = failed.filter((l) => !before.includes(l));
|
|
550
|
+
if (fresh.length && isPro() && notifyEnabled()) send(`limitcast needs a fix: ${fresh[0]} Run: limitcast doctor`);
|
|
551
|
+
return failed;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Free installs: for one day a week, what the guard preview saw Pro would have done, e.g.
|
|
556
|
+
* "this week Pro would have stopped 2 subagents and moved 5 to Sonnet · limitcast trial". Silent when it's nothing.
|
|
557
|
+
* @param {number} t epoch ms
|
|
558
|
+
*/
|
|
559
|
+
function freeWeeklyHint(t) {
|
|
560
|
+
const file = join(stateDir(), 'free-weekly.json');
|
|
561
|
+
let from = 0;
|
|
562
|
+
try {
|
|
563
|
+
from = JSON.parse(readFileSync(file, 'utf8')).from ?? 0;
|
|
564
|
+
} catch {
|
|
565
|
+
/* first run: start the clock */
|
|
566
|
+
}
|
|
567
|
+
const WEEK = 7 * 86400_000;
|
|
568
|
+
if (!from || t >= from + 86400_000) {
|
|
569
|
+
// First run starts a week out; afterwards the next day-long showing is a week after this one.
|
|
570
|
+
from = from ? from + Math.ceil((t - from - 86400_000 + 1) / WEEK) * WEEK : t + WEEK;
|
|
571
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
572
|
+
writeFileSync(file, JSON.stringify({ from }));
|
|
573
|
+
}
|
|
574
|
+
if (t < from) return null;
|
|
575
|
+
const preview = loadBlocks(t - WEEK).filter((b) => b.shadow);
|
|
576
|
+
const stopped = preview.filter((b) => b.kind !== 'switch').length;
|
|
577
|
+
const moved = preview.length - stopped;
|
|
578
|
+
if (!stopped && !moved) return null;
|
|
579
|
+
const parts = [stopped ? `stopped ${stopped} subagent${stopped === 1 ? '' : 's'}` : '', moved ? `moved ${moved} to Sonnet` : ''].filter(Boolean);
|
|
580
|
+
return `this week Pro would have ${parts.join(' and ')} · limitcast trial`;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** Free tier, a running trial, or an ended one, in one line. */
|
|
584
|
+
function trialLine() {
|
|
585
|
+
const t = trialStatus(now);
|
|
586
|
+
if (!t) return `Free tier. Try Pro free for 7 days, no card: limitcast trial. Buy: ${UPGRADE_URL}`;
|
|
587
|
+
if (t.active)
|
|
588
|
+
return `Pro trial: ${Math.ceil((t.ends - now) / 86400_000)} days left (until ${new Date(t.ends).toLocaleDateString()}). Keep Pro: ${UPGRADE_URL}`;
|
|
589
|
+
return `Pro trial ended ${new Date(t.ends).toLocaleDateString()}. Keep Pro: ${UPGRADE_URL}`;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** The status-line hint while the last health check found something to fix. */
|
|
593
|
+
function healthHint() {
|
|
594
|
+
try {
|
|
595
|
+
const { failed } = JSON.parse(readFileSync(join(stateDir(), 'health.json'), 'utf8'));
|
|
596
|
+
return failed?.length ? '⚠ run limitcast doctor' : null;
|
|
597
|
+
} catch {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
443
602
|
/** Fold the last 8 days of readings and blocks, and any new sessions, into the long-term value record. */
|
|
444
603
|
async function refreshValue() {
|
|
445
604
|
const since = now - KEEP_MS;
|
|
@@ -449,6 +608,9 @@ async function refreshValue() {
|
|
|
449
608
|
const start = Math.min(now, o?.first.at ?? now, ...claude.map((s) => s.t));
|
|
450
609
|
const v = foldEvents(loadValue(), { now, samples: [...claude, ...(await readCodex(since))], blocks: loadBlocks(since), start });
|
|
451
610
|
await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
|
|
611
|
+
// Recalibrate from the last 8 days when there is enough data; keep the last good calibration otherwise.
|
|
612
|
+
const c = calibrate(claude, await readUsage(since, {}));
|
|
613
|
+
if (c) v.calib = { ...c, at: now };
|
|
452
614
|
saveValue(v);
|
|
453
615
|
return v;
|
|
454
616
|
}
|
package/package.json
CHANGED
|
@@ -1,16 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.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
|
-
"bin": {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
"
|
|
10
|
-
|
|
11
|
-
|
|
6
|
+
"bin": {
|
|
7
|
+
"limitcast": "bin/limitcast.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=20"
|
|
15
|
+
},
|
|
16
|
+
"os": [
|
|
17
|
+
"darwin",
|
|
18
|
+
"linux"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "node --test"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"claude-code",
|
|
25
|
+
"codex",
|
|
26
|
+
"rate-limit",
|
|
27
|
+
"usage-limit",
|
|
28
|
+
"tokens",
|
|
29
|
+
"hooks",
|
|
30
|
+
"status-line",
|
|
31
|
+
"ai-agents"
|
|
32
|
+
],
|
|
12
33
|
"homepage": "https://limitcast.dev",
|
|
13
|
-
"repository": {
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/SamStull9007/limitcast.git"
|
|
37
|
+
},
|
|
14
38
|
"author": "Sam Stull",
|
|
15
39
|
"license": "Elastic-2.0"
|
|
16
40
|
}
|
package/src/apply.mjs
CHANGED
|
@@ -189,6 +189,52 @@ export function undoTrim({ settings = settingsPath(), claudeJson = claudeJsonPat
|
|
|
189
189
|
return last;
|
|
190
190
|
}
|
|
191
191
|
|
|
192
|
+
/**
|
|
193
|
+
* Keep the last --apply in place. A running Claude Code session can rewrite ~/.claude.json (or settings) and drop
|
|
194
|
+
* every change at once: then put them back. When only some are gone, you turned those back on yourself (/mcp,
|
|
195
|
+
* /skills): leave them and forget them, so limitcast never fights your choice. Checked per file.
|
|
196
|
+
* @param {{settings?:string, claudeJson?:string}} [o]
|
|
197
|
+
* @returns {{reapplied:string[], released:string[]}}
|
|
198
|
+
*/
|
|
199
|
+
export function reapplyTrim({ settings = settingsPath(), claudeJson = claudeJsonPath() } = {}) {
|
|
200
|
+
const ledger = loadLedger();
|
|
201
|
+
const last = ledger.at(-1);
|
|
202
|
+
const out = { reapplied: /** @type {string[]} */ ([]), released: /** @type {string[]} */ ([]) };
|
|
203
|
+
if (!last) return out;
|
|
204
|
+
if (last.skills.length && existsSync(settings)) {
|
|
205
|
+
const cfg = readSettings(settings);
|
|
206
|
+
const gone = last.skills.filter((s) => cfg.skillOverrides?.[s.name] !== 'user-invocable-only');
|
|
207
|
+
if (gone.length === last.skills.length) {
|
|
208
|
+
cfg.skillOverrides ??= {};
|
|
209
|
+
for (const s of gone) cfg.skillOverrides[s.name] = 'user-invocable-only';
|
|
210
|
+
backup(settings);
|
|
211
|
+
writeJson(settings, cfg);
|
|
212
|
+
out.reapplied.push(...gone.map((s) => s.name));
|
|
213
|
+
} else if (gone.length) {
|
|
214
|
+
last.skills = last.skills.filter((s) => !gone.includes(s));
|
|
215
|
+
out.released.push(...gone.map((s) => s.name));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (last.mcp.length && existsSync(claudeJson)) {
|
|
219
|
+
const cj = readSettings(claudeJson);
|
|
220
|
+
const list = cj.projects?.[last.cwd]?.disabledMcpServers ?? [];
|
|
221
|
+
const gone = last.mcp.filter((n) => !list.includes(n));
|
|
222
|
+
if (gone.length === last.mcp.length) {
|
|
223
|
+
cj.projects ??= {};
|
|
224
|
+
cj.projects[last.cwd] ??= {};
|
|
225
|
+
cj.projects[last.cwd].disabledMcpServers = [...list, ...gone];
|
|
226
|
+
backup(claudeJson);
|
|
227
|
+
writeJson(claudeJson, cj);
|
|
228
|
+
out.reapplied.push(...gone);
|
|
229
|
+
} else if (gone.length) {
|
|
230
|
+
last.mcp = last.mcp.filter((n) => !gone.includes(n));
|
|
231
|
+
out.released.push(...gone);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (out.released.length) writeJson(ledgerPath(), ledger);
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
|
|
192
238
|
/**
|
|
193
239
|
* Items an earlier --apply turned off that still loaded in a session started after it
|
|
194
240
|
* (for example, a running Claude Code session rewrote ~/.claude.json).
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { claudeAccounts } from './forecast.mjs';
|
|
3
|
+
|
|
4
|
+
// How many tokens move this user's Claude 5-hour meter by 1%, from their own readings and transcripts.
|
|
5
|
+
// Each pair of consecutive readings of one account's window where usage rose is one observation: the rise
|
|
6
|
+
// against the tokens that account's sessions used in between, split into new tokens (input, cache writes,
|
|
7
|
+
// output) and cache reads, which count far less. Least squares with no intercept gives % per token of each.
|
|
8
|
+
|
|
9
|
+
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
10
|
+
/** @typedef {import('./usage.mjs').Usage} Usage */
|
|
11
|
+
|
|
12
|
+
const MIN_OBS = 30;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {Sample[]} samples
|
|
16
|
+
* @param {Usage[]} usage
|
|
17
|
+
* @returns {{fresh:number, read:number, n:number}|null} % of the 5h window per million new / cached tokens
|
|
18
|
+
*/
|
|
19
|
+
export function calibrate(samples, usage) {
|
|
20
|
+
const obs = [];
|
|
21
|
+
const claude = usage.filter((u) => u.src === 'claude').sort((a, b) => a.t - b.t);
|
|
22
|
+
for (const acct of claudeAccounts(samples)) {
|
|
23
|
+
const sids = new Set(acct.map((s) => s.sid));
|
|
24
|
+
const mine = claude.filter((u) => sids.has(u.session));
|
|
25
|
+
const w5 = acct.filter((s) => s.win === '5h').sort((a, b) => a.t - b.t);
|
|
26
|
+
for (let i = 1; i < w5.length; i++) {
|
|
27
|
+
const p = w5[i - 1];
|
|
28
|
+
const c = w5[i];
|
|
29
|
+
if (Math.abs(c.reset - p.reset) > 120 || c.pct <= p.pct) continue;
|
|
30
|
+
let f = 0;
|
|
31
|
+
let r = 0;
|
|
32
|
+
for (const u of mine) {
|
|
33
|
+
if (u.t <= p.t) continue;
|
|
34
|
+
if (u.t > c.t) break;
|
|
35
|
+
f += u.input + u.cacheWrite + u.output;
|
|
36
|
+
r += u.cacheRead;
|
|
37
|
+
}
|
|
38
|
+
if (f + r > 0) obs.push({ d: c.pct - p.pct, f: f / 1e6, r: r / 1e6 });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (obs.length < MIN_OBS) return null;
|
|
42
|
+
let ff = 0;
|
|
43
|
+
let rr = 0;
|
|
44
|
+
let fr = 0;
|
|
45
|
+
let fd = 0;
|
|
46
|
+
let rd = 0;
|
|
47
|
+
for (const o of obs) {
|
|
48
|
+
ff += o.f * o.f;
|
|
49
|
+
rr += o.r * o.r;
|
|
50
|
+
fr += o.f * o.r;
|
|
51
|
+
fd += o.f * o.d;
|
|
52
|
+
rd += o.r * o.d;
|
|
53
|
+
}
|
|
54
|
+
const det = ff * rr - fr * fr;
|
|
55
|
+
if (!det) return null;
|
|
56
|
+
const fresh = (fd * rr - rd * fr) / det;
|
|
57
|
+
const read = (rd * ff - fd * fr) / det;
|
|
58
|
+
// Both must count, and new tokens must count more than cached ones; anything else is noise, not a calibration.
|
|
59
|
+
if (!(fresh > 0 && read > 0 && fresh > read)) return null;
|
|
60
|
+
return { fresh, read, n: obs.length };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* What a smaller starting context was worth against the 5-hour limit, in % of one window: each session writes its
|
|
65
|
+
* starting context once (new tokens) and re-reads it on every call (cached tokens).
|
|
66
|
+
* @param {{fresh:number, read:number}} c
|
|
67
|
+
* @param {{writes:number, reads:number}} saved tokens not written / not re-read
|
|
68
|
+
*/
|
|
69
|
+
export const windowPct = (c, saved) => (saved.writes / 1e6) * c.fresh + (saved.reads / 1e6) * c.read;
|
package/src/install.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeF
|
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { stateDir } from './store.mjs';
|
|
6
7
|
|
|
7
8
|
export const settingsPath = () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'settings.json');
|
|
8
9
|
export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'hooks.json');
|
|
@@ -13,10 +14,62 @@ const CODEX_MATCHER = '.*spawn_agent.*';
|
|
|
13
14
|
/** Shell-quote one argument. @param {string} s */
|
|
14
15
|
const q = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
|
15
16
|
|
|
16
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* The command hooks run: a launcher script in the state dir that runs this copy of limitcast (absolute node +
|
|
19
|
+
* script, so hooks work without PATH) and outlives a Node upgrade, which moves both under nvm and Homebrew.
|
|
20
|
+
*/
|
|
17
21
|
export function selfCommand() {
|
|
18
|
-
|
|
19
|
-
|
|
22
|
+
return `/bin/sh ${q(writeLauncher())}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const launcherPath = () => join(stateDir(), 'limitcast-hook.sh');
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Write the hook launcher. If this node or script is gone, it runs `limitcast` from PATH; if that is gone too,
|
|
29
|
+
* the status line still runs your own wrapped command and every other hook allows (exit 0).
|
|
30
|
+
* @returns {string} its path
|
|
31
|
+
*/
|
|
32
|
+
export function writeLauncher(node = process.execPath, bin = realpathSync(fileURLToPath(new URL('../bin/limitcast.mjs', import.meta.url)))) {
|
|
33
|
+
const path = launcherPath();
|
|
34
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
35
|
+
writeFileSync(
|
|
36
|
+
path,
|
|
37
|
+
[
|
|
38
|
+
'#!/bin/sh',
|
|
39
|
+
'# limitcast hook launcher, written by `limitcast install`. Survives Node upgrades.',
|
|
40
|
+
`NODE=${q(node)}`,
|
|
41
|
+
`BIN=${q(bin)}`,
|
|
42
|
+
'if [ -x "$NODE" ] && [ -f "$BIN" ]; then exec "$NODE" "$BIN" "$@"; fi',
|
|
43
|
+
'PATH="$PATH:/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin"',
|
|
44
|
+
'if command -v limitcast >/dev/null 2>&1; then exec limitcast "$@"; fi',
|
|
45
|
+
'# limitcast is gone: keep your status line working, allow every hook.',
|
|
46
|
+
'if [ "$1" = statusline ]; then',
|
|
47
|
+
' while [ $# -gt 0 ] && [ "$1" != -- ]; do shift; done',
|
|
48
|
+
' if [ $# -gt 0 ]; then shift; exec "$@"; fi',
|
|
49
|
+
'fi',
|
|
50
|
+
'exit 0',
|
|
51
|
+
'',
|
|
52
|
+
].join('\n'),
|
|
53
|
+
{ mode: 0o755 },
|
|
54
|
+
);
|
|
55
|
+
return path;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The node and script a launcher points at (null when it isn't a launcher).
|
|
60
|
+
* @param {string} path
|
|
61
|
+
*/
|
|
62
|
+
export function launcherTargets(path) {
|
|
63
|
+
try {
|
|
64
|
+
const text = readFileSync(path, 'utf8');
|
|
65
|
+
const val = (/** @type {string} */ k) => {
|
|
66
|
+
const m = new RegExp(`^${k}=(?:'((?:[^']|'\\\\'')*)'|(\\S+))$`, 'm').exec(text);
|
|
67
|
+
return m ? (m[1] ?? m[2]).replace(/'\\''/g, "'") : null;
|
|
68
|
+
};
|
|
69
|
+
return { node: val('NODE'), bin: val('BIN') };
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
20
73
|
}
|
|
21
74
|
|
|
22
75
|
/**
|
|
@@ -131,6 +184,19 @@ export function wrappedCommand(command) {
|
|
|
131
184
|
return plain ? plain[1] : rest;
|
|
132
185
|
}
|
|
133
186
|
|
|
187
|
+
/**
|
|
188
|
+
* Which optional parts are installed, so `doctor --fix` can re-install exactly those.
|
|
189
|
+
* @param {string} [path]
|
|
190
|
+
*/
|
|
191
|
+
export function installedFeatures(path = settingsPath()) {
|
|
192
|
+
const cfg = readSettings(path);
|
|
193
|
+
return {
|
|
194
|
+
statusLine: Boolean(cfg.statusLine?.command?.includes(MARK)),
|
|
195
|
+
guard: (cfg.hooks?.PreToolUse ?? []).some(isGuard),
|
|
196
|
+
alerts: (cfg.hooks?.SessionStart ?? []).some(isAlert),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
134
200
|
/** @param {any} h */
|
|
135
201
|
const isGuard = (h) =>
|
|
136
202
|
(h.hooks ?? []).some((/** @type {any} */ x) => typeof x.command === 'string' && x.command.includes(MARK) && /\bguard\b/.test(x.command));
|
|
@@ -206,13 +272,27 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
|
|
|
206
272
|
ok: sl.includes(MARK),
|
|
207
273
|
line: sl.includes(MARK) ? 'Status-line recorder installed' : 'Status-line recorder missing: run `limitcast install`',
|
|
208
274
|
});
|
|
209
|
-
const
|
|
210
|
-
const
|
|
211
|
-
if (sl.includes(MARK) &&
|
|
275
|
+
const launcher = /^\/bin\/sh '?([^' ]+limitcast-hook\.sh)'?/.exec(sl)?.[1];
|
|
276
|
+
const targets = launcher ? launcherTargets(launcher) : null;
|
|
277
|
+
if (sl.includes(MARK) && targets) {
|
|
278
|
+
const ok = Boolean(targets.node && existsSync(targets.node) && targets.bin && existsSync(targets.bin));
|
|
212
279
|
out.push({
|
|
213
|
-
ok
|
|
214
|
-
line:
|
|
280
|
+
ok,
|
|
281
|
+
line: ok
|
|
282
|
+
? 'Hook launcher points at this Node and limitcast'
|
|
283
|
+
: 'Node or limitcast moved (a Node upgrade?): hooks fall back to `limitcast` on PATH. Fix: `limitcast doctor --fix`',
|
|
215
284
|
});
|
|
285
|
+
} else if (sl.includes(MARK)) {
|
|
286
|
+
// Installed before 0.10: settings call node directly.
|
|
287
|
+
const exe = sl.match(/^'([^']+)'|^(\S+)/);
|
|
288
|
+
const exePath = exe?.[1] ?? exe?.[2];
|
|
289
|
+
if (exePath?.startsWith('/'))
|
|
290
|
+
out.push({
|
|
291
|
+
ok: existsSync(exePath),
|
|
292
|
+
line: existsSync(exePath)
|
|
293
|
+
? 'Node path in settings exists (`limitcast doctor --fix` switches to the upgrade-proof launcher)'
|
|
294
|
+
: `Node path in settings is gone (${exePath}): run \`limitcast doctor --fix\``,
|
|
295
|
+
});
|
|
216
296
|
}
|
|
217
297
|
const guard = /** @type {any} */ (cfg.hooks?.PreToolUse ?? []).some(isGuard);
|
|
218
298
|
out.push({
|
package/src/license.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// @ts-check
|
|
2
2
|
import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
|
|
3
3
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
-
import {
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
5
6
|
import { loadPolar, polarStatus } from './polar.mjs';
|
|
6
7
|
import { stateDir } from './store.mjs';
|
|
7
8
|
|
|
@@ -68,4 +69,42 @@ export function activate(key) {
|
|
|
68
69
|
return res;
|
|
69
70
|
}
|
|
70
71
|
|
|
71
|
-
export const isPro = () => currentLicense()?.ok === true;
|
|
72
|
+
export const isPro = () => currentLicense()?.ok === true || trialStatus()?.active === true;
|
|
73
|
+
|
|
74
|
+
const TRIAL_MS = 7 * 86400_000;
|
|
75
|
+
const trialFile = () => join(stateDir(), 'trial.json');
|
|
76
|
+
// A second marker outside the state dir, so clearing limitcast's state doesn't restart the trial.
|
|
77
|
+
// shortcut: a determined user can still delete both; fine at this price, move to a server check if it matters.
|
|
78
|
+
const trialMarker = () => join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'limitcast', 'trial-used');
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The no-card Pro trial on this machine: active, or when it ended. null if never started.
|
|
82
|
+
* @param {number} [now]
|
|
83
|
+
*/
|
|
84
|
+
export function trialStatus(now = Date.now()) {
|
|
85
|
+
let start = 0;
|
|
86
|
+
for (const f of [trialFile(), trialMarker()]) {
|
|
87
|
+
try {
|
|
88
|
+
start ||= Number(JSON.parse(readFileSync(f, 'utf8')).start) || 0;
|
|
89
|
+
} catch {
|
|
90
|
+
/* not this one */
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (!start) return null;
|
|
94
|
+
const ends = start + TRIAL_MS;
|
|
95
|
+
return { active: now < ends, ends };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Start the 7-day trial, once per machine.
|
|
100
|
+
* @param {number} [now]
|
|
101
|
+
*/
|
|
102
|
+
export function startTrial(now = Date.now()) {
|
|
103
|
+
const existing = trialStatus(now);
|
|
104
|
+
if (existing) return { ok: false, ...existing };
|
|
105
|
+
for (const f of [trialFile(), trialMarker()]) {
|
|
106
|
+
mkdirSync(dirname(f), { recursive: true });
|
|
107
|
+
writeFileSync(f, JSON.stringify({ start: now }));
|
|
108
|
+
}
|
|
109
|
+
return { ok: true, active: true, ends: now + TRIAL_MS };
|
|
110
|
+
}
|
package/src/usage.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { basename, join } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline';
|
|
6
|
+
import { stateDir } from './store.mjs';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* One model response's token usage.
|
|
@@ -166,24 +167,58 @@ function grokLedgers(root, since) {
|
|
|
166
167
|
export async function readUsage(since, roots = {}, activity) {
|
|
167
168
|
/** @type {Usage[]} */
|
|
168
169
|
const out = [];
|
|
170
|
+
// Parsed transcripts are cached by size and mtime: only new or changed ones are read again.
|
|
171
|
+
const cache = loadUsageCache();
|
|
172
|
+
/** @type {typeof cache} */
|
|
173
|
+
const next = {};
|
|
174
|
+
/**
|
|
175
|
+
* @param {string} file
|
|
176
|
+
* @param {(file:string)=>Promise<{u:Usage[], a?:{skills:string[], mcp:string[]}}>} parse
|
|
177
|
+
*/
|
|
178
|
+
const cached = async (file, parse) => {
|
|
179
|
+
const st = statSync(file);
|
|
180
|
+
const hit = cache[file];
|
|
181
|
+
const entry = hit && hit.s === st.size && hit.m === st.mtimeMs ? hit : { s: st.size, m: st.mtimeMs, ...(await parse(file)) };
|
|
182
|
+
next[file] = entry;
|
|
183
|
+
return entry;
|
|
184
|
+
};
|
|
169
185
|
for (const file of jsonlFiles(roots.claude ?? claudeRoot(), since, () => true)) {
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
186
|
+
const e = await cached(file, async (f) => {
|
|
187
|
+
const seen = new Set();
|
|
188
|
+
const session = basename(f, '.jsonl');
|
|
189
|
+
/** @type {import('./trim.mjs').Activity} */
|
|
190
|
+
const act = { skills: new Set(), mcp: new Set() };
|
|
191
|
+
const u = [];
|
|
192
|
+
for await (const line of lines(f)) {
|
|
193
|
+
claudeActivity(line, act);
|
|
194
|
+
const x = claudeUsage(line, seen, session);
|
|
195
|
+
if (x) u.push(x);
|
|
196
|
+
}
|
|
197
|
+
return { u, a: { skills: [...act.skills], mcp: [...act.mcp] } };
|
|
198
|
+
});
|
|
199
|
+
for (const u of e.u) if (u.t >= since) out.push(u);
|
|
200
|
+
if (activity && e.a) {
|
|
201
|
+
for (const s of e.a.skills) activity.skills.add(s);
|
|
202
|
+
for (const m of e.a.mcp) activity.mcp.add(m);
|
|
176
203
|
}
|
|
177
204
|
}
|
|
178
205
|
for (const file of jsonlFiles(roots.codex ?? codexRoot(), since, (n) => n.startsWith('rollout-'))) {
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
const u =
|
|
184
|
-
|
|
185
|
-
|
|
206
|
+
const e = await cached(file, async (f) => {
|
|
207
|
+
const st = { prev: null, cwd: '', model: '' };
|
|
208
|
+
// rollout-2026-10-23T18-39-41-<session uuid>.jsonl → the uuid
|
|
209
|
+
const session = basename(f, '.jsonl').replace(/^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-/, '');
|
|
210
|
+
const u = [];
|
|
211
|
+
for await (const line of lines(f)) {
|
|
212
|
+
const x = codexUsage(line, st, session);
|
|
213
|
+
if (x) u.push(x);
|
|
214
|
+
}
|
|
215
|
+
return { u };
|
|
216
|
+
});
|
|
217
|
+
for (const u of e.u) if (u.t >= since) out.push(u);
|
|
186
218
|
}
|
|
219
|
+
// Keep entries for files this run didn't need (another period) while they are recent; drop the rest.
|
|
220
|
+
for (const [f, e] of Object.entries(cache)) if (!next[f] && e.m >= Date.now() - CACHE_KEEP_MS && existsSync(f)) next[f] = e;
|
|
221
|
+
saveUsageCache(next);
|
|
187
222
|
for (const { file, session, project } of grokLedgers(roots.grok ?? grokRoot(), since)) {
|
|
188
223
|
let ledger;
|
|
189
224
|
try {
|
|
@@ -196,6 +231,28 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
196
231
|
return out;
|
|
197
232
|
}
|
|
198
233
|
|
|
234
|
+
const CACHE_KEEP_MS = 35 * 86400_000;
|
|
235
|
+
const usageCacheFile = () => join(stateDir(), 'usage-cache.json');
|
|
236
|
+
|
|
237
|
+
/** @returns {Record<string, {s:number, m:number, u:Usage[], a?:{skills:string[], mcp:string[]}}>} */
|
|
238
|
+
function loadUsageCache() {
|
|
239
|
+
try {
|
|
240
|
+
return JSON.parse(readFileSync(usageCacheFile(), 'utf8'));
|
|
241
|
+
} catch {
|
|
242
|
+
return {};
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** @param {ReturnType<typeof loadUsageCache>} c */
|
|
247
|
+
function saveUsageCache(c) {
|
|
248
|
+
try {
|
|
249
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
250
|
+
writeFileSync(usageCacheFile(), JSON.stringify(c));
|
|
251
|
+
} catch {
|
|
252
|
+
/* a cache: the next run just reads the transcripts */
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
199
256
|
/** @param {string} s */
|
|
200
257
|
function safeDecode(s) {
|
|
201
258
|
try {
|
package/src/value.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { createReadStream, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { createInterface } from 'node:readline';
|
|
5
|
+
import { windowPct } from './calibrate.mjs';
|
|
5
6
|
import { blockOutcomes, limitHits } from './results.mjs';
|
|
6
7
|
import { startupBreakdown } from './startup.mjs';
|
|
7
8
|
import { stateDir } from './store.mjs';
|
|
@@ -15,7 +16,7 @@ import { claudeUsage } from './usage.mjs';
|
|
|
15
16
|
/** @typedef {{at:number, turns:number, savedPerTurn:number}} SessionValue savedPerTurn: tokens below the first measured start */
|
|
16
17
|
/** @typedef {{src:string, win:string, at:number, lead:number|null, unseen:boolean}} HitValue lead: minutes of warning */
|
|
17
18
|
/** @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>, switches?:Record<string, {shadow:boolean}
|
|
19
|
+
/** @typedef {{since:number, scanned:number, sessions:Record<string, SessionValue>, hits:Record<string, HitValue>, blocks:Record<string, BlockValue>, switches?:Record<string, {shadow:boolean}>, calib?:{fresh:number, read:number, n:number, at:number}}} Value */
|
|
19
20
|
|
|
20
21
|
const file = () => join(stateDir(), 'value.json');
|
|
21
22
|
const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
@@ -154,6 +155,14 @@ export function valueTotals(v) {
|
|
|
154
155
|
confirmed: blocks.filter((b) => b.outcome === 'hit').length,
|
|
155
156
|
switched: Object.values(v.switches ?? {}).filter((s) => !s.shadow).length,
|
|
156
157
|
switchPreviewed: Object.values(v.switches ?? {}).filter((s) => s.shadow).length,
|
|
158
|
+
calib: v.calib ?? null,
|
|
159
|
+
// Against the 5-hour limit: each session wrote its smaller start once and re-read it on every call.
|
|
160
|
+
windowPct: v.calib
|
|
161
|
+
? windowPct(v.calib, {
|
|
162
|
+
writes: sessions.reduce((a, s) => a + s.savedPerTurn, 0),
|
|
163
|
+
reads: sessions.reduce((a, s) => a + s.turns * s.savedPerTurn, 0),
|
|
164
|
+
})
|
|
165
|
+
: null,
|
|
157
166
|
};
|
|
158
167
|
}
|
|
159
168
|
|
|
@@ -170,6 +179,10 @@ export function valueSection(t, { now, pro }) {
|
|
|
170
179
|
out.push(
|
|
171
180
|
`- **${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.)`,
|
|
172
181
|
);
|
|
182
|
+
if (t.windowPct !== null && t.calib)
|
|
183
|
+
out.push(
|
|
184
|
+
` Against your limit: **≈ ${t.windowPct < 1 ? t.windowPct.toFixed(2) : t.windowPct.toFixed(1)}% of a 5-hour window.** From your own readings, 1% of it is about ${fmtBig(Math.round(1e6 / t.calib.fresh))} new tokens or ${fmtBig(Math.round(1e6 / t.calib.read))} cached ones, so cached context is cheap and new tokens (long sessions, subagents) are what run you out.`,
|
|
185
|
+
);
|
|
173
186
|
} else if (t.sessions) {
|
|
174
187
|
out.push(`- Starting context: no smaller than when limitcast first measured it. \`limitcast trim\` shows what to cut.`);
|
|
175
188
|
}
|