lake-meter 0.0.0-stage → 0.1.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/init.js ADDED
@@ -0,0 +1,132 @@
1
+ // `lake-meter init`: copy a pinned runtime to ~/.lake-meter/runtime and register hooks, a statusline,
2
+ // a /meter skill and two optional cheap-model subagents in Claude Code settings. `uninstall` reverses it.
3
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, cpSync, rmSync, copyFileSync } from 'node:fs';
4
+ import { join, dirname } from 'node:path';
5
+ import { homedir } from 'node:os';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { home, saveUserConfig, DEFAULT_CONFIG } from './state.js';
8
+
9
+ const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
10
+ const MARK = 'lake-meter';
11
+
12
+ function readJson(p) {
13
+ if (!existsSync(p)) return {};
14
+ const raw = readFileSync(p, 'utf8');
15
+ if (!raw.trim()) return {};
16
+ return JSON.parse(raw); // throw on broken JSON rather than overwrite the user's file
17
+ }
18
+
19
+ export function targets({ project, cwd = process.cwd(), claudeHome = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude') }) {
20
+ const base = project ? join(cwd, '.claude') : claudeHome;
21
+ return {
22
+ settings: join(base, project ? 'settings.local.json' : 'settings.json'),
23
+ skillDir: join(base, 'skills', 'meter'),
24
+ agentsDir: join(base, 'agents'),
25
+ };
26
+ }
27
+
28
+ function hookEntry(node, cli, event, extra = {}) {
29
+ return { ...extra, hooks: [{ type: 'command', command: node, args: [cli, 'hook', event], timeout: event === 'stop' ? 20 : 10 }] };
30
+ }
31
+
32
+ const isOurs = (group) => (group?.hooks || []).some((h) => [h.command, ...(h.args || [])].some((x) => String(x).includes(MARK)));
33
+
34
+ export function installRuntime() {
35
+ const rt = join(home(), 'runtime');
36
+ rmSync(rt, { recursive: true, force: true });
37
+ mkdirSync(rt, { recursive: true });
38
+ for (const d of ['bin', 'src']) cpSync(join(pkgRoot, d), join(rt, d), { recursive: true });
39
+ copyFileSync(join(pkgRoot, 'package.json'), join(rt, 'package.json'));
40
+ return join(rt, 'bin', 'lake-meter.js');
41
+ }
42
+
43
+ export function init(opts = {}) {
44
+ const log = opts.log || console.log;
45
+ const node = opts.node || process.execPath;
46
+ const cli = opts.cli || installRuntime();
47
+ const t = targets(opts);
48
+ const settings = readJson(t.settings);
49
+ if (existsSync(t.settings)) copyFileSync(t.settings, `${t.settings}.lake-meter.bak`);
50
+ settings.hooks ||= {};
51
+ const add = (evt, group) => {
52
+ settings.hooks[evt] = (settings.hooks[evt] || []).filter((g) => !isOurs(g));
53
+ settings.hooks[evt].push(group);
54
+ };
55
+ add('UserPromptSubmit', hookEntry(node, cli, 'user-prompt-submit'));
56
+ add('PreToolUse', hookEntry(node, cli, 'pre-tool-use', { matcher: '*' }));
57
+ add('PostToolUse', hookEntry(node, cli, 'post-tool-use', { matcher: '*' }));
58
+ add('Stop', hookEntry(node, cli, 'stop'));
59
+
60
+ let statusNote = 'statusline installed';
61
+ const ourStatus = { type: 'command', command: `"${node}" "${cli}" statusline`, padding: 0 };
62
+ if (!settings.statusLine || isOurs({ hooks: [settings.statusLine] }) || opts.statusline) {
63
+ if (settings.statusLine && !isOurs({ hooks: [settings.statusLine] })) writeFileSync(join(home(), 'previous-statusline.json'), JSON.stringify(settings.statusLine, null, 2));
64
+ settings.statusLine = ourStatus;
65
+ } else {
66
+ statusNote = 'kept your existing statusline (run `init --statusline` to replace it; the 5-hour-window cap needs it)';
67
+ }
68
+ mkdirSync(dirname(t.settings), { recursive: true });
69
+ writeFileSync(t.settings, JSON.stringify(settings, null, 2) + '\n');
70
+
71
+ mkdirSync(t.skillDir, { recursive: true });
72
+ writeFileSync(join(t.skillDir, 'SKILL.md'), `---
73
+ name: meter
74
+ description: Lake Meter. Show this run's spend, set the per-run cap, or estimate a plan. Usage /meter [status|cap <usd>|cap off|plan <file>|report]
75
+ disable-model-invocation: true
76
+ allowed-tools: Bash(${node} *)
77
+ argument-hint: "[status | cap <usd> | cap off | plan <file> | report]"
78
+ ---
79
+ !\`"${node}" "${cli}" cmd --session \${CLAUDE_SESSION_ID} $ARGUMENTS\`
80
+
81
+ Show the Lake Meter output above to the user exactly as written, in a code block. Do not take any other action.
82
+ `);
83
+
84
+ if (opts.agents !== false) {
85
+ mkdirSync(t.agentsDir, { recursive: true });
86
+ writeFileSync(join(t.agentsDir, 'lake-light.md'), `---
87
+ name: lake-light
88
+ description: Low-cost worker on Haiku for mechanical plan steps that Lake Meter rated light (renames, docs, config, boilerplate, simple tests). Not for design, security, concurrency or debugging work.
89
+ model: haiku
90
+ ---
91
+ You carry out one small, well-specified step of an approved plan. Follow the step exactly, keep the change minimal, run the relevant checks, and report what you changed. If the step turns out to need design decisions, stop and say so instead of guessing.
92
+ `);
93
+ writeFileSync(join(t.agentsDir, 'lake-standard.md'), `---
94
+ name: lake-standard
95
+ description: Mid-cost worker on Sonnet for plan steps that Lake Meter rated standard (normal feature work in a known area). Not for architecture, migrations or security-sensitive changes.
96
+ model: sonnet
97
+ ---
98
+ You implement one step of an approved plan. Stay inside the step's scope, follow the codebase's conventions, run the relevant tests, and report what you changed and anything you were unsure about.
99
+ `);
100
+ }
101
+
102
+ if (!existsSync(join(home(), 'config.json'))) saveUserConfig({ capUsd: opts.capUsd ?? DEFAULT_CONFIG.capUsd, onCap: DEFAULT_CONFIG.onCap });
103
+ else if (opts.capUsd != null) saveUserConfig({ capUsd: opts.capUsd });
104
+
105
+ log(`✓ Lake Meter installed in ${t.settings}`);
106
+ log(` hooks: UserPromptSubmit, PreToolUse, PostToolUse, Stop · ${statusNote}`);
107
+ log(` /meter skill: ${t.skillDir}${opts.agents !== false ? ` · subagents lake-light (haiku), lake-standard (sonnet) in ${t.agentsDir}` : ''}`);
108
+ log(` per-run cap: ${'$'}${opts.capUsd ?? JSON.parse(readFileSync(join(home(), 'config.json'), 'utf8')).capUsd} (change with: npx lake-meter cap 10)`);
109
+ log(' Restart Claude Code (or open /hooks) to load it. No data leaves your machine.');
110
+ return t;
111
+ }
112
+
113
+ export function uninstall(opts = {}) {
114
+ const log = opts.log || console.log;
115
+ const t = targets(opts);
116
+ if (existsSync(t.settings)) {
117
+ const s = readJson(t.settings);
118
+ for (const evt of Object.keys(s.hooks || {})) {
119
+ s.hooks[evt] = s.hooks[evt].filter((g) => !isOurs(g));
120
+ if (!s.hooks[evt].length) delete s.hooks[evt];
121
+ }
122
+ if (s.hooks && !Object.keys(s.hooks).length) delete s.hooks;
123
+ if (s.statusLine && isOurs({ hooks: [s.statusLine] })) {
124
+ const prev = join(home(), 'previous-statusline.json');
125
+ if (existsSync(prev)) s.statusLine = JSON.parse(readFileSync(prev, 'utf8')); else delete s.statusLine;
126
+ }
127
+ writeFileSync(t.settings, JSON.stringify(s, null, 2) + '\n');
128
+ }
129
+ rmSync(t.skillDir, { recursive: true, force: true });
130
+ for (const a of ['lake-light.md', 'lake-standard.md']) rmSync(join(t.agentsDir, a), { force: true });
131
+ log(`✓ Lake Meter removed from ${t.settings}. Local data stays in ${home()} (delete it if you like).`);
132
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,71 @@
1
+ // Minimal MCP server over stdio (JSON-RPC 2.0, newline-delimited), no dependencies.
2
+ // Tools: estimate_plan (any MCP client: Claude Code, Cursor, ...) and meter_status (Claude Code sessions).
3
+ import { createInterface } from 'node:readline';
4
+ import { loadPrices } from './pricing.js';
5
+ import { analyzePlan } from './plan.js';
6
+ import { planMarkdown, runSummary } from './format.js';
7
+ import { loadSession, latestSessionId, loadConfig } from './state.js';
8
+ import { totals } from './transcript.js';
9
+ import { effectiveCaps } from './hooks.js';
10
+
11
+ const TOOLS = [
12
+ {
13
+ name: 'estimate_plan',
14
+ description: 'Split a markdown implementation plan into steps, rate each step\'s complexity, recommend the cheapest model tier that should handle it, and estimate token and USD cost ranges per step and in total, compared with running everything on the top model. Heuristic estimate, not a measurement.',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ plan: { type: 'string', description: 'The plan in markdown (numbered steps, headings or bullets).' },
19
+ provider: { type: 'string', enum: ['anthropic', 'openai'], description: 'Model family to recommend from. Default anthropic.' },
20
+ },
21
+ required: ['plan'],
22
+ },
23
+ },
24
+ {
25
+ name: 'meter_status',
26
+ description: 'Measured spend of the current Claude Code run (tokens from the session transcript, priced at list price) and the active cap. Only works where the Lake Meter hooks are installed.',
27
+ inputSchema: { type: 'object', properties: { session_id: { type: 'string' } } },
28
+ },
29
+ ];
30
+
31
+ export function handle(msg, prices = loadPrices()) {
32
+ const { id, method, params } = msg;
33
+ const ok = (result) => ({ jsonrpc: '2.0', id, result });
34
+ if (method === 'initialize') {
35
+ return ok({ protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'lake-meter', version: '0.1.0' } });
36
+ }
37
+ if (method === 'notifications/initialized' || id === undefined) return null;
38
+ if (method === 'ping') return ok({});
39
+ if (method === 'tools/list') return ok({ tools: TOOLS });
40
+ if (method === 'tools/call') {
41
+ const args = params?.arguments || {};
42
+ try {
43
+ if (params.name === 'estimate_plan') {
44
+ const a = analyzePlan(args.plan, prices, { provider: args.provider });
45
+ return ok({ content: [{ type: 'text', text: planMarkdown(a) }], structuredContent: a });
46
+ }
47
+ if (params.name === 'meter_status') {
48
+ const sid = args.session_id || latestSessionId();
49
+ const s = sid ? loadSession(sid) : null;
50
+ if (!s?.run) return ok({ content: [{ type: 'text', text: 'No Lake Meter run found. Are the hooks installed (npx lake-meter init)?' }] });
51
+ const t = totals(s.run.seen, prices);
52
+ return ok({ content: [{ type: 'text', text: runSummary(t, { cap: effectiveCaps(loadConfig(process.cwd()), s.run).usd }) }] });
53
+ }
54
+ return { jsonrpc: '2.0', id, error: { code: -32602, message: `Unknown tool ${params.name}` } };
55
+ } catch (e) {
56
+ return ok({ content: [{ type: 'text', text: `lake-meter error: ${e.message}` }], isError: true });
57
+ }
58
+ }
59
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } };
60
+ }
61
+
62
+ export function serve() {
63
+ const prices = loadPrices();
64
+ const rl = createInterface({ input: process.stdin });
65
+ rl.on('line', (line) => {
66
+ if (!line.trim()) return;
67
+ let msg; try { msg = JSON.parse(line); } catch { return; }
68
+ const res = handle(msg, prices);
69
+ if (res) process.stdout.write(JSON.stringify(res) + '\n');
70
+ });
71
+ }
package/src/plan.js ADDED
@@ -0,0 +1,114 @@
1
+ // Plan breakdown: split a markdown plan into steps, rate complexity 1-5 with transparent heuristics,
2
+ // recommend the cheapest model tier that should handle each step, and estimate token / USD ranges.
3
+ // Everything here is an ESTIMATE. The reasons for each score are returned so users can disagree.
4
+ import { costOfBudget } from './pricing.js';
5
+
6
+ const SKIP_HEADINGS = /^(context|background|overview|summary|goal|goals|notes?|open questions?|assumptions|out of scope|non-goals|references|tl;?dr|why|problem|motivation)\b/i;
7
+
8
+ /** Split markdown into steps. Prefers step-like headings, then top-level numbered items, then bullets. */
9
+ export function splitPlan(markdown) {
10
+ const text = String(markdown || '').replace(/\r\n/g, '\n');
11
+ const lines = text.split('\n');
12
+
13
+ // 1) Headings (##..####) that are not the document title and not context sections.
14
+ const heads = [];
15
+ lines.forEach((l, i) => { const m = /^(#{2,4})\s+(.*)$/.exec(l); if (m) heads.push({ i, level: m[1].length, title: m[2].trim() }); });
16
+ const CONTAINER = /^(steps?|plan|implementation( plan)?|tasks?|changes|approach|proposed changes|work items?)\b/i;
17
+ const stepLike = (h) => !SKIP_HEADINGS.test(h.title.replace(/^(step|phase|part)?\s*\d+[.:)]?\s*/i, '')) && !CONTAINER.test(h.title);
18
+ const byLevel = {};
19
+ for (const h of heads) if (stepLike(h)) (byLevel[h.level] ||= []).push(h);
20
+ const levels = Object.keys(byLevel).map(Number).sort((a, b) => byLevel[b].length - byLevel[a].length || b - a);
21
+ if (levels.length && byLevel[levels[0]].length >= 2) {
22
+ const level = levels[0];
23
+ return byLevel[level].map((h) => {
24
+ const next = heads.find((x) => x.i > h.i && x.level <= level);
25
+ const body = lines.slice(h.i + 1, next ? next.i : lines.length).join('\n').trim();
26
+ return { title: clean(h.title), body };
27
+ });
28
+ }
29
+
30
+ // 2) Top-level numbered list items (also "- [ ]" checkboxes), with indented continuation lines.
31
+ for (const re of [/^(\d+)[.)]\s+(.*)$/, /^[-*]\s+\[[ xX]\]\s+(.*)$/, /^[-*]\s+(.*)$/]) {
32
+ const items = [];
33
+ let cur = null;
34
+ for (const l of lines) {
35
+ const m = re.exec(l);
36
+ if (m) { cur = { title: clean(m[m.length - 1]), body: '' }; items.push(cur); continue; }
37
+ if (cur && (/^\s+\S/.test(l) || l.trim() === '')) { cur.body += l.trim() ? l.trim() + '\n' : ''; continue; }
38
+ if (cur && /^#{1,6}\s/.test(l)) cur = null;
39
+ else if (cur && l.trim()) cur = null;
40
+ }
41
+ if (items.length >= 2) return items.map((s) => ({ title: s.title, body: s.body.trim() }));
42
+ }
43
+
44
+ // 3) Fallback: paragraphs.
45
+ const paras = text.split(/\n\s*\n/).map((p) => p.trim()).filter((p) => p && !/^#\s/.test(p));
46
+ return paras.slice(0, 30).map((p) => ({ title: clean(p.split('\n')[0]).slice(0, 90), body: p }));
47
+ }
48
+
49
+ function clean(s) {
50
+ return s.replace(/^(step|phase|part)\s*\d+\s*[.:)\-–—]\s*/i, '').replace(/^\d+[.)]\s*/, '').replace(/\*\*|__|`/g, '').trim();
51
+ }
52
+
53
+ const SIGNALS = [
54
+ // [regex, weight, reason]
55
+ [/\b(architect\w*|redesign|re-?architect|system design)\b/i, 2, 'architecture'],
56
+ [/\b(migrat\w+|schema change|data model|backfill)\b/i, 2, 'data/schema migration'],
57
+ [/\b(concurren\w+|race condition|deadlock|lock(ing)?|distributed|consisten\w+|idempoten\w+|transaction\w*)\b/i, 2, 'concurrency/consistency'],
58
+ [/\b(security|auth\w*|permission\w*|encrypt\w*|secret\w*|oauth|csrf|xss|injection)\b/i, 2, 'security-sensitive'],
59
+ [/\b(payment\w*|billing|invoice\w*|money)\b/i, 1, 'money paths'],
60
+ [/\b(performance|optimi[sz]\w+|latency|memory leak|profil\w+)\b/i, 1, 'performance work'],
61
+ [/\b(refactor\w*|restructur\w+|rewrite)\b/i, 1, 'refactor'],
62
+ [/\b(algorithm\w*|parser|compiler|protocol|state machine)\b/i, 2, 'algorithmic'],
63
+ [/\b(debug\w*|investigat\w+|root cause|flaky|intermittent)\b/i, 1, 'debugging/unknowns'],
64
+ [/\b(across|cross-cutting|every (file|module|service)|monorepo|multiple services)\b/i, 1, 'cross-cutting'],
65
+ [/\b(implement\w*|integrat\w+|endpoint|api|component|service|hook|middleware|query|cache|websocket|queue)\b/i, 1, 'new behavior'],
66
+ [/\b(rename|typo|readme|docs?|documentation|comment\w*|changelog|format\w*|lint\w*|prettier|bump|version|copy|wording|text|label)\b/i, -1, 'mechanical/docs'],
67
+ [/\b(config\w*|env(ironment)? var\w*|flag|constant|stub|scaffold\w*|boilerplate|placeholder)\b/i, -1, 'config/boilerplate'],
68
+ [/\b(delete|remove unused|cleanup|clean up|dead code)\b/i, -1, 'cleanup'],
69
+ ];
70
+
71
+ /** Score one step. Returns { complexity 1-5, reasons[] }. */
72
+ export function scoreStep(step) {
73
+ const text = `${step.title}\n${step.body || ''}`;
74
+ let score = 0;
75
+ const reasons = [];
76
+ for (const [re, w, why] of SIGNALS) if (re.test(text)) { score += w; reasons.push(`${w > 0 ? '+' : ''}${w} ${why}`); }
77
+ const files = new Set((text.match(/[\w@./-]+\.(ts|tsx|js|jsx|mjs|py|go|rs|java|kt|rb|php|cs|swift|sql|vue|svelte|css|scss|json|yaml|yml|md)\b/g) || []));
78
+ if (files.size >= 6) { score += 2; reasons.push(`+2 touches ${files.size} files`); }
79
+ else if (files.size >= 3) { score += 1; reasons.push(`+1 touches ${files.size} files`); }
80
+ if (text.length > 900) { score += 1; reasons.push('+1 long step description'); }
81
+ const complexity = Math.max(1, Math.min(5, Math.round(2 + score * 0.75)));
82
+ if (!reasons.length) reasons.push('no strong signals (default 2)');
83
+ return { complexity, reasons };
84
+ }
85
+
86
+ /**
87
+ * Full breakdown. options: { provider: 'anthropic'|'openai', baseline?: modelKey, allowFrontier?: boolean }
88
+ */
89
+ export function analyzePlan(markdown, prices, options = {}) {
90
+ const provider = options.provider || 'anthropic';
91
+ const rec = prices.recommend[provider];
92
+ const baseline = options.baseline || prices.baseline[provider];
93
+ const a = prices.assumptions;
94
+ const steps = splitPlan(markdown).map((s, idx) => {
95
+ const { complexity, reasons } = scoreStep(s);
96
+ let tier = a.complexityToTier[String(complexity)];
97
+ if (complexity === 5 && options.allowFrontier) tier = 'frontier';
98
+ const model = rec[tier];
99
+ const budget = a.stepTokens[String(complexity)];
100
+ const mult = a.tierTokenMultiplier[tier] ?? 1;
101
+ const tokLo = Math.round((budget.input[0] + budget.output[0]) * mult);
102
+ const tokHi = Math.round((budget.input[1] + budget.output[1]) * mult);
103
+ const usdLo = costOfBudget(model, budget.input[0] * mult, budget.output[0] * mult, prices);
104
+ const usdHi = costOfBudget(model, budget.input[1] * mult, budget.output[1] * mult, prices);
105
+ const baseLo = costOfBudget(baseline, budget.input[0], budget.output[0], prices);
106
+ const baseHi = costOfBudget(baseline, budget.input[1], budget.output[1], prices);
107
+ return { n: idx + 1, title: s.title, complexity, reasons, tier, model, modelLabel: prices.models[model].label, alias: prices.models[model].alias || model, tokens: [tokLo, tokHi], usd: [usdLo, usdHi], baselineUsd: [baseLo, baseHi] };
108
+ });
109
+ const sum = (k, i) => steps.reduce((t, s) => t + s[k][i], 0);
110
+ const total = { tokens: [sum('tokens', 0), sum('tokens', 1)], usd: [sum('usd', 0), sum('usd', 1)], baselineUsd: [sum('baselineUsd', 0), sum('baselineUsd', 1)] };
111
+ const mid = (r) => (r[0] + r[1]) / 2;
112
+ total.savingsPct = mid(total.baselineUsd) > 0 ? Math.round((1 - mid(total.usd) / mid(total.baselineUsd)) * 100) : 0;
113
+ return { provider, baseline, baselineLabel: prices.models[baseline].label, steps, total, pricesVerifiedAt: prices.verifiedAt, estimate: true };
114
+ }
@@ -0,0 +1,111 @@
1
+ {
2
+ "$comment": "Lake Meter price and model table. Edit this one file when list prices change. Prices are USD per 1M tokens, standard (non-batch, non-fast, global) API list prices.",
3
+ "verifiedAt": "2026-11-12",
4
+ "sources": {
5
+ "anthropic": "https://platform.claude.com/docs/en/about-claude/pricing",
6
+ "openai": "https://developers.openai.com/api/docs/pricing",
7
+ "claudeCodeAliases": "https://code.claude.com/docs/en/model-config"
8
+ },
9
+ "models": {
10
+ "claude-haiku-5-5": {
11
+ "provider": "anthropic", "label": "Haiku 5.5", "tier": "light", "alias": "haiku",
12
+ "match": ["haiku-5-5", "haiku-5.5"],
13
+ "input": 0.10, "cacheWrite5m": 0.125, "cacheWrite1h": 0.20, "cacheRead": 0.01, "output": 0.50,
14
+ "longContext": { "overPromptTokens": 100000, "input": 0.50, "cacheWrite5m": 0.625, "cacheWrite1h": 1.00, "cacheRead": 0.05, "output": 2.50 }
15
+ },
16
+ "claude-haiku-4-5": {
17
+ "provider": "anthropic", "label": "Haiku 4.5", "tier": "light",
18
+ "match": ["haiku-4-5", "haiku-4.5"],
19
+ "input": 1.00, "cacheWrite5m": 1.25, "cacheWrite1h": 2.00, "cacheRead": 0.10, "output": 5.00
20
+ },
21
+ "claude-sonnet-5-5": {
22
+ "provider": "anthropic", "label": "Sonnet 5.5", "tier": "standard", "alias": "sonnet",
23
+ "match": ["sonnet-5-5", "sonnet-5.5"],
24
+ "input": 2.00, "cacheWrite5m": 2.50, "cacheWrite1h": 4.00, "cacheRead": 0.10, "output": 10.00
25
+ },
26
+ "claude-sonnet-5": {
27
+ "provider": "anthropic", "label": "Sonnet 5", "tier": "standard",
28
+ "match": ["sonnet-5"],
29
+ "input": 2.00, "cacheWrite5m": 2.50, "cacheWrite1h": 4.00, "cacheRead": 0.20, "output": 10.00
30
+ },
31
+ "claude-sonnet-4-6": {
32
+ "provider": "anthropic", "label": "Sonnet 4.6", "tier": "standard",
33
+ "match": ["sonnet-4-6", "sonnet-4.6", "sonnet-4-5", "sonnet-4.5"],
34
+ "input": 3.00, "cacheWrite5m": 3.75, "cacheWrite1h": 6.00, "cacheRead": 0.30, "output": 15.00
35
+ },
36
+ "claude-opus-5-5": {
37
+ "provider": "anthropic", "label": "Opus 5.5", "tier": "heavy", "alias": "opus",
38
+ "match": ["opus-5-5", "opus-5.5"],
39
+ "input": 4.00, "cacheWrite5m": 5.00, "cacheWrite1h": 8.00, "cacheRead": 0.20, "output": 20.00
40
+ },
41
+ "claude-opus-5": {
42
+ "provider": "anthropic", "label": "Opus 5", "tier": "heavy",
43
+ "match": ["opus-5", "opus-4-8", "opus-4-7", "opus-4-6", "opus-4-5"],
44
+ "input": 5.00, "cacheWrite5m": 6.25, "cacheWrite1h": 10.00, "cacheRead": 0.50, "output": 25.00
45
+ },
46
+ "claude-fable-5-2": {
47
+ "provider": "anthropic", "label": "Fable 5.2", "tier": "frontier", "alias": "fable",
48
+ "match": ["fable-5-2", "fable-5.2", "mythos-5-2"],
49
+ "input": 8.00, "cacheWrite5m": 10.00, "cacheWrite1h": 16.00, "cacheRead": 0.20, "output": 40.00
50
+ },
51
+ "claude-fable-5-1": {
52
+ "provider": "anthropic", "label": "Fable 5.1", "tier": "frontier",
53
+ "match": ["fable-5-1", "fable-5.1", "mythos-5-1"],
54
+ "input": 10.00, "cacheWrite5m": 12.50, "cacheWrite1h": 20.00, "cacheRead": 0.25, "output": 50.00
55
+ },
56
+ "gpt-6-luna": {
57
+ "provider": "openai", "label": "GPT-6 Luna", "tier": "light",
58
+ "match": ["gpt-6-luna"],
59
+ "input": 0.10, "cacheWrite5m": 0.125, "cacheRead": 0.01, "output": 0.50,
60
+ "longContext": { "overPromptTokens": 272000, "input": 0.20, "cacheWrite5m": 0.25, "cacheRead": 0.02, "output": 0.75 }
61
+ },
62
+ "gpt-6.1-terra": {
63
+ "provider": "openai", "label": "GPT-6.1 Terra", "tier": "standard",
64
+ "match": ["gpt-6.1-terra", "gpt-6-1-terra"],
65
+ "input": 1.00, "cacheWrite5m": 1.25, "cacheRead": 0.05, "output": 5.00,
66
+ "longContext": { "overPromptTokens": 272000, "input": 2.00, "cacheWrite5m": 2.50, "cacheRead": 0.10, "output": 7.50 }
67
+ },
68
+ "gpt-6.1-sol": {
69
+ "provider": "openai", "label": "GPT-6.1 Sol", "tier": "heavy",
70
+ "match": ["gpt-6.1-sol", "gpt-6-1-sol"],
71
+ "input": 2.00, "cacheWrite5m": 2.50, "cacheRead": 0.10, "output": 10.00,
72
+ "longContext": { "overPromptTokens": 272000, "input": 4.00, "cacheWrite5m": 5.00, "cacheRead": 0.20, "output": 15.00 }
73
+ },
74
+ "gpt-6-astra": {
75
+ "provider": "openai", "label": "GPT-6 Astra", "tier": "frontier",
76
+ "match": ["gpt-6-astra"],
77
+ "input": 10.00, "cacheWrite5m": 12.50, "cacheRead": 1.00, "output": 50.00,
78
+ "longContext": { "overPromptTokens": 272000, "input": 20.00, "cacheWrite5m": 25.00, "cacheRead": 2.00, "output": 75.00 }
79
+ },
80
+ "gpt-5.3-codex": {
81
+ "provider": "openai", "label": "GPT-5.3 Codex", "tier": "standard",
82
+ "match": ["gpt-5.3-codex", "gpt-5-3-codex"],
83
+ "input": 1.75, "cacheRead": 0.175, "output": 14.00
84
+ },
85
+ "gpt-5-mini": {
86
+ "provider": "openai", "label": "GPT-5 mini", "tier": "light",
87
+ "match": ["gpt-5-mini"],
88
+ "input": 0.25, "cacheRead": 0.025, "output": 2.00
89
+ }
90
+ },
91
+ "recommend": {
92
+ "anthropic": { "light": "claude-haiku-5-5", "standard": "claude-sonnet-5-5", "heavy": "claude-opus-5-5", "frontier": "claude-fable-5-2" },
93
+ "openai": { "light": "gpt-6-luna", "standard": "gpt-6.1-terra", "heavy": "gpt-6.1-sol", "frontier": "gpt-6-astra" }
94
+ },
95
+ "baseline": { "anthropic": "claude-opus-5-5", "openai": "gpt-6.1-sol" },
96
+ "familyFallback": { "haiku": "claude-haiku-5-5", "sonnet": "claude-sonnet-5-5", "opus": "claude-opus-5-5", "fable": "claude-fable-5-2", "mythos": "claude-fable-5-2" },
97
+ "assumptions": {
98
+ "$comment": "Heuristic token budgets per plan step by complexity (1-5). 'input' counts all prompt tokens processed across the step's agent turns, including cache reads. Tune these from your own `lake-meter report` history.",
99
+ "stepTokens": {
100
+ "1": { "input": [30000, 120000], "output": [1000, 4000] },
101
+ "2": { "input": [80000, 300000], "output": [3000, 10000] },
102
+ "3": { "input": [250000, 900000], "output": [8000, 25000] },
103
+ "4": { "input": [700000, 2500000], "output": [20000, 60000] },
104
+ "5": { "input": [1500000, 6000000], "output": [40000, 150000] }
105
+ },
106
+ "inputMix": { "uncached": 0.05, "cacheWrite": 0.10, "cacheRead": 0.85 },
107
+ "avgPromptTokens": 60000,
108
+ "tierTokenMultiplier": { "light": 1.3, "standard": 1.1, "heavy": 1.0, "frontier": 1.0 },
109
+ "complexityToTier": { "1": "light", "2": "light", "3": "standard", "4": "heavy", "5": "heavy" }
110
+ }
111
+ }
package/src/pricing.js ADDED
@@ -0,0 +1,84 @@
1
+ // Price lookups and cost math. All prices come from prices.json (USD per 1M tokens).
2
+ import { readFileSync, existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { homedir } from 'node:os';
6
+
7
+ const here = fileURLToPath(new URL('.', import.meta.url));
8
+
9
+ /** Load the bundled table, optionally overridden by ~/.lake-meter/prices.json (same shape). */
10
+ export function loadPrices(overridePath = join(process.env.LAKE_METER_HOME || join(homedir(), '.lake-meter'), 'prices.json')) {
11
+ const base = JSON.parse(readFileSync(join(here, 'prices.json'), 'utf8'));
12
+ if (overridePath && existsSync(overridePath)) {
13
+ try {
14
+ const o = JSON.parse(readFileSync(overridePath, 'utf8'));
15
+ return { ...base, ...o, models: { ...base.models, ...(o.models || {}) }, assumptions: { ...base.assumptions, ...(o.assumptions || {}) } };
16
+ } catch { /* ignore a broken override, fall back to bundled table */ }
17
+ }
18
+ return base;
19
+ }
20
+
21
+ export function normalizeModelId(id) {
22
+ return String(id || '').toLowerCase().replace(/\[.*?\]/g, '').replace(/^.*\//, '').replace(/\./g, '-').trim();
23
+ }
24
+
25
+ /** Resolve a raw model id (e.g. "claude-opus-5-5-20261001", "opus", "us.anthropic.claude-sonnet-5-5") to a table key. */
26
+ export function resolveModel(rawId, prices) {
27
+ if (!rawId) return null;
28
+ const id = normalizeModelId(rawId);
29
+ if (prices.models[rawId]) return rawId;
30
+ let best = null, bestLen = 0;
31
+ for (const [key, m] of Object.entries(prices.models)) {
32
+ for (const token of [key, ...(m.match || [])]) {
33
+ const t = normalizeModelId(token);
34
+ if (id.includes(t) && t.length > bestLen) { best = key; bestLen = t.length; }
35
+ }
36
+ if (m.alias && id === m.alias) return key;
37
+ }
38
+ if (best) return best;
39
+ for (const [fam, key] of Object.entries(prices.familyFallback || {})) if (id.includes(fam)) return key;
40
+ return null;
41
+ }
42
+
43
+ function rate(m, field, promptTokens) {
44
+ const lc = m.longContext;
45
+ const src = lc && promptTokens > lc.overPromptTokens ? lc : m;
46
+ const v = src[field] ?? m[field];
47
+ if (v != null) return v;
48
+ if (field === 'cacheWrite1h') return (src.input ?? m.input) * 2;
49
+ if (field === 'cacheWrite5m') return (src.input ?? m.input) * 1.25;
50
+ if (field === 'cacheRead') return (src.input ?? m.input) * 0.1;
51
+ return 0;
52
+ }
53
+
54
+ /**
55
+ * Cost of one API response's usage object (Anthropic usage shape, as written to Claude Code transcripts).
56
+ * Long-context pricing is decided per request from its own prompt size.
57
+ */
58
+ export function costOfUsage(modelKey, usage, prices) {
59
+ const m = prices.models[modelKey];
60
+ if (!m || !usage) return null;
61
+ const inp = usage.input_tokens || 0;
62
+ const cr = usage.cache_read_input_tokens || 0;
63
+ const cwTotal = usage.cache_creation_input_tokens || 0;
64
+ const cw1h = usage.cache_creation?.ephemeral_1h_input_tokens || 0;
65
+ const cw5m = usage.cache_creation?.ephemeral_5m_input_tokens ?? Math.max(0, cwTotal - cw1h);
66
+ const out = usage.output_tokens || 0;
67
+ const prompt = inp + cr + cwTotal;
68
+ return (inp * rate(m, 'input', prompt) + cr * rate(m, 'cacheRead', prompt) + cw5m * rate(m, 'cacheWrite5m', prompt)
69
+ + cw1h * rate(m, 'cacheWrite1h', prompt) + out * rate(m, 'output', prompt)) / 1e6;
70
+ }
71
+
72
+ /** Estimated cost of an aggregate token budget on a model, using the configured input mix. */
73
+ export function costOfBudget(modelKey, inputTokens, outputTokens, prices) {
74
+ const m = prices.models[modelKey];
75
+ const a = prices.assumptions;
76
+ const mix = a.inputMix;
77
+ const p = a.avgPromptTokens;
78
+ return (inputTokens * (mix.uncached * rate(m, 'input', p) + mix.cacheWrite * rate(m, 'cacheWrite5m', p) + mix.cacheRead * rate(m, 'cacheRead', p))
79
+ + outputTokens * rate(m, 'output', p)) / 1e6;
80
+ }
81
+
82
+ export function providerOf(modelKey, prices) {
83
+ return prices.models[modelKey]?.provider || 'anthropic';
84
+ }
package/src/state.js ADDED
@@ -0,0 +1,84 @@
1
+ // Local state only. Nothing leaves the machine. Layout under ~/.lake-meter (or $LAKE_METER_HOME):
2
+ // config.json user settings (cap, mode, provider)
3
+ // sessions/<id>.json per-session meter state (offsets, current run, plan estimate)
4
+ // runs.jsonl one line per finished run, for `lake-meter report`
5
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, appendFileSync, readdirSync, statSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { homedir } from 'node:os';
8
+
9
+ export const DEFAULT_CONFIG = {
10
+ capUsd: 5, // per-run cap in USD (API list-price equivalent)
11
+ capTokens: null, // optional per-run cap in total tokens (input + output + cache)
12
+ capFiveHourPct: null, // optional: stop when the 5-hour subscription window passes this % (needs the statusline)
13
+ sessionCapUsd: null, // optional cap across the whole session
14
+ onCap: 'ask', // 'ask' = permission prompt before the next tool call; 'stop' = end the turn
15
+ extendPct: 50, // approving a cap prompt adds this % of the cap as headroom
16
+ warnPct: 80, // one heads-up when a run passes this % of its cap
17
+ provider: 'anthropic',
18
+ };
19
+
20
+ export function home() {
21
+ return process.env.LAKE_METER_HOME || join(homedir(), '.lake-meter');
22
+ }
23
+
24
+ function readJson(p, fallback) {
25
+ try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return fallback; }
26
+ }
27
+
28
+ export function writeJsonAtomic(p, data) {
29
+ mkdirSync(join(p, '..'), { recursive: true });
30
+ const tmp = `${p}.${process.pid}.${Date.now()}.tmp`;
31
+ writeFileSync(tmp, JSON.stringify(data, null, 2));
32
+ renameSync(tmp, p);
33
+ }
34
+
35
+ /** Config = defaults < ~/.lake-meter/config.json < <project>/.lake-meter.json */
36
+ export function loadConfig(cwd) {
37
+ const user = readJson(join(home(), 'config.json'), {});
38
+ const proj = cwd ? readJson(join(cwd, '.lake-meter.json'), {}) : {};
39
+ return { ...DEFAULT_CONFIG, ...user, ...proj };
40
+ }
41
+
42
+ export function saveUserConfig(patch) {
43
+ const p = join(home(), 'config.json');
44
+ const cur = readJson(p, {});
45
+ writeJsonAtomic(p, { ...cur, ...patch });
46
+ }
47
+
48
+ const safeId = (id) => String(id || 'unknown').replace(/[^\w.-]/g, '_');
49
+
50
+ export function sessionPath(sessionId) {
51
+ return join(home(), 'sessions', `${safeId(sessionId)}.json`);
52
+ }
53
+
54
+ export function loadSession(sessionId) {
55
+ return readJson(sessionPath(sessionId), { sessionId, offsets: {}, run: null, plan: null, statusline: null });
56
+ }
57
+
58
+ export function saveSession(s) {
59
+ writeJsonAtomic(sessionPath(s.sessionId), s);
60
+ }
61
+
62
+ /** Most recently touched session (for CLI commands run outside Claude Code). */
63
+ export function latestSessionId() {
64
+ const dir = join(home(), 'sessions');
65
+ if (!existsSync(dir)) return null;
66
+ let best = null, bestT = 0;
67
+ for (const f of readdirSync(dir)) {
68
+ if (!f.endsWith('.json')) continue;
69
+ const t = statSync(join(dir, f)).mtimeMs;
70
+ if (t > bestT) { bestT = t; best = f.slice(0, -5); }
71
+ }
72
+ return best;
73
+ }
74
+
75
+ export function appendRun(record) {
76
+ mkdirSync(home(), { recursive: true });
77
+ appendFileSync(join(home(), 'runs.jsonl'), JSON.stringify(record) + '\n');
78
+ }
79
+
80
+ export function readRuns() {
81
+ const p = join(home(), 'runs.jsonl');
82
+ if (!existsSync(p)) return [];
83
+ return readFileSync(p, 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
84
+ }