limitcast 0.8.1 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -4
- package/bin/limitcast.mjs +164 -11
- package/package.json +1 -1
- package/src/codex.mjs +195 -0
- package/src/forecast.mjs +31 -2
- package/src/guard.mjs +34 -1
- package/src/hints.mjs +79 -0
- package/src/html.mjs +114 -0
- package/src/notify.mjs +88 -0
- package/src/results.mjs +14 -3
- package/src/value.mjs +15 -2
package/README.md
CHANGED
|
@@ -11,8 +11,10 @@ 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, 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
|
|
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). `trim --codex` does the same for Codex (AGENTS.md, MCP servers).
|
|
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, and while a Claude window is tight runs new subagents on Sonnet instead of your main model. Free installs get a preview that never acts and shows what it would have done.
|
|
16
|
+
- **Daily allowance (free):** today's even share of each weekly window, so you can pace the week: `7d 41% · today 6% left`.
|
|
17
|
+
- **Pro extras:** desktop notifications (`limitcast notify on`), run a job after the reset (`limitcast after-reset -- …`), a pointer to your other account when this one is near its limit, a `/compact` nudge in long sessions, and an HTML dashboard (`limitcast results --html`).
|
|
16
18
|
- **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.
|
|
17
19
|
- **Burn report (Pro):** Claude Code, Codex and Grok tokens by day, project, model and session.
|
|
18
20
|
- **Runout forecast (free):** burn rate and the clock time each window runs out.
|
|
@@ -47,7 +49,11 @@ limitcast doctor
|
|
|
47
49
|
|
|
48
50
|
| Command | |
|
|
49
51
|
|---|---|
|
|
50
|
-
| `limitcast status [--json]` | Used, burn rate, runout time and reset for each window |
|
|
52
|
+
| `limitcast status [--json]` | Used, burn rate, runout time and reset for each window, and today's share of each weekly one. **Pro** also lists your other Claude accounts |
|
|
53
|
+
| `limitcast trim --codex [--apply / --undo]` | Codex: AGENTS.md size and MCP servers in `~/.codex/config.toml` you haven't used. **Pro** names them and turns them off (`enabled = false`; `--undo` restores the file exactly) |
|
|
54
|
+
| `limitcast notify on/off/test` | **Pro.** A desktop notification when a Claude window turns NEAR, AT_RISK or HIT, and when it resets after a HIT |
|
|
55
|
+
| `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
|
|
56
|
+
| `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
|
|
51
57
|
| `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
|
|
52
58
|
| `limitcast doctor` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads |
|
|
53
59
|
| `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
|
|
@@ -70,7 +76,7 @@ Each limit reading is saved to `~/.local/state/limitcast/samples.jsonl` when it
|
|
|
70
76
|
|
|
71
77
|
## Pricing
|
|
72
78
|
|
|
73
|
-
Free: runout forecast with NEAR warnings, status-line readout, your starting-context total with how much you never use, `results`, and a guard
|
|
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.
|
|
74
80
|
|
|
75
81
|
## License
|
|
76
82
|
|
package/bin/limitcast.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @ts-check
|
|
3
3
|
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
-
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import {
|
|
@@ -15,11 +15,15 @@ import {
|
|
|
15
15
|
transcriptCwd,
|
|
16
16
|
undoTrim,
|
|
17
17
|
} from '../src/apply.mjs';
|
|
18
|
-
import {
|
|
18
|
+
import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
|
|
19
|
+
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
19
20
|
import { formatChecks } from '../src/formats.mjs';
|
|
20
21
|
import { runGuard } from '../src/guard.mjs';
|
|
22
|
+
import { accountForecasts, compactHint, headroom, lastCallTokens } from '../src/hints.mjs';
|
|
23
|
+
import { htmlPage } from '../src/html.mjs';
|
|
21
24
|
import { doctor, install, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
22
25
|
import { activate, currentLicense, isPro, UPGRADE_URL } from '../src/license.mjs';
|
|
26
|
+
import { notifyChanges, notifyEnabled, send, setNotify } from '../src/notify.mjs';
|
|
23
27
|
import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
|
|
24
28
|
import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
|
|
25
29
|
import { burnReport } from '../src/report.mjs';
|
|
@@ -38,8 +42,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
|
|
|
38
42
|
(without Pro the guard is a preview: it records what it would block, never blocks)
|
|
39
43
|
limitcast uninstall remove it and restore your original status line
|
|
40
44
|
limitcast doctor check the setup
|
|
41
|
-
limitcast status [--json] used, burn rate, runout time and
|
|
45
|
+
limitcast status [--json] used, burn rate, runout time, reset, and today's share of each weekly window
|
|
42
46
|
limitcast trim [--share] tokens every session loads before you type, and how much you never use
|
|
47
|
+
limitcast trim --codex the same for Codex: AGENTS.md size and MCP servers you haven't used
|
|
43
48
|
limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
|
|
44
49
|
[--share] totals only, safe to post
|
|
45
50
|
limitcast license show the license and re-check it with Polar
|
|
@@ -48,10 +53,17 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
|
|
|
48
53
|
limitcast trim [--days N] [--share] names what to cut and what each costs
|
|
49
54
|
(--share: totals only, no names, safe to post)
|
|
50
55
|
limitcast trim --apply / --undo hide those skills and turn off those MCP servers (backed up, reversible)
|
|
56
|
+
limitcast trim --codex --apply / --undo turn off unused Codex MCP servers (enabled = false; reversible)
|
|
51
57
|
limitcast saved tokens saved since limitcast first measured you
|
|
52
|
-
limitcast install --guard block new subagents when a window is on pace to run out
|
|
58
|
+
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
59
|
+
them on Sonnet while a window is tight (NEAR or AT_RISK)
|
|
53
60
|
limitcast install --alerts tell you when your starting context grows, plus a weekly summary
|
|
61
|
+
limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets
|
|
62
|
+
limitcast after-reset [--src claude|codex] [--window 5h|7d] [--detach] -- <command>
|
|
63
|
+
run a heavy job once the window has reset
|
|
64
|
+
limitcast results --html [--out FILE] results, current windows and the burn report as one page
|
|
54
65
|
limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
|
|
66
|
+
(status line, Pro: points to another account with room, and suggests /compact past ~150k tokens a call)
|
|
55
67
|
limitcast activate <license-key> unlock Pro on this computer (online once; then a weekly check, offline up to 30 days)
|
|
56
68
|
limitcast deactivate free this computer's activation to use the key elsewhere
|
|
57
69
|
|
|
@@ -79,11 +91,19 @@ if (cmd === 'status') {
|
|
|
79
91
|
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
|
|
80
92
|
else {
|
|
81
93
|
console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, or run Codex once.');
|
|
94
|
+
// Pro: the other Claude accounts limitcast has current readings for (the table shows the latest one).
|
|
95
|
+
if (isPro())
|
|
96
|
+
for (const a of accountForecasts(load(now - KEEP_MS), now).slice(1))
|
|
97
|
+
console.log(
|
|
98
|
+
`other Claude account (last used ${clock(a.lastSeen)}): ${a.rows.map((f) => `${f.win} ${f.verdict === 'RESET' ? 0 : Math.round(f.pct)}%${f.verdict === 'OK' || f.verdict === 'RESET' ? '' : ` ${f.verdict}`}`).join(' · ')}`,
|
|
99
|
+
);
|
|
82
100
|
if (existsSync(grokRoot())) console.log('grok: no limit readings (Grok keeps none on disk); its token use is in `limitcast report`');
|
|
83
101
|
}
|
|
84
102
|
} else if (cmd === 'statusline') {
|
|
85
103
|
const input = readStdin();
|
|
86
104
|
let sid;
|
|
105
|
+
/** @type {string[]} */
|
|
106
|
+
const hints = [];
|
|
87
107
|
try {
|
|
88
108
|
const feed = JSON.parse(input);
|
|
89
109
|
sid = feed?.session_id;
|
|
@@ -93,6 +113,14 @@ if (cmd === 'status') {
|
|
|
93
113
|
if (refreshDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'license'], { detached: true, stdio: 'ignore' }).unref();
|
|
94
114
|
// Readings are kept 8 days; the daily rollup folds what they showed into the long-term value record.
|
|
95
115
|
if (dailyDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'rollup'], { detached: true, stdio: 'ignore' }).unref();
|
|
116
|
+
if (isPro()) {
|
|
117
|
+
const samples = load(now - KEEP_MS);
|
|
118
|
+
if (notifyEnabled()) notifyChanges(forecastAll(oneClaudeAccount(samples, sid), now), clock);
|
|
119
|
+
const room = headroom(samples, sid, now);
|
|
120
|
+
if (room) hints.push(room);
|
|
121
|
+
const ctx = typeof feed?.transcript_path === 'string' ? compactHint(lastCallTokens(feed.transcript_path)) : null;
|
|
122
|
+
if (ctx) hints.push(ctx);
|
|
123
|
+
}
|
|
96
124
|
} catch {
|
|
97
125
|
/* never break the status line */
|
|
98
126
|
}
|
|
@@ -100,17 +128,29 @@ if (cmd === 'status') {
|
|
|
100
128
|
const wrapped = sep >= 0 ? args.slice(sep + 1) : [];
|
|
101
129
|
if (wrapped.length) {
|
|
102
130
|
const r = spawnSync(wrapped[0], wrapped.slice(1), { input, stdio: ['pipe', 'inherit', 'inherit'] });
|
|
131
|
+
// Your status line stays as it was; Pro adds a second line only when there is something to act on.
|
|
132
|
+
if (hints.length) console.log(`limitcast: ${hints.join(' · ')}`);
|
|
103
133
|
process.exit(r.status ?? 1);
|
|
104
134
|
}
|
|
105
|
-
console.log(oneLine(forecastAll(oneClaudeAccount(load(now - KEEP_MS), sid), now)));
|
|
135
|
+
console.log([oneLine(forecastAll(oneClaudeAccount(load(now - KEEP_MS), sid), now)), ...hints].join(' · '));
|
|
106
136
|
} else if (cmd === 'guard') {
|
|
107
137
|
// Blocking is Pro; without a valid license the guard only previews (logs what Pro would block) and allows everything.
|
|
108
138
|
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
109
139
|
try {
|
|
110
|
-
const
|
|
111
|
-
if (
|
|
140
|
+
const d = await runGuard(JSON.parse(readStdin()), now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30), { preview: !isPro() });
|
|
141
|
+
if (typeof d === 'string') {
|
|
142
|
+
console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d } }));
|
|
143
|
+
} else if (d) {
|
|
144
|
+
// Model switch: allow the spawn with the same input and model "sonnet" (updatedInput replaces the whole input).
|
|
112
145
|
console.log(
|
|
113
|
-
JSON.stringify({
|
|
146
|
+
JSON.stringify({
|
|
147
|
+
hookSpecificOutput: {
|
|
148
|
+
hookEventName: 'PreToolUse',
|
|
149
|
+
permissionDecision: 'allow',
|
|
150
|
+
permissionDecisionReason: d.reason,
|
|
151
|
+
updatedInput: d.updatedInput,
|
|
152
|
+
},
|
|
153
|
+
}),
|
|
114
154
|
);
|
|
115
155
|
}
|
|
116
156
|
} catch (e) {
|
|
@@ -149,6 +189,35 @@ if (cmd === 'status') {
|
|
|
149
189
|
process.exit(2);
|
|
150
190
|
}
|
|
151
191
|
const since = now - days() * 86400_000;
|
|
192
|
+
if (cmd === 'trim' && args.includes('--codex')) {
|
|
193
|
+
// Codex: AGENTS.md and the MCP servers in ~/.codex/config.toml. Free counts them; Pro names them and turns them off.
|
|
194
|
+
if ((args.includes('--apply') || args.includes('--undo')) && !pro) {
|
|
195
|
+
console.log(`\`limitcast trim --codex --apply\` is part of limitcast Pro: ${UPGRADE_URL}`);
|
|
196
|
+
process.exit(2);
|
|
197
|
+
}
|
|
198
|
+
if (args.includes('--undo')) {
|
|
199
|
+
const e = undoCodexTrim();
|
|
200
|
+
console.log(
|
|
201
|
+
e ? `✓ Back to how they were: ${e.servers.map((s) => s.name).join(', ')}. Takes effect in your next Codex session.` : 'Nothing to undo.',
|
|
202
|
+
);
|
|
203
|
+
process.exit(0);
|
|
204
|
+
}
|
|
205
|
+
if (!existsSync(codexConfigPath())) {
|
|
206
|
+
console.log(`No Codex setup found (${codexConfigPath()}). Set CODEX_HOME if Codex keeps it elsewhere.`);
|
|
207
|
+
process.exit(0);
|
|
208
|
+
}
|
|
209
|
+
const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
|
|
210
|
+
const r = codexTrimReport({ servers, used: await codexUsedServers(since), startup: await codexStartup(), days: days(), pro });
|
|
211
|
+
if (args.includes('--apply')) {
|
|
212
|
+
const changed = applyCodexTrim(r.unused);
|
|
213
|
+
console.log(
|
|
214
|
+
changed.length
|
|
215
|
+
? `✓ Turned off ${changed.length} Codex MCP servers (enabled = false in ${codexConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Codex session. Undo: limitcast trim --codex --undo`
|
|
216
|
+
: 'Nothing to turn off: every server that is on was used.',
|
|
217
|
+
);
|
|
218
|
+
} else console.log(r.text);
|
|
219
|
+
process.exit(0);
|
|
220
|
+
}
|
|
152
221
|
/** @type {import('../src/trim.mjs').Activity} */
|
|
153
222
|
const used = { skills: new Set(), mcp: new Set() };
|
|
154
223
|
const usage = await readUsage(since, {}, cmd === 'trim' ? used : undefined);
|
|
@@ -260,7 +329,80 @@ if (cmd === 'status') {
|
|
|
260
329
|
notResent: totals.tokens,
|
|
261
330
|
}),
|
|
262
331
|
);
|
|
263
|
-
else
|
|
332
|
+
else if (args.includes('--html')) {
|
|
333
|
+
// Pro: results, the current windows and the burn report on one page, opened in the browser.
|
|
334
|
+
if (!pro) {
|
|
335
|
+
console.log(`The HTML dashboard is part of limitcast Pro: ${UPGRADE_URL}`);
|
|
336
|
+
process.exit(2);
|
|
337
|
+
}
|
|
338
|
+
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
|
|
339
|
+
const burn = burnReport(await readUsage(since, {}), { since, now }).replace(/^(#{1,2}) /gm, '#$1 ');
|
|
340
|
+
const md = [
|
|
341
|
+
resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }) }),
|
|
342
|
+
'## Right now',
|
|
343
|
+
'```',
|
|
344
|
+
rows.length ? table(rows) : 'No readings yet.',
|
|
345
|
+
'```',
|
|
346
|
+
burn,
|
|
347
|
+
].join('\n\n');
|
|
348
|
+
const out = flag('--out') ?? join(stateDir(), 'dashboard.html');
|
|
349
|
+
writeFileSync(out, htmlPage(md, { title: 'limitcast dashboard', generated: new Date(now).toLocaleString() }));
|
|
350
|
+
console.log(`Wrote ${out}`);
|
|
351
|
+
if (!args.includes('--no-open')) {
|
|
352
|
+
const opener = spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [out], { detached: true, stdio: 'ignore' });
|
|
353
|
+
opener.on('error', () => {});
|
|
354
|
+
opener.unref();
|
|
355
|
+
}
|
|
356
|
+
} else console.log(resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }) }));
|
|
357
|
+
} else if (cmd === 'notify') {
|
|
358
|
+
// Desktop notifications from the status line (Pro, opt-in).
|
|
359
|
+
if (!isPro()) {
|
|
360
|
+
console.log(`Desktop notifications are part of limitcast Pro: ${UPGRADE_URL}`);
|
|
361
|
+
process.exit(2);
|
|
362
|
+
}
|
|
363
|
+
const what = args[0];
|
|
364
|
+
if (what === 'on' || what === 'off') setNotify(what === 'on');
|
|
365
|
+
if (what === 'test') send('limitcast notifications work.');
|
|
366
|
+
console.log(
|
|
367
|
+
what === 'test'
|
|
368
|
+
? 'Sent a test notification. Nothing showed up? Allow notifications for Script Editor (macOS) or install notify-send (Linux).'
|
|
369
|
+
: `Notifications are ${notifyEnabled() ? 'on: you get one when a Claude window turns NEAR, AT_RISK or HIT, and when it resets after a HIT' : 'off'}. (limitcast notify on|off|test)`,
|
|
370
|
+
);
|
|
371
|
+
} else if (cmd === 'after-reset') {
|
|
372
|
+
// Run a command once a window has reset: queue the heavy job instead of watching the clock.
|
|
373
|
+
if (!isPro()) {
|
|
374
|
+
console.log(`\`limitcast after-reset\` is part of limitcast Pro: ${UPGRADE_URL}`);
|
|
375
|
+
process.exit(2);
|
|
376
|
+
}
|
|
377
|
+
const sep = args.indexOf('--');
|
|
378
|
+
const command = sep >= 0 ? args.slice(sep + 1) : [];
|
|
379
|
+
const src = flag('--src') ?? 'claude';
|
|
380
|
+
const win = flag('--window') ?? '5h';
|
|
381
|
+
if (!command.length) {
|
|
382
|
+
console.log('Usage: limitcast after-reset [--src claude|codex] [--window 5h|7d] [--detach] -- <command...>');
|
|
383
|
+
process.exit(1);
|
|
384
|
+
}
|
|
385
|
+
const samples = src === 'codex' ? await readCodex(now - KEEP_MS) : oneClaudeAccount(load(now - KEEP_MS));
|
|
386
|
+
const f = forecastAll(samples, now).find((x) => x.src === src && x.win === win);
|
|
387
|
+
if (!f) {
|
|
388
|
+
console.log(`No ${src} ${win} readings yet, so the reset time is unknown.`);
|
|
389
|
+
process.exit(1);
|
|
390
|
+
}
|
|
391
|
+
const at = resetTarget(f, now);
|
|
392
|
+
if (args.includes('--detach')) {
|
|
393
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
394
|
+
const log = join(stateDir(), `after-reset-${now}.log`);
|
|
395
|
+
const out = openSync(log, 'a');
|
|
396
|
+
const rest = args.filter((a) => a !== '--detach');
|
|
397
|
+
spawn(process.execPath, [fileURLToPath(import.meta.url), 'after-reset', ...rest], { detached: true, stdio: ['ignore', out, out] }).unref();
|
|
398
|
+
console.log(`Will run at ${clock(at)} (after the ${src} ${win} reset), in the background. Output: ${log}`);
|
|
399
|
+
process.exit(0);
|
|
400
|
+
}
|
|
401
|
+
if (at > now) console.log(`Waiting for the ${src} ${win} reset at ${clock(at)}…`);
|
|
402
|
+
// Short sleeps against the wall clock, so a laptop that sleeps through the reset still wakes on time.
|
|
403
|
+
while (Date.now() < at) await new Promise((r) => setTimeout(r, Math.min(60_000, at - Date.now())));
|
|
404
|
+
const r = spawnSync(command[0], command.slice(1), { stdio: 'inherit' });
|
|
405
|
+
process.exit(r.status ?? 1);
|
|
264
406
|
} else if (cmd === 'rollup') {
|
|
265
407
|
// Started daily in the background by the status line: keeps the value record current. Never prints.
|
|
266
408
|
try {
|
|
@@ -380,9 +522,10 @@ function table(rows) {
|
|
|
380
522
|
f.rate === null ? '-' : `${f.rate >= 0 ? '+' : ''}${f.rate.toFixed(1)}%/h`,
|
|
381
523
|
f.verdict === 'AT_RISK' ? clock(f.wall) : '-',
|
|
382
524
|
clock(f.reset),
|
|
525
|
+
f.today ? todayLabel(f.today) : '-',
|
|
383
526
|
f.verdict,
|
|
384
527
|
]);
|
|
385
|
-
const head = ['window', 'used', 'burn', 'runs out', 'resets', 'status'];
|
|
528
|
+
const head = ['window', 'used', 'burn', 'runs out', 'resets', 'today', 'status'];
|
|
386
529
|
const w = head.map((h, i) => Math.max(h.length, ...lines.map((l) => l[i].length)));
|
|
387
530
|
return [head, ...lines]
|
|
388
531
|
.map((l) =>
|
|
@@ -401,8 +544,18 @@ function oneLine(rows) {
|
|
|
401
544
|
.filter((f) => f.src === 'claude')
|
|
402
545
|
.map(
|
|
403
546
|
(f) =>
|
|
404
|
-
`${f.win} ${Math.round(f.pct)}%${f.verdict === 'AT_RISK' ? ` ⚠ out ${clock(f.wall)}` : f.verdict === 'NEAR' ? ' ⚠ near limit' : f.verdict === 'HIT' ? ' ⛔' : ''}
|
|
547
|
+
`${f.win} ${Math.round(f.pct)}%${f.verdict === 'AT_RISK' ? ` ⚠ out ${clock(f.wall)}` : f.verdict === 'NEAR' ? ' ⚠ near limit' : f.verdict === 'HIT' ? ' ⛔' : ''}` +
|
|
548
|
+
(f.today && f.verdict !== 'HIT' ? ` · today ${todayLabel(f.today)}` : ''),
|
|
405
549
|
)
|
|
406
550
|
.join(' · ') || 'limitcast: waiting for data'
|
|
407
551
|
);
|
|
408
552
|
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* "6% left" / "3% over" of today's even share of a weekly window.
|
|
556
|
+
* @param {{left:number}} t
|
|
557
|
+
*/
|
|
558
|
+
function todayLabel(t) {
|
|
559
|
+
const n = Math.round(Math.abs(t.left));
|
|
560
|
+
return t.left >= 0 ? `${n}% left` : `${n}% over`;
|
|
561
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
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" },
|
package/src/codex.mjs
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { chmodSync, copyFileSync, createReadStream, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline';
|
|
6
|
+
import { stateDir } from './store.mjs';
|
|
7
|
+
import { jsonlFiles } from './usage.mjs';
|
|
8
|
+
|
|
9
|
+
// `limitcast trim --codex`: what Codex loads before you type (AGENTS.md, MCP servers) and which servers you never use.
|
|
10
|
+
// --apply turns unused servers off with `enabled = false` in ~/.codex/config.toml; --undo puts back exactly what it changed.
|
|
11
|
+
|
|
12
|
+
const codexHome = () => process.env.CODEX_HOME ?? join(homedir(), '.codex');
|
|
13
|
+
export const codexConfigPath = () => join(codexHome(), 'config.toml');
|
|
14
|
+
const ledgerPath = () => join(stateDir(), 'codex-trim-applied.json');
|
|
15
|
+
const norm = (/** @type {string} */ s) => s.toLowerCase().replace(/[^a-z0-9]/g, '_');
|
|
16
|
+
const HEADER = /^\[mcp_servers\.(?:"([^"]+)"|([A-Za-z0-9_-]+))\]\s*(#.*)?$/;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The MCP servers in a config.toml, with their `enabled` setting (undefined when the key is absent: on).
|
|
20
|
+
* @param {string} toml
|
|
21
|
+
*/
|
|
22
|
+
export function codexServers(toml) {
|
|
23
|
+
const lines = toml.split('\n');
|
|
24
|
+
return lines.flatMap((line, i) => {
|
|
25
|
+
const m = HEADER.exec(line.trim());
|
|
26
|
+
if (!m) return [];
|
|
27
|
+
const body = tableBody(lines, i);
|
|
28
|
+
const at = body.find((j) => /^\s*enabled\s*=/.test(lines[j]));
|
|
29
|
+
const enabled = at === undefined ? undefined : /=\s*true\b/.test(lines[at]);
|
|
30
|
+
return [{ name: m[1] ?? m[2], enabled }];
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Line indexes of a table's own keys: after its header, up to the next table header. */
|
|
35
|
+
function tableBody(/** @type {string[]} */ lines, /** @type {number} */ header) {
|
|
36
|
+
const out = [];
|
|
37
|
+
for (let j = header + 1; j < lines.length && !lines[j].trim().startsWith('['); j++) out.push(j);
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {string[]} lines @param {string} name */
|
|
42
|
+
const headerOf = (lines, name) =>
|
|
43
|
+
lines.findIndex((l) => {
|
|
44
|
+
const m = HEADER.exec(l.trim());
|
|
45
|
+
return m && (m[1] ?? m[2]) === name;
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Set `enabled` on the named servers. value null removes the key (back to the default: on).
|
|
50
|
+
* @param {string} toml
|
|
51
|
+
* @param {Record<string, boolean|null>} changes
|
|
52
|
+
*/
|
|
53
|
+
export function setEnabled(toml, changes) {
|
|
54
|
+
const lines = toml.split('\n');
|
|
55
|
+
for (const [name, value] of Object.entries(changes)) {
|
|
56
|
+
const h = headerOf(lines, name);
|
|
57
|
+
if (h < 0) continue;
|
|
58
|
+
const at = tableBody(lines, h).find((j) => /^\s*enabled\s*=/.test(lines[j]));
|
|
59
|
+
if (value === null) {
|
|
60
|
+
if (at !== undefined) lines.splice(at, 1);
|
|
61
|
+
} else if (at !== undefined) lines[at] = `enabled = ${value}`;
|
|
62
|
+
else lines.splice(h + 1, 0, `enabled = ${value}`);
|
|
63
|
+
}
|
|
64
|
+
return lines.join('\n');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* MCP servers Codex sessions called since `since`, by normalized name. Codex records each call as an
|
|
69
|
+
* `McpToolCall` item with the server's config key, and the model's call with namespace `mcp__<server>`.
|
|
70
|
+
* @param {number} since
|
|
71
|
+
*/
|
|
72
|
+
export async function codexUsedServers(since, root = join(codexHome(), 'sessions')) {
|
|
73
|
+
const used = new Set();
|
|
74
|
+
for (const f of jsonlFiles(root, since, (n) => n.startsWith('rollout-'))) {
|
|
75
|
+
const rl = createInterface({ input: createReadStream(f), crlfDelay: Infinity });
|
|
76
|
+
for await (const line of rl) {
|
|
77
|
+
if (line.includes('"McpToolCall"')) {
|
|
78
|
+
try {
|
|
79
|
+
const item = JSON.parse(line)?.payload?.item;
|
|
80
|
+
if (item?.type === 'McpToolCall' && typeof item.server === 'string') used.add(norm(item.server));
|
|
81
|
+
} catch {
|
|
82
|
+
/* a torn line */
|
|
83
|
+
}
|
|
84
|
+
} else if (line.includes('"namespace":"mcp__')) {
|
|
85
|
+
const ns = /"namespace":"mcp__([^"]+)"/.exec(line)?.[1];
|
|
86
|
+
if (ns) used.add(norm(ns));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return used;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Sizes from the newest rollout's head: the AGENTS.md chain Codex loaded and its own base instructions (characters).
|
|
95
|
+
* @returns {Promise<{agentsMd:number, base:number}|null>}
|
|
96
|
+
*/
|
|
97
|
+
export async function codexStartup(root = join(codexHome(), 'sessions')) {
|
|
98
|
+
const files = jsonlFiles(root, 0, (n) => n.startsWith('rollout-'))
|
|
99
|
+
.map((p) => ({ p, m: statSync(p).mtimeMs }))
|
|
100
|
+
.sort((a, b) => b.m - a.m);
|
|
101
|
+
if (!files.length) return null;
|
|
102
|
+
let agentsMd = 0;
|
|
103
|
+
let base = 0;
|
|
104
|
+
let n = 0;
|
|
105
|
+
const rl = createInterface({ input: createReadStream(files[0].p), crlfDelay: Infinity });
|
|
106
|
+
for await (const line of rl) {
|
|
107
|
+
if (++n > 40) break;
|
|
108
|
+
try {
|
|
109
|
+
const ev = JSON.parse(line);
|
|
110
|
+
if (ev.type === 'session_meta') base = String(ev.payload?.base_instructions?.text ?? '').length;
|
|
111
|
+
if (ev.type === 'world_state') agentsMd = String(ev.payload?.state?.agents_md?.text ?? '').length;
|
|
112
|
+
} catch {
|
|
113
|
+
/* skip */
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
rl.close();
|
|
117
|
+
return { agentsMd, base };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean}} r
|
|
122
|
+
*/
|
|
123
|
+
export function codexTrimReport({ servers, used, startup, days, pro }) {
|
|
124
|
+
const on = servers.filter((s) => s.enabled !== false);
|
|
125
|
+
const unused = on.filter((s) => !used.has(norm(s.name)));
|
|
126
|
+
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
127
|
+
const out = ['# limitcast trim --codex', ''];
|
|
128
|
+
if (startup)
|
|
129
|
+
out.push(
|
|
130
|
+
`Codex sessions start with ~${tok(startup.agentsMd)} tokens of AGENTS.md (your instruction files) and ~${tok(startup.base)} of Codex's own instructions, re-sent on every turn.`,
|
|
131
|
+
'',
|
|
132
|
+
);
|
|
133
|
+
out.push(`## MCP servers: ${on.length} on, ${unused.length} not used in ${days} days`);
|
|
134
|
+
if (!unused.length) out.push('Every server that is on was used.');
|
|
135
|
+
else if (pro)
|
|
136
|
+
out.push(...unused.map((s) => `- ${s.name}`), '', 'Turn them off: `limitcast trim --codex --apply` (backed up; `--undo` reverses it).');
|
|
137
|
+
else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
|
|
138
|
+
out.push(
|
|
139
|
+
'',
|
|
140
|
+
'Each server that is on starts with every Codex session and adds its tool list to the context. AGENTS.md: every 1k tokens you move into files read on demand saves 1k per turn.',
|
|
141
|
+
);
|
|
142
|
+
return { text: out.join('\n'), unused: unused.map((s) => s.name) };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** @param {string} path @param {string} text */
|
|
146
|
+
function writeText(path, text) {
|
|
147
|
+
const tmp = `${path}.limitcast-tmp`;
|
|
148
|
+
const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
|
|
149
|
+
writeFileSync(tmp, text, { mode });
|
|
150
|
+
chmodSync(tmp, mode);
|
|
151
|
+
renameSync(tmp, path);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** @returns {{at:number, servers:{name:string, prev:boolean|null}[]}[]} */
|
|
155
|
+
function loadLedger() {
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(readFileSync(ledgerPath(), 'utf8'));
|
|
158
|
+
} catch {
|
|
159
|
+
return [];
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Turn the named servers off in config.toml, backing it up and recording each server's previous setting.
|
|
165
|
+
* @param {string[]} names
|
|
166
|
+
*/
|
|
167
|
+
export function applyCodexTrim(names, { now = Date.now(), path = codexConfigPath() } = {}) {
|
|
168
|
+
if (!names.length || !existsSync(path)) return [];
|
|
169
|
+
const toml = readFileSync(path, 'utf8');
|
|
170
|
+
const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
|
|
171
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
|
|
172
|
+
writeText(path, setEnabled(toml, Object.fromEntries(names.map((n) => [n, false]))));
|
|
173
|
+
const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
|
|
174
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
175
|
+
writeFileSync(ledgerPath(), JSON.stringify([...loadLedger(), { at: now, servers }], null, 2));
|
|
176
|
+
return servers;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Reverse the last --apply: each server goes back to its previous setting (or no `enabled` key). */
|
|
180
|
+
export function undoCodexTrim({ path = codexConfigPath() } = {}) {
|
|
181
|
+
const ledger = loadLedger();
|
|
182
|
+
const last = ledger.pop();
|
|
183
|
+
if (!last || !existsSync(path)) return null;
|
|
184
|
+
const toml = readFileSync(path, 'utf8');
|
|
185
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
186
|
+
// Only servers still off: anything turned back on since is left as the user set it.
|
|
187
|
+
const off = new Set(
|
|
188
|
+
codexServers(toml)
|
|
189
|
+
.filter((s) => s.enabled === false)
|
|
190
|
+
.map((s) => s.name),
|
|
191
|
+
);
|
|
192
|
+
writeText(path, setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev]))));
|
|
193
|
+
writeFileSync(ledgerPath(), JSON.stringify(ledger, null, 2));
|
|
194
|
+
return last;
|
|
195
|
+
}
|
package/src/forecast.mjs
CHANGED
|
@@ -43,8 +43,37 @@ export function forecast(samples, now) {
|
|
|
43
43
|
rate = (last.pct - then) / 24;
|
|
44
44
|
wall = runout(rate);
|
|
45
45
|
}
|
|
46
|
-
|
|
47
|
-
return { ...base, rate,
|
|
46
|
+
const today = len >= DAY_MS ? allowance(window, last, now, resetMs - len) : null;
|
|
47
|
+
if (wall === null) return { ...base, rate, verdict: calm, today };
|
|
48
|
+
return { ...base, rate, wall, verdict: wall < resetMs ? 'AT_RISK' : calm, today };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* When to run a job queued for after a window's reset: now if it already reset, else a minute after the reset
|
|
53
|
+
* (the provider's reset time and the first reading after it can differ by seconds).
|
|
54
|
+
* @param {{verdict:string, reset:number}} f
|
|
55
|
+
* @param {number} now
|
|
56
|
+
*/
|
|
57
|
+
export const resetTarget = (f, now) => (f.verdict === 'RESET' || f.reset <= now ? now : f.reset + 60_000);
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Daily allowance for a multi-day window: an even share of what was left at the start of today (local time)
|
|
61
|
+
* across the days until the reset, and how much of it today has used.
|
|
62
|
+
* @param {Sample[]} window readings of the current window, sorted
|
|
63
|
+
* @param {Sample} last
|
|
64
|
+
* @param {number} now epoch ms
|
|
65
|
+
* @param {number} start epoch ms the window began
|
|
66
|
+
*/
|
|
67
|
+
export function allowance(window, last, now, start) {
|
|
68
|
+
const midnight = new Date(now).setHours(0, 0, 0, 0);
|
|
69
|
+
const from = Math.max(midnight, start);
|
|
70
|
+
// Usage at the start of today: 0% if the window began today, else the last reading before midnight.
|
|
71
|
+
// shortcut: with no reading before midnight (limitcast installed today), today's first reading stands in.
|
|
72
|
+
const then = start >= midnight ? 0 : (window.filter((s) => s.t <= from).at(-1) ?? window[0]).pct;
|
|
73
|
+
const daysLeft = (last.reset * 1000 - from) / DAY_MS;
|
|
74
|
+
const budget = (100 - then) / Math.max(1, daysLeft);
|
|
75
|
+
const used = last.pct - then;
|
|
76
|
+
return { budget, used, left: budget - used };
|
|
48
77
|
}
|
|
49
78
|
|
|
50
79
|
/**
|
package/src/guard.mjs
CHANGED
|
@@ -90,5 +90,38 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
90
90
|
/* a failed log must not change the decision */
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
-
return preview ? null : reason;
|
|
93
|
+
if (reason) return preview ? null : reason;
|
|
94
|
+
// Not blocked, but a window is tight: run a new Claude subagent on Sonnet instead of the main (usually Opus) model.
|
|
95
|
+
const input = hook?.tool_input ?? hook?.toolInput;
|
|
96
|
+
const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
|
|
97
|
+
if (src !== 'claude' || !tight || !switchable(input?.model)) return null;
|
|
98
|
+
try {
|
|
99
|
+
logBlock({
|
|
100
|
+
t: now,
|
|
101
|
+
kind: 'switch',
|
|
102
|
+
src: 'claude',
|
|
103
|
+
win: tight.win,
|
|
104
|
+
pct: tight.pct,
|
|
105
|
+
wall: tight.wall ?? tight.reset,
|
|
106
|
+
reset: tight.reset,
|
|
107
|
+
from: input?.model ?? 'default',
|
|
108
|
+
...(preview ? { shadow: true } : {}),
|
|
109
|
+
});
|
|
110
|
+
} catch {
|
|
111
|
+
/* a failed log must not change the decision */
|
|
112
|
+
}
|
|
113
|
+
if (preview) return null;
|
|
114
|
+
return {
|
|
115
|
+
updatedInput: { ...input, model: SWITCH_TO },
|
|
116
|
+
reason: `limitcast: Claude ${tight.win} limit is ${Math.round(tight.pct)}% used${tight.verdict === 'AT_RISK' ? ' and on pace to run out before it resets' : ''}; this subagent runs on Sonnet. Set LIMITCAST_ALLOW=1 to keep the main model.`,
|
|
117
|
+
};
|
|
94
118
|
}
|
|
119
|
+
|
|
120
|
+
const SWITCH_TO = 'sonnet';
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Whether a subagent's model is worth switching: unset or "inherit" (the main model, usually Opus), or Opus/Fable.
|
|
124
|
+
* An explicit Sonnet or Haiku is left alone.
|
|
125
|
+
* @param {unknown} model
|
|
126
|
+
*/
|
|
127
|
+
export const switchable = (model) => model === undefined || model === null || model === 'inherit' || /opus|fable/i.test(String(model));
|
package/src/hints.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { closeSync, openSync, readSync, statSync } from 'node:fs';
|
|
3
|
+
import { claudeAccounts, forecastAll } from './forecast.mjs';
|
|
4
|
+
|
|
5
|
+
// Pro hints for the status line: another account with room, and when a long session is worth compacting.
|
|
6
|
+
|
|
7
|
+
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
8
|
+
|
|
9
|
+
const TROUBLE = new Set(['NEAR', 'AT_RISK', 'HIT']);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Every Claude account limitcast has current readings for, with its forecasts. An account whose windows have
|
|
13
|
+
* all reset since it was last seen is left out: its usage now is unknown, not zero.
|
|
14
|
+
* @param {Sample[]} samples
|
|
15
|
+
* @param {number} now
|
|
16
|
+
*/
|
|
17
|
+
export function accountForecasts(samples, now) {
|
|
18
|
+
return claudeAccounts(samples)
|
|
19
|
+
.map((acct) => ({
|
|
20
|
+
sids: new Set(acct.map((s) => s.sid)),
|
|
21
|
+
lastSeen: Math.max(...acct.map((s) => s.t)),
|
|
22
|
+
rows: forecastAll(acct, now),
|
|
23
|
+
}))
|
|
24
|
+
.filter((a) => a.rows.some((f) => f.verdict !== 'RESET'));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* When the current account is near or at a limit, the other account with the most room, e.g. "⇄ other account 5h 12% · 7d 30%".
|
|
29
|
+
* @param {Sample[]} samples
|
|
30
|
+
* @param {string|undefined} sid current session
|
|
31
|
+
* @param {number} now
|
|
32
|
+
*/
|
|
33
|
+
export function headroom(samples, sid, now) {
|
|
34
|
+
const accounts = accountForecasts(samples, now);
|
|
35
|
+
if (accounts.length < 2) return null;
|
|
36
|
+
const current = accounts.find((a) => sid && a.sids.has(sid)) ?? accounts[0];
|
|
37
|
+
if (!current.rows.some((f) => TROUBLE.has(f.verdict))) return null;
|
|
38
|
+
const used = (/** @type {typeof accounts[0]} */ a) => Math.max(...a.rows.map((f) => (f.verdict === 'RESET' ? 0 : f.pct)));
|
|
39
|
+
const best = accounts.filter((a) => a !== current && !a.rows.some((f) => TROUBLE.has(f.verdict))).sort((a, b) => used(a) - used(b))[0];
|
|
40
|
+
if (!best) return null;
|
|
41
|
+
const parts = best.rows.map((f) => `${f.win} ${f.verdict === 'RESET' ? 0 : Math.round(f.pct)}%`);
|
|
42
|
+
return `⇄ other account ${parts.join(' · ')}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const COMPACT_AT = 150_000; // tokens re-sent per model call worth a /compact
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Tokens the latest main-thread model call of a session sent (input + cache), from the transcript's tail.
|
|
49
|
+
* Reads at most the last 256 KB, so it stays cheap on multi-megabyte transcripts.
|
|
50
|
+
* @param {string} path
|
|
51
|
+
*/
|
|
52
|
+
export function lastCallTokens(path) {
|
|
53
|
+
const size = statSync(path).size;
|
|
54
|
+
const len = Math.min(size, 256 * 1024);
|
|
55
|
+
const buf = Buffer.alloc(len);
|
|
56
|
+
const fd = openSync(path, 'r');
|
|
57
|
+
readSync(fd, buf, 0, len, size - len);
|
|
58
|
+
closeSync(fd);
|
|
59
|
+
const lines = buf.toString('utf8').split('\n').reverse();
|
|
60
|
+
for (const line of lines) {
|
|
61
|
+
if (!line.includes('"usage"') || line.includes('"isSidechain":true')) continue;
|
|
62
|
+
try {
|
|
63
|
+
const u = JSON.parse(line)?.message?.usage;
|
|
64
|
+
if (u) return (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
|
|
65
|
+
} catch {
|
|
66
|
+
/* a torn first line of the tail */
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* "ctx 162k · /compact" when a session re-sends more than ~150k tokens on every call.
|
|
74
|
+
* @param {number|null} tokens per call
|
|
75
|
+
*/
|
|
76
|
+
export function compactHint(tokens) {
|
|
77
|
+
if (!tokens || tokens < COMPACT_AT) return null;
|
|
78
|
+
return `ctx ${Math.round(tokens / 1000)}k · /compact`;
|
|
79
|
+
}
|
package/src/html.mjs
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
// `limitcast results --html`: the Markdown reports as one self-contained page (no scripts, no network).
|
|
4
|
+
|
|
5
|
+
/** @param {string} s */
|
|
6
|
+
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
7
|
+
|
|
8
|
+
/** Inline Markdown: **bold**, `code`, _italic_. @param {string} s */
|
|
9
|
+
const inline = (s) =>
|
|
10
|
+
esc(s)
|
|
11
|
+
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
|
12
|
+
.replace(/`([^`]+)`/g, '<code>$1</code>')
|
|
13
|
+
.replace(/(^|\s)_(.+?)_(?=\s|$|[.,;:])/g, '$1<em>$2</em>');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The subset of Markdown limitcast's reports use: headings, bullet lists, tables, paragraphs.
|
|
17
|
+
* @param {string} md
|
|
18
|
+
*/
|
|
19
|
+
export function mdToHtml(md) {
|
|
20
|
+
const out = [];
|
|
21
|
+
const lines = md.split('\n');
|
|
22
|
+
for (let i = 0; i < lines.length; i++) {
|
|
23
|
+
const line = lines[i];
|
|
24
|
+
const h = /^(#{1,3}) (.*)$/.exec(line);
|
|
25
|
+
if (h) out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
|
|
26
|
+
else if (line.startsWith('- ')) {
|
|
27
|
+
out.push('<ul>');
|
|
28
|
+
for (; i < lines.length && lines[i].startsWith('- '); i++) out.push(`<li>${inline(lines[i].slice(2))}</li>`);
|
|
29
|
+
i--;
|
|
30
|
+
out.push('</ul>');
|
|
31
|
+
} else if (line.startsWith('|')) {
|
|
32
|
+
const rows = [];
|
|
33
|
+
for (; i < lines.length && lines[i].startsWith('|'); i++) rows.push(lines[i]);
|
|
34
|
+
i--;
|
|
35
|
+
const cells = (/** @type {string} */ r) =>
|
|
36
|
+
r
|
|
37
|
+
.slice(1, r.endsWith('|') ? -1 : undefined)
|
|
38
|
+
.split('|')
|
|
39
|
+
.map((c) => c.trim());
|
|
40
|
+
const [head, sep, ...body] = rows;
|
|
41
|
+
const right = sep ? cells(sep).map((c) => c.endsWith(':')) : [];
|
|
42
|
+
const td = (/** @type {string} */ tag, /** @type {string} */ c, /** @type {number} */ j) =>
|
|
43
|
+
`<${tag}${right[j] ? ' class="num"' : ''}>${inline(c)}</${tag}>`;
|
|
44
|
+
out.push(
|
|
45
|
+
'<div class="table"><table>',
|
|
46
|
+
`<thead><tr>${cells(head)
|
|
47
|
+
.map((c, j) => td('th', c, j))
|
|
48
|
+
.join('')}</tr></thead>`,
|
|
49
|
+
`<tbody>${body
|
|
50
|
+
.map(
|
|
51
|
+
(r) =>
|
|
52
|
+
`<tr>${cells(r)
|
|
53
|
+
.map((c, j) => td('td', c, j))
|
|
54
|
+
.join('')}</tr>`,
|
|
55
|
+
)
|
|
56
|
+
.join('')}</tbody>`,
|
|
57
|
+
'</table></div>',
|
|
58
|
+
);
|
|
59
|
+
} else if (line.startsWith(' ') || line.startsWith('```')) {
|
|
60
|
+
// Pre-formatted blocks (the status table) keep their alignment.
|
|
61
|
+
const fenced = line.startsWith('```');
|
|
62
|
+
const block = [];
|
|
63
|
+
for (i += fenced ? 1 : 0; i < lines.length && (fenced ? !lines[i].startsWith('```') : lines[i].startsWith(' ')); i++)
|
|
64
|
+
block.push(fenced ? lines[i] : lines[i].slice(4));
|
|
65
|
+
if (!fenced) i--;
|
|
66
|
+
out.push(`<pre>${esc(block.join('\n'))}</pre>`);
|
|
67
|
+
} else if (line.trim()) out.push(`<p>${inline(line)}</p>`);
|
|
68
|
+
}
|
|
69
|
+
return out.join('\n');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @param {string} md
|
|
74
|
+
* @param {{title:string, generated:string}} o
|
|
75
|
+
*/
|
|
76
|
+
export function htmlPage(md, { title, generated }) {
|
|
77
|
+
return `<!doctype html>
|
|
78
|
+
<html lang="en">
|
|
79
|
+
<head>
|
|
80
|
+
<meta charset="utf-8">
|
|
81
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
82
|
+
<title>${esc(title)}</title>
|
|
83
|
+
<style>
|
|
84
|
+
:root { --bg: #fbfaf7; --fg: #1d1c1a; --muted: #5f5c55; --line: #e4e0d8; --card: #ffffff; --accent: #c2410c; --code-bg: #f1ede6; }
|
|
85
|
+
@media (prefers-color-scheme: dark) {
|
|
86
|
+
:root { --bg: #141312; --fg: #eeeae2; --muted: #a8a399; --line: #2c2a27; --card: #1b1a18; --accent: #f97316; --code-bg: #24221f; color-scheme: dark; }
|
|
87
|
+
}
|
|
88
|
+
* { box-sizing: border-box; }
|
|
89
|
+
body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
|
|
90
|
+
main { max-width: 860px; margin: 0 auto; padding: 32px max(16px, env(safe-area-inset-right, 0px)) 64px max(16px, env(safe-area-inset-left, 0px)); }
|
|
91
|
+
h1 { font-size: 1.9rem; letter-spacing: -0.02em; margin: 32px 0 8px; }
|
|
92
|
+
h2 { font-size: 1.3rem; margin: 32px 0 8px; padding-top: 16px; border-top: 1px solid var(--line); }
|
|
93
|
+
h3 { font-size: 1.05rem; margin: 20px 0 6px; }
|
|
94
|
+
p, li { max-width: 70ch; }
|
|
95
|
+
strong { color: var(--accent); }
|
|
96
|
+
code { font: 0.9em ui-monospace, Menlo, monospace; background: var(--code-bg); padding: 1px 5px; border-radius: 4px; }
|
|
97
|
+
pre { font: 13px/1.5 ui-monospace, Menlo, monospace; background: var(--code-bg); padding: 14px 16px; border-radius: 8px; overflow-x: auto; }
|
|
98
|
+
.table { overflow-x: auto; }
|
|
99
|
+
table { border-collapse: collapse; min-width: 420px; width: 100%; font-variant-numeric: tabular-nums; }
|
|
100
|
+
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); }
|
|
101
|
+
th { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); }
|
|
102
|
+
.num { text-align: right; }
|
|
103
|
+
footer { margin-top: 48px; color: var(--muted); font-size: 0.9rem; }
|
|
104
|
+
</style>
|
|
105
|
+
</head>
|
|
106
|
+
<body>
|
|
107
|
+
<main>
|
|
108
|
+
${mdToHtml(md)}
|
|
109
|
+
<footer>Generated by limitcast on ${esc(generated)} from data on this computer. https://limitcast.dev</footer>
|
|
110
|
+
</main>
|
|
111
|
+
</body>
|
|
112
|
+
</html>
|
|
113
|
+
`;
|
|
114
|
+
}
|
package/src/notify.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { stateDir } from './store.mjs';
|
|
6
|
+
|
|
7
|
+
// Desktop notifications (Pro, opt-in): one per change of state, raised from the status line.
|
|
8
|
+
|
|
9
|
+
const flag = () => join(stateDir(), 'notify.on');
|
|
10
|
+
const stateFile = () => join(stateDir(), 'notified.json');
|
|
11
|
+
const RANK = { OK: 0, RESET: 0, NEAR: 1, AT_RISK: 2, HIT: 3 };
|
|
12
|
+
const NAMES = { claude: 'Claude', codex: 'Codex' };
|
|
13
|
+
|
|
14
|
+
export const notifyEnabled = () => existsSync(flag());
|
|
15
|
+
|
|
16
|
+
/** @param {boolean} on */
|
|
17
|
+
export function setNotify(on) {
|
|
18
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
19
|
+
if (on) writeFileSync(flag(), '');
|
|
20
|
+
else rmSync(flag(), { force: true });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Messages for windows that got worse since the last notification, or reset after reaching their limit.
|
|
25
|
+
* Within one window the state only ratchets up, so a pace that wobbles around a threshold notifies once.
|
|
26
|
+
* @param {{src:string, win:string, pct:number, reset:number, wall:number|null, verdict:string}[]} rows
|
|
27
|
+
* @param {Record<string, {reset:number, verdict:string}>} prev
|
|
28
|
+
* @param {(ms:number)=>string} clock
|
|
29
|
+
*/
|
|
30
|
+
export function transitions(rows, prev, clock) {
|
|
31
|
+
const messages = [];
|
|
32
|
+
const next = { ...prev };
|
|
33
|
+
for (const f of rows) {
|
|
34
|
+
const key = `${f.src}|${f.win}`;
|
|
35
|
+
const name = `${NAMES[/** @type {'claude'} */ (f.src)] ?? f.src} ${f.win}`;
|
|
36
|
+
const p = prev[key];
|
|
37
|
+
const sameWindow = p && Math.abs(p.reset - f.reset) <= 120_000;
|
|
38
|
+
if (!sameWindow) {
|
|
39
|
+
if (p?.verdict === 'HIT' && f.verdict !== 'HIT') messages.push(`${name} limit reset: you're clear.`);
|
|
40
|
+
next[key] = { reset: f.reset, verdict: 'OK' };
|
|
41
|
+
}
|
|
42
|
+
const before = next[key].verdict;
|
|
43
|
+
const rank = RANK[/** @type {'OK'} */ (f.verdict)] ?? 0;
|
|
44
|
+
if (rank <= (RANK[/** @type {'OK'} */ (before)] ?? 0)) continue;
|
|
45
|
+
next[key] = { reset: f.reset, verdict: f.verdict };
|
|
46
|
+
if (f.verdict === 'NEAR') messages.push(`${name} limit is at ${Math.round(f.pct)}%. Resets ${clock(f.reset)}.`);
|
|
47
|
+
if (f.verdict === 'AT_RISK' && f.wall)
|
|
48
|
+
messages.push(`${name} limit is on pace to run out at ${clock(f.wall)}, before it resets at ${clock(f.reset)}.`);
|
|
49
|
+
if (f.verdict === 'HIT') messages.push(`${name} limit reached. Resets ${clock(f.reset)}.`);
|
|
50
|
+
}
|
|
51
|
+
return { messages, next };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Check the rows against what was last notified and send what's new. Never throws.
|
|
56
|
+
* @param {Parameters<typeof transitions>[0]} rows
|
|
57
|
+
* @param {(ms:number)=>string} clock
|
|
58
|
+
*/
|
|
59
|
+
export function notifyChanges(rows, clock) {
|
|
60
|
+
try {
|
|
61
|
+
let prev = {};
|
|
62
|
+
try {
|
|
63
|
+
prev = JSON.parse(readFileSync(stateFile(), 'utf8'));
|
|
64
|
+
} catch {
|
|
65
|
+
/* first run */
|
|
66
|
+
}
|
|
67
|
+
const { messages, next } = transitions(rows, prev, clock);
|
|
68
|
+
if (JSON.stringify(next) !== JSON.stringify(prev)) writeFileSync(stateFile(), JSON.stringify(next));
|
|
69
|
+
for (const m of messages) send(m);
|
|
70
|
+
return messages;
|
|
71
|
+
} catch {
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Show a desktop notification: macOS through osascript, Linux through notify-send. Fire and forget.
|
|
78
|
+
* @param {string} message
|
|
79
|
+
*/
|
|
80
|
+
export function send(message) {
|
|
81
|
+
const [cmd, args] =
|
|
82
|
+
process.platform === 'darwin'
|
|
83
|
+
? ['osascript', ['-e', `display notification ${JSON.stringify(message)} with title "limitcast"`]]
|
|
84
|
+
: ['notify-send', ['limitcast', message]];
|
|
85
|
+
const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
|
|
86
|
+
child.on('error', () => {}); // no notifier installed: nothing to do
|
|
87
|
+
child.unref();
|
|
88
|
+
}
|
package/src/results.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { claudeAccounts, forecast } from './forecast.mjs';
|
|
|
5
5
|
import { stateDir } from './store.mjs';
|
|
6
6
|
|
|
7
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 */
|
|
8
|
+
/** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, shadow?:boolean, kind?:string, from?:string}} Block t, wall, reset: epoch ms; shadow: a free install's preview, not acted on; kind "switch": a subagent moved to Sonnet instead of blocked */
|
|
9
9
|
|
|
10
10
|
const JITTER_MS = 120_000; // Codex resets_at drifts by seconds between events
|
|
11
11
|
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
@@ -122,8 +122,13 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
|
|
|
122
122
|
const watched = hits.filter((h) => !h.unseen);
|
|
123
123
|
const leads = hits.flatMap((h) => (h.warnedAt === null ? [] : [Math.round((h.at - h.warnedAt) / 60_000)]));
|
|
124
124
|
const mine = blocks.filter((b) => b.t >= since && Boolean(b.shadow) === !pro);
|
|
125
|
-
const outcomes = blockOutcomes(
|
|
126
|
-
|
|
125
|
+
const outcomes = blockOutcomes(
|
|
126
|
+
mine.filter((b) => b.kind !== 'switch'),
|
|
127
|
+
samples,
|
|
128
|
+
now,
|
|
129
|
+
);
|
|
130
|
+
const switches = mine.filter((b) => b.kind === 'switch').length;
|
|
131
|
+
return { readings, hits, watched: watched.length, leads, outcomes, switches };
|
|
127
132
|
}
|
|
128
133
|
|
|
129
134
|
/**
|
|
@@ -138,6 +143,7 @@ export function resultsShare(st, { days, pro, savedPerSession, notResent = 0 })
|
|
|
138
143
|
parts.push(`forecast ${st.leads.length} of the ${st.watched} it watched in advance${st.leads.length ? ` (avg ${avg(st.leads)} min ahead)` : ''}`);
|
|
139
144
|
if (st.outcomes.length)
|
|
140
145
|
parts.push(`${pro ? 'blocked' : 'would have blocked'} ${st.outcomes.length} runaway subagent${st.outcomes.length === 1 ? '' : 's'}`);
|
|
146
|
+
if (st.switches) parts.push(`${pro ? 'moved' : 'would have moved'} ${st.switches} subagent${st.switches === 1 ? '' : 's'} to Sonnet`);
|
|
141
147
|
if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller per session`);
|
|
142
148
|
if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent since install`);
|
|
143
149
|
return `${parts[0]} ${parts.slice(1).join('; ')}. https://limitcast.dev`;
|
|
@@ -153,6 +159,7 @@ export function weeklyLine(st, savedPerSession, notResent = 0) {
|
|
|
153
159
|
const parts = [`${st.hits.length} limit${st.hits.length === 1 ? '' : 's'} reached`];
|
|
154
160
|
if (st.leads.length) parts.push(`warned ahead on ${st.leads.length} (avg ${avg(st.leads)} min)`);
|
|
155
161
|
parts.push(`guard blocked ${st.outcomes.length} subagent${st.outcomes.length === 1 ? '' : 's'}`);
|
|
162
|
+
if (st.switches) parts.push(`moved ${st.switches} to Sonnet`);
|
|
156
163
|
if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller`);
|
|
157
164
|
if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent`);
|
|
158
165
|
return `limitcast this week: ${parts.join(', ')}. Details: limitcast results`;
|
|
@@ -241,6 +248,10 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
|
|
|
241
248
|
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
249
|
}
|
|
243
250
|
}
|
|
251
|
+
if (st.switches)
|
|
252
|
+
out.push(
|
|
253
|
+
`${pro ? 'Ran' : 'Pro would have run'} ${st.switches} subagent${st.switches === 1 ? '' : 's'} on Sonnet instead of your main model while a window was tight.`,
|
|
254
|
+
);
|
|
244
255
|
|
|
245
256
|
out.push('', '## Starting context');
|
|
246
257
|
out.push(saved ?? 'Run `limitcast trim` once to record your starting context, then check back here.');
|
package/src/value.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { claudeUsage } from './usage.mjs';
|
|
|
15
15
|
/** @typedef {{at:number, turns:number, savedPerTurn:number}} SessionValue savedPerTurn: tokens below the first measured start */
|
|
16
16
|
/** @typedef {{src:string, win:string, at:number, lead:number|null, unseen:boolean}} HitValue lead: minutes of warning */
|
|
17
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 */
|
|
18
|
+
/** @typedef {{since:number, scanned:number, sessions:Record<string, SessionValue>, hits:Record<string, HitValue>, blocks:Record<string, BlockValue>, switches?:Record<string, {shadow:boolean}>}} Value */
|
|
19
19
|
|
|
20
20
|
const file = () => join(stateDir(), 'value.json');
|
|
21
21
|
const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
@@ -74,7 +74,13 @@ export function foldEvents(v, { now, samples, blocks, start }) {
|
|
|
74
74
|
unseen: prev ? prev.unseen && h.unseen : h.unseen,
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
|
-
|
|
77
|
+
v.switches ??= {};
|
|
78
|
+
for (const b of blocks.filter((x) => x.kind === 'switch')) v.switches[String(b.t)] = { shadow: Boolean(b.shadow) };
|
|
79
|
+
for (const o of blockOutcomes(
|
|
80
|
+
blocks.filter((x) => x.kind !== 'switch'),
|
|
81
|
+
samples,
|
|
82
|
+
now,
|
|
83
|
+
)) {
|
|
78
84
|
const prev = v.blocks[String(o.t)];
|
|
79
85
|
if (prev && prev.outcome !== 'open') continue; // final once the window reset
|
|
80
86
|
v.blocks[String(o.t)] = { t: o.t, src: o.src, win: o.win, shadow: Boolean(o.shadow), outcome: o.outcome };
|
|
@@ -146,6 +152,8 @@ export function valueTotals(v) {
|
|
|
146
152
|
blocked: blocks.filter((b) => !b.shadow).length,
|
|
147
153
|
previewed: blocks.filter((b) => b.shadow).length,
|
|
148
154
|
confirmed: blocks.filter((b) => b.outcome === 'hit').length,
|
|
155
|
+
switched: Object.values(v.switches ?? {}).filter((s) => !s.shadow).length,
|
|
156
|
+
switchPreviewed: Object.values(v.switches ?? {}).filter((s) => s.shadow).length,
|
|
149
157
|
};
|
|
150
158
|
}
|
|
151
159
|
|
|
@@ -180,6 +188,11 @@ export function valueSection(t, { now, pro }) {
|
|
|
180
188
|
} else if (t.previewed) {
|
|
181
189
|
out.push(`- **Pro would have stopped ${t.previewed} subagent${t.previewed === 1 ? '' : 's'}** while a window was about to run out.`);
|
|
182
190
|
}
|
|
191
|
+
const moved = pro ? t.switched : t.switchPreviewed;
|
|
192
|
+
if (moved)
|
|
193
|
+
out.push(
|
|
194
|
+
`- **${pro ? 'Ran' : 'Pro would have run'} ${moved} subagent${moved === 1 ? '' : 's'} on Sonnet** instead of your main model while a window was tight.`,
|
|
195
|
+
);
|
|
183
196
|
return out.join('\n');
|
|
184
197
|
}
|
|
185
198
|
|