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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lake
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,177 @@
1
- # Temporary Holding Version
1
+ # lake-meter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **A model for every step, and a hard stop for every run. For Claude Code.**
4
+
5
+ Claude Code is great until a run loops, fans out into subagents, or quietly eats your 5‑hour window on a step a cheaper model could have done. `lake-meter` adds two things using only Claude Code's own extension points (hooks, statusline, skills, MCP):
6
+
7
+ 1. **Model per step.** When Claude writes a plan in plan mode, lake-meter rates each step's complexity, recommends the cheapest model that should handle it (Haiku / Sonnet / Opus), and estimates tokens and dollars per step and in total, next to the cost of running everything on Opus. The table appears inside Claude Code's own "Ready to code?" plan dialog.
8
+ 2. **A per-run cap that stops and asks.** Set `$5` (or a token budget, or a % of your 5‑hour window). When a run reaches it, the next tool call becomes a permission prompt: **Yes** continues with +50% headroom, **No** stops Claude right there. In unattended modes it ends the turn instead.
9
+ 3. **An end-of-run receipt.** Measured tokens and list-price dollars for the run, split by model and subagents, compared with the plan's estimate.
10
+
11
+ Local only. No account, no server, **no telemetry**.
12
+
13
+ ```bash
14
+ npx lake-meter init
15
+ ```
16
+
17
+ That's the whole install. Restart Claude Code (or open `/hooks`) and work as usual.
18
+
19
+ If the npm package is not available yet, install from GitHub first:
20
+
21
+ ```bash
22
+ npm i -g github:getlake/lake-meter
23
+ lake-meter init
24
+ ```
25
+
26
+ ---
27
+
28
+ ## What you see
29
+
30
+ **In plan mode**, at the top of the plan dialog:
31
+
32
+ ```
33
+ Ready to code?
34
+ Here is Claude's plan:
35
+ ▎ Lake Meter estimate: $3.53–$13.0 with a model per step, vs $3.96–$14.5 all on Opus 5.5. Table at the end.
36
+ ```
37
+
38
+ and at the end of the plan:
39
+
40
+ ```
41
+ ┌─────┬─────────────────────────────────────┬────────────┬─────────────────────┬───────────┬─────────────┐
42
+ │ # │ Step │ Complexity │ Recommended model │ Tokens │ Est. cost │
43
+ ├─────┼─────────────────────────────────────┼────────────┼─────────────────────┼───────────┼─────────────┤
44
+ │ 1 │ Add retry settings to config │ 1/5 │ Haiku 5.5 (haiku) │ 40k–161k │ <$0.01 │
45
+ │ 2 │ Design an idempotent delivery queue │ 5/5 │ Opus 5.5 (opus) │ 1.5M–6.2M │ $2.10–$8.22 │
46
+ │ 3 │ Implement the retry worker │ 4/5 │ Opus 5.5 (opus) │ 720k–2.6M │ $1.01–$3.38 │
47
+ │ 4 │ Expose delivery status in the API │ 3/5 │ Sonnet 5.5 (sonnet) │ 284k–1.0M │ $0.21–$0.71 │
48
+ │ 5 │ Tests for failure paths │ 3/5 │ Sonnet 5.5 (sonnet) │ 284k–1.0M │ $0.21–$0.71 │
49
+ │ 6 │ Update the changelog │ 1/5 │ Haiku 5.5 (haiku) │ 40k–161k │ <$0.01 │
50
+ └─────┴─────────────────────────────────────┴────────────┴─────────────────────┴───────────┴─────────────┘
51
+ Total: $3.53–$13.0 vs $3.96–$14.5 with everything on Opus 5.5 (about 10% less).
52
+ ```
53
+
54
+ **When the cap is reached**, before the next tool call:
55
+
56
+ ```
57
+ │ Hook PreToolUse:Bash requires confirmation for this command:
58
+ │ Lake Meter: this run has used about $2.15 (cap $2.00). Approve to continue with +$1.00 headroom.
59
+ │ Deny to stop here. Or run /meter cap <usd> to set a new cap. [settings]
60
+ Do you want to proceed?
61
+ ❯ 1. Yes
62
+ 2. No
63
+ ```
64
+
65
+ **When the run ends:**
66
+
67
+ ```
68
+ Stop says: Lake Meter · run $3.44 · 524k tok (313k cache reads, 155k out) · Opus 5.5 $3.44 · cap $7.00
69
+ Since plan approved: $3.25 measured vs $3.53–$13.0 estimated
70
+ ```
71
+
72
+ **All the time**, in the statusline: `◒ Lake · run $0.65 / $5.00 · session $4.54 · 5h 42%`
73
+
74
+ (These are copied from a real Claude Code 2.1.322 session; see [Verification](#verification).)
75
+
76
+ ## Commands
77
+
78
+ | | |
79
+ |---|---|
80
+ | `npx lake-meter init` | install hooks, statusline, `/meter` skill and two optional subagents into `~/.claude` |
81
+ | `npx lake-meter init --project` | install into this repo's `.claude/settings.local.json` instead |
82
+ | `npx lake-meter init --cap 10 --no-agents --statusline` | set the cap, skip the subagents, replace an existing statusline |
83
+ | `/meter`, `/meter cap 10`, `/meter cap off`, `/meter report` | inside Claude Code (uses one short model turn to display) |
84
+ | `lake-meter cap 10` · `lake-meter status` · `lake-meter report` | same, from any terminal, no model turn |
85
+ | `lake-meter plan plan.md [--why] [--openai] [--json]` | plan breakdown for any markdown plan |
86
+ | `lake-meter mcp` | MCP server with `estimate_plan` and `meter_status` (works in Cursor too) |
87
+ | `npx lake-meter uninstall` | remove everything `init` added (your settings are restored; a backup is kept as `settings.json.lake-meter.bak`) |
88
+
89
+ ### Config
90
+
91
+ `~/.lake-meter/config.json` (per-project override: `.lake-meter.json` in the repo root):
92
+
93
+ ```json
94
+ {
95
+ "capUsd": 5, // per run, API list-price equivalent. null = off
96
+ "capTokens": null, // per run, all tokens incl. cache reads
97
+ "capFiveHourPct": null, // e.g. 80: stop when your 5-hour subscription window passes 80% (needs the statusline)
98
+ "sessionCapUsd": null, // across the whole session
99
+ "onCap": "ask", // "ask" = permission prompt; "stop" = end the turn
100
+ "extendPct": 50, // headroom granted when you press Yes
101
+ "warnPct": 80, // one heads-up (to you and to Claude) at 80% of the cap
102
+ "provider": "anthropic",// or "openai" for plan recommendations
103
+ "annotatePlans": true // add the table to plan files in plan mode
104
+ }
105
+ ```
106
+
107
+ A **run** is everything from one prompt you submit until Claude stops.
108
+
109
+ ### Cursor and other MCP clients
110
+
111
+ ```json
112
+ // ~/.cursor/mcp.json
113
+ { "mcpServers": { "lake-meter": { "command": "npx", "args": ["-y", "lake-meter", "mcp"] } } }
114
+ ```
115
+
116
+ Then ask the agent to "estimate this plan with lake-meter". In Cursor you get the per-step model and cost breakdown. The cap and the receipt are Claude Code only, because Cursor doesn't expose per-run token usage to extensions.
117
+
118
+ ## Measured vs estimated (read this)
119
+
120
+ | | How | Accuracy |
121
+ |---|---|---|
122
+ | **Tokens per run** | **Measured.** Read from Claude Code's session transcript (`message.usage` on each response, de-duplicated by message id) plus subagent transcripts in `<session>/subagents/`. | Exact as reported by the API, up to transcript write lag (see limits). |
123
+ | **Dollars per run** | **Computed** from measured tokens × list prices in [`src/prices.json`](src/prices.json), per request, including cache writes (5m/1h), cache reads and Haiku's long-context tier. | Matches Claude Code's own `total_cost_usd` in our tests. It's an **API-equivalent** figure: on Pro/Max you don't pay it per token; it tells you how heavy a run was. Your invoice can differ (discounts, batch, regions). |
124
+ | **5-hour window %** | **Reported by Claude Code** to the statusline (`rate_limits.five_hour.used_percentage`, Pro/Max only). | As accurate as Claude Code's own number. |
125
+ | **Plan breakdown** | **Estimate.** Keyword and size heuristics rate each step 1–5; token budgets per complexity live in `prices.json` (`assumptions`). Run `lake-meter plan plan.md --why` to see every reason. | Rough. Ranges are wide on purpose. Tune the budgets from your own `lake-meter report` history. |
126
+ | **Model recommendation** | **Opinion**, encoded as complexity → tier (1–2 Haiku, 3 Sonnet, 4–5 Opus). Frontier models are never recommended by default. | A starting point, not a guarantee of quality. |
127
+
128
+ Prices last verified **2026‑11‑12** from [Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing) and [OpenAI pricing](https://developers.openai.com/api/docs/pricing). To update, edit `src/prices.json`, or drop an override at `~/.lake-meter/prices.json` with the same shape.
129
+
130
+ ## How it works
131
+
132
+ `init` copies a pinned runtime to `~/.lake-meter/runtime` (so hooks run in ~50 ms with plain `node`, no `npx` per call) and adds to your Claude Code settings:
133
+
134
+ | Extension point | What lake-meter does |
135
+ |---|---|
136
+ | `UserPromptSubmit` hook | marks the start of a run |
137
+ | `PreToolUse` hook (`*`) | reads new transcript bytes, prices them, and returns `permissionDecision: "ask"` when the cap is reached (or `continue: false` in `bypassPermissions` / `dontAsk` / `onCap: "stop"`). On `ExitPlanMode` it records the plan estimate and gives Claude a one-line note about cheaper subagents |
138
+ | `PostToolUse` hook (`*`) | if the tool we asked about ran, you pressed Yes, so headroom is added. When Claude writes a plan file in plan mode, appends the per-step table to it |
139
+ | `Stop` hook | prints the receipt (`systemMessage`, never blocks) and appends one line to `~/.lake-meter/runs.jsonl` |
140
+ | `statusLine` | shows the meter and stores Claude Code's own session cost and rate-limit % for the window cap. Only installed if you don't already have a statusline |
141
+ | `~/.claude/skills/meter` | the `/meter` command |
142
+ | `~/.claude/agents/lake-light.md`, `lake-standard.md` | optional subagents pinned to `haiku` and `sonnet`, so the per-step advice is actionable. Claude only uses them if it decides to; skip with `--no-agents` |
143
+
144
+ ## Limits (honest list)
145
+
146
+ - **The cap is checked before each tool call.** A single long model response can overshoot it, and the final text answer of a turn isn't gated. Expect a run to end slightly above the cap.
147
+ - **Transcript lag.** Claude Code writes transcripts asynchronously, so the newest response may land a moment late. Spend can lag by about one response.
148
+ - **Pressing No interrupts the turn.** Claude Code doesn't run Stop hooks on interrupts, so there's no receipt for that turn; `lake-meter status` still has the numbers.
149
+ - **"Run" = one submitted prompt.** Background subagent reports and `/loop` iterations also fire `UserPromptSubmit` and start a new run; use `sessionCapUsd` to bound the whole session.
150
+ - **Dollar figures are list-price equivalents**, not your bill. On subscriptions use `capTokens` or `capFiveHourPct` if dollars feel abstract.
151
+ - **Plan breakdown is heuristic** and English-keyword based. Unknown models count tokens but not dollars (and the receipt says so).
152
+ - **`/meter` costs one short model turn** because skills run through the model; the CLI commands don't.
153
+ - Claude Code only for caps and receipts. Cursor, Codex and others get the MCP plan estimate.
154
+
155
+ ## Privacy
156
+
157
+ Everything stays in `~/.lake-meter` on your machine: config, per-session counters, and a run log with token counts and dollar totals (no prompts, no code, no file names). lake-meter makes **no network requests**. There's no telemetry, opt-in or otherwise. Debugging: `touch ~/.lake-meter/debug` logs raw hook inputs locally to `~/.lake-meter/debug.jsonl`; delete the file to stop.
158
+
159
+ ## Verification
160
+
161
+ - `npm test`: 38 tests (pricing math, transcript parsing and de-duplication, plan splitting and scoring, every hook path, install/uninstall round-trip, MCP over stdio, a simulated session through the real CLI).
162
+ - `test/real-claude.test.js` runs the **real Claude Code binary** (2.1.322 at time of writing) against a local mock of the Messages API (`scripts/mock-anthropic.js`, no account needed). It checks that the hooks fire, the cap produces a permission decision, `bypassPermissions` stops the turn, and that lake-meter's measured run cost equals Claude Code's own `total_cost_usd`. Skipped when no Claude Code binary is installed.
163
+ - The screens in [What you see](#what-you-see) were captured from an interactive Claude Code session driven against the same mock.
164
+
165
+ ## Demo (no account needed)
166
+
167
+ ```bash
168
+ npm run demo # simulated session: plan breakdown → cap prompt → receipt
169
+ ```
170
+
171
+ ## Pro for teams (coming soon)
172
+
173
+ Shared caps across a team, a dashboard of runs by repo and model, and a plan approval step before expensive runs. [Join the waitlist](https://getlake.github.io/lake-meter/#waitlist).
174
+
175
+ ## License
176
+
177
+ MIT © Lake
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+ main(process.argv.slice(2)).catch((e) => { process.stderr.write(`lake-meter: ${e.message}\n`); process.exit(1); });
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "lake-meter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Per-step model picks and a hard per-run cost cap for Claude Code. Hooks + MCP, local only, no telemetry.",
5
+ "type": "module",
6
+ "bin": {
7
+ "lake-meter": "bin/lake-meter.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18.17"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test test/*.test.js",
20
+ "demo": "bash scripts/demo.sh"
21
+ },
22
+ "keywords": [
23
+ "claude-code",
24
+ "claude",
25
+ "hooks",
26
+ "mcp",
27
+ "cost",
28
+ "tokens",
29
+ "budget",
30
+ "llm",
31
+ "cursor",
32
+ "ai-agents"
33
+ ],
34
+ "license": "MIT",
35
+ "author": "Lake",
36
+ "homepage": "https://github.com/getlake/lake-meter#readme",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/getlake/lake-meter.git"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/getlake/lake-meter/issues"
43
+ },
44
+ "mcpName": "io.github.getlake/lake-meter"
45
+ }
package/src/cli.js ADDED
@@ -0,0 +1,129 @@
1
+ import { readFileSync, existsSync, appendFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { loadPrices } from './pricing.js';
4
+ import { analyzePlan } from './plan.js';
5
+ import { planTable, runSummary, usd } from './format.js';
6
+ import { onUserPromptSubmit, onPreToolUse, onPostToolUse, onStop, onStatusLine, effectiveCaps } from './hooks.js';
7
+ import { loadConfig, saveUserConfig, loadSession, latestSessionId, readRuns, home } from './state.js';
8
+ import { totals } from './transcript.js';
9
+ import { init, uninstall } from './init.js';
10
+ import { serve } from './mcp.js';
11
+
12
+ const HELP = `lake-meter · per-step model picks and a hard per-run cap for Claude Code
13
+
14
+ npx lake-meter init [--project] [--cap 5] [--no-agents] [--statusline] install hooks, statusline, /meter
15
+ lake-meter plan <file.md> [--openai] [--why] plan breakdown: complexity, model per step, cost ranges
16
+ lake-meter cap <usd> | off set the per-run cap (also: /meter cap 10 inside Claude Code)
17
+ lake-meter status this run's measured spend
18
+ lake-meter report your last runs (local history)
19
+ lake-meter mcp run the MCP server (estimate_plan, meter_status)
20
+ lake-meter uninstall [--project] remove everything init added
21
+ Data stays in ${'~'}/.lake-meter. No telemetry.`;
22
+
23
+ function readStdin() {
24
+ return new Promise((res) => {
25
+ if (process.stdin.isTTY) return res('');
26
+ let d = ''; process.stdin.setEncoding('utf8');
27
+ process.stdin.on('data', (c) => (d += c)); process.stdin.on('end', () => res(d));
28
+ });
29
+ }
30
+
31
+ const flag = (args, f) => args.includes(f);
32
+ const opt = (args, f) => { const i = args.indexOf(f); return i >= 0 ? args[i + 1] : undefined; };
33
+
34
+ function status(sessionId) {
35
+ const sid = sessionId || latestSessionId();
36
+ const s = sid ? loadSession(sid) : null;
37
+ if (!s?.run) return 'No run recorded yet. Is Lake Meter installed? Run: npx lake-meter init';
38
+ const cfg = loadConfig(process.cwd());
39
+ const t = totals(s.run.seen, loadPrices());
40
+ return runSummary(t, { cap: effectiveCaps(cfg, s.run).usd, capHits: s.run.capHits });
41
+ }
42
+
43
+ function setCap(v) {
44
+ if (v === 'off' || v === 'none') { saveUserConfig({ capUsd: null }); return 'Per-run cap turned off.'; }
45
+ const n = Number(String(v).replace('$', ''));
46
+ if (!Number.isFinite(n) || n <= 0) return 'Usage: cap <usd> | off e.g. cap 10';
47
+ saveUserConfig({ capUsd: n });
48
+ return `Per-run cap set to ${usd(n)} (API list-price equivalent). Applies from the next tool call.`;
49
+ }
50
+
51
+ function report() {
52
+ const runs = readRuns().slice(-15);
53
+ if (!runs.length) return 'No finished runs yet.';
54
+ const lines = ['Lake Meter · last runs (measured tokens, list-price $)', ''];
55
+ for (const r of runs) {
56
+ const when = new Date(r.end).toLocaleString();
57
+ lines.push(`${when.padEnd(24)} ${usd(r.usd).padStart(7)} ${String(Math.round(r.tokens / 1000) + 'k tok').padStart(9)}${r.capHits ? ` cap hit ×${r.capHits}` : ''}${r.plan ? ` plan est ${usd(r.plan.estimateUsd[0])}–${usd(r.plan.estimateUsd[1])}` : ''}`);
58
+ }
59
+ const sum = runs.reduce((a, r) => a + r.usd, 0);
60
+ lines.push('', `Total of these runs: ${usd(sum)}`);
61
+ return lines.join('\n');
62
+ }
63
+
64
+ export async function main(argv) {
65
+ const [cmd, ...args] = argv;
66
+ switch (cmd) {
67
+ case 'hook': {
68
+ const raw = await readStdin();
69
+ let input = {}; try { input = JSON.parse(raw || '{}'); } catch { return; }
70
+ if (existsSync(join(home(), 'debug'))) appendFileSync(join(home(), 'debug.jsonl'), JSON.stringify({ event: args[0], input }) + '\n'); // opt-in local debug log: touch ~/.lake-meter/debug
71
+ let out = null;
72
+ try {
73
+ if (args[0] === 'user-prompt-submit') out = onUserPromptSubmit(input);
74
+ else if (args[0] === 'pre-tool-use') out = onPreToolUse(input);
75
+ else if (args[0] === 'post-tool-use') out = onPostToolUse(input);
76
+ else if (args[0] === 'stop') out = await onStop(input);
77
+ } catch (e) {
78
+ // Never break the user's session because of the meter: report on stderr and exit 0 (non-blocking).
79
+ process.stderr.write(`lake-meter: ${e.message}\n`);
80
+ return;
81
+ }
82
+ if (out) process.stdout.write(JSON.stringify(out));
83
+ return;
84
+ }
85
+ case 'statusline': {
86
+ const raw = await readStdin();
87
+ try { process.stdout.write(onStatusLine(JSON.parse(raw || '{}'))); } catch { process.stdout.write('◒ Lake'); }
88
+ return;
89
+ }
90
+ case 'cmd': { // used by the /meter skill
91
+ const sid = opt(args, '--session');
92
+ const rest = args.filter((a, i) => a !== '--session' && args[i - 1] !== '--session');
93
+ const sub = rest[0] || 'status';
94
+ if (sub === 'status') console.log(status(sid));
95
+ else if (sub === 'cap') console.log(setCap(rest[1]));
96
+ else if (sub === 'report') console.log(report());
97
+ else if (sub === 'plan') console.log(planFile(rest[1], rest));
98
+ else console.log('Usage: /meter [status | cap <usd> | cap off | plan <file> | report]');
99
+ return;
100
+ }
101
+ case 'plan': {
102
+ console.log(planFile(args[0], args));
103
+ return;
104
+ }
105
+ case 'cap': console.log(setCap(args[0])); return;
106
+ case 'status': console.log(status(opt(args, '--session'))); return;
107
+ case 'report': console.log(report()); return;
108
+ case 'mcp': serve(); return;
109
+ case 'init': {
110
+ const cap = opt(args, '--cap');
111
+ init({ project: flag(args, '--project'), capUsd: cap != null ? Number(cap) : undefined, agents: !flag(args, '--no-agents'), statusline: flag(args, '--statusline') });
112
+ return;
113
+ }
114
+ case 'uninstall': uninstall({ project: flag(args, '--project') }); return;
115
+ case 'where': console.log(home()); return;
116
+ case '--version': case '-v': console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url))).version); return;
117
+ default: console.log(HELP);
118
+ }
119
+ }
120
+
121
+ function planFile(file, args) {
122
+ let text;
123
+ if (!file || file === '-') text = readFileSync(0, 'utf8');
124
+ else if (existsSync(file)) text = readFileSync(file, 'utf8');
125
+ else return `File not found: ${file}`;
126
+ const a = analyzePlan(text, loadPrices(), { provider: flag(args, '--openai') ? 'openai' : loadConfig(process.cwd()).provider });
127
+ if (!a.steps.length) return 'Could not find steps in that plan (use numbered items, headings or bullets).';
128
+ return flag(args, '--json') ? JSON.stringify(a, null, 2) : planTable(a, { reasons: flag(args, '--why') });
129
+ }
package/src/format.js ADDED
@@ -0,0 +1,51 @@
1
+ // Plain-text rendering for terminals, hook messages and MCP results.
2
+ export const usd = (n) => (n == null ? 'n/a' : n < 0.01 && n > 0 ? '<$0.01' : `$${n < 10 ? n.toFixed(2) : n < 100 ? n.toFixed(1) : Math.round(n)}`);
3
+ export const range = (r) => (r[1] < 0.01 ? '<$0.01' : `${usd(r[0])}–${usd(r[1])}`);
4
+ export const tok = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n));
5
+ export const tokRange = (r) => `${tok(r[0])}–${tok(r[1])}`;
6
+
7
+ const pad = (s, n) => { s = String(s); return s.length >= n ? s.slice(0, n - 1) + '…' : s + ' '.repeat(n - s.length); };
8
+ const dots = (c) => '●'.repeat(c) + '○'.repeat(5 - c);
9
+
10
+ export function planTable(a, { reasons = false } = {}) {
11
+ const lines = [];
12
+ lines.push(`Lake Meter · plan breakdown (estimate, ${a.provider} list prices verified ${a.pricesVerifiedAt})`);
13
+ lines.push('');
14
+ lines.push(`${pad('#', 3)}${pad('Step', 42)}${pad('Complexity', 12)}${pad('Model', 14)}${pad('Tokens', 13)}Cost`);
15
+ for (const s of a.steps) {
16
+ lines.push(`${pad(s.n, 3)}${pad(s.title, 42)}${pad(dots(s.complexity), 12)}${pad(s.modelLabel, 14)}${pad(tokRange(s.tokens), 13)}${range(s.usd)}`);
17
+ if (reasons) lines.push(` ${s.reasons.join(', ')}`);
18
+ }
19
+ lines.push('');
20
+ lines.push(`Total with per-step models: ${range(a.total.usd)} (${tokRange(a.total.tokens)} tokens)`);
21
+ lines.push(`Everything on ${a.baselineLabel}: ${range(a.total.baselineUsd)} → about ${a.total.savingsPct}% less with the mix above`);
22
+ lines.push('Estimates come from keyword heuristics and token budgets in prices.json. Measured spend shows at the end of each run.');
23
+ return lines.join('\n');
24
+ }
25
+
26
+ export function planMarkdown(a) {
27
+ const rows = a.steps.map((s) => `| ${s.n} | ${s.title.replace(/\|/g, '/')} | ${s.complexity}/5 | ${s.modelLabel} (\`${s.alias}\`) | ${tokRange(s.tokens)} | ${range(s.usd)} |`);
28
+ return [
29
+ `**Lake Meter plan breakdown** (estimate; ${a.provider} list prices verified ${a.pricesVerifiedAt})`,
30
+ '',
31
+ '| # | Step | Complexity | Recommended model | Tokens | Est. cost |',
32
+ '|---|---|---|---|---|---|',
33
+ ...rows,
34
+ '',
35
+ `Total: **${range(a.total.usd)}** vs **${range(a.total.baselineUsd)}** with everything on ${a.baselineLabel} (about ${a.total.savingsPct}% less).`,
36
+ ].join('\n');
37
+ }
38
+
39
+ export function runSummary(t, ctx = {}) {
40
+ const parts = [`Lake Meter · run ${usd(t.usd)}`];
41
+ parts.push(`${tok(t.tokens)} tok (${tok(t.cacheRead)} cache reads, ${tok(t.output)} out)`);
42
+ const models = Object.entries(t.byModel).sort((a, b) => b[1].usd - a[1].usd).map(([m, v]) => `${m} ${usd(v.usd)}`);
43
+ if (models.length) parts.push(models.join(' + '));
44
+ if (t.subagent.requests) parts.push(`subagents ${usd(t.subagent.usd)}`);
45
+ if (ctx.cap) parts.push(`cap ${usd(ctx.cap)}`);
46
+ if (ctx.capHits) parts.push(`cap hit ×${ctx.capHits}`);
47
+ let s = parts.join(' · ');
48
+ if (ctx.plan) s += `\nSince plan approved: ${usd(ctx.plan.actualUsd)} measured vs ${range(ctx.plan.estimateUsd)} estimated`;
49
+ if (t.unpricedRequests) s += `\n${t.unpricedRequests} responses used a model missing from prices.json (tokens counted, $ not).`;
50
+ return s;
51
+ }
package/src/hooks.js ADDED
@@ -0,0 +1,215 @@
1
+ // Claude Code hook handlers. Each takes the hook's stdin JSON and returns the JSON to print (or null).
2
+ // Docs: https://code.claude.com/docs/en/hooks
3
+ import { loadPrices } from './pricing.js';
4
+ import { sessionFiles, scanFile, absorb, totals } from './transcript.js';
5
+ import { loadConfig, loadSession, saveSession, appendRun } from './state.js';
6
+ import { analyzePlan } from './plan.js';
7
+ import { usd, range, runSummary, planTable, planMarkdown } from './format.js';
8
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+
10
+ const UNATTENDED_MODES = new Set(['bypassPermissions', 'dontAsk']);
11
+
12
+ function ensureRun(s, now) {
13
+ if (!s.run) s.run = { start: 0, seen: {}, extraUsd: 0, extraTokens: 0, capHits: 0, warned: false, pendingAsk: null, startedAt: now };
14
+ return s.run;
15
+ }
16
+
17
+ /** Scan new transcript bytes into the current run. Returns run totals (measured tokens, list-price USD). */
18
+ export function refresh(s, input, prices) {
19
+ if (input.transcript_path) s.transcriptPath = input.transcript_path;
20
+ const run = ensureRun(s, Date.now());
21
+ s.offsets ||= {};
22
+ s.sessionSeen ||= {};
23
+ for (const f of sessionFiles(s.transcriptPath)) {
24
+ const { entries, offset } = scanFile(f, s.offsets[f] || 0);
25
+ s.offsets[f] = offset;
26
+ absorb(run.seen, entries, run.start);
27
+ absorb((s.sessionSeen ||= {}), entries, 0);
28
+ }
29
+ const fresh = s.statusline?.costUsd != null && Date.now() - s.statusline.at < 10 * 60e3;
30
+ s.sessionUsd = fresh ? s.statusline.costUsd : totals(s.sessionSeen, prices).usd;
31
+ return totals(run.seen, prices);
32
+ }
33
+
34
+ export function effectiveCaps(cfg, run) {
35
+ return {
36
+ usd: cfg.capUsd != null ? cfg.capUsd + (run.extraUsd || 0) : null,
37
+ tokens: cfg.capTokens != null ? cfg.capTokens + (run.extraTokens || 0) : null,
38
+ fiveHourPct: cfg.capFiveHourPct != null ? cfg.capFiveHourPct + (run.extraPct || 0) : null,
39
+ };
40
+ }
41
+
42
+ function overCap(t, caps, s, cfg) {
43
+ if (caps.usd != null && t.usd >= caps.usd) return `this run has used about ${usd(t.usd)} (cap ${usd(caps.usd)})`;
44
+ if (caps.tokens != null && t.tokens >= caps.tokens) return `this run has used ${Math.round(t.tokens / 1000)}k tokens (cap ${Math.round(caps.tokens / 1000)}k)`;
45
+ const sl = s.statusline;
46
+ if (caps.fiveHourPct != null && sl?.fiveHourPct != null && Date.now() - sl.at < 10 * 60e3 && sl.fiveHourPct >= caps.fiveHourPct)
47
+ return `your 5-hour usage window is at ${Math.round(sl.fiveHourPct)}% (cap ${caps.fiveHourPct}%)`;
48
+ if (cfg.sessionCapUsd != null && s.sessionUsd != null && s.sessionUsd >= cfg.sessionCapUsd) return `this session has used about ${usd(s.sessionUsd)} (session cap ${usd(cfg.sessionCapUsd)})`;
49
+ return null;
50
+ }
51
+
52
+ /** UserPromptSubmit: a new run starts. */
53
+ export function onUserPromptSubmit(input) {
54
+ const s = loadSession(input.session_id);
55
+ if (input.transcript_path) s.transcriptPath = input.transcript_path;
56
+ // Advance offsets so earlier history is never re-read for this run.
57
+ s.offsets ||= {};
58
+ for (const f of sessionFiles(s.transcriptPath)) {
59
+ const { entries, offset } = scanFile(f, s.offsets[f] || 0);
60
+ s.offsets[f] = offset;
61
+ absorb((s.sessionSeen ||= {}), entries, 0);
62
+ }
63
+ const now = Date.now();
64
+ s.run = { start: now, seen: {}, extraUsd: 0, extraTokens: 0, extraPct: 0, capHits: 0, warned: false, pendingAsk: null, startedAt: now };
65
+ saveSession(s);
66
+ return null;
67
+ }
68
+
69
+ /** PreToolUse (all tools): enforce the cap; on ExitPlanMode also produce the plan breakdown. */
70
+ export function onPreToolUse(input, prices = loadPrices()) {
71
+ const cfg = loadConfig(input.cwd);
72
+ const s = loadSession(input.session_id);
73
+ const t = refresh(s, input, prices);
74
+ const run = s.run;
75
+ const out = { hookSpecificOutput: { hookEventName: 'PreToolUse' } };
76
+ const ctx = [];
77
+ const msgs = [];
78
+
79
+ if (input.tool_name === 'ExitPlanMode' && input.tool_input?.plan) {
80
+ const a = analyzePlan(stripPlanSection(input.tool_input.plan), prices, { provider: cfg.provider });
81
+ if (a.steps.length) {
82
+ s.plan = { createdAt: Date.now(), estimateUsd: a.total.usd, baselineUsd: a.total.baselineUsd, steps: a.steps.map((x) => ({ title: x.title, complexity: x.complexity, model: x.alias, usd: x.usd })) };
83
+ msgs.push(planTable(a));
84
+ const light = a.steps.filter((x) => x.tier === 'light').map((x) => x.n);
85
+ const std = a.steps.filter((x) => x.tier === 'standard').map((x) => x.n);
86
+ ctx.push(`Lake Meter estimated this plan at ${range(a.total.usd)} with per-step models, vs ${range(a.total.baselineUsd)} on ${a.baselineLabel} for everything.`
87
+ + (light.length ? ` Steps ${light.join(', ')} are rated light (mechanical); the lake-light subagent (model: haiku) exists for steps like these.` : '')
88
+ + (std.length ? ` Steps ${std.join(', ')} are rated standard; the lake-standard subagent (model: sonnet) exists for steps like these.` : '')
89
+ + ' Delegating is optional and up to the user and the main agent.');
90
+ }
91
+ }
92
+
93
+ const caps = effectiveCaps(cfg, run);
94
+ const reason = overCap(t, caps, s, cfg);
95
+ if (reason) {
96
+ run.capHits++;
97
+ const ext = cfg.capUsd != null ? usd(cfg.capUsd * cfg.extendPct / 100) : `${cfg.extendPct}%`;
98
+ const unattended = cfg.onCap === 'stop' || UNATTENDED_MODES.has(input.permission_mode);
99
+ if (unattended) {
100
+ out.continue = false;
101
+ out.stopReason = `Lake Meter paused the run: ${reason}. Reply "continue" to start a new run, or raise the cap with /meter cap <usd>.`;
102
+ out.hookSpecificOutput.permissionDecision = 'deny';
103
+ out.hookSpecificOutput.permissionDecisionReason = `Lake Meter cap reached: ${reason}. The user has been asked how to proceed. Stop and wait for the user.`;
104
+ appendRun({ session: input.session_id, start: run.start || null, end: Date.now(), usd: +t.usd.toFixed(4), tokens: t.tokens, output: t.output, cacheRead: t.cacheRead, requests: t.requests, byModel: t.byModel, subagentUsd: +t.subagent.usd.toFixed(4), capUsd: caps.usd, capHits: run.capHits, stoppedByCap: true });
105
+ } else {
106
+ run.pendingAsk = input.tool_use_id || 'pending';
107
+ out.hookSpecificOutput.permissionDecision = 'ask';
108
+ out.hookSpecificOutput.permissionDecisionReason = `Lake Meter: ${reason}. Approve to continue with +${ext} headroom. Deny to stop here. Or run /meter cap <usd> to set a new cap.`;
109
+ }
110
+ } else if (!run.warned && caps.usd && t.usd >= caps.usd * (cfg.warnPct / 100)) {
111
+ run.warned = true;
112
+ msgs.push(`Lake Meter: this run is at ${usd(t.usd)} of its ${usd(caps.usd)} cap.`);
113
+ ctx.push(`Run spend is at ${Math.round((t.usd / caps.usd) * 100)}% of the user's per-run budget of ${usd(caps.usd)}. Tool calls will need the user's approval once it is reached.`);
114
+ }
115
+
116
+ saveSession(s);
117
+ if (ctx.length) out.hookSpecificOutput.additionalContext = ctx.join('\n');
118
+ if (msgs.length) out.systemMessage = msgs.join('\n\n');
119
+ const hso = out.hookSpecificOutput;
120
+ if (!out.systemMessage && !hso.additionalContext && !hso.permissionDecision && out.continue === undefined) return null;
121
+ return out;
122
+ }
123
+
124
+ export const PLAN_SECTION = '## Lake Meter: model per step (estimate)';
125
+
126
+ /** Strip a previous Lake Meter section so re-analysis never feeds on itself. */
127
+ const TOP_MARK = '> **Lake Meter estimate:**';
128
+ export function stripPlanSection(text) {
129
+ let t = String(text);
130
+ const i = t.indexOf(PLAN_SECTION);
131
+ if (i !== -1) t = t.slice(0, i).trimEnd() + '\n';
132
+ if (t.startsWith(TOP_MARK)) t = t.slice(t.indexOf('\n') + 1).replace(/^\n+/, '');
133
+ return t;
134
+ }
135
+
136
+ /**
137
+ * When Claude writes or edits its plan file in plan mode, append (or refresh) a per-step model and cost
138
+ * section at the end of that file, so it shows up in Claude Code's own "Ready to code?" plan dialog.
139
+ */
140
+ export function annotatePlanFile(input, prices, cfg, s) {
141
+ const fp = input.tool_input?.file_path;
142
+ if (!fp || !/[\\/]plans[\\/][^\\/]+\.md$/.test(fp) || !existsSync(fp)) return false;
143
+ if (input.permission_mode && input.permission_mode !== 'plan') return false;
144
+ if (cfg.annotatePlans === false) return false;
145
+ const original = stripPlanSection(readFileSync(fp, 'utf8'));
146
+ const a = analyzePlan(original, prices, { provider: cfg.provider });
147
+ if (a.steps.length < 2) return false;
148
+ s.plan = { createdAt: Date.now(), estimateUsd: a.total.usd, baselineUsd: a.total.baselineUsd, steps: a.steps.map((x) => ({ title: x.title, complexity: x.complexity, model: x.alias, usd: x.usd })) };
149
+ const md = planMarkdown(a).replace(/^\*\*Lake Meter plan breakdown\*\* /, '');
150
+ const top = `${TOP_MARK} ${range(a.total.usd)} with a model per step, vs ${range(a.total.baselineUsd)} all on ${a.baselineLabel}. Table at the end.\n\n`;
151
+ writeFileSync(fp, `${top}${original.trimEnd()}\n\n${PLAN_SECTION}\n\n${md}\n\nCheap steps can go to the \`lake-light\` (Haiku) or \`lake-standard\` (Sonnet) subagents. Heuristic estimate by lake-meter; measured spend is shown when the run ends.\n`);
152
+ return true;
153
+ }
154
+
155
+ /** PostToolUse: plan-file annotation, and cap approvals (the tool we asked about ran, so the user said yes). */
156
+ export function onPostToolUse(input, prices = loadPrices()) {
157
+ const s = loadSession(input.session_id);
158
+ if (/^(Write|Edit|MultiEdit)$/.test(input.tool_name || '')) {
159
+ try { if (annotatePlanFile(input, prices, loadConfig(input.cwd), s)) saveSession(s); } catch { /* never break the session */ }
160
+ }
161
+ const run = s.run;
162
+ if (!run?.pendingAsk) return null;
163
+ if (run.pendingAsk !== 'pending' && input.tool_use_id && input.tool_use_id !== run.pendingAsk) return null;
164
+ const cfg = loadConfig(input.cwd);
165
+ const t = totals(run.seen, prices);
166
+ if (cfg.capUsd != null) {
167
+ const target = Math.max(t.usd, cfg.capUsd + run.extraUsd) + cfg.capUsd * cfg.extendPct / 100;
168
+ run.extraUsd = target - cfg.capUsd;
169
+ }
170
+ if (cfg.capTokens != null) run.extraTokens = Math.max(t.tokens, cfg.capTokens + run.extraTokens) + cfg.capTokens * cfg.extendPct / 100 - cfg.capTokens;
171
+ if (cfg.capFiveHourPct != null) run.extraPct = Math.max(0, (s.statusline?.fiveHourPct ?? cfg.capFiveHourPct) - cfg.capFiveHourPct) + 5;
172
+ run.pendingAsk = null;
173
+ run.warned = true; // the user just chose to continue; no extra heads-up for this extension
174
+ saveSession(s);
175
+ return null;
176
+ }
177
+
178
+ /** Stop: end-of-run summary (shown to the user, never blocks). */
179
+ export async function onStop(input, prices = loadPrices(), { settleMs = 300 } = {}) {
180
+ if (settleMs) await new Promise((r) => setTimeout(r, settleMs)); // transcript is written asynchronously
181
+ const cfg = loadConfig(input.cwd);
182
+ const s = loadSession(input.session_id);
183
+ const t = refresh(s, input, prices);
184
+ const run = s.run;
185
+ let plan = null;
186
+ if (s.plan) {
187
+ const seen = {};
188
+ for (const f of sessionFiles(s.transcriptPath)) absorb(seen, scanFile(f, 0).entries, s.plan.createdAt);
189
+ plan = { actualUsd: totals(seen, prices).usd, estimateUsd: s.plan.estimateUsd };
190
+ }
191
+ const caps = effectiveCaps(cfg, run);
192
+ const summary = runSummary(t, { cap: caps.usd, capHits: run.capHits, plan });
193
+ appendRun({ session: input.session_id, start: run.start || null, end: Date.now(), usd: +t.usd.toFixed(4), tokens: t.tokens, output: t.output, cacheRead: t.cacheRead, requests: t.requests, byModel: t.byModel, subagentUsd: +t.subagent.usd.toFixed(4), capUsd: caps.usd, capHits: run.capHits, plan, statuslineSessionUsd: s.statusline?.costUsd ?? null });
194
+ s.lastRun = { usd: t.usd, tokens: t.tokens, end: Date.now() };
195
+ saveSession(s);
196
+ if (!t.requests) return null;
197
+ return { systemMessage: summary };
198
+ }
199
+
200
+ /** statusLine command: show the meter, and keep Claude Code's own session cost + rate-limit % for cap checks. */
201
+ export function onStatusLine(input, prices = loadPrices()) {
202
+ const cfg = loadConfig(input.cwd || input.workspace?.current_dir);
203
+ const s = loadSession(input.session_id);
204
+ const fiveHourPct = input.rate_limits?.five_hour?.used_percentage ?? null;
205
+ s.statusline = { costUsd: input.cost?.total_cost_usd ?? null, fiveHourPct, sevenDayPct: input.rate_limits?.seven_day?.used_percentage ?? null, at: Date.now() };
206
+ s.sessionUsd = s.statusline.costUsd ?? s.sessionUsd ?? null;
207
+ const t = s.run ? totals(s.run.seen, prices) : null;
208
+ saveSession(s);
209
+ const caps = s.run ? effectiveCaps(cfg, s.run) : { usd: cfg.capUsd };
210
+ const parts = ['◒ Lake'];
211
+ if (t) parts.push(`run ${usd(t.usd)}${caps.usd != null ? ` / ${usd(caps.usd)}` : ''}`);
212
+ if (s.statusline.costUsd != null) parts.push(`session ${usd(s.statusline.costUsd)}`);
213
+ if (fiveHourPct != null) parts.push(`5h ${Math.round(fiveHourPct)}%`);
214
+ return parts.join(' · ');
215
+ }