limitcast 0.12.0 → 0.13.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 CHANGED
@@ -51,7 +51,7 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
51
51
 
52
52
  **Codex:** forecasts and reports need no setup (`~/.codex/sessions`, or `$CODEX_HOME/sessions`). With `--guard`, `install` also appends the guard to `~/.codex/hooks.json`, after your existing hooks so the ones you've already trusted keep their trust. Codex runs a new hook only once you approve it: start Codex and accept it. `limitcast doctor` shows whether it's trusted.
53
53
 
54
- **Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json`. `install` wraps `[ui.status_line]` in `~/.grok/config.toml` (session model, context % and cost on one line; the limitcast forecast under it). `--guard` writes `~/.grok/hooks/limitcast.json` matching `spawn_subagent`. Grok stores spend, not a % used, so the status line shows `grok 5h $X · 7d $Y` until you set a dollar cap (`limitcast budget grok <usd>`); then `status` forecasts that window and the guard blocks new spawns when it is on pace to run out. Restart Grok to load the status line and hook.
54
+ **Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json` and prices Grok models at xAI list prices (the same API-equivalent column as Claude). `install` wraps `[ui.status_line]` in `~/.grok/config.toml` (session model, context % and cost on one line; the limitcast forecast under it). `--guard` writes `~/.grok/hooks/limitcast.json` matching `spawn_subagent`. Grok stores spend, not a % used, so the status line shows `grok 5h $X · 7d $Y` until you set a dollar cap (`limitcast budget grok <usd>`); then `status` forecasts that window and the guard blocks new spawns when it is on pace to run out. `limitcast subagent-model explore grok-4.3` writes `[subagents.models]` (restart Grok). Restart Grok to load the status line and hook.
55
55
 
56
56
  ## Commands
57
57
 
@@ -63,13 +63,15 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
63
63
  | `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 |
64
64
  | `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 |
65
65
  | `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) |
66
+ | `limitcast subagent-model <type> <sonnet\|opus\|haiku\|claude-id\|grok-id>` / `off` | **Pro.** Run new subagents of that type (for example `Explore` or `explore`) on that model, unless the spawn names a model itself. Grok ids also write `[subagents.models]` in `~/.grok/config.toml` (restart Grok). Without arguments it lists what is pinned and the types you ran in the last 30 days. Needs `install --guard`; `results` counts the subagents it moved |
67
+ | `limitcast plan [--days N]`, `limitcast plan set <pro\|max5\|max20>` / `off` | **Pro.** Does your Claude plan fit how much you use? From a long-lived record of the peak of every 5-hour and weekly window (kept 120 days; it starts when you install this version) it says whether you reached your limits often enough to look at the next plan, or used so little that a smaller one would have fit, with the monthly price difference, and shows what your Claude Code tokens would cost at API list prices. Tell it your plan first with `plan set`. Plan prices (Pro $20, Max 5x $100, Max 20x $200) and the 5x / 20x multipliers are from claude.com/pricing (2026-10-26; the Max 20x price was not on that page: change any price in `prices.json`, `{"plans": {"max20": 200}}`). It assumes weekly limits scale like the 5-hour limit, and it cannot see extra-usage spend |
66
68
  | `limitcast budget grok <usd>` / `off` / `7d <usd>` | **Pro.** Dollar cap for Grok's aligned 5-hour window (optional 7-day cap). Turns Grok spend into a % so `status` can forecast runout and the guard can block `spawn_subagent` |
67
69
  | `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
68
70
  | `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
69
71
  | `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
70
72
  | `limitcast doctor [--fix]` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads. Also runs daily in the background and flags problems in the status line. `--fix` re-installs with the current Node (after a Node upgrade) |
71
73
  | `limitcast trial` | Pro free for 7 days on this computer, no card, once |
72
- | `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
74
+ | `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share; and the API-equivalent cost: what the tokens would cost at the API's list prices (Claude and Grok models; a subscription is not billed this way). Prices are in the code as of 2026-10-26; add or change a model in `~/.local/state/limitcast/prices.json` (`{"models": {"claude-opus-4-1": {"input": 15, "output": 75}}}`, dollars per million tokens) |
73
75
  | `limitcast report --why [--days N]` | **Pro.** Where your new tokens went: subagents, session starts, cache rebuilds after idle, tool results by tool, model output, and the largest single steps (Claude Code only) |
74
76
  | `limitcast report --jobs [--days N]` | **Pro.** The scheduled (headless) jobs that spend the most tokens just starting: runs, average start, share of all new tokens, and how to launch a job leaner (Claude Code only) |
75
77
  | `limitcast trim [--days N] [--share]` | Measured starting context of your latest session and how much you haven't used in N days (default 7). **Pro** names each item. `--share`: totals only, no names, safe to post |
package/bin/limitcast.mjs CHANGED
@@ -22,6 +22,7 @@ import { coldCost, coldMessage, firstWarning } from '../src/cold.mjs';
22
22
  import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
23
23
  import { formatChecks } from '../src/formats.mjs';
24
24
  import {
25
+ applyGrokSubagentModel,
25
26
  applyGrokTrim,
26
27
  getGrokBudget,
27
28
  grokConfigPath,
@@ -43,13 +44,27 @@ import { doctor, install, installedFeatures, readSettings, settingsPath, uninsta
43
44
  import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
44
45
  import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
45
46
  import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
47
+ import { advise, getPlan, loadPeaks, PLANS, planPrices, planStats, recordPeaks, setPlan } from '../src/plan.mjs';
46
48
  import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
49
+ import { costOf, fmtUsd } from '../src/prices.mjs';
47
50
  import { burnReport } from '../src/report.mjs';
48
51
  import { loadBlocks, logBlock, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
49
52
  import { claudeSamples, readCodex } from '../src/sources.mjs';
50
53
  import { countInteractiveSince, latestInteractiveTranscript } from '../src/startup.mjs';
51
54
  import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
52
- import { budgetSpent, getBudget, loadSubagents, logSubagent, receiptMessage, setBudget, subagentUsage, windowStart } from '../src/subagents.mjs';
55
+ import {
56
+ budgetSpent,
57
+ getBudget,
58
+ getSubagentModels,
59
+ loadSubagents,
60
+ logSubagent,
61
+ receiptMessage,
62
+ setBudget,
63
+ setSubagentModel,
64
+ subagentUsage,
65
+ validModel,
66
+ windowStart,
67
+ } from '../src/subagents.mjs';
53
68
  import { forTerminal } from '../src/term.mjs';
54
69
  import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
55
70
  import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
@@ -86,6 +101,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
86
101
  one starts; hold the first message after the prompt
87
102
  cache expired (idle over 60 min, LIMITCAST_CACHE_MINUTES) and say what it costs
88
103
  limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
104
+ limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku, grok-… or a model id
105
+ limitcast plan [--days N] does your Claude plan fit your use? Hit-limit and headroom evidence, and the monthly price difference
106
+ limitcast plan set <pro|max5|max20>|off tell limitcast which Claude plan you are on
89
107
  limitcast budget grok <usd>|off Grok 5-hour dollar cap (Grok stores spend, not a % used; the guard
90
108
  needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
91
109
  limitcast install --alerts tell you when your starting context grows, plus a weekly summary, and
@@ -293,6 +311,85 @@ if (cmd === 'status') {
293
311
  } catch {
294
312
  /* a hook must never break the session */
295
313
  }
314
+ } else if (cmd === 'plan') {
315
+ if (!isPro()) {
316
+ console.log(
317
+ `\`limitcast plan\` is part of limitcast Pro: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`,
318
+ );
319
+ process.exit(2);
320
+ }
321
+ if (args[0] === 'set') {
322
+ const id = args[1];
323
+ if (id !== 'off' && !(id in PLANS)) {
324
+ console.log('Usage: limitcast plan set <pro|max5|max20>|off');
325
+ process.exit(1);
326
+ }
327
+ setPlan(id === 'off' ? null : /** @type {keyof typeof PLANS} */ (id));
328
+ console.log(id === 'off' ? 'Plan forgotten.' : `Plan set to Claude ${PLANS[/** @type {keyof typeof PLANS} */ (id)].name}. Run: limitcast plan`);
329
+ process.exit(0);
330
+ }
331
+ const planDays = Math.max(1, Number(flag('--days') ?? 28));
332
+ recordPeaks(load(now - KEEP_MS), now);
333
+ const plan = getPlan();
334
+ const prices = planPrices();
335
+ const advice = advise(plan, planStats(loadPeaks(), now, planDays), prices);
336
+ const out = [
337
+ '# limitcast plan',
338
+ '',
339
+ `Claude plan: ${plan ? `${PLANS[plan].name}, ${fmtUsd(prices[plan])} a month` : 'not set'}`,
340
+ '',
341
+ ...advice.lines,
342
+ ];
343
+ const used = (await readUsage(now - planDays * 86400_000, {})).filter((u) => u.src === 'claude');
344
+ const cost = costOf(used);
345
+ if (plan && cost.priced) {
346
+ const span = Math.min(planDays, Math.max(1, (now - Math.min(...used.map((u) => u.t))) / 86400_000));
347
+ out.push(
348
+ '',
349
+ `At API list prices your Claude Code tokens of the last ${Math.round(span)} days would have cost ${fmtUsd(cost.total)} (about ${fmtUsd((cost.total * 30) / span)} a month at this pace), against ${fmtUsd(prices[plan])} for your plan.`,
350
+ );
351
+ }
352
+ out.push(
353
+ '',
354
+ '_From the peak of every 5-hour and weekly window limitcast has seen; plan prices and multipliers from claude.com/pricing, 2026-10-26._',
355
+ );
356
+ console.log(forTerminal(out.join('\n')));
357
+ process.exit(0);
358
+ } else if (cmd === 'subagent-model') {
359
+ if (!isPro()) {
360
+ console.log(`Per-type subagent models are part of limitcast Pro: ${UPGRADE_URL}`);
361
+ process.exit(2);
362
+ }
363
+ const [type, model] = args;
364
+ if (type && (model === undefined || (model !== 'off' && !validModel(model)))) {
365
+ console.log(
366
+ 'Usage: limitcast subagent-model <type> <sonnet|opus|haiku|claude-id|grok-id>|off\n limitcast subagent-model list them',
367
+ );
368
+ process.exit(1);
369
+ }
370
+ if (type) {
371
+ const next = model === 'off' ? null : model;
372
+ setSubagentModel(type, next);
373
+ applyGrokSubagentModel(type, next);
374
+ }
375
+ const pinned = Object.entries(getSubagentModels());
376
+ console.log(pinned.length ? pinned.map(([t, m]) => `${t}: ${m}`).join('\n') : 'No subagent type is pinned to a model.');
377
+ const ran = new Map();
378
+ for (const e of loadSubagents(now - 30 * 86400_000)) if (e.type) ran.set(e.type, (ran.get(e.type) ?? 0) + 1);
379
+ if (ran.size)
380
+ console.log(
381
+ `\nTypes you ran in the last 30 days: ${[...ran]
382
+ .sort((a, b) => b[1] - a[1])
383
+ .map(([t, n]) => `${t} (${n})`)
384
+ .join(', ')}`,
385
+ );
386
+ if (pinned.length) {
387
+ console.log(
388
+ '\nNew subagents of these types run on that model unless the spawn names one itself. Needs the guard: limitcast install --guard, then restart Claude Code.',
389
+ );
390
+ if (pinned.some(([, m]) => /^grok-/i.test(m))) console.log('Grok also writes [subagents.models] in ~/.grok/config.toml; restart Grok.');
391
+ } else console.log('\nExample: limitcast subagent-model Explore haiku');
392
+ process.exit(0);
296
393
  } else if (cmd === 'budget') {
297
394
  if (!isPro()) {
298
395
  console.log(`Budgets are part of limitcast Pro: ${UPGRADE_URL}`);
@@ -848,6 +945,7 @@ function healthHint() {
848
945
  async function refreshValue() {
849
946
  const since = now - KEEP_MS;
850
947
  const claude = load(since);
948
+ recordPeaks(claude, now); // the long-lived record of window peaks behind `limitcast plan`
851
949
  const o = loadOverhead();
852
950
  // limitcast started watching at its first status-line reading (or first measurement), not when Codex's logs begin.
853
951
  const start = Math.min(now, o?.first.at ?? now, ...claude.map((s) => s.t));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.12.0",
3
+ "version": "0.13.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": {
package/src/grok.mjs CHANGED
@@ -395,6 +395,48 @@ export function restoreStatusLine(toml, previous) {
395
395
  * A one-line session summary from Grok's status-line JSON (model, context %, session cost).
396
396
  * @param {any} feed
397
397
  */
398
+ /**
399
+ * Set or clear a Grok `[subagents.models]` pin. A non-grok model (or null) removes that type's key.
400
+ * @param {string} type
401
+ * @param {string|null} model
402
+ * @param {{path?:string}} [opts]
403
+ */
404
+ export function applyGrokSubagentModel(type, model, { path = grokConfigPath() } = {}) {
405
+ if (!existsSync(path)) return false;
406
+ const grokId = typeof model === 'string' && /^grok-[a-z0-9.-]+$/i.test(model) ? model : null;
407
+ const prev = readFileSync(path, 'utf8');
408
+ const next = patchGrokSubagentModel(prev, type, grokId);
409
+ if (next === prev) return false;
410
+ backup(path);
411
+ writeText(path, next);
412
+ return true;
413
+ }
414
+
415
+ /**
416
+ * Pure TOML patch for `[subagents.models.<type>]`. `model` null deletes the key; an empty table is removed.
417
+ * @param {string} toml
418
+ * @param {string} type
419
+ * @param {string|null} model
420
+ */
421
+ export function patchGrokSubagentModel(toml, type, model) {
422
+ const key = type.toLowerCase().replace(/[^a-z0-9_-]/g, '');
423
+ if (!key) return toml;
424
+ const range = tableRange(toml, 'subagents.models');
425
+ if (!range) {
426
+ if (!model) return toml;
427
+ return `${toml.trimEnd()}\n\n[subagents.models]\n${key} = ${tomlString(model)}\n`;
428
+ }
429
+ const keys = parseTable(range.body);
430
+ if (model) keys[key] = model;
431
+ else delete keys[key];
432
+ if (!Object.keys(keys).length) {
433
+ const before = toml.slice(0, range.start).trimEnd();
434
+ const after = toml.slice(range.end).replace(/^\n+/, '');
435
+ return after ? `${before}\n\n${after}` : `${before}\n`;
436
+ }
437
+ return toml.slice(0, range.start) + renderTable('subagents.models', keys, range.body) + toml.slice(range.end);
438
+ }
439
+
398
440
  export function grokSessionLine(feed) {
399
441
  if (!feed || typeof feed !== 'object') return '';
400
442
  if (feed.rate_limits) return ''; // Claude Code feed
@@ -548,7 +590,7 @@ function parseTable(body) {
548
590
  /** @type {Record<string, string>} */
549
591
  const keys = {};
550
592
  for (const line of body.split('\n').slice(1)) {
551
- const m = /^\s*([A-Za-z0-9_]+)\s*=\s*(.*)$/.exec(line);
593
+ const m = /^\s*([A-Za-z0-9_-]+)\s*=\s*(.*)$/.exec(line);
552
594
  if (!m) continue;
553
595
  keys[m[1]] = unquote(m[2].trim());
554
596
  }
@@ -572,7 +614,7 @@ function unquote(v) {
572
614
  function renderTable(name, keys, previousBody) {
573
615
  const order = [];
574
616
  for (const line of previousBody.split('\n').slice(1)) {
575
- const m = /^\s*([A-Za-z0-9_]+)\s*=/.exec(line);
617
+ const m = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line);
576
618
  if (m && keys[m[1]] !== undefined && !order.includes(m[1])) order.push(m[1]);
577
619
  }
578
620
  for (const k of Object.keys(keys)) if (!order.includes(k)) order.push(k);
package/src/guard.mjs CHANGED
@@ -4,7 +4,7 @@ import { grokSamples } from './grok.mjs';
4
4
  import { logBlock } from './results.mjs';
5
5
  import { readCodex } from './sources.mjs';
6
6
  import { KEEP_MS, load } from './store.mjs';
7
- import { budgetMessage, budgetSpent, getBudget, loadSubagents, spawnNotice, windowStart } from './subagents.mjs';
7
+ import { budgetMessage, budgetSpent, getBudget, loadSubagents, pinnedModel, spawnNotice, windowStart } from './subagents.mjs';
8
8
 
9
9
  const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
10
10
 
@@ -124,8 +124,36 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
124
124
  // Not blocked, but a window is tight: run a new Claude subagent on Sonnet instead of the main (usually Opus) model.
125
125
  const input = hook?.tool_input ?? hook?.toolInput;
126
126
  const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
127
+ const type = String(input?.subagent_type ?? input?.subagentType ?? '');
128
+ const pinned = isUnset(input?.model) && type ? pinnedModel(type) : undefined;
129
+ if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview);
127
130
  if (src !== 'claude') return null;
128
- if (!tight || !switchable(input?.model)) {
131
+ const model = pinned ?? input?.model;
132
+ if (!tight || !switchable(model)) {
133
+ if (pinned) {
134
+ try {
135
+ logBlock({
136
+ t: now,
137
+ kind: 'default',
138
+ src: 'claude',
139
+ win: '5h',
140
+ pct: 0,
141
+ wall: now,
142
+ reset: now,
143
+ from: input?.model ?? 'default',
144
+ to: pinned,
145
+ type,
146
+ ...(preview ? { shadow: true } : {}),
147
+ });
148
+ } catch {
149
+ /* a failed log must not change the decision */
150
+ }
151
+ if (preview) return null;
152
+ return {
153
+ updatedInput: { ...input, model: pinned },
154
+ reason: `limitcast: ${type} subagents run on ${pinned}, the model you set for them. Set LIMITCAST_ALLOW=1 to keep the main model.`,
155
+ };
156
+ }
129
157
  // Allowed as is: tell the user (never the model) what this kind of subagent has cost so far.
130
158
  if (preview) return null;
131
159
  const win = forecasts.find((x) => x.src === 'claude' && x.win === '5h' && x.verdict !== 'RESET');
@@ -141,7 +169,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
141
169
  pct: tight.pct,
142
170
  wall: tight.wall ?? tight.reset,
143
171
  reset: tight.reset,
144
- from: input?.model ?? 'default',
172
+ from: model ?? 'default',
145
173
  ...(preview ? { shadow: true } : {}),
146
174
  });
147
175
  } catch {
@@ -162,3 +190,49 @@ const SWITCH_TO = 'sonnet';
162
190
  * @param {unknown} model
163
191
  */
164
192
  export const switchable = (model) => model === undefined || model === null || model === 'inherit' || /opus|fable/i.test(String(model));
193
+
194
+ /** Whether a spawn names no model of its own, so a pinned one may apply. @param {unknown} model */
195
+ const isUnset = (model) => model === undefined || model === null || model === '' || model === 'inherit';
196
+
197
+ /**
198
+ * Grok: pin via updatedInput only when the spawn already has a `model` field (adding one fails the tool schema and
199
+ * denies the call). [subagents.models] in config.toml covers the rest after restart. Spawn notice when a cap exists.
200
+ * @param {any} input
201
+ * @param {string} type
202
+ * @param {string|undefined} pinned
203
+ * @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
204
+ * @param {number} now
205
+ * @param {boolean} preview
206
+ */
207
+ function grokPinOrNotice(input, type, pinned, forecasts, now, preview) {
208
+ const grokPin = pinned && /^grok-/i.test(pinned) ? pinned : undefined;
209
+ const hasModelField = input && typeof input === 'object' && Object.hasOwn(input, 'model');
210
+ if (grokPin && hasModelField) {
211
+ try {
212
+ logBlock({
213
+ t: now,
214
+ kind: 'default',
215
+ src: 'grok',
216
+ win: '5h',
217
+ pct: 0,
218
+ wall: now,
219
+ reset: now,
220
+ from: input?.model ?? 'default',
221
+ to: grokPin,
222
+ type,
223
+ ...(preview ? { shadow: true } : {}),
224
+ });
225
+ } catch {
226
+ /* a failed log must not change the decision */
227
+ }
228
+ if (preview) return null;
229
+ return {
230
+ updatedInput: { ...input, model: grokPin },
231
+ reason: `limitcast: ${type} subagents run on ${grokPin}, the model you set for them. Set LIMITCAST_ALLOW=1 to keep the main model.`,
232
+ };
233
+ }
234
+ if (preview) return null;
235
+ const win = forecasts.find((x) => x.src === 'grok' && x.win === '5h' && x.verdict !== 'RESET');
236
+ const notice = spawnNotice(loadSubagents(now - 30 * 86400_000), type, win);
237
+ return notice ? { notice } : null;
238
+ }
package/src/plan.mjs ADDED
@@ -0,0 +1,196 @@
1
+ // @ts-check
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { claudeAccounts } from './forecast.mjs';
5
+ import { fmtUsd } from './prices.mjs';
6
+ import { stateDir } from './store.mjs';
7
+
8
+ // `limitcast plan` (Pro): does your Claude plan fit how much you use? From a long-lived record of the peak of every
9
+ // 5-hour and weekly window (the samples themselves are only kept for 8 days), it says whether you hit your limits often
10
+ // enough to justify the next plan, or use so little that a smaller one would do, with the monthly price difference.
11
+
12
+ /** Individual plans. mult: usage per 5-hour session relative to Pro (Anthropic: Max is "5x or 20x the usage of Pro").
13
+ * usd: monthly price, platform claude.com/pricing read 2026-10-26: Pro $20 ($17 a month billed yearly), Max from $100.
14
+ * The Max 20x price ($200) was not on that page: change any price in ~/.local/state/limitcast/prices.json
15
+ * ({"plans": {"max20": 200}}). */
16
+ export const PLANS = {
17
+ pro: { name: 'Pro', mult: 1, usd: 20 },
18
+ max5: { name: 'Max 5x', mult: 5, usd: 100 },
19
+ max20: { name: 'Max 20x', mult: 20, usd: 200 },
20
+ };
21
+ /** @typedef {keyof typeof PLANS} PlanId */
22
+ const ORDER = /** @type {PlanId[]} */ (['pro', 'max5', 'max20']);
23
+
24
+ const configFile = () => join(stateDir(), 'config.json');
25
+ const peaksFile = () => join(stateDir(), 'plan-peaks.json');
26
+ const KEEP_DAYS = 120;
27
+ const HIT = 99; // % from which a window counts as reached
28
+ const FIT = 85; // a smaller plan must keep your busiest window at or under this % of its limit
29
+ const MIN_DAYS_UP = 7;
30
+ const MIN_DAYS_DOWN = 14;
31
+ const MIN_WINDOWS = 10;
32
+
33
+ /** @returns {PlanId|null} the plan you told limitcast you are on */
34
+ export function getPlan() {
35
+ try {
36
+ const p = JSON.parse(readFileSync(configFile(), 'utf8')).plan;
37
+ return p in PLANS ? p : null;
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ /** @param {PlanId|null} plan */
44
+ export function setPlan(plan) {
45
+ let cfg = {};
46
+ try {
47
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
48
+ } catch {
49
+ /* new */
50
+ }
51
+ mkdirSync(stateDir(), { recursive: true });
52
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, plan }));
53
+ }
54
+
55
+ /**
56
+ * Monthly prices with your overrides from prices.json ({"plans": {"max20": 200}}).
57
+ * @returns {Record<PlanId, number>}
58
+ */
59
+ export function planPrices() {
60
+ const base = { pro: PLANS.pro.usd, max5: PLANS.max5.usd, max20: PLANS.max20.usd };
61
+ try {
62
+ const o = JSON.parse(readFileSync(join(stateDir(), 'prices.json'), 'utf8')).plans ?? {};
63
+ for (const id of ORDER) if (Number(o[id]) > 0) base[id] = Number(o[id]);
64
+ } catch {
65
+ /* defaults */
66
+ }
67
+ return base;
68
+ }
69
+
70
+ /** @typedef {{w:string, reset:number, pct:number}} Cycle one window cycle: its length ('5h' or '7d'), reset (epoch s), peak % */
71
+
72
+ /** Readings of one cycle differ in `reset` by a little: bucket them (cycles are hours apart). @param {number} reset */
73
+ const bucket = (reset) => Math.round(reset / 1200);
74
+
75
+ /**
76
+ * Fold the readings of the Claude account you used last into the record of cycle peaks. Pure: returns the new record.
77
+ * @param {Record<string, Cycle>} cycles
78
+ * @param {import('./forecast.mjs').Sample[]} samples
79
+ * @param {number} now epoch ms
80
+ * @returns {Record<string, Cycle>}
81
+ */
82
+ export function foldPeaks(cycles, samples, now) {
83
+ const accounts = claudeAccounts(samples.filter((s) => s.src === 'claude'));
84
+ const latest = accounts.sort((a, b) => Math.max(...b.map((s) => s.t)) - Math.max(...a.map((s) => s.t)))[0] ?? [];
85
+ const out = { ...cycles };
86
+ for (const s of latest) {
87
+ if (s.win !== '5h' && s.win !== '7d') continue;
88
+ const k = `${s.win}:${bucket(s.reset)}`;
89
+ const prev = out[k];
90
+ out[k] = { w: s.win, reset: Math.max(prev?.reset ?? 0, s.reset), pct: Math.max(prev?.pct ?? 0, s.pct) };
91
+ }
92
+ const floor = now / 1000 - KEEP_DAYS * 86400;
93
+ return Object.fromEntries(Object.entries(out).filter(([, c]) => c.reset >= floor));
94
+ }
95
+
96
+ /** @returns {Record<string, Cycle>} */
97
+ export function loadPeaks() {
98
+ try {
99
+ const d = JSON.parse(readFileSync(peaksFile(), 'utf8'));
100
+ return d.v === 1 ? d.cycles : {};
101
+ } catch {
102
+ return {};
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Add the current readings to the record on disk.
108
+ * @param {import('./forecast.mjs').Sample[]} samples
109
+ * @param {number} now
110
+ */
111
+ export function recordPeaks(samples, now) {
112
+ try {
113
+ mkdirSync(stateDir(), { recursive: true });
114
+ writeFileSync(peaksFile(), JSON.stringify({ v: 1, cycles: foldPeaks(loadPeaks(), samples, now) }));
115
+ } catch {
116
+ /* a record: the next run adds the readings again */
117
+ }
118
+ }
119
+
120
+ /**
121
+ * What the record says over the last `days`: for each window length, the windows with use, how many reached the limit,
122
+ * and the busiest one; and how many days the record covers.
123
+ * @param {Record<string, Cycle>} cycles
124
+ * @param {number} now epoch ms
125
+ * @param {number} days
126
+ */
127
+ export function planStats(cycles, now, days) {
128
+ const since = now / 1000 - days * 86400;
129
+ const mine = Object.values(cycles).filter((c) => c.reset >= since);
130
+ const of = (/** @type {string} */ w) => {
131
+ const cs = mine.filter((c) => c.w === w && c.pct > 0);
132
+ return { n: cs.length, hits: cs.filter((c) => c.pct >= HIT).length, peak: Math.max(0, ...cs.map((c) => c.pct)) };
133
+ };
134
+ const five = mine.filter((c) => c.w === '5h').map((c) => c.reset);
135
+ const spanDays = five.length ? (Math.max(...five) - Math.min(...five)) / 86400 : 0;
136
+ return { five: of('5h'), week: of('7d'), spanDays };
137
+ }
138
+
139
+ const pct = (/** @type {number} */ n) => `${Math.round(n)}%`;
140
+
141
+ /**
142
+ * The advice, as lines of text, and its kind.
143
+ * @param {PlanId|null} plan the plan you set
144
+ * @param {ReturnType<typeof planStats>} st
145
+ * @param {Record<PlanId, number>} usd monthly prices
146
+ * @returns {{kind:'unknown'|'thin'|'upgrade'|'downgrade'|'fits', lines:string[]}}
147
+ */
148
+ export function advise(plan, st, usd) {
149
+ const evidence = `Over ${Math.round(st.spanDays)} days: ${st.five.n} five-hour windows with use (${st.five.hits} reached the limit, busiest ${pct(st.five.peak)}), ${st.week.n} weekly windows (${st.week.hits} reached the limit, busiest ${pct(st.week.peak)}).`;
150
+ if (!plan) return { kind: 'unknown', lines: [evidence, 'Tell limitcast your plan to get a recommendation: limitcast plan set <pro|max5|max20>'] };
151
+ const i = ORDER.indexOf(plan);
152
+ const next = ORDER[i + 1];
153
+ const lower = ORDER[i - 1];
154
+ const hits = st.five.hits;
155
+ const need = (/** @type {number} */ days) => st.spanDays < days || st.five.n < MIN_WINDOWS;
156
+ if (need(MIN_DAYS_UP)) {
157
+ return {
158
+ kind: 'thin',
159
+ lines: [
160
+ evidence,
161
+ `Not enough history yet for a recommendation (it needs ${MIN_DAYS_UP}+ days and ${MIN_WINDOWS}+ windows with use). limitcast keeps this record from now on: ask again later.`,
162
+ ],
163
+ };
164
+ }
165
+ if (next && (hits >= 3 || st.week.hits >= 1)) {
166
+ const x = PLANS[next].mult / PLANS[plan].mult;
167
+ return {
168
+ kind: 'upgrade',
169
+ lines: [
170
+ evidence,
171
+ `You reached a limit often enough that ${PLANS[next].name} is worth a look: ${x}x the usage per 5-hour session for ${fmtUsd(usd[next] - usd[plan])} more a month (${fmtUsd(usd[next])} vs ${fmtUsd(usd[plan])}).`,
172
+ 'If this is rare, paid extra usage may cost less than a bigger plan. limitcast cannot see that spend.',
173
+ ],
174
+ };
175
+ }
176
+ if (lower && !need(MIN_DAYS_DOWN) && hits === 0 && st.week.hits === 0) {
177
+ const r = PLANS[plan].mult / PLANS[lower].mult;
178
+ const five = st.five.peak * r;
179
+ const week = st.week.peak * r;
180
+ if (five <= FIT && week <= FIT) {
181
+ return {
182
+ kind: 'downgrade',
183
+ lines: [
184
+ evidence,
185
+ `${PLANS[lower].name} would have fit: it has 1/${r} of the usage per session, so your busiest 5-hour window (${pct(st.five.peak)}) would have been about ${pct(five)} and your busiest week about ${pct(week)}. That saves ${fmtUsd(usd[plan] - usd[lower])} a month (${fmtUsd(usd[lower])} vs ${fmtUsd(usd[plan])}).`,
186
+ 'Anthropic states the multiplier for the 5-hour session; this assumes weekly limits scale the same way.',
187
+ ],
188
+ };
189
+ }
190
+ }
191
+ const tight = lower && hits === 0 && st.five.peak * (PLANS[plan].mult / PLANS[lower].mult) <= 100;
192
+ return {
193
+ kind: 'fits',
194
+ lines: [evidence, `${PLANS[plan].name} fits how you use it.${tight ? ` ${PLANS[lower].name} would have been tight.` : ''}`],
195
+ };
196
+ }
package/src/prices.mjs ADDED
@@ -0,0 +1,107 @@
1
+ // @ts-check
2
+ import { readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { stateDir } from './store.mjs';
5
+
6
+ // What your tokens would cost at the API's list prices ("API-equivalent cost"). A subscription is not billed this way:
7
+ // it is a yardstick for what the plan covers. Claude and Grok models; any other model is left out, never priced at 0.
8
+
9
+ /**
10
+ * USD per million tokens. input/output: base prices; readX: cache read as a multiple of input; over: the prices that
11
+ * apply to a call whose whole prompt is above `above` tokens. Cache writes default to 1.25x input (5 minutes) or 2x
12
+ * (1 hour) for Claude; Grok sets writeX 1 (xAI lists cached input, not a write multiplier).
13
+ * Sources: platform.claude.com/docs/en/about-claude/pricing and docs.x.ai/developers/models, read 2026-10-26.
14
+ * Override or add models in ~/.local/state/limitcast/prices.json:
15
+ * {"models": {"claude-opus-4-1": {"input": 15, "output": 75, "readX": 0.1}}}.
16
+ * @typedef {{input:number, output:number, readX:number, writeX?:number, write1hX?:number, over?:{above:number, input:number, output:number, readX?:number}}} Price
17
+ * @type {Record<string, Price>}
18
+ */
19
+ export const PRICES = {
20
+ 'claude-fable-5-1': { input: 10, output: 50, readX: 0.025 },
21
+ 'claude-opus-5-5': { input: 4, output: 20, readX: 0.05 },
22
+ 'claude-sonnet-5-5': { input: 2, output: 10, readX: 0.05 },
23
+ 'claude-haiku-5-5': { input: 0.1, output: 0.5, readX: 0.1, over: { above: 100_000, input: 0.5, output: 2.5 } },
24
+ // xAI: cache read is listed in $/1M; writeX 1 = cache creation billed as input. Long-context at 200k prompt tokens.
25
+ 'grok-4.7': { input: 2, output: 6, readX: 0.25, writeX: 1, write1hX: 1, over: { above: 200_000, input: 4, output: 12 } },
26
+ 'grok-4.6': { input: 2, output: 6, readX: 0.25, writeX: 1, write1hX: 1, over: { above: 200_000, input: 4, output: 12 } },
27
+ 'grok-4.5': { input: 2, output: 6, readX: 0.15, writeX: 1, write1hX: 1, over: { above: 200_000, input: 4, output: 12 } },
28
+ 'grok-4.3': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
29
+ 'grok-4.20': { input: 1.25, output: 2.5, readX: 0.16, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2.5, output: 5 } },
30
+ 'grok-build-0.1': { input: 1, output: 2, readX: 0.2, writeX: 1, write1hX: 1, over: { above: 200_000, input: 2, output: 4 } },
31
+ };
32
+
33
+ const WRITE_5M = 1.25;
34
+ const WRITE_1H = 2;
35
+
36
+ /**
37
+ * The price table with your overrides on top. A bad or missing file changes nothing.
38
+ * @returns {Record<string, Price>}
39
+ */
40
+ export function priceTable() {
41
+ try {
42
+ const o = JSON.parse(readFileSync(join(stateDir(), 'prices.json'), 'utf8')).models;
43
+ const good = Object.entries(o ?? {}).filter(([, p]) => p && typeof p === 'object' && Number(p.input) > 0 && Number(p.output) > 0);
44
+ if (!good.length) return PRICES;
45
+ return { ...PRICES, ...Object.fromEntries(good.map(([k, p]) => [k, { readX: 0.1, ...p }])) };
46
+ } catch {
47
+ return PRICES;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * The price of a model id: an exact key, else the longest key it starts with (ids carry a date suffix at times).
53
+ * @param {string|undefined} model
54
+ * @param {Record<string, Price>} table
55
+ */
56
+ export function priceFor(model, table) {
57
+ if (!model) return null;
58
+ const key = Object.keys(table)
59
+ .filter((k) => model === k || model.startsWith(`${k}-`))
60
+ .sort((a, b) => b.length - a.length)[0];
61
+ return key ? table[key] : null;
62
+ }
63
+
64
+ /**
65
+ * API-equivalent dollars of one model call, or null when its model has no price.
66
+ * @param {{model?:string, input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number}} u
67
+ * @param {Record<string, Price>} [table]
68
+ */
69
+ export function callCost(u, table = priceTable()) {
70
+ const base = priceFor(u.model, table);
71
+ if (!base) return null;
72
+ const p = base.over && u.input + u.cacheWrite + u.cacheRead > base.over.above ? { ...base, ...base.over } : base;
73
+ const w1h = Math.min(u.cacheWrite1h ?? 0, u.cacheWrite);
74
+ const w5m = u.cacheWrite - w1h;
75
+ const write5 = p.writeX ?? WRITE_5M;
76
+ const write1h = p.write1hX ?? WRITE_1H;
77
+ return (u.input * p.input + (w5m * write5 + w1h * write1h) * p.input + u.cacheRead * p.readX * p.input + u.output * p.output) / 1e6;
78
+ }
79
+
80
+ /**
81
+ * Total API-equivalent dollars of many calls, how many tokens were priced and how many were not, and dollars by model.
82
+ * @param {Parameters<typeof callCost>[0][]} calls
83
+ */
84
+ export function costOf(calls) {
85
+ const table = priceTable();
86
+ let total = 0;
87
+ let priced = 0;
88
+ let unpriced = 0;
89
+ /** @type {Map<string, number>} */
90
+ const byModel = new Map();
91
+ for (const u of calls) {
92
+ const n = u.input + u.cacheWrite + u.cacheRead + u.output;
93
+ const c = callCost(u, table);
94
+ if (c === null) {
95
+ unpriced += n;
96
+ continue;
97
+ }
98
+ total += c;
99
+ priced += n;
100
+ const k = u.model ?? '';
101
+ byModel.set(k, (byModel.get(k) ?? 0) + c);
102
+ }
103
+ return { total, priced, unpriced, byModel };
104
+ }
105
+
106
+ /** "$0.42", "$12.34", "$1,234". @param {number} d */
107
+ export const fmtUsd = (d) => (d >= 100 ? `$${Math.round(d).toLocaleString('en-US')}` : `$${d.toFixed(2)}`);
package/src/report.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // @ts-check
2
2
  import { homedir } from 'node:os';
3
+ import { costOf, fmtUsd } from './prices.mjs';
3
4
  import { total } from './usage.mjs';
4
5
 
5
6
  /** @typedef {import('./usage.mjs').Usage} Usage */
@@ -13,15 +14,31 @@ export function burnReport(usage, { since, now }) {
13
14
  const sum = (/** @type {Usage[]} */ xs) => xs.reduce((a, u) => a + total(u), 0);
14
15
  const all = sum(usage);
15
16
  const lines = [`# limitcast burn report`, '', `${day(since)} to ${day(now)} · ${fmt(all)} tokens`, ''];
16
- if (!usage.length) return [...lines, 'No Claude Code or Codex usage in this period.'].join('\n');
17
+ if (!usage.length) return [...lines, 'No Claude Code, Codex or Grok usage in this period.'].join('\n');
17
18
 
19
+ // API-equivalent dollars: what the tokens would cost at list prices. Claude and Grok models are priced; others show "-".
20
+ const cost = (/** @type {Usage[]} */ xs) => {
21
+ const c = costOf(xs);
22
+ return c.priced ? c.total : null;
23
+ };
24
+ const usd = (/** @type {Usage[]} */ xs) => {
25
+ const c = cost(xs);
26
+ return c === null ? '-' : fmtUsd(c);
27
+ };
18
28
  const byTool = group(usage, (u) => u.src);
19
- lines.push('| tool | tokens | output | cache reads | share |', '|---|---:|---:|---:|---:|');
29
+ lines.push('| tool | tokens | output | cache reads | share | API-equivalent |', '|---|---:|---:|---:|---:|---:|');
20
30
  for (const [k, xs] of byTool) {
21
31
  lines.push(
22
- `| ${k} | ${fmt(sum(xs))} | ${fmt(xs.reduce((a, u) => a + u.output, 0))} | ${fmt(xs.reduce((a, u) => a + u.cacheRead, 0))} | ${pct(sum(xs), all)} |`,
32
+ `| ${k} | ${fmt(sum(xs))} | ${fmt(xs.reduce((a, u) => a + u.output, 0))} | ${fmt(xs.reduce((a, u) => a + u.cacheRead, 0))} | ${pct(sum(xs), all)} | ${usd(xs)} |`,
23
33
  );
24
34
  }
35
+ const all$ = costOf(usage);
36
+ if (all$.priced)
37
+ lines.push(
38
+ '',
39
+ `**API-equivalent cost: ${fmtUsd(all$.total)}** at list prices for Claude and Grok models, not what a subscription charges.` +
40
+ (all$.unpriced ? ` ${fmt(all$.unpriced)} tokens on other models are not counted.` : ''),
41
+ );
25
42
 
26
43
  const claude = usage.filter((u) => u.src === 'claude');
27
44
  if (claude.length) {
@@ -36,6 +53,9 @@ export function burnReport(usage, { since, now }) {
36
53
  sum,
37
54
  all,
38
55
  false,
56
+ Infinity,
57
+ 'tokens',
58
+ cost,
39
59
  );
40
60
  // Ranked by new tokens (input, cache writes, output): cached reads barely count against the limit.
41
61
  const fresh = (/** @type {Usage[]} */ xs) => xs.reduce((a, u) => a + u.input + u.cacheWrite + u.output, 0);
@@ -49,6 +69,7 @@ export function burnReport(usage, { since, now }) {
49
69
  true,
50
70
  8,
51
71
  'new tokens',
72
+ cost,
52
73
  );
53
74
  table(
54
75
  lines,
@@ -59,6 +80,7 @@ export function burnReport(usage, { since, now }) {
59
80
  true,
60
81
  6,
61
82
  'new tokens',
83
+ cost,
62
84
  );
63
85
  table(
64
86
  lines,
@@ -69,8 +91,9 @@ export function burnReport(usage, { since, now }) {
69
91
  true,
70
92
  5,
71
93
  'new tokens',
94
+ cost,
72
95
  );
73
- lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code and Codex logs._`);
96
+ lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code, Codex and Grok logs._`);
74
97
  return lines.join('\n');
75
98
  }
76
99
 
@@ -83,12 +106,16 @@ export function burnReport(usage, { since, now }) {
83
106
  * @param {boolean} sortBySize
84
107
  * @param {number} [limit]
85
108
  * @param {string} [col] header of the token column
109
+ * @param {(xs:Usage[])=>number|null} [cost] API-equivalent dollars of a group, null when none of it is priced
86
110
  */
87
- function table(lines, title, groups, sum, all, sortBySize, limit = Infinity, col = 'tokens') {
88
- let rows = [...groups].map(([k, xs]) => /** @type {[string, number]} */ ([k, sum(xs)]));
111
+ function table(lines, title, groups, sum, all, sortBySize, limit = Infinity, col = 'tokens', cost) {
112
+ let rows = [...groups].map(([k, xs]) => /** @type {[string, number, Usage[]]} */ ([k, sum(xs), xs]));
89
113
  rows = sortBySize ? rows.sort((a, b) => b[1] - a[1]) : rows.sort((a, b) => a[0].localeCompare(b[0]));
90
- lines.push('', `## ${title}`, '', `| | ${col} | share |`, '|---|---:|---:|');
91
- for (const [k, n] of rows.slice(0, limit)) lines.push(`| ${k} | ${fmt(n)} | ${pct(n, all)} |`);
114
+ lines.push('', `## ${title}`, '', `| | ${col} | share${cost ? ' | API-equivalent' : ''} |`, `|---|---:|---:${cost ? '|---:' : ''}|`);
115
+ for (const [k, n, xs] of rows.slice(0, limit)) {
116
+ const c = cost?.(xs);
117
+ lines.push(`| ${k} | ${fmt(n)} | ${pct(n, all)}${cost ? ` | ${c === null || c === undefined ? '-' : fmtUsd(c)}` : ''} |`);
118
+ }
92
119
  }
93
120
 
94
121
  /**
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, 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 */
8
+ /** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, shadow?:boolean, kind?:string, from?:string, to?:string, type?: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' };
@@ -128,6 +128,7 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
128
128
  now,
129
129
  );
130
130
  const switches = mine.filter((b) => b.kind === 'switch').length;
131
+ const defaults = mine.filter((b) => b.kind === 'default').length;
131
132
  const colds = mine.filter((b) => b.kind === 'cold');
132
133
  const budgets = mine.filter((b) => b.kind === 'budget').length;
133
134
  return {
@@ -137,6 +138,7 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
137
138
  leads,
138
139
  outcomes,
139
140
  switches,
141
+ defaults,
140
142
  colds: colds.length,
141
143
  coldPct: colds.reduce((a, b) => a + b.pct, 0),
142
144
  budgets,
@@ -156,6 +158,7 @@ export function resultsShare(st, { days, pro, savedPerSession, notResent = 0 })
156
158
  if (st.outcomes.length)
157
159
  parts.push(`${pro ? 'blocked' : 'would have blocked'} ${st.outcomes.length} runaway subagent${st.outcomes.length === 1 ? '' : 's'}`);
158
160
  if (st.switches) parts.push(`${pro ? 'moved' : 'would have moved'} ${st.switches} subagent${st.switches === 1 ? '' : 's'} to Sonnet`);
161
+ if (st.defaults) parts.push(`${pro ? 'ran' : 'would have run'} ${st.defaults} on the model you set for their type`);
159
162
  if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller per session`);
160
163
  if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent since install`);
161
164
  return `${parts[0]} ${parts.slice(1).join('; ')}. https://limitcast.dev`;
@@ -172,6 +175,7 @@ export function weeklyLine(st, savedPerSession, notResent = 0) {
172
175
  if (st.leads.length) parts.push(`warned ahead on ${st.leads.length} (avg ${avg(st.leads)} min)`);
173
176
  parts.push(`guard blocked ${st.outcomes.length} subagent${st.outcomes.length === 1 ? '' : 's'}`);
174
177
  if (st.switches) parts.push(`moved ${st.switches} to Sonnet`);
178
+ if (st.defaults) parts.push(`ran ${st.defaults} on their set model`);
175
179
  if (st.budgets) parts.push(`held ${st.budgets} over budget`);
176
180
  if (st.colds) parts.push(`caught ${st.colds} cold-cache message${st.colds === 1 ? '' : 's'}`);
177
181
  if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller`);
@@ -267,6 +271,10 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
267
271
  out.push(
268
272
  `${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.`,
269
273
  );
274
+ if (st.defaults)
275
+ out.push(
276
+ `${pro ? 'Ran' : 'Pro would have run'} ${st.defaults} subagent${st.defaults === 1 ? '' : 's'} on the model you set for their type (limitcast subagent-model).`,
277
+ );
270
278
  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
279
 
272
280
  const recent = subagents.filter((e) => e.t >= now - days * 86400_000);
package/src/subagents.mjs CHANGED
@@ -131,6 +131,50 @@ export function setBudget(pct) {
131
131
  writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
132
132
  }
133
133
 
134
+ /** A model a subagent type can be pinned to: sonnet, opus, haiku, a claude-... id, or a grok-... id. */
135
+ export const validModel = (/** @type {unknown} */ m) => typeof m === 'string' && /^(sonnet|opus|haiku|claude-[a-z0-9.-]+|grok-[a-z0-9.-]+)$/i.test(m);
136
+
137
+ /**
138
+ * The pinned model for a subagent type, matching the stored name case-insensitively (Claude "Explore" vs Grok "explore").
139
+ * @param {unknown} type
140
+ */
141
+ export function pinnedModel(type) {
142
+ if (typeof type !== 'string' || !type) return undefined;
143
+ const models = getSubagentModels();
144
+ if (models[type]) return models[type];
145
+ const want = type.toLowerCase();
146
+ return Object.entries(models).find(([t]) => t.toLowerCase() === want)?.[1];
147
+ }
148
+
149
+ /** @returns {Record<string, string>} the model each subagent type runs on by default, e.g. {Explore: 'haiku'} */
150
+ export function getSubagentModels() {
151
+ try {
152
+ const m = JSON.parse(readFileSync(configFile(), 'utf8')).subagentModels;
153
+ return m && typeof m === 'object' ? Object.fromEntries(Object.entries(m).filter(([, v]) => validModel(v))) : {};
154
+ } catch {
155
+ return {};
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Pin a subagent type to a model, or null to remove it.
161
+ * @param {string} type
162
+ * @param {string|null} model
163
+ */
164
+ export function setSubagentModel(type, model) {
165
+ let cfg = /** @type {any} */ ({});
166
+ try {
167
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
168
+ } catch {
169
+ /* new */
170
+ }
171
+ const models = { ...cfg.subagentModels };
172
+ if (model === null) delete models[type];
173
+ else models[type] = model;
174
+ mkdirSync(stateDir(), { recursive: true });
175
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentModels: models }));
176
+ }
177
+
134
178
  /**
135
179
  * When the current Claude 5-hour window started: its reset minus 5 hours, or 5 hours ago without a reading.
136
180
  * @param {{src:string, win:string, verdict:string, reset:number}[]} forecasts
package/src/usage.mjs CHANGED
@@ -8,7 +8,8 @@ import { stateDir } from './store.mjs';
8
8
  /**
9
9
  * One model response's token usage.
10
10
  * @typedef {{t:number, src:'claude'|'codex'|'grok', session:string, project:string, model:string, sidechain:boolean,
11
- * input:number, cacheWrite:number, cacheRead:number, output:number, entry?:string}} Usage entry: how Claude Code was launched (cli, sdk-py, ...)
11
+ * input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number, entry?:string}} Usage
12
+ * entry: how Claude Code was launched (cli, sdk-py, ...); cacheWrite1h: the part of cacheWrite that used the 1-hour cache
12
13
  */
13
14
 
14
15
  export const claudeRoot = () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'projects');
@@ -46,6 +47,7 @@ export function claudeUsage(line, seen, session) {
46
47
  sidechain: !!ev.isSidechain,
47
48
  input: u.input_tokens ?? 0,
48
49
  cacheWrite: u.cache_creation_input_tokens ?? 0,
50
+ cacheWrite1h: u.cache_creation?.ephemeral_1h_input_tokens ?? 0,
49
51
  cacheRead: u.cache_read_input_tokens ?? 0,
50
52
  output: u.output_tokens ?? 0,
51
53
  ...(ev.entrypoint ? { entry: String(ev.entrypoint) } : {}),
@@ -232,12 +234,14 @@ export async function readUsage(since, roots = {}, activity) {
232
234
  }
233
235
 
234
236
  const CACHE_KEEP_MS = 35 * 86400_000;
237
+ const USAGE_CACHE_VERSION = 2; // 2: records carry cacheWrite1h; an older cache is read again
235
238
  const usageCacheFile = () => join(stateDir(), 'usage-cache.json');
236
239
 
237
240
  /** @returns {Record<string, {s:number, m:number, u:Usage[], a?:{skills:string[], mcp:string[]}}>} */
238
241
  function loadUsageCache() {
239
242
  try {
240
- return JSON.parse(readFileSync(usageCacheFile(), 'utf8'));
243
+ const d = JSON.parse(readFileSync(usageCacheFile(), 'utf8'));
244
+ return d.v === USAGE_CACHE_VERSION ? d.files : {};
241
245
  } catch {
242
246
  return {};
243
247
  }
@@ -247,7 +251,7 @@ function loadUsageCache() {
247
251
  function saveUsageCache(c) {
248
252
  try {
249
253
  mkdirSync(stateDir(), { recursive: true });
250
- writeFileSync(usageCacheFile(), JSON.stringify(c));
254
+ writeFileSync(usageCacheFile(), JSON.stringify({ v: USAGE_CACHE_VERSION, files: c }));
251
255
  } catch {
252
256
  /* a cache: the next run just reads the transcripts */
253
257
  }
package/src/where.mjs CHANGED
@@ -395,7 +395,9 @@ export function jobsReport(r, { since, now }) {
395
395
  '',
396
396
  `Every run loads your settings, plugins, hooks, MCP servers, skills and instruction files before it reads its prompt. "New tokens at start" is what counts against your limit; "starting prompt" is the whole context, cached or not. The smallest starting prompt among these jobs averages ${avg(lean.size, lean)} (${leanJob.replace(/\|/g, '/')}); the heaviest job's averages ${avg(ranked[0][1].size, ranked[0][1])}.`,
397
397
  '',
398
- 'A job that does not need all of that can leave it out: launch it with `claude -p --setting-sources "" --strict-mcp-config`, plus `--mcp-config` for the servers it uses. That also drops hooks, plugins and permission rules, so pass `--model` and `--permission-mode` and check the job still does what it should.',
398
+ 'A job that does not need your hooks can leave them out and keep its claude.ai connectors: launch it with `claude -p --settings \'{"disableAllHooks": true}\'`. In a test on one scheduled job that cut each start from about 16k new tokens to about 5k.',
399
+ '',
400
+ 'To leave out everything else too, add `--setting-sources "" --strict-mcp-config` (and `--mcp-config` for the servers it uses). That also drops the claude.ai connectors, plugins and permission rules, so a job that reads from one (HubSpot, Slack) cannot use it. Pass `--model` and `--permission-mode`, and check the job still does what it should.',
399
401
  '',
400
402
  '_Estimated from your local transcripts. A job is its first 45 characters of prompt, so runs of the same job group together._',
401
403
  );