limitcast 0.10.0 → 0.11.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 CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Stretch your Claude Code plan. Every session starts with ~100k tokens of context before you type, re-sent on every turn and to every subagent. limitcast measures what's in it, names what you never use, and stops runaway subagents before they burn the rest of your window.
4
4
 
5
+ ![limitcast status, trim and results running in a terminal](https://limitcast.dev/demo.gif)
6
+
5
7
  ```
6
8
  $ limitcast trim
7
9
  Every Claude Code session starts at 102.7k tokens before your first message.
@@ -13,12 +15,15 @@ Every Claude Code session starts at 102.7k tokens before your first message.
13
15
 
14
16
  - **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
17
  - **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.
18
+ - **Subagent receipts and budgets (Pro):** when a subagent finishes you see what it cost: "that Explore subagent used ≈2.1% of your 5-hour window (34 calls)". `limitcast budget subagents 15` holds new subagents once they have used 15% of the current window.
19
+ - **Cold-cache warning (Pro):** after a long pause (60 min, `LIMITCAST_CACHE_MINUTES`) the prompt cache has expired and your next message re-sends the whole context as new tokens. limitcast holds that first message once and tells you what it will cost; send it again to go ahead, or `/compact` first.
20
+ - **Limit-change alert (Pro):** limitcast re-measures how many tokens move your meter by 1% every day and notifies you when that shifts by 15% or more, so you know when the limit itself changed.
16
21
  - **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`).
22
+ - **Pro extras:** desktop notifications (`limitcast notify on`), also to your phone (`notify ntfy <topic>`) or a Slack/Discord webhook (`notify webhook <url>`), run a job after the reset (`limitcast after-reset -- …`), a pointer to your other account when this one is near its limit, a `/compact` nudge in long sessions, and an HTML dashboard (`limitcast results --html`).
18
23
  - **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.
19
24
  - **Burn report (Pro):** Claude Code, Codex and Grok tokens by day, project, model and session.
20
25
  - **Runout forecast (free):** burn rate and the clock time each window runs out.
21
- - **Local only.** Reads the limit readings Claude Code passes to your status line and the logs Claude Code, Codex and Grok already write. No logins, and your usage data never leaves your machine. The free tier makes no network calls; a Pro license key talks to Polar only to activate, to re-check weekly, and to deactivate (it sends the key and your computer's name).
26
+ - **Local only.** Reads the limit readings Claude Code passes to your status line and the logs Claude Code, Codex and Grok already write. No logins, and your usage data never leaves your machine. The free tier makes no network calls; a Pro license key talks to Polar only to activate, to re-check weekly, and to deactivate (it sends the key and your computer's name). If you turn on phone or webhook notifications (Pro, off by default), each notification's text goes to the service you chose (ntfy.sh or your webhook) and nothing else.
22
27
 
23
28
  | | Claude Code | Codex | Grok |
24
29
  |---|---|---|---|
@@ -54,6 +59,8 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
54
59
  | `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 |
55
60
  | `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) |
56
61
  | `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. On macOS they come from a tiny limitcast notifier app, listed as "limitcast" in System Settings → Notifications |
62
+ | `limitcast notify ntfy <topic or https URL>` / `notify webhook <https URL>` | **Pro.** Also send every notification to your phone through [ntfy](https://ntfy.sh) (install the app, subscribe to the topic) or to a Slack or Discord incoming webhook. `off` removes it. Sent in the background, so no hook waits on the network |
63
+ | `limitcast budget subagents <percent>` / `off` | **Pro.** Once subagents have used that share of the current 5-hour window, the guard holds new ones until it resets. Priced from your own readings (needs about a day of use first) |
57
64
  | `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
58
65
  | `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
59
66
  | `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
@@ -73,13 +80,15 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
73
80
 
74
81
  Without a valid license the guard runs as a preview: it allows everything and records what it would have blocked (`limitcast results` shows it), so an expired license never blocks your work. Blocks a new subagent only when the spawning tool's window is on pace to run out before it resets, within 30 minutes (`LIMITCAST_GUARD_MINUTES`). A window already at 100% is left to Claude Code, so extra usage keeps working. `LIMITCAST_ALLOW=1` overrides. If the guard itself fails, it allows the call.
75
82
 
83
+ `install --guard` also adds two more hooks. A SubagentStop hook prices each finished subagent from its own transcript and, with Pro, shows you the receipt (never the model); `limitcast budget` and `results` use the same record. A UserPromptSubmit hook holds the first message after the prompt cache expired, once per pause, when the session re-sends 100k+ tokens; messages from background agents and `/compact` or `/clear` are never held. Installed `--guard` before 0.11? Run `limitcast doctor --fix` to add them.
84
+
76
85
  ## How the forecast works
77
86
 
78
87
  Each limit reading is saved to `~/.local/state/limitcast/samples.jsonl` when it changes (kept 8 days). The burn rate is the least-squares slope of percent used over the last hour of the current window, and the runout time is where that line reaches 100%. Windows of a day or more (the weekly one) use the average pace over the last full day, idle time included, unless the last hour's pace runs them out within the hour. **AT_RISK** means that happens before the reset; **NEAR** means 95% or more is used. Claude sessions of the same account share one history (matched by window reset times, and usage that only rises), so two accounts used in parallel never mix.
79
88
 
80
89
  ## Pricing
81
90
 
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.
91
+ 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, subagent receipts and budgets, the cold-cache warning, limit-change alerts, burn report, alerts, a weekly summary, notifications (desktop, phone or webhook), 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.
83
92
 
84
93
  ## License
85
94
 
package/bin/limitcast.mjs CHANGED
@@ -16,23 +16,26 @@ import {
16
16
  transcriptCwd,
17
17
  undoTrim,
18
18
  } from '../src/apply.mjs';
19
- import { calibrate } from '../src/calibrate.mjs';
19
+ import { calibrate, limitChange, limitChangeMessage, windowPct } from '../src/calibrate.mjs';
20
20
  import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
21
+ import { coldCost, coldMessage, firstWarning } from '../src/cold.mjs';
21
22
  import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
22
23
  import { formatChecks } from '../src/formats.mjs';
23
24
  import { runGuard } from '../src/guard.mjs';
24
- import { accountForecasts, compactHint, headroom, lastCallTokens } from '../src/hints.mjs';
25
+ import { accountForecasts, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
25
26
  import { htmlPage } from '../src/html.mjs';
26
27
  import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
27
28
  import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
28
- import { buildNotifierApp, notifierApp, notifyChanges, notifyEnabled, send, setNotify } from '../src/notify.mjs';
29
+ import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
29
30
  import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
30
31
  import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
31
32
  import { burnReport } from '../src/report.mjs';
32
- import { loadBlocks, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
33
+ import { loadBlocks, logBlock, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
33
34
  import { claudeSamples, readCodex } from '../src/sources.mjs';
34
35
  import { countInteractiveSince, latestInteractiveTranscript } from '../src/startup.mjs';
35
36
  import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
37
+ import { budgetSpent, getBudget, loadSubagents, logSubagent, receiptMessage, setBudget, subagentUsage, windowStart } from '../src/subagents.mjs';
38
+ import { forTerminal } from '../src/term.mjs';
36
39
  import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
37
40
  import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
38
41
  import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valueSection, valueTotals } from '../src/value.mjs';
@@ -59,9 +62,15 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
59
62
  limitcast trim --codex --apply / --undo turn off unused Codex MCP servers (enabled = false; reversible)
60
63
  limitcast saved tokens saved since limitcast first measured you
61
64
  limitcast install --guard block new subagents when a window is on pace to run out, and run
62
- them on Sonnet while a window is tight (NEAR or AT_RISK)
65
+ them on Sonnet while a window is tight (NEAR or AT_RISK); show what
66
+ each finished subagent cost; hold the first message after the prompt
67
+ cache expired (idle over 60 min, LIMITCAST_CACHE_MINUTES) and say what it costs
68
+ limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
63
69
  limitcast install --alerts tell you when your starting context grows, plus a weekly summary
64
- limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets
70
+ limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
71
+ and when your Claude limit itself changes
72
+ limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
73
+ limitcast notify webhook <url>|off also send them to a Slack or Discord webhook
65
74
  limitcast after-reset [--src claude|codex] [--window 5h|7d] [--detach] -- <command>
66
75
  run a heavy job once the window has reset
67
76
  limitcast results --html [--out FILE] results, current windows and the burn report as one page
@@ -73,6 +82,8 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
73
82
  Used by Claude Code and Codex (set up by install)
74
83
  limitcast statusline [-- <cmd...>] record limit readings, then run your status-line command
75
84
  limitcast guard PreToolUse hook (Pro)
85
+ limitcast prompt-check UserPromptSubmit hook: the cold-cache warning (Pro)
86
+ limitcast subagent-receipt SubagentStop hook: what the subagent cost (Pro)
76
87
  limitcast drift [--hook] SessionStart hook: compare starting context with the last session (Pro)
77
88
  `;
78
89
 
@@ -165,6 +176,85 @@ if (cmd === 'status') {
165
176
  // Fail open: a broken governor must not stop the agent.
166
177
  console.error(`limitcast guard skipped: ${e instanceof Error ? e.message : e}`);
167
178
  }
179
+ } else if (cmd === 'prompt-check') {
180
+ // UserPromptSubmit hook: hold the first message after the prompt cache expired, once, with its cost.
181
+ // Pro blocks; free only records what Pro would have held. Fails open.
182
+ try {
183
+ const hook = JSON.parse(readStdin());
184
+ const path = hook?.transcript_path;
185
+ const last = process.env.LIMITCAST_ALLOW !== '1' && typeof path === 'string' && existsSync(path) ? lastCall(path) : null;
186
+ const c = coldCost(hook?.prompt, last, now, { minutes: Number(process.env.LIMITCAST_CACHE_MINUTES ?? 60), calib: loadValue().calib });
187
+ if (c && last && firstWarning(String(hook.session_id), last.t)) {
188
+ const pro = isPro();
189
+ logBlock({
190
+ t: now,
191
+ kind: 'cold',
192
+ src: 'claude',
193
+ win: '5h',
194
+ pct: c.pct ?? 0,
195
+ wall: now,
196
+ reset: now,
197
+ tokens: c.tokens,
198
+ sid: hook.session_id,
199
+ ...(pro ? {} : { shadow: true }),
200
+ });
201
+ if (pro) console.log(JSON.stringify({ decision: 'block', reason: coldMessage(c) }));
202
+ }
203
+ } catch {
204
+ /* a hook must never stop a prompt by failing */
205
+ }
206
+ } else if (cmd === 'subagent-receipt') {
207
+ // SubagentStop hook: price the finished subagent against the 5-hour window and log it (for budgets and results).
208
+ // Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
209
+ try {
210
+ const hook = JSON.parse(readStdin());
211
+ const path = hook?.agent_transcript_path;
212
+ if (hook?.agent_type && typeof path === 'string') {
213
+ const u = subagentUsage(path);
214
+ const calib = loadValue().calib;
215
+ const pct = calib ? windowPct(calib, { writes: u.fresh, reads: u.read }) : null;
216
+ if (u.calls) {
217
+ logSubagent({
218
+ t: now,
219
+ id: hook.agent_id,
220
+ sid: hook.session_id,
221
+ type: hook.agent_type,
222
+ calls: u.calls,
223
+ fresh: u.fresh,
224
+ read: u.read,
225
+ ...(pct === null ? {} : { pct }),
226
+ });
227
+ if (isPro()) console.log(JSON.stringify({ systemMessage: receiptMessage(hook.agent_type, u, pct) }));
228
+ }
229
+ }
230
+ } catch {
231
+ /* a hook must never break the session */
232
+ }
233
+ } else if (cmd === 'budget') {
234
+ if (!isPro()) {
235
+ console.log(`Subagent budgets are part of limitcast Pro: ${UPGRADE_URL}`);
236
+ process.exit(2);
237
+ }
238
+ const value = args[1];
239
+ if (args[0] !== 'subagents' || (value !== undefined && value !== 'off' && !(Number(value) > 0 && Number(value) <= 100))) {
240
+ console.log('Usage: limitcast budget subagents <percent of the 5-hour window, 1-100>|off');
241
+ process.exit(1);
242
+ }
243
+ if (value !== undefined) setBudget(value === 'off' ? null : Number(value));
244
+ const budget = getBudget();
245
+ const samples = oneClaudeAccount(load(now - KEEP_MS));
246
+ const start = windowStart(forecastAll(samples, now), now);
247
+ const spent = budgetSpent(loadSubagents(start), new Set(samples.map((s) => s.sid)), new Set(load(now - KEEP_MS).map((s) => s.sid)));
248
+ console.log(
249
+ budget
250
+ ? `Subagent budget: ${budget}% of each 5-hour window. Used this window so far: ≈${spent.toFixed(1)}%. Once it's spent, the guard holds new subagents until the window resets.`
251
+ : `No subagent budget. Subagents used ≈${spent.toFixed(1)}% of this 5-hour window so far. Set one: limitcast budget subagents 15`,
252
+ );
253
+ if (budget && !installedFeatures().guard) console.log('The budget is enforced by the guard: limitcast install --guard');
254
+ if (budget && !loadValue().calib)
255
+ console.log(
256
+ 'limitcast prices subagents from your own limit readings, which takes about a day of use; until then nothing counts against the budget.',
257
+ );
168
258
  } else if (cmd === 'install') {
169
259
  const wantGuard = args.includes('--guard');
170
260
  const wantAlerts = args.includes('--alerts');
@@ -254,7 +344,7 @@ if (cmd === 'status') {
254
344
  ? `✓ 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`
255
345
  : 'Nothing to turn off: every server that is on was used.',
256
346
  );
257
- } else console.log(r.text);
347
+ } else console.log(forTerminal(r.text));
258
348
  process.exit(0);
259
349
  }
260
350
  /** @type {import('../src/trim.mjs').Activity} */
@@ -298,7 +388,7 @@ if (cmd === 'status') {
298
388
  if (out) {
299
389
  writeFileSync(out, `${text}\n`);
300
390
  console.log(`Wrote ${out}`);
301
- } else console.log(text);
391
+ } else console.log(forTerminal(text));
302
392
  } else if (cmd === 'drift') {
303
393
  // SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
304
394
  const hook = args.includes('--hook');
@@ -335,7 +425,7 @@ if (cmd === 'status') {
335
425
  if (lines.length) console.log(JSON.stringify({ systemMessage: lines.join('\n') }));
336
426
  } else if (!latest) console.log('No interactive Claude Code session found yet.');
337
427
  else if (!d) console.log('Starting context recorded. limitcast will tell you when it grows.');
338
- else console.log(d.alert ? driftMessage(d) : 'No meaningful change in your starting context since the last session.');
428
+ else console.log(d.alert ? forTerminal(driftMessage(d)) : 'No meaningful change in your starting context since the last session.');
339
429
  } catch (e) {
340
430
  if (!hook) throw e; // a hook must never break session start
341
431
  }
@@ -347,7 +437,9 @@ if (cmd === 'status') {
347
437
  const latest = await latestInteractiveTranscript(claudeRoot());
348
438
  if (latest) recordOverhead(snapshot(latest));
349
439
  const s = loadOverhead();
350
- console.log(s ? savedSummary(s, await countInteractiveSince(claudeRoot(), s.first.at)) : 'Nothing measured yet. Run `limitcast trim` first.');
440
+ console.log(
441
+ forTerminal(s ? savedSummary(s, await countInteractiveSince(claudeRoot(), s.first.at)) : 'Nothing measured yet. Run `limitcast trim` first.'),
442
+ );
351
443
  } else if (cmd === 'results') {
352
444
  // Free shows limits reached, how far ahead limitcast warned, and the guard preview; Pro adds real blocks and savings.
353
445
  const pro = isPro();
@@ -385,7 +477,7 @@ if (cmd === 'status') {
385
477
  const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
386
478
  const burn = burnReport(await readUsage(since, {}), { since, now }).replace(/^(#{1,2}) /gm, '#$1 ');
387
479
  const md = [
388
- resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }) }),
480
+ resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }), subagents: loadSubagents(since) }),
389
481
  '## Right now',
390
482
  '```',
391
483
  rows.length ? table(rows) : 'No readings yet.',
@@ -400,7 +492,12 @@ if (cmd === 'status') {
400
492
  opener.on('error', () => {});
401
493
  opener.unref();
402
494
  }
403
- } else console.log(resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }) }));
495
+ } else
496
+ console.log(
497
+ forTerminal(
498
+ resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }), subagents: loadSubagents(since) }),
499
+ ),
500
+ );
404
501
  } else if (cmd === 'notify') {
405
502
  // Desktop notifications from the status line (Pro, opt-in).
406
503
  if (!isPro()) {
@@ -408,6 +505,25 @@ if (cmd === 'status') {
408
505
  process.exit(2);
409
506
  }
410
507
  const what = args[0];
508
+ if (what === 'ntfy' || what === 'webhook') {
509
+ // Phone (ntfy) or Slack/Discord: every notification also goes there; setting one turns notifications on.
510
+ const err = args[1] ? setChannel(what, args[1]) : 'Usage: limitcast notify ntfy <topic|https-url>|off, or notify webhook <https-url>|off';
511
+ if (err) {
512
+ console.log(err);
513
+ process.exit(1);
514
+ }
515
+ if (args[1] !== 'off') {
516
+ setNotify(true);
517
+ send('limitcast notifications work.');
518
+ }
519
+ const ch = loadChannels();
520
+ console.log(
521
+ args[1] === 'off'
522
+ ? `Stopped sending to ${what === 'ntfy' ? 'ntfy' : 'the webhook'}.`
523
+ : `Sent a test to ${what === 'ntfy' ? `${ch.ntfy} (subscribe to that topic in the ntfy app)` : 'the webhook'}. Notifications are on. limitcast sends only the notification text there.`,
524
+ );
525
+ process.exit(0);
526
+ }
411
527
  if (what === 'on' || what === 'off') setNotify(what === 'on');
412
528
  // macOS: limitcast's own notifier app, so it shows up as "limitcast" in System Settings → Notifications.
413
529
  const mac = process.platform === 'darwin';
@@ -573,10 +689,15 @@ function freeWeeklyHint(t) {
573
689
  }
574
690
  if (t < from) return null;
575
691
  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);
692
+ const stopped = preview.filter((b) => !b.kind || b.kind === 'budget').length;
693
+ const moved = preview.filter((b) => b.kind === 'switch').length;
694
+ const cold = preview.filter((b) => b.kind === 'cold').length;
695
+ if (!stopped && !moved && !cold) return null;
696
+ const parts = [
697
+ stopped ? `stopped ${stopped} subagent${stopped === 1 ? '' : 's'}` : '',
698
+ moved ? `moved ${moved} to Sonnet` : '',
699
+ cold ? `caught ${cold} cold-cache message${cold === 1 ? '' : 's'}` : '',
700
+ ].filter(Boolean);
580
701
  return `this week Pro would have ${parts.join(' and ')} · limitcast trial`;
581
702
  }
582
703
 
@@ -609,8 +730,24 @@ async function refreshValue() {
609
730
  const v = foldEvents(loadValue(), { now, samples: [...claude, ...(await readCodex(since))], blocks: loadBlocks(since), start });
610
731
  await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
611
732
  // 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, {}));
733
+ const usage = await readUsage(since, {});
734
+ const c = calibrate(claude, usage);
613
735
  if (c) v.calib = { ...c, at: now };
736
+ // Once a day, the last 3 days on their own: a lasting shift against earlier days means the limit itself changed.
737
+ const cut = now - 3 * 86400_000;
738
+ const history = v.calibHistory ?? [];
739
+ if (!history.length || now - /** @type {number} */ (history.at(-1)?.at) >= 20 * 3600_000) {
740
+ const recent = calibrate(
741
+ claude.filter((s) => s.t >= cut),
742
+ usage.filter((u) => u.t >= cut),
743
+ );
744
+ if (recent) v.calibHistory = [...history, { ...recent, at: now }].slice(-60);
745
+ }
746
+ const change = limitChange(v.calibHistory ?? []);
747
+ if (change && (!v.limitChange || now - v.limitChange.at > 7 * 86400_000)) {
748
+ v.limitChange = { ...change, at: now };
749
+ if (isPro() && notifyEnabled()) send(limitChangeMessage(change));
750
+ }
614
751
  saveValue(v);
615
752
  return v;
616
753
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Stretch your Claude Code plan: measure what every session loads before you type, cut what you never use, and stop runaway subagents before they burn your window.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/calibrate.mjs CHANGED
@@ -60,6 +60,31 @@ export function calibrate(samples, usage) {
60
60
  return { fresh, read, n: obs.length };
61
61
  }
62
62
 
63
+ const DAY = 86400_000;
64
+
65
+ /**
66
+ * Has the limit itself changed? Compares the newest 3-day calibration with the median of those from 3 to 30 days
67
+ * before it. Returns new tokens per 1% of the 5-hour window then and now, when they differ by 15% or more.
68
+ * @param {{fresh:number, at:number}[]} history one calibration of the last 3 days per day, oldest first
69
+ * @returns {{from:number, to:number}|null}
70
+ */
71
+ export function limitChange(history) {
72
+ const last = history.at(-1);
73
+ if (!last) return null;
74
+ const before = history
75
+ .filter((h) => h.at <= last.at - 3 * DAY && h.at >= last.at - 30 * DAY)
76
+ .map((h) => h.fresh)
77
+ .sort((a, b) => a - b);
78
+ if (before.length < 3) return null;
79
+ const from = Math.round(1e6 / before[Math.floor(before.length / 2)]);
80
+ const to = Math.round(1e6 / last.fresh);
81
+ return Math.abs(to / from - 1) >= 0.15 ? { from, to } : null;
82
+ }
83
+
84
+ /** @param {{from:number, to:number}} c */
85
+ export const limitChangeMessage = (c) =>
86
+ `Your Claude limit looks ${c.to < c.from ? 'smaller' : 'bigger'}: 1% of the 5-hour window now takes ~${Math.round(c.to / 1000)}k new tokens, ${c.to < c.from ? 'down' : 'up'} from ~${Math.round(c.from / 1000)}k.`;
87
+
63
88
  /**
64
89
  * What a smaller starting context was worth against the 5-hour limit, in % of one window: each session writes its
65
90
  * starting context once (new tokens) and re-reads it on every call (cached tokens).
package/src/cold.mjs ADDED
@@ -0,0 +1,66 @@
1
+ // @ts-check
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { stateDir } from './store.mjs';
5
+
6
+ // Cold-cache warning (Pro, UserPromptSubmit hook). After a long pause the prompt cache has expired, so the next
7
+ // message re-sends the whole context as new tokens, which count against the limit far more than cached ones.
8
+ // The first message after such a pause is held once with its cost; sending it again goes through.
9
+
10
+ const MIN_TOKENS = 100_000;
11
+ const stateFile = () => join(stateDir(), 'cold.json');
12
+
13
+ /**
14
+ * What the next message will cost because the cache went cold, or null when it isn't worth a warning.
15
+ * @param {unknown} prompt
16
+ * @param {{tokens:number, t:number}|null} last the session's latest model call
17
+ * @param {number} now epoch ms
18
+ * @param {{minutes:number, calib?:{fresh:number, read:number}|null}} o minutes: the cache lifetime
19
+ * @returns {{tokens:number, idle:number, pct:number|null, warm:number|null}|null} pct/warm: % of the 5h window cold/warm
20
+ */
21
+ export function coldCost(prompt, last, now, { minutes, calib }) {
22
+ if (!last?.t || last.tokens < MIN_TOKENS) return null;
23
+ const p = String(prompt ?? '').trimStart();
24
+ // Background agents and other sessions report back as prompts; /compact and /clear are what the warning suggests.
25
+ if (p.startsWith('<') || /^\/(compact|clear)\b/.test(p)) return null;
26
+ const idle = Math.round((now - last.t) / 60_000);
27
+ if (idle < minutes) return null;
28
+ const m = last.tokens / 1e6;
29
+ return { tokens: last.tokens, idle, pct: calib ? m * calib.fresh : null, warm: calib ? m * calib.read : null };
30
+ }
31
+
32
+ /** @param {NonNullable<ReturnType<typeof coldCost>>} c */
33
+ export function coldMessage(c) {
34
+ const idle = c.idle >= 120 ? `${Math.round(c.idle / 60)} hours` : `${c.idle} minutes`;
35
+ const cost =
36
+ c.pct !== null && c.warm !== null
37
+ ? `≈${pct(c.pct)} of your 5-hour window (≈${pct(c.warm)} if the cache were still warm)`
38
+ : 'all at the new-token rate instead of the much cheaper cached one';
39
+ return (
40
+ `limitcast: this session sat idle for ${idle}, so its prompt cache has expired. Your message re-sends ${Math.round(c.tokens / 1000)}k tokens of context: ${cost}. ` +
41
+ 'Send it again to go ahead, or run /compact first to shrink it.'
42
+ );
43
+ }
44
+
45
+ const pct = (/** @type {number} */ x) => `${x < 1 ? x.toFixed(2) : x.toFixed(1)}%`;
46
+
47
+ /**
48
+ * True the first time a session is warned about this pause, false when the user re-sends.
49
+ * A held message never reaches the model, so the latest call stays the same until it goes through.
50
+ * @param {string} sid
51
+ * @param {number} lastT the latest model call's time
52
+ */
53
+ export function firstWarning(sid, lastT) {
54
+ /** @type {Record<string, number>} */
55
+ let seen = {};
56
+ try {
57
+ seen = JSON.parse(readFileSync(stateFile(), 'utf8'));
58
+ } catch {
59
+ /* first warning */
60
+ }
61
+ if (seen[sid] === lastT) return false;
62
+ const keep = Object.entries(seen).slice(-49); // the 49 most recent other sessions
63
+ mkdirSync(stateDir(), { recursive: true });
64
+ writeFileSync(stateFile(), JSON.stringify(Object.fromEntries([...keep.filter(([k]) => k !== sid), [sid, lastT]])));
65
+ return true;
66
+ }
package/src/guard.mjs CHANGED
@@ -3,6 +3,7 @@ import { forecastAll, oneClaudeAccount } from './forecast.mjs';
3
3
  import { logBlock } from './results.mjs';
4
4
  import { readCodex } from './sources.mjs';
5
5
  import { KEEP_MS, load } from './store.mjs';
6
+ import { budgetMessage, budgetSpent, getBudget, loadSubagents, windowStart } from './subagents.mjs';
6
7
 
7
8
  const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
8
9
 
@@ -91,6 +92,32 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
91
92
  }
92
93
  }
93
94
  if (reason) return preview ? null : reason;
95
+ // Pro: hold new Claude subagents once those of this account have used their budget of the current 5-hour window.
96
+ const budget = src === 'claude' ? getBudget() : null;
97
+ if (budget) {
98
+ const start = windowStart(forecasts, now);
99
+ const sid = hook.session_id ?? hook.sessionId;
100
+ const known = new Set(load(now - KEEP_MS).map((s) => s.sid));
101
+ const spent = budgetSpent(loadSubagents(start), new Set([...samples.map((s) => s.sid), sid]), known);
102
+ if (spent >= budget) {
103
+ try {
104
+ logBlock({
105
+ t: now,
106
+ kind: 'budget',
107
+ src: 'claude',
108
+ win: '5h',
109
+ pct: spent,
110
+ wall: now,
111
+ reset: start + 5 * 3600_000,
112
+ sid,
113
+ ...(preview ? { shadow: true } : {}),
114
+ });
115
+ } catch {
116
+ /* a failed log must not change the decision */
117
+ }
118
+ if (!preview) return budgetMessage(spent, budget);
119
+ }
120
+ }
94
121
  // Not blocked, but a window is tight: run a new Claude subagent on Sonnet instead of the main (usually Opus) model.
95
122
  const input = hook?.tool_input ?? hook?.toolInput;
96
123
  const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
package/src/hints.mjs CHANGED
@@ -46,10 +46,17 @@ const COMPACT_AT = 150_000; // tokens re-sent per model call worth a /compact
46
46
 
47
47
  /**
48
48
  * Tokens the latest main-thread model call of a session sent (input + cache), from the transcript's tail.
49
+ * @param {string} path
50
+ */
51
+ export const lastCallTokens = (path) => lastCall(path)?.tokens ?? null;
52
+
53
+ /**
54
+ * The latest main-thread model call of a session: tokens it sent (input + cache) and when (epoch ms; 0 if unknown).
49
55
  * Reads at most the last 256 KB, so it stays cheap on multi-megabyte transcripts.
50
56
  * @param {string} path
57
+ * @returns {{tokens:number, t:number}|null}
51
58
  */
52
- export function lastCallTokens(path) {
59
+ export function lastCall(path) {
53
60
  const size = statSync(path).size;
54
61
  const len = Math.min(size, 256 * 1024);
55
62
  const buf = Buffer.alloc(len);
@@ -60,8 +67,13 @@ export function lastCallTokens(path) {
60
67
  for (const line of lines) {
61
68
  if (!line.includes('"usage"') || line.includes('"isSidechain":true')) continue;
62
69
  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);
70
+ const e = JSON.parse(line);
71
+ const u = e?.message?.usage;
72
+ if (u)
73
+ return {
74
+ tokens: (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0),
75
+ t: Date.parse(e.timestamp) || 0,
76
+ };
65
77
  } catch {
66
78
  /* a torn first line of the tail */
67
79
  }
package/src/install.mjs CHANGED
@@ -97,15 +97,12 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
97
97
  }
98
98
  if (guard) {
99
99
  upsertGuard(cfg, { matcher: 'Task|Agent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] });
100
- changes.push('added the Claude Code subagent guard');
100
+ upsertHook(cfg, 'UserPromptSubmit', { hooks: [{ type: 'command', command: `${self} prompt-check`, timeout: 10 }] }, isPromptCheck);
101
+ upsertHook(cfg, 'SubagentStop', { matcher: '', hooks: [{ type: 'command', command: `${self} subagent-receipt`, timeout: 15 }] }, isReceipt);
102
+ changes.push('added the Claude Code subagent guard, subagent receipts and the cold-cache warning');
101
103
  }
102
104
  if (alerts) {
103
- cfg.hooks ??= {};
104
- const list = (cfg.hooks.SessionStart ??= []);
105
- const entry = { matcher: '', hooks: [{ type: 'command', command: `${self} drift --hook`, timeout: 15 }] };
106
- const i = list.findIndex(isAlert);
107
- if (i >= 0) list[i] = entry;
108
- else list.push(entry);
105
+ upsertHook(cfg, 'SessionStart', { matcher: '', hooks: [{ type: 'command', command: `${self} drift --hook`, timeout: 15 }] }, isAlert);
109
106
  changes.push('added the starting-context alert');
110
107
  }
111
108
  writeSettings(path, cfg);
@@ -126,9 +123,20 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
126
123
  * @param {any} entry
127
124
  */
128
125
  function upsertGuard(cfg, entry) {
126
+ upsertHook(cfg, 'PreToolUse', entry, isGuard);
127
+ }
128
+
129
+ /**
130
+ * Put limitcast's entry in one hook event: update it where it is, else append.
131
+ * @param {any} cfg
132
+ * @param {string} event
133
+ * @param {any} entry
134
+ * @param {(h:any)=>boolean} mine
135
+ */
136
+ function upsertHook(cfg, event, entry, mine) {
129
137
  cfg.hooks ??= {};
130
- const list = (cfg.hooks.PreToolUse ??= []);
131
- const i = list.findIndex(isGuard);
138
+ const list = (cfg.hooks[event] ??= []);
139
+ const i = list.findIndex(mine);
132
140
  if (i >= 0) list[i] = entry;
133
141
  else list.push(entry);
134
142
  }
@@ -152,10 +160,15 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath()
152
160
  cfg.hooks.PreToolUse = cfg.hooks.PreToolUse.filter((/** @type {any} */ h) => !isGuard(h));
153
161
  if (cfg.hooks.PreToolUse.length < before) changes.push('removed the Claude Code subagent guard');
154
162
  }
155
- const alertsBefore = cfg.hooks?.SessionStart?.length ?? 0;
156
- if (alertsBefore) {
157
- cfg.hooks.SessionStart = cfg.hooks.SessionStart.filter((/** @type {any} */ h) => !isAlert(h));
158
- if (cfg.hooks.SessionStart.length < alertsBefore) changes.push('removed the starting-context alert');
163
+ for (const [event, mine, what] of /** @type {[string, (h:any)=>boolean, string][]} */ ([
164
+ ['SessionStart', isAlert, 'the starting-context alert'],
165
+ ['UserPromptSubmit', isPromptCheck, 'the cold-cache warning'],
166
+ ['SubagentStop', isReceipt, 'subagent receipts'],
167
+ ])) {
168
+ const n = cfg.hooks?.[event]?.length ?? 0;
169
+ if (!n) continue;
170
+ cfg.hooks[event] = cfg.hooks[event].filter((/** @type {any} */ h) => !mine(h));
171
+ if (cfg.hooks[event].length < n) changes.push(`removed ${what}`);
159
172
  }
160
173
  writeSettings(path, cfg);
161
174
  if (existsSync(codexPath)) {
@@ -200,9 +213,12 @@ export function installedFeatures(path = settingsPath()) {
200
213
  /** @param {any} h */
201
214
  const isGuard = (h) =>
202
215
  (h.hooks ?? []).some((/** @type {any} */ x) => typeof x.command === 'string' && x.command.includes(MARK) && /\bguard\b/.test(x.command));
203
- /** @param {any} h */
204
- const isAlert = (h) =>
205
- (h.hooks ?? []).some((/** @type {any} */ x) => typeof x.command === 'string' && x.command.includes(MARK) && /\bdrift --hook\b/.test(x.command));
216
+ /** @param {RegExp} re @returns {(h:any)=>boolean} */
217
+ const runs = (re) => (h) =>
218
+ (h.hooks ?? []).some((/** @type {any} */ x) => typeof x.command === 'string' && x.command.includes(MARK) && re.test(x.command));
219
+ const isAlert = runs(/\bdrift --hook\b/);
220
+ const isPromptCheck = runs(/\bprompt-check\b/);
221
+ const isReceipt = runs(/\bsubagent-receipt\b/);
206
222
 
207
223
  /** @param {string} path */
208
224
  export function readSettings(path) {
@@ -294,11 +310,19 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
294
310
  : `Node path in settings is gone (${exePath}): run \`limitcast doctor --fix\``,
295
311
  });
296
312
  }
297
- const guard = /** @type {any} */ (cfg.hooks?.PreToolUse ?? []).some(isGuard);
313
+ const hooks = /** @type {any} */ (cfg).hooks ?? {};
314
+ const guard = (hooks.PreToolUse ?? []).some(isGuard);
298
315
  out.push({
299
316
  ok: true,
300
317
  line: guard ? 'Claude Code subagent guard installed' : 'Claude Code subagent guard not installed (optional: `limitcast install --guard`)',
301
318
  });
319
+ // Installed with --guard before 0.11: the cold-cache warning and subagent receipts are missing until a re-install.
320
+ const newer = (hooks.UserPromptSubmit ?? []).some(isPromptCheck) && (hooks.SubagentStop ?? []).some(isReceipt);
321
+ if (guard && !newer)
322
+ out.push({
323
+ ok: !license?.ok,
324
+ line: 'Cold-cache warning and subagent receipts not installed yet: run `limitcast doctor --fix`',
325
+ });
302
326
  if (existsSync(codexPath)) out.push(codexGuardCheck(codexPath));
303
327
  out.push(
304
328
  samplesAgeMs === null
package/src/notify.mjs CHANGED
@@ -2,9 +2,11 @@
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
+ import { isPro } from './license.mjs';
5
6
  import { stateDir } from './store.mjs';
6
7
 
7
8
  // Desktop notifications (Pro, opt-in): one per change of state, raised from the status line.
9
+ // Optionally also sent to a phone (ntfy) or a Slack/Discord webhook.
8
10
 
9
11
  const flag = () => join(stateDir(), 'notify.on');
10
12
  const stateFile = () => join(stateDir(), 'notified.json');
@@ -80,6 +82,12 @@ export function notifyChanges(rows, clock) {
80
82
  * @param {string} message
81
83
  */
82
84
  export function send(message) {
85
+ // Pro: the same message to the phone (ntfy) or a chat webhook, by a detached curl so no hook waits on the network.
86
+ try {
87
+ if (isPro()) for (const a of remoteArgs(loadChannels(), message)) run('curl', a);
88
+ } catch {
89
+ /* a broken channel config must not stop the desktop notification */
90
+ }
83
91
  if (process.platform === 'darwin' && existsSync(notifierApp())) {
84
92
  appendFileSync(queueFile(), `${message.replace(/\n/g, ' ')}\n`);
85
93
  run('open', ['-g', '-a', notifierApp()]);
@@ -89,6 +97,52 @@ export function send(message) {
89
97
  else run('notify-send', ['limitcast', message]);
90
98
  }
91
99
 
100
+ const channelsFile = () => join(stateDir(), 'notify.json');
101
+
102
+ /** @returns {{ntfy?:string, webhook?:string}} */
103
+ export function loadChannels() {
104
+ try {
105
+ return JSON.parse(readFileSync(channelsFile(), 'utf8'));
106
+ } catch {
107
+ return {};
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Set or remove ("off") a remote channel. An ntfy topic becomes https://ntfy.sh/<topic>; URLs must be https.
113
+ * @param {'ntfy'|'webhook'} kind
114
+ * @param {string} value
115
+ * @returns {string|null} the error, if the value is not usable
116
+ */
117
+ export function setChannel(kind, value) {
118
+ const channels = loadChannels();
119
+ if (value === 'off') delete channels[kind];
120
+ else {
121
+ const url = kind === 'ntfy' && /^[\w-]{1,64}$/.test(value) ? `https://ntfy.sh/${value}` : value;
122
+ if (!/^https:\/\/[^\s/]+/.test(url))
123
+ return kind === 'ntfy' ? 'Give an ntfy topic (letters, digits, - and _) or an https:// URL.' : 'Give an https:// webhook URL.';
124
+ channels[kind] = url;
125
+ }
126
+ mkdirSync(stateDir(), { recursive: true });
127
+ writeFileSync(channelsFile(), JSON.stringify(channels), { mode: 0o600 }); // a webhook URL is a secret
128
+ return null;
129
+ }
130
+
131
+ /**
132
+ * curl arguments for each configured channel. Webhooks get {text, content}: Slack reads text, Discord content.
133
+ * --data-raw, so a message starting with @ is never read as a file name.
134
+ * @param {{ntfy?:string, webhook?:string}} channels
135
+ * @param {string} message
136
+ */
137
+ export function remoteArgs(channels, message) {
138
+ const base = ['-s', '-m', '10', '-o', '/dev/null'];
139
+ const out = [];
140
+ if (channels.ntfy) out.push([...base, '-H', 'Title: limitcast', '--data-raw', message, channels.ntfy]);
141
+ if (channels.webhook)
142
+ out.push([...base, '-H', 'Content-Type: application/json', '--data-raw', JSON.stringify({ text: message, content: message }), channels.webhook]);
143
+ return out;
144
+ }
145
+
92
146
  /** @param {string} cmd @param {string[]} args */
93
147
  function run(cmd, args) {
94
148
  const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
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, 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 */
8
+ /** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, shadow?:boolean, kind?:string, from?:string, tokens?:number}} 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, "budget": a subagent held over the budget, "cold": a message held after the prompt cache expired (pct: its cost, tokens: context re-sent); no kind: a forecast block */
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' };
@@ -123,12 +123,24 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
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
125
  const outcomes = blockOutcomes(
126
- mine.filter((b) => b.kind !== 'switch'),
126
+ mine.filter((b) => !b.kind),
127
127
  samples,
128
128
  now,
129
129
  );
130
130
  const switches = mine.filter((b) => b.kind === 'switch').length;
131
- return { readings, hits, watched: watched.length, leads, outcomes, switches };
131
+ const colds = mine.filter((b) => b.kind === 'cold');
132
+ const budgets = mine.filter((b) => b.kind === 'budget').length;
133
+ return {
134
+ readings,
135
+ hits,
136
+ watched: watched.length,
137
+ leads,
138
+ outcomes,
139
+ switches,
140
+ colds: colds.length,
141
+ coldPct: colds.reduce((a, b) => a + b.pct, 0),
142
+ budgets,
143
+ };
132
144
  }
133
145
 
134
146
  /**
@@ -160,6 +172,8 @@ export function weeklyLine(st, savedPerSession, notResent = 0) {
160
172
  if (st.leads.length) parts.push(`warned ahead on ${st.leads.length} (avg ${avg(st.leads)} min)`);
161
173
  parts.push(`guard blocked ${st.outcomes.length} subagent${st.outcomes.length === 1 ? '' : 's'}`);
162
174
  if (st.switches) parts.push(`moved ${st.switches} to Sonnet`);
175
+ if (st.budgets) parts.push(`held ${st.budgets} over budget`);
176
+ if (st.colds) parts.push(`caught ${st.colds} cold-cache message${st.colds === 1 ? '' : 's'}`);
163
177
  if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller`);
164
178
  if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent`);
165
179
  return `limitcast this week: ${parts.join(', ')}. Details: limitcast results`;
@@ -183,15 +197,16 @@ export function weeklyDue(now) {
183
197
  return last !== null;
184
198
  }
185
199
 
200
+ const pctText = (/** @type {number} */ x) => `${x < 1 ? x.toFixed(2) : x.toFixed(1)}%`;
186
201
  const avg = (/** @type {number[]} */ xs) => Math.round(xs.reduce((a, b) => a + b, 0) / xs.length);
187
202
  const fmtK = (/** @type {number} */ n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
188
203
 
189
204
  /**
190
- * @param {{now:number, days:number, samples:Sample[], blocks:Block[], pro:boolean, saved:string|null, value?:string}} r
205
+ * @param {{now:number, days:number, samples:Sample[], blocks:Block[], pro:boolean, saved:string|null, value?:string, subagents?:import('./subagents.mjs').SubagentEntry[]}} r
191
206
  * blocks: every logged block (Pro blocks and free previews); saved: the starting-context text, if any;
192
- * value: the "since you installed" section, shown first
207
+ * value: the "since you installed" section, shown first; subagents: the finished-subagent ledger
193
208
  */
194
- export function resultsReport({ now, days, samples, blocks, pro, saved, value = '' }) {
209
+ export function resultsReport({ now, days, samples, blocks, pro, saved, value = '', subagents = [] }) {
195
210
  const when = (/** @type {number} */ ms) =>
196
211
  new Date(ms).toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false });
197
212
  const name = (/** @type {{src:string, win:string}} */ x) => `${NAMES[/** @type {'claude'} */ (x.src)] ?? x.src} ${x.win}`;
@@ -252,6 +267,25 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
252
267
  out.push(
253
268
  `${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
269
  );
270
+ if (st.budgets) out.push(`Held ${st.budgets} subagent${st.budgets === 1 ? '' : 's'} once subagents had used their budget of the 5-hour window.`);
271
+
272
+ const recent = subagents.filter((e) => e.t >= now - days * 86400_000);
273
+ if (recent.length || st.colds) {
274
+ out.push('', '## Subagents and cold caches');
275
+ const priced = recent.filter((e) => e.pct !== undefined).map((e) => /** @type {number} */ (e.pct));
276
+ if (recent.length)
277
+ out.push(
278
+ `${recent.length} subagent${recent.length === 1 ? '' : 's'} finished` +
279
+ (priced.length
280
+ ? `, ≈${pctText(priced.reduce((a, b) => a + b, 0))} of a 5-hour window in all; the biggest ≈${pctText(Math.max(...priced))}.${pro ? '' : " Pro shows each one's cost when it finishes and can cap them per window."}`
281
+ : '.'),
282
+ );
283
+ if (st.colds)
284
+ out.push(
285
+ `${pro ? 'Held' : 'Pro would have held'} ${st.colds} message${st.colds === 1 ? '' : 's'} sent after the prompt cache had expired` +
286
+ (st.coldPct ? `, each re-sending the whole context (≈${pctText(st.coldPct)} of a 5-hour window in all).` : '.'),
287
+ );
288
+ }
255
289
 
256
290
  out.push('', '## Starting context');
257
291
  out.push(saved ?? 'Run `limitcast trim` once to record your starting context, then check back here.');
@@ -0,0 +1,133 @@
1
+ // @ts-check
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { stateDir } from './store.mjs';
6
+
7
+ // Subagent receipts and budgets (Pro). A SubagentStop hook prices each finished subagent against the 5-hour window
8
+ // (from the user's own calibration) and logs it; the guard holds new subagents once a window's budget is spent.
9
+
10
+ /** @typedef {{t:number, id?:string, sid?:string, type?:string, calls:number, fresh:number, read:number, pct?:number}} SubagentEntry */
11
+
12
+ const ledger = () => join(stateDir(), 'subagents.jsonl');
13
+ const configFile = () => join(stateDir(), 'config.json');
14
+ const FIVE_H = 5 * 3600_000;
15
+
16
+ /**
17
+ * New (input, cache writes, output) and cached tokens a subagent used, and its model calls.
18
+ * A call's usage repeats on every content block it streamed, so calls are counted once by message id.
19
+ * @param {string} path the subagent's transcript
20
+ */
21
+ export function subagentUsage(path) {
22
+ const file = path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
23
+ /** @type {Map<string, any>} */
24
+ const calls = new Map();
25
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
26
+ if (!line.includes('"usage"')) continue;
27
+ try {
28
+ const m = JSON.parse(line)?.message;
29
+ if (m?.usage) calls.set(m.id ?? `line${calls.size}`, m.usage);
30
+ } catch {
31
+ /* a partial line */
32
+ }
33
+ }
34
+ let fresh = 0;
35
+ let read = 0;
36
+ for (const u of calls.values()) {
37
+ fresh += (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.output_tokens ?? 0);
38
+ read += u.cache_read_input_tokens ?? 0;
39
+ }
40
+ return { fresh, read, calls: calls.size };
41
+ }
42
+
43
+ /**
44
+ * "limitcast: that Explore subagent used ≈2.1% of your 5-hour window (34 calls)."
45
+ * @param {string} type
46
+ * @param {{fresh:number, read:number, calls:number}} u
47
+ * @param {number|null} pct
48
+ */
49
+ export function receiptMessage(type, u, pct) {
50
+ const what = type ? `that ${type} subagent` : 'that subagent';
51
+ const calls = `${u.calls} call${u.calls === 1 ? '' : 's'}`;
52
+ if (pct === null) return `limitcast: ${what} used ${k(u.fresh + u.read)} tokens, ${k(u.fresh)} of them new (${calls}).`;
53
+ return `limitcast: ${what} used ≈${pct < 1 ? pct.toFixed(2) : pct.toFixed(1)}% of your 5-hour window (${calls}, ${k(u.fresh)} new tokens).`;
54
+ }
55
+
56
+ const k = (/** @type {number} */ n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
57
+
58
+ /** @param {SubagentEntry} e */
59
+ export function logSubagent(e) {
60
+ mkdirSync(stateDir(), { recursive: true });
61
+ appendFileSync(ledger(), `${JSON.stringify(e)}\n`);
62
+ }
63
+
64
+ /**
65
+ * Subagents that finished since `since`. A subagent that stops twice (a hook kept it going) counts once, as its last.
66
+ * shortcut: never pruned; one short line per subagent, prune when someone's ledger passes a few MB.
67
+ * @param {number} since epoch ms
68
+ * @returns {SubagentEntry[]}
69
+ */
70
+ export function loadSubagents(since) {
71
+ if (!existsSync(ledger())) return [];
72
+ /** @type {Map<string, SubagentEntry>} */
73
+ const out = new Map();
74
+ for (const line of readFileSync(ledger(), 'utf8').split('\n')) {
75
+ try {
76
+ const e = JSON.parse(line);
77
+ if (e.t >= since) out.set(e.id ?? `t${e.t}`, e);
78
+ } catch {
79
+ /* blank or partial line */
80
+ }
81
+ }
82
+ return [...out.values()];
83
+ }
84
+
85
+ /** @returns {number|null} % of each 5-hour window subagents may use */
86
+ export function getBudget() {
87
+ try {
88
+ const b = JSON.parse(readFileSync(configFile(), 'utf8')).subagentBudget;
89
+ return typeof b === 'number' && b > 0 ? b : null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+
95
+ /** @param {number|null} pct */
96
+ export function setBudget(pct) {
97
+ let cfg = {};
98
+ try {
99
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
100
+ } catch {
101
+ /* new */
102
+ }
103
+ mkdirSync(stateDir(), { recursive: true });
104
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
105
+ }
106
+
107
+ /**
108
+ * When the current Claude 5-hour window started: its reset minus 5 hours, or 5 hours ago without a reading.
109
+ * @param {{src:string, win:string, verdict:string, reset:number}[]} forecasts
110
+ * @param {number} now
111
+ */
112
+ export function windowStart(forecasts, now) {
113
+ const f = forecasts.find((x) => x.src === 'claude' && x.win === '5h' && x.verdict !== 'RESET');
114
+ return f ? f.reset - FIVE_H : now - FIVE_H;
115
+ }
116
+
117
+ /**
118
+ * % of the window this account's subagents used: those of its sessions, and of sessions no account has readings
119
+ * for yet. Subagents priced before the first calibration count 0.
120
+ * @param {SubagentEntry[]} entries
121
+ * @param {Set<string|undefined>} mine sessions of the account
122
+ * @param {Set<string|undefined>} known sessions of every account
123
+ */
124
+ export const budgetSpent = (entries, mine, known) =>
125
+ entries.filter((e) => mine.has(e.sid) || !known.has(e.sid)).reduce((a, e) => a + (e.pct ?? 0), 0);
126
+
127
+ /**
128
+ * @param {number} spent
129
+ * @param {number} budget
130
+ */
131
+ export const budgetMessage = (spent, budget) =>
132
+ `limitcast: subagents have used ≈${spent.toFixed(1)}% of this 5-hour window, over your ${budget}% budget. ` +
133
+ 'Finish with the agents already running, raise it with `limitcast budget subagents <percent>`, or set LIMITCAST_ALLOW=1 to spawn anyway.';
package/src/term.mjs ADDED
@@ -0,0 +1,13 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * The Markdown reports for a person at a terminal: headings and **bold** in bold, markers gone.
5
+ * Piped or written to a file, the Markdown is left as is. NO_COLOR drops the styling, not the cleanup.
6
+ * @param {string} md
7
+ * @param {{tty?: boolean, color?: boolean}} [o]
8
+ */
9
+ export function forTerminal(md, { tty = process.stdout.isTTY === true, color = !process.env.NO_COLOR } = {}) {
10
+ if (!tty) return md;
11
+ const b = color ? (/** @type {string} */ s) => `\x1b[1m${s}\x1b[22m` : (/** @type {string} */ s) => s;
12
+ return md.replace(/^#{1,6} (.+)$/gm, (_, h) => b(h)).replace(/\*\*(.+?)\*\*/g, (_, s) => b(s));
13
+ }
package/src/value.mjs CHANGED
@@ -2,7 +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
+ import { limitChangeMessage, windowPct } from './calibrate.mjs';
6
6
  import { blockOutcomes, limitHits } from './results.mjs';
7
7
  import { startupBreakdown } from './startup.mjs';
8
8
  import { stateDir } from './store.mjs';
@@ -16,7 +16,8 @@ import { claudeUsage } from './usage.mjs';
16
16
  /** @typedef {{at:number, turns:number, savedPerTurn:number}} SessionValue savedPerTurn: tokens below the first measured start */
17
17
  /** @typedef {{src:string, win:string, at:number, lead:number|null, unseen:boolean}} HitValue lead: minutes of warning */
18
18
  /** @typedef {{t:number, src:string, win:string, shadow:boolean, outcome:string}} BlockValue */
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
+ /** @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}, calibHistory?:{fresh:number, read:number, n:number, at:number}[], limitChange?:{from:number, to:number, at:number}}} Value
20
+ * calibHistory: one calibration of the last 3 days per day, to notice limit changes */
20
21
 
21
22
  const file = () => join(stateDir(), 'value.json');
22
23
  const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
@@ -78,7 +79,7 @@ export function foldEvents(v, { now, samples, blocks, start }) {
78
79
  v.switches ??= {};
79
80
  for (const b of blocks.filter((x) => x.kind === 'switch')) v.switches[String(b.t)] = { shadow: Boolean(b.shadow) };
80
81
  for (const o of blockOutcomes(
81
- blocks.filter((x) => x.kind !== 'switch'),
82
+ blocks.filter((x) => !x.kind),
82
83
  samples,
83
84
  now,
84
85
  )) {
@@ -156,6 +157,7 @@ export function valueTotals(v) {
156
157
  switched: Object.values(v.switches ?? {}).filter((s) => !s.shadow).length,
157
158
  switchPreviewed: Object.values(v.switches ?? {}).filter((s) => s.shadow).length,
158
159
  calib: v.calib ?? null,
160
+ limitChange: v.limitChange ?? null,
159
161
  // Against the 5-hour limit: each session wrote its smaller start once and re-read it on every call.
160
162
  windowPct: v.calib
161
163
  ? windowPct(v.calib, {
@@ -201,6 +203,8 @@ export function valueSection(t, { now, pro }) {
201
203
  } else if (t.previewed) {
202
204
  out.push(`- **Pro would have stopped ${t.previewed} subagent${t.previewed === 1 ? '' : 's'}** while a window was about to run out.`);
203
205
  }
206
+ if (t.limitChange && now - t.limitChange.at < 14 * 86400_000)
207
+ out.push(`- **${limitChangeMessage(t.limitChange)}** (noticed ${new Date(t.limitChange.at).toLocaleDateString()}, from your own readings)`);
204
208
  const moved = pro ? t.switched : t.switchPreviewed;
205
209
  if (moved)
206
210
  out.push(