limitcast 0.11.5 → 0.13.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/src/install.mjs CHANGED
@@ -3,6 +3,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeF
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { grokDoctor, grokHome, grokPresent, installGrok, uninstallGrok } from './grok.mjs';
6
7
  import { stateDir } from './store.mjs';
7
8
 
8
9
  export const settingsPath = () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'settings.json');
@@ -77,9 +78,9 @@ export function launcherTargets(path) {
77
78
  * Idempotent; backs up settings.json first; remembers the original status line for uninstall.
78
79
  * With `guard`, Codex gets the guard too when ~/.codex exists. With `alerts`, a SessionStart hook tells you
79
80
  * (never the model) when your starting context grew.
80
- * @param {{guard:boolean, alerts?:boolean, path?:string, codexPath?:string, self?:string}} opts
81
+ * @param {{guard:boolean, alerts?:boolean, path?:string, codexPath?:string, grokDir?:string, self?:string}} opts
81
82
  */
82
- export function install({ guard, alerts = false, path = settingsPath(), codexPath = codexHooksPath(), self = selfCommand() }) {
83
+ export function install({ guard, alerts = false, path = settingsPath(), codexPath = codexHooksPath(), grokDir = grokHome(), self = selfCommand() }) {
83
84
  const cfg = readSettings(path);
84
85
  backup(path);
85
86
  const changes = [];
@@ -104,6 +105,13 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
104
105
  if (alerts) {
105
106
  upsertHook(cfg, 'SessionStart', { matcher: '', hooks: [{ type: 'command', command: `${self} drift --hook`, timeout: 15 }] }, isAlert);
106
107
  changes.push('added the starting-context alert');
108
+ upsertHook(
109
+ cfg,
110
+ 'PostToolUse',
111
+ { matcher: 'Bash|Read|Grep|WebFetch|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-check`, timeout: 10 }] },
112
+ isToolCheck,
113
+ );
114
+ changes.push('added the large tool-output notice');
107
115
  }
108
116
  writeSettings(path, cfg);
109
117
  if (guard && existsSync(join(codexPath, '..'))) {
@@ -113,6 +121,7 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
113
121
  writeSettings(codexPath, codex);
114
122
  changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new hook)');
115
123
  }
124
+ if (grokPresent(grokDir)) changes.push(...installGrok({ guard, self, home: grokDir }));
116
125
  return changes;
117
126
  }
118
127
 
@@ -143,9 +152,9 @@ function upsertHook(cfg, event, entry, mine) {
143
152
 
144
153
  /**
145
154
  * Remove everything limitcast added and restore the original status line.
146
- * @param {{path?:string, codexPath?:string}} [opts]
155
+ * @param {{path?:string, codexPath?:string, grokDir?:string}} [opts]
147
156
  */
148
- export function uninstall({ path = settingsPath(), codexPath = codexHooksPath() } = {}) {
157
+ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(), grokDir = grokHome() } = {}) {
149
158
  const cfg = readSettings(path);
150
159
  backup(path);
151
160
  const changes = [];
@@ -164,6 +173,7 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath()
164
173
  ['SessionStart', isAlert, 'the starting-context alert'],
165
174
  ['UserPromptSubmit', isPromptCheck, 'the cold-cache warning'],
166
175
  ['SubagentStop', isReceipt, 'subagent receipts'],
176
+ ['PostToolUse', isToolCheck, 'the large tool-output notice'],
167
177
  ])) {
168
178
  const n = cfg.hooks?.[event]?.length ?? 0;
169
179
  if (!n) continue;
@@ -181,6 +191,7 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath()
181
191
  changes.push('removed the Codex subagent guard');
182
192
  }
183
193
  }
194
+ changes.push(...uninstallGrok({ home: grokDir }));
184
195
  return changes;
185
196
  }
186
197
 
@@ -219,6 +230,7 @@ const runs = (re) => (h) =>
219
230
  const isAlert = runs(/\bdrift --hook\b/);
220
231
  const isPromptCheck = runs(/\bprompt-check\b/);
221
232
  const isReceipt = runs(/\bsubagent-receipt\b/);
233
+ const isToolCheck = runs(/\btool-check\b/);
222
234
 
223
235
  /** @param {string} path */
224
236
  export function readSettings(path) {
@@ -324,6 +336,7 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
324
336
  line: 'Cold-cache warning and subagent receipts not installed yet: run `limitcast doctor --fix`',
325
337
  });
326
338
  if (existsSync(codexPath)) out.push(codexGuardCheck(codexPath));
339
+ out.push(...grokDoctor());
327
340
  out.push(
328
341
  samplesAgeMs === null
329
342
  ? { ok: false, line: 'No Claude limit readings yet: send a message in Claude Code' }
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,96 @@
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 models only; 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 are 1.25x input (5 minutes) or 2x (1 hour).
12
+ * Source: platform.claude.com/docs/en/about-claude/pricing, read 2026-10-26. Override or add models in
13
+ * ~/.local/state/limitcast/prices.json: {"models": {"claude-opus-4-1": {"input": 15, "output": 75, "readX": 0.1}}}.
14
+ * @typedef {{input:number, output:number, readX:number, over?:{above:number, input:number, output:number}}} Price
15
+ * @type {Record<string, Price>}
16
+ */
17
+ export const PRICES = {
18
+ 'claude-fable-5-1': { input: 10, output: 50, readX: 0.025 },
19
+ 'claude-opus-5-5': { input: 4, output: 20, readX: 0.05 },
20
+ 'claude-sonnet-5-5': { input: 2, output: 10, readX: 0.05 },
21
+ 'claude-haiku-5-5': { input: 0.1, output: 0.5, readX: 0.1, over: { above: 100_000, input: 0.5, output: 2.5 } },
22
+ };
23
+
24
+ const WRITE_5M = 1.25;
25
+ const WRITE_1H = 2;
26
+
27
+ /**
28
+ * The price table with your overrides on top. A bad or missing file changes nothing.
29
+ * @returns {Record<string, Price>}
30
+ */
31
+ export function priceTable() {
32
+ try {
33
+ const o = JSON.parse(readFileSync(join(stateDir(), 'prices.json'), 'utf8')).models;
34
+ const good = Object.entries(o ?? {}).filter(([, p]) => p && typeof p === 'object' && Number(p.input) > 0 && Number(p.output) > 0);
35
+ if (!good.length) return PRICES;
36
+ return { ...PRICES, ...Object.fromEntries(good.map(([k, p]) => [k, { readX: 0.1, ...p }])) };
37
+ } catch {
38
+ return PRICES;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * The price of a model id: an exact key, else the longest key it starts with (ids carry a date suffix at times).
44
+ * @param {string|undefined} model
45
+ * @param {Record<string, Price>} table
46
+ */
47
+ export function priceFor(model, table) {
48
+ if (!model) return null;
49
+ const key = Object.keys(table)
50
+ .filter((k) => model === k || model.startsWith(`${k}-`))
51
+ .sort((a, b) => b.length - a.length)[0];
52
+ return key ? table[key] : null;
53
+ }
54
+
55
+ /**
56
+ * API-equivalent dollars of one model call, or null when its model has no price.
57
+ * @param {{model?:string, input:number, cacheWrite:number, cacheWrite1h?:number, cacheRead:number, output:number}} u
58
+ * @param {Record<string, Price>} [table]
59
+ */
60
+ export function callCost(u, table = priceTable()) {
61
+ const base = priceFor(u.model, table);
62
+ if (!base) return null;
63
+ const p = base.over && u.input + u.cacheWrite + u.cacheRead > base.over.above ? { ...base, ...base.over } : base;
64
+ const w1h = Math.min(u.cacheWrite1h ?? 0, u.cacheWrite);
65
+ const w5m = u.cacheWrite - w1h;
66
+ return (u.input * p.input + (w5m * WRITE_5M + w1h * WRITE_1H) * p.input + u.cacheRead * p.readX * p.input + u.output * p.output) / 1e6;
67
+ }
68
+
69
+ /**
70
+ * Total API-equivalent dollars of many calls, how many tokens were priced and how many were not, and dollars by model.
71
+ * @param {Parameters<typeof callCost>[0][]} calls
72
+ */
73
+ export function costOf(calls) {
74
+ const table = priceTable();
75
+ let total = 0;
76
+ let priced = 0;
77
+ let unpriced = 0;
78
+ /** @type {Map<string, number>} */
79
+ const byModel = new Map();
80
+ for (const u of calls) {
81
+ const n = u.input + u.cacheWrite + u.cacheRead + u.output;
82
+ const c = callCost(u, table);
83
+ if (c === null) {
84
+ unpriced += n;
85
+ continue;
86
+ }
87
+ total += c;
88
+ priced += n;
89
+ const k = u.model ?? '';
90
+ byModel.set(k, (byModel.get(k) ?? 0) + c);
91
+ }
92
+ return { total, priced, unpriced, byModel };
93
+ }
94
+
95
+ /** "$0.42", "$12.34", "$1,234". @param {number} d */
96
+ 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 */
@@ -15,13 +16,29 @@ export function burnReport(usage, { since, now }) {
15
16
  const lines = [`# limitcast burn report`, '', `${day(since)} to ${day(now)} · ${fmt(all)} tokens`, ''];
16
17
  if (!usage.length) return [...lines, 'No Claude Code or Codex usage in this period.'].join('\n');
17
18
 
19
+ // API-equivalent dollars: what the tokens would cost at list prices. Only Claude 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 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,33 +53,45 @@ export function burnReport(usage, { since, now }) {
36
53
  sum,
37
54
  all,
38
55
  false,
56
+ Infinity,
57
+ 'tokens',
58
+ cost,
39
59
  );
60
+ // Ranked by new tokens (input, cache writes, output): cached reads barely count against the limit.
61
+ const fresh = (/** @type {Usage[]} */ xs) => xs.reduce((a, u) => a + u.input + u.cacheWrite + u.output, 0);
62
+ const allFresh = fresh(usage);
40
63
  table(
41
64
  lines,
42
65
  'Top projects',
43
66
  group(usage, (u) => short(u.project) || '(unknown)'),
44
- sum,
45
- all,
67
+ fresh,
68
+ allFresh,
46
69
  true,
47
70
  8,
71
+ 'new tokens',
72
+ cost,
48
73
  );
49
74
  table(
50
75
  lines,
51
76
  'By model',
52
77
  group(usage, (u) => u.model || '(unknown)'),
53
- sum,
54
- all,
78
+ fresh,
79
+ allFresh,
55
80
  true,
56
81
  6,
82
+ 'new tokens',
83
+ cost,
57
84
  );
58
85
  table(
59
86
  lines,
60
87
  'Heaviest sessions',
61
88
  group(usage, (u) => `${u.src} ${u.session.slice(0, 8)} · ${short(u.project)}`),
62
- sum,
63
- all,
89
+ fresh,
90
+ allFresh,
64
91
  true,
65
92
  5,
93
+ 'new tokens',
94
+ cost,
66
95
  );
67
96
  lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code and Codex logs._`);
68
97
  return lines.join('\n');
@@ -76,12 +105,17 @@ export function burnReport(usage, { since, now }) {
76
105
  * @param {number} all
77
106
  * @param {boolean} sortBySize
78
107
  * @param {number} [limit]
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
79
110
  */
80
- function table(lines, title, groups, sum, all, sortBySize, limit = Infinity) {
81
- 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]));
82
113
  rows = sortBySize ? rows.sort((a, b) => b[1] - a[1]) : rows.sort((a, b) => a[0].localeCompare(b[0]));
83
- lines.push('', `## ${title}`, '', '| | tokens | share |', '|---|---:|---:|');
84
- 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
+ }
85
119
  }
86
120
 
87
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
@@ -54,6 +54,33 @@ export function receiptMessage(type, u, pct) {
54
54
  }
55
55
 
56
56
  const k = (/** @type {number} */ n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
57
+ const pct1 = (/** @type {number} */ p) => (p < 1 ? p.toFixed(2) : p.toFixed(1));
58
+
59
+ const NOTICE_MIN_RUNS = 3;
60
+ const NOTICE_MIN_PCT = 1; // a typical run under 1% of a window is not worth a message
61
+
62
+ /**
63
+ * Before a subagent starts: what that kind has cost you so far, from the receipts ledger.
64
+ * "limitcast: Explore subagents have cost you a median ≈1.2% (max ≈3.6%) of a 5-hour window over 7 runs; this window is 38% used."
65
+ * Uses the same type when it has at least 3 priced runs, else every subagent. Null with too little history, or when
66
+ * the typical run is under 1% of a window and the window is not NEAR.
67
+ * @param {SubagentEntry[]} entries
68
+ * @param {unknown} type the subagent type about to start
69
+ * @param {{pct:number, verdict:string}|undefined} win the current 5-hour window
70
+ */
71
+ export function spawnNotice(entries, type, win) {
72
+ const priced = entries.filter((e) => typeof e.pct === 'number');
73
+ const same = typeof type === 'string' && type ? priced.filter((e) => e.type === type) : [];
74
+ const runs = same.length >= NOTICE_MIN_RUNS ? same : priced;
75
+ if (runs.length < NOTICE_MIN_RUNS) return null;
76
+ const sorted = runs.map((e) => /** @type {number} */ (e.pct)).sort((a, b) => a - b);
77
+ const mid = sorted.length >> 1;
78
+ const median = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
79
+ if (median < NOTICE_MIN_PCT && win?.verdict !== 'NEAR') return null;
80
+ const who = runs === same ? `${type} subagents have` : 'Your subagents have';
81
+ const used = win ? `; this window is ${Math.round(win.pct)}% used` : '';
82
+ return `limitcast: ${who} cost you a median ≈${pct1(median)}% (max ≈${pct1(sorted.at(-1) ?? 0)}%) of a 5-hour window over ${runs.length} runs${used}.`;
83
+ }
57
84
 
58
85
  /** @param {SubagentEntry} e */
59
86
  export function logSubagent(e) {
@@ -104,6 +131,38 @@ export function setBudget(pct) {
104
131
  writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
105
132
  }
106
133
 
134
+ /** A model a subagent type can be pinned to: sonnet, opus, haiku or a full claude-... id. */
135
+ export const validModel = (/** @type {unknown} */ m) => typeof m === 'string' && /^(sonnet|opus|haiku|claude-[a-z0-9.-]+)$/i.test(m);
136
+
137
+ /** @returns {Record<string, string>} the model each subagent type runs on by default, e.g. {Explore: 'haiku'} */
138
+ export function getSubagentModels() {
139
+ try {
140
+ const m = JSON.parse(readFileSync(configFile(), 'utf8')).subagentModels;
141
+ return m && typeof m === 'object' ? Object.fromEntries(Object.entries(m).filter(([, v]) => validModel(v))) : {};
142
+ } catch {
143
+ return {};
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Pin a subagent type to a model, or null to remove it.
149
+ * @param {string} type
150
+ * @param {string|null} model
151
+ */
152
+ export function setSubagentModel(type, model) {
153
+ let cfg = /** @type {any} */ ({});
154
+ try {
155
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
156
+ } catch {
157
+ /* new */
158
+ }
159
+ const models = { ...cfg.subagentModels };
160
+ if (model === null) delete models[type];
161
+ else models[type] = model;
162
+ mkdirSync(stateDir(), { recursive: true });
163
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentModels: models }));
164
+ }
165
+
107
166
  /**
108
167
  * When the current Claude 5-hour window started: its reset minus 5 hours, or 5 hours ago without a reading.
109
168
  * @param {{src:string, win:string, verdict:string, reset:number}[]} forecasts