limitcast 0.12.0 → 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/README.md +3 -1
- package/bin/limitcast.mjs +91 -1
- package/package.json +1 -1
- package/src/guard.mjs +34 -3
- package/src/plan.mjs +196 -0
- package/src/prices.mjs +96 -0
- package/src/report.mjs +33 -6
- package/src/results.mjs +9 -1
- package/src/subagents.mjs +32 -0
- package/src/usage.mjs +7 -3
package/README.md
CHANGED
|
@@ -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\|model-id>` / `off` | **Pro.** Run new subagents of that type (for example `Explore`) on that model, unless the spawn names a model itself. 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 models only; 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
|
@@ -43,13 +43,27 @@ import { doctor, install, installedFeatures, readSettings, settingsPath, uninsta
|
|
|
43
43
|
import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
|
|
44
44
|
import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
|
|
45
45
|
import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
|
|
46
|
+
import { advise, getPlan, loadPeaks, PLANS, planPrices, planStats, recordPeaks, setPlan } from '../src/plan.mjs';
|
|
46
47
|
import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
|
|
48
|
+
import { costOf, fmtUsd } from '../src/prices.mjs';
|
|
47
49
|
import { burnReport } from '../src/report.mjs';
|
|
48
50
|
import { loadBlocks, logBlock, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
|
|
49
51
|
import { claudeSamples, readCodex } from '../src/sources.mjs';
|
|
50
52
|
import { countInteractiveSince, latestInteractiveTranscript } from '../src/startup.mjs';
|
|
51
53
|
import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
|
|
52
|
-
import {
|
|
54
|
+
import {
|
|
55
|
+
budgetSpent,
|
|
56
|
+
getBudget,
|
|
57
|
+
getSubagentModels,
|
|
58
|
+
loadSubagents,
|
|
59
|
+
logSubagent,
|
|
60
|
+
receiptMessage,
|
|
61
|
+
setBudget,
|
|
62
|
+
setSubagentModel,
|
|
63
|
+
subagentUsage,
|
|
64
|
+
validModel,
|
|
65
|
+
windowStart,
|
|
66
|
+
} from '../src/subagents.mjs';
|
|
53
67
|
import { forTerminal } from '../src/term.mjs';
|
|
54
68
|
import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
|
|
55
69
|
import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
@@ -86,6 +100,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
86
100
|
one starts; hold the first message after the prompt
|
|
87
101
|
cache expired (idle over 60 min, LIMITCAST_CACHE_MINUTES) and say what it costs
|
|
88
102
|
limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
|
|
103
|
+
limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku or a model id
|
|
104
|
+
limitcast plan [--days N] does your Claude plan fit your use? Hit-limit and headroom evidence, and the monthly price difference
|
|
105
|
+
limitcast plan set <pro|max5|max20>|off tell limitcast which Claude plan you are on
|
|
89
106
|
limitcast budget grok <usd>|off Grok 5-hour dollar cap (Grok stores spend, not a % used; the guard
|
|
90
107
|
needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
|
|
91
108
|
limitcast install --alerts tell you when your starting context grows, plus a weekly summary, and
|
|
@@ -293,6 +310,78 @@ if (cmd === 'status') {
|
|
|
293
310
|
} catch {
|
|
294
311
|
/* a hook must never break the session */
|
|
295
312
|
}
|
|
313
|
+
} else if (cmd === 'plan') {
|
|
314
|
+
if (!isPro()) {
|
|
315
|
+
console.log(
|
|
316
|
+
`\`limitcast plan\` is part of limitcast Pro: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`,
|
|
317
|
+
);
|
|
318
|
+
process.exit(2);
|
|
319
|
+
}
|
|
320
|
+
if (args[0] === 'set') {
|
|
321
|
+
const id = args[1];
|
|
322
|
+
if (id !== 'off' && !(id in PLANS)) {
|
|
323
|
+
console.log('Usage: limitcast plan set <pro|max5|max20>|off');
|
|
324
|
+
process.exit(1);
|
|
325
|
+
}
|
|
326
|
+
setPlan(id === 'off' ? null : /** @type {keyof typeof PLANS} */ (id));
|
|
327
|
+
console.log(id === 'off' ? 'Plan forgotten.' : `Plan set to Claude ${PLANS[/** @type {keyof typeof PLANS} */ (id)].name}. Run: limitcast plan`);
|
|
328
|
+
process.exit(0);
|
|
329
|
+
}
|
|
330
|
+
const planDays = Math.max(1, Number(flag('--days') ?? 28));
|
|
331
|
+
recordPeaks(load(now - KEEP_MS), now);
|
|
332
|
+
const plan = getPlan();
|
|
333
|
+
const prices = planPrices();
|
|
334
|
+
const advice = advise(plan, planStats(loadPeaks(), now, planDays), prices);
|
|
335
|
+
const out = [
|
|
336
|
+
'# limitcast plan',
|
|
337
|
+
'',
|
|
338
|
+
`Claude plan: ${plan ? `${PLANS[plan].name}, ${fmtUsd(prices[plan])} a month` : 'not set'}`,
|
|
339
|
+
'',
|
|
340
|
+
...advice.lines,
|
|
341
|
+
];
|
|
342
|
+
const used = (await readUsage(now - planDays * 86400_000, {})).filter((u) => u.src === 'claude');
|
|
343
|
+
const cost = costOf(used);
|
|
344
|
+
if (plan && cost.priced) {
|
|
345
|
+
const span = Math.min(planDays, Math.max(1, (now - Math.min(...used.map((u) => u.t))) / 86400_000));
|
|
346
|
+
out.push(
|
|
347
|
+
'',
|
|
348
|
+
`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.`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
out.push(
|
|
352
|
+
'',
|
|
353
|
+
'_From the peak of every 5-hour and weekly window limitcast has seen; plan prices and multipliers from claude.com/pricing, 2026-10-26._',
|
|
354
|
+
);
|
|
355
|
+
console.log(forTerminal(out.join('\n')));
|
|
356
|
+
process.exit(0);
|
|
357
|
+
} else if (cmd === 'subagent-model') {
|
|
358
|
+
if (!isPro()) {
|
|
359
|
+
console.log(`Per-type subagent models are part of limitcast Pro: ${UPGRADE_URL}`);
|
|
360
|
+
process.exit(2);
|
|
361
|
+
}
|
|
362
|
+
const [type, model] = args;
|
|
363
|
+
if (type && (model === undefined || (model !== 'off' && !validModel(model)))) {
|
|
364
|
+
console.log('Usage: limitcast subagent-model <type> <sonnet|opus|haiku|claude-id>|off\n limitcast subagent-model list them');
|
|
365
|
+
process.exit(1);
|
|
366
|
+
}
|
|
367
|
+
if (type) setSubagentModel(type, model === 'off' ? null : model);
|
|
368
|
+
const pinned = Object.entries(getSubagentModels());
|
|
369
|
+
console.log(pinned.length ? pinned.map(([t, m]) => `${t}: ${m}`).join('\n') : 'No subagent type is pinned to a model.');
|
|
370
|
+
const ran = new Map();
|
|
371
|
+
for (const e of loadSubagents(now - 30 * 86400_000)) if (e.type) ran.set(e.type, (ran.get(e.type) ?? 0) + 1);
|
|
372
|
+
if (ran.size)
|
|
373
|
+
console.log(
|
|
374
|
+
`\nTypes you ran in the last 30 days: ${[...ran]
|
|
375
|
+
.sort((a, b) => b[1] - a[1])
|
|
376
|
+
.map(([t, n]) => `${t} (${n})`)
|
|
377
|
+
.join(', ')}`,
|
|
378
|
+
);
|
|
379
|
+
if (pinned.length)
|
|
380
|
+
console.log(
|
|
381
|
+
'\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.',
|
|
382
|
+
);
|
|
383
|
+
else console.log('\nExample: limitcast subagent-model Explore haiku');
|
|
384
|
+
process.exit(0);
|
|
296
385
|
} else if (cmd === 'budget') {
|
|
297
386
|
if (!isPro()) {
|
|
298
387
|
console.log(`Budgets are part of limitcast Pro: ${UPGRADE_URL}`);
|
|
@@ -848,6 +937,7 @@ function healthHint() {
|
|
|
848
937
|
async function refreshValue() {
|
|
849
938
|
const since = now - KEEP_MS;
|
|
850
939
|
const claude = load(since);
|
|
940
|
+
recordPeaks(claude, now); // the long-lived record of window peaks behind `limitcast plan`
|
|
851
941
|
const o = loadOverhead();
|
|
852
942
|
// limitcast started watching at its first status-line reading (or first measurement), not when Codex's logs begin.
|
|
853
943
|
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.
|
|
3
|
+
"version": "0.13.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/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, getSubagentModels, loadSubagents, spawnNotice, windowStart } from './subagents.mjs';
|
|
8
8
|
|
|
9
9
|
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
10
10
|
|
|
@@ -125,7 +125,35 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
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
127
|
if (src !== 'claude') return null;
|
|
128
|
-
|
|
128
|
+
// A subagent type pinned to a model (`limitcast subagent-model Explore haiku`) runs on it unless the spawn names a model itself.
|
|
129
|
+
const type = String(input?.subagent_type ?? '');
|
|
130
|
+
const pinned = isUnset(input?.model) && type ? getSubagentModels()[type] : undefined;
|
|
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:
|
|
172
|
+
from: model ?? 'default',
|
|
145
173
|
...(preview ? { shadow: true } : {}),
|
|
146
174
|
});
|
|
147
175
|
} catch {
|
|
@@ -162,3 +190,6 @@ 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';
|
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,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,6 +91,7 @@ export function burnReport(usage, { since, now }) {
|
|
|
69
91
|
true,
|
|
70
92
|
5,
|
|
71
93
|
'new tokens',
|
|
94
|
+
cost,
|
|
72
95
|
);
|
|
73
96
|
lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code and Codex logs._`);
|
|
74
97
|
return lines.join('\n');
|
|
@@ -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))
|
|
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,38 @@ 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 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
|
+
|
|
134
166
|
/**
|
|
135
167
|
* When the current Claude 5-hour window started: its reset minus 5 hours, or 5 hours ago without a reading.
|
|
136
168
|
* @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
|
|
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
|
-
|
|
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
|
}
|