lake-meter 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,14 +72,14 @@ Stop says: Lake Meter · run $3.44 · 524k tok (313k cache reads, 155k out) · O
72
72
 
73
73
  | | |
74
74
  |---|---|
75
- | `npx lake-meter init` | install hooks, statusline, `/meter` skill and two optional subagents into `~/.claude` |
76
- | `npx lake-meter init --project` | install into this repo's `.claude/settings.local.json` instead |
77
- | `npx lake-meter init --cap 10 --no-agents --statusline` | set the cap, skip the subagents, replace an existing statusline |
75
+ | `npx lake-meter@latest init` | install hooks, statusline, `/meter` skill and two subagents (installed by default; skip with `--no-agents`) into `~/.claude` |
76
+ | `npx lake-meter@latest init --project` | install hooks into this repo's `.claude/settings.local.json` (also writes `.claude/skills` and `.claude/agents` with machine-specific paths: don't commit them) |
77
+ | `npx lake-meter@latest init --cap 10 --no-agents --statusline` | set the cap, skip the subagents, replace an existing statusline |
78
78
  | `/meter`, `/meter cap 10`, `/meter cap off`, `/meter report` | inside Claude Code (uses one short model turn to display) |
79
- | `lake-meter cap 10` · `lake-meter status` · `lake-meter report` | same, from any terminal, no model turn |
80
- | `lake-meter plan plan.md [--why] [--openai] [--json]` | plan breakdown for any markdown plan |
81
- | `lake-meter mcp` | MCP server with `estimate_plan` and `meter_status` (works in Cursor too) |
82
- | `npx lake-meter uninstall` | remove everything `init` added (your settings are restored; a backup is kept as `settings.json.lake-meter.bak`) |
79
+ | `npx lake-meter@latest cap 10` · `npx lake-meter@latest status` · `npx lake-meter@latest report` | same, from any terminal, no model turn (or `npm i -g lake-meter` and drop `npx`) |
80
+ | `npx lake-meter@latest plan plan.md [--why] [--openai] [--json]` (flags after the file) | plan breakdown for any markdown plan |
81
+ | `npx lake-meter@latest mcp` | MCP server with `estimate_plan` and `meter_status` (works in Cursor too) |
82
+ | `npx lake-meter@latest uninstall` | remove everything `init` added (your settings are restored; a backup of the original is kept as `settings.json.lake-meter.bak`) |
83
83
 
84
84
  ### Config
85
85
 
@@ -87,25 +87,40 @@ Stop says: Lake Meter · run $3.44 · 524k tok (313k cache reads, 155k out) · O
87
87
 
88
88
  ```json
89
89
  {
90
- "capUsd": 5, // per run, API list-price equivalent. null = off
91
- "capTokens": null, // per run, all tokens incl. cache reads
92
- "capFiveHourPct": null, // e.g. 80: stop when your 5-hour subscription window passes 80% (needs the statusline)
93
- "sessionCapUsd": null, // across the whole session
94
- "onCap": "ask", // "ask" = permission prompt; "stop" = end the turn
95
- "extendPct": 50, // headroom granted when you press Yes
96
- "warnPct": 80, // one heads-up (to you and to Claude) at 80% of the cap
97
- "provider": "anthropic",// or "openai" for plan recommendations
98
- "annotatePlans": true // add the table to plan files in plan mode
90
+ "capUsd": 5,
91
+ "capTokens": null,
92
+ "capFiveHourPct": null,
93
+ "sessionCapUsd": null,
94
+ "onCap": "ask",
95
+ "extendPct": 50,
96
+ "warnPct": 80,
97
+ "provider": "anthropic",
98
+ "annotatePlans": true
99
99
  }
100
100
  ```
101
101
 
102
+ | Key | Meaning |
103
+ |---|---|
104
+ | `capUsd` | per run, API list-price equivalent. `null` = off |
105
+ | `capTokens` | per run, all tokens incl. cache reads |
106
+ | `capFiveHourPct` | e.g. `80`: stop when your 5-hour subscription window passes 80% (needs the statusline) |
107
+ | `sessionCapUsd` | across the whole session |
108
+ | `onCap` | `"ask"` = permission prompt; `"stop"` = end the turn |
109
+ | `extendPct` | headroom granted when you press Yes |
110
+ | `warnPct` | one heads-up (to you and to Claude) at this % of the cap |
111
+ | `provider` | `"anthropic"` or `"openai"` for plan recommendations |
112
+ | `annotatePlans` | add the table to plan files in plan mode |
113
+
114
+ Simplest: `npx lake-meter@latest cap 10` writes this file for you.
115
+
102
116
  A **run** is everything from one prompt you submit until Claude stops.
103
117
 
104
118
  ### Cursor and other MCP clients
105
119
 
120
+ Add to `~/.cursor/mcp.json` (or any MCP client's config):
121
+
106
122
  ```json
107
- // ~/.cursor/mcp.json
108
- { "mcpServers": { "lake-meter": { "command": "npx", "args": ["-y", "lake-meter", "mcp"] } } }
123
+ { "mcpServers": { "lake-meter": { "command": "npx", "args": ["-y", "lake-meter@latest", "mcp"] } } }
109
124
  ```
110
125
 
111
126
  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,7 +132,7 @@ Then ask the agent to "estimate this plan with lake-meter". In Cursor you get th
117
132
  | **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). |
118
133
  | **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). |
119
134
  | **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. |
120
- | **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. |
135
+ | **Plan breakdown** | **Estimate.** Keyword and size heuristics rate each step 1–5; token budgets per complexity live in `prices.json` (`assumptions`). Run `npx lake-meter@latest plan plan.md --why` to see every reason. | Rough. Ranges are wide on purpose. Tune the budgets from your own `npx lake-meter@latest report` history. |
121
136
  | **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. |
122
137
 
123
138
  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.
@@ -134,13 +149,13 @@ Prices last verified **2026‑11‑12** from [Anthropic pricing](https://platfor
134
149
  | `Stop` hook | prints the receipt (`systemMessage`, never blocks) and appends one line to `~/.lake-meter/runs.jsonl` |
135
150
  | `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 |
136
151
  | `~/.claude/skills/meter` | the `/meter` command |
137
- | `~/.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` |
152
+ | `~/.claude/agents/lake-light.md`, `lake-standard.md` | subagents pinned to `haiku` and `sonnet` (installed by default; skip with `--no-agents`), so the per-step advice is actionable. Claude only uses them if it decides to |
138
153
 
139
154
  ## Limits (honest list)
140
155
 
141
156
  - **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.
142
157
  - **Transcript lag.** Claude Code writes transcripts asynchronously, so the newest response may land a moment late. Spend can lag by about one response.
143
- - **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.
158
+ - **Pressing No interrupts the turn.** Claude Code doesn't run Stop hooks on interrupts, so there's no receipt for that turn; `npx lake-meter@latest status` still has the numbers.
144
159
  - **"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.
145
160
  - **Dollar figures are list-price equivalents**, not your bill. On subscriptions use `capTokens` or `capFiveHourPct` if dollars feel abstract.
146
161
  - **Plan breakdown is heuristic** and English-keyword based. Unknown models count tokens but not dollars (and the receipt says so).
@@ -153,11 +168,11 @@ Step titles are stored locally in `~/.lake-meter`, along with config and a run l
153
168
 
154
169
  ## Verification
155
170
 
156
- - `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).
171
+ - `npm test`: 48 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).
157
172
  - `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.
158
173
  - The screens in [What you see](#what-you-see) were captured from an interactive Claude Code session driven against the same mock.
159
174
 
160
- ## Demo (no account needed)
175
+ ## Demo (from a clone, no account needed)
161
176
 
162
177
  ```bash
163
178
  npm run demo # simulated session: plan breakdown → cap prompt → receipt
@@ -165,7 +180,7 @@ npm run demo # simulated session: plan breakdown → cap prompt → recei
165
180
 
166
181
  ## Teams
167
182
 
168
- Works with [lake-gate](https://getlake.github.io/lake-gate/): a teammate approves the plan before the expensive run. Shared caps and a dashboard of runs by repo and model are in early access. [Talk to us](https://getlake.github.io/lake-meter/#waitlist).
183
+ Works with [lake-gate](https://getlake.github.io/lake-gate/): a teammate approves the plan before the expensive run. Shared caps and a dashboard of runs by repo and model are in early access. [Request a team pilot](https://getlake.github.io/lake-meter/#waitlist).
169
184
 
170
185
  ## License
171
186
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lake-meter",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Per-step model picks and a hard per-run cost cap for Claude Code. Hooks + MCP, local only, no telemetry.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -4,7 +4,7 @@ import { loadPrices } from './pricing.js';
4
4
  import { analyzePlan } from './plan.js';
5
5
  import { planTable, runSummary, usd } from './format.js';
6
6
  import { onUserPromptSubmit, onPreToolUse, onPostToolUse, onStop, onStatusLine, effectiveCaps } from './hooks.js';
7
- import { loadConfig, saveUserConfig, loadSession, latestSessionId, readRuns, home } from './state.js';
7
+ import { loadConfig, saveUserConfig, loadSession, latestSessionId, readRuns, home, parseCapUsd } from './state.js';
8
8
  import { totals } from './transcript.js';
9
9
  import { init, uninstall } from './init.js';
10
10
  import { serve } from './mcp.js';
@@ -41,11 +41,23 @@ function status(sessionId) {
41
41
  }
42
42
 
43
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.`;
44
+ if (v == null || v === '') {
45
+ process.exitCode = 1;
46
+ return 'Usage: cap <usd> | off e.g. cap 10 or cap \'$10\'';
47
+ }
48
+ const parsed = parseCapUsd(v, { allowOff: true });
49
+ if (!parsed.ok) {
50
+ process.exitCode = 1;
51
+ return `lake-meter: invalid cap '${v}'. Use a positive number (e.g. 10 or $10) or 'off'.`;
52
+ }
53
+ try {
54
+ if (parsed.value == null) { saveUserConfig({ capUsd: null }); return 'Per-run cap turned off.'; }
55
+ saveUserConfig({ capUsd: parsed.value });
56
+ } catch (e) {
57
+ process.exitCode = 1;
58
+ return e.message;
59
+ }
60
+ return `Per-run cap set to ${usd(parsed.value)} (API list-price equivalent). Applies from the next tool call.`;
49
61
  }
50
62
 
51
63
  function report() {
@@ -99,7 +111,8 @@ export async function main(argv) {
99
111
  return;
100
112
  }
101
113
  case 'plan': {
102
- console.log(planFile(args[0], args));
114
+ const out = planFile(args[0], args);
115
+ console.log(out);
103
116
  return;
104
117
  }
105
118
  case 'cap': console.log(setCap(args[0])); return;
@@ -108,13 +121,33 @@ export async function main(argv) {
108
121
  case 'mcp': serve(); return;
109
122
  case 'init': {
110
123
  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') });
124
+ let capUsd;
125
+ if (cap != null) {
126
+ const parsed = parseCapUsd(cap);
127
+ if (!parsed.ok) {
128
+ process.stderr.write(`lake-meter: invalid --cap '${cap}'. Use a positive number, e.g. --cap 10 or --cap '$10'.\n`);
129
+ process.exitCode = 1;
130
+ return;
131
+ }
132
+ capUsd = parsed.value;
133
+ }
134
+ try {
135
+ init({ project: flag(args, '--project'), capUsd, agents: !flag(args, '--no-agents'), statusline: flag(args, '--statusline') });
136
+ } catch (e) {
137
+ process.stderr.write(`lake-meter: ${e.message}\n`);
138
+ process.exitCode = 1;
139
+ }
112
140
  return;
113
141
  }
114
142
  case 'uninstall': uninstall({ project: flag(args, '--project') }); return;
115
143
  case 'where': console.log(home()); return;
116
144
  case '--version': case '-v': console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url))).version); return;
117
- default: console.log(HELP);
145
+ case '--help': case '-h': case undefined:
146
+ console.log(HELP);
147
+ return;
148
+ default:
149
+ process.stderr.write(`lake-meter: unknown command '${cmd}'\n${HELP}\n`);
150
+ process.exitCode = 1;
118
151
  }
119
152
  }
120
153
 
@@ -122,7 +155,10 @@ function planFile(file, args) {
122
155
  let text;
123
156
  if (!file || file === '-') text = readFileSync(0, 'utf8');
124
157
  else if (existsSync(file)) text = readFileSync(file, 'utf8');
125
- else return `File not found: ${file}`;
158
+ else {
159
+ process.exitCode = 1;
160
+ return `File not found: ${file}`;
161
+ }
126
162
  const a = analyzePlan(text, loadPrices(), { provider: flag(args, '--openai') ? 'openai' : loadConfig(process.cwd()).provider });
127
163
  if (!a.steps.length) return 'Could not find steps in that plan (use numbered items, headings or bullets).';
128
164
  return flag(args, '--json') ? JSON.stringify(a, null, 2) : planTable(a, { reasons: flag(args, '--why') });
package/src/hooks.js CHANGED
@@ -31,25 +31,77 @@ export function refresh(s, input, prices) {
31
31
  return totals(run.seen, prices);
32
32
  }
33
33
 
34
- export function effectiveCaps(cfg, run) {
34
+ export function effectiveCaps(cfg, run, s = {}) {
35
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,
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
+ sessionUsd: cfg.sessionCapUsd != null ? cfg.sessionCapUsd + (s.extraSessionUsd || 0) : null,
39
40
  };
40
41
  }
41
42
 
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)`;
43
+ function overCap(t, caps, s) {
44
+ if (caps.usd != null && t.usd >= caps.usd)
45
+ return { kind: 'usd', reason: `this run has used about ${usd(t.usd)} (cap ${usd(caps.usd)})`, amount: t.usd, cap: caps.usd };
46
+ if (caps.tokens != null && t.tokens >= caps.tokens)
47
+ return { kind: 'tokens', reason: `this run has used ${Math.round(t.tokens / 1000)}k tokens (cap ${Math.round(caps.tokens / 1000)}k)`, amount: t.tokens, cap: caps.tokens };
45
48
  const sl = s.statusline;
46
49
  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)})`;
50
+ return { kind: 'fiveHour', reason: `your 5-hour usage window is at ${Math.round(sl.fiveHourPct)}% (cap ${Math.round(caps.fiveHourPct)}%)`, amount: sl.fiveHourPct, cap: caps.fiveHourPct };
51
+ if (caps.sessionUsd != null && s.sessionUsd != null && s.sessionUsd >= caps.sessionUsd)
52
+ return { kind: 'session', reason: `this session has used about ${usd(s.sessionUsd)} (session cap ${usd(caps.sessionUsd)})`, amount: s.sessionUsd, cap: caps.sessionUsd };
49
53
  return null;
50
54
  }
51
55
 
52
- /** UserPromptSubmit: a new run starts. */
56
+ function headroomLabel(hit, cfg) {
57
+ const pct = cfg.extendPct;
58
+ if (hit.kind === 'usd' && cfg.capUsd != null) return usd(cfg.capUsd * pct / 100);
59
+ if (hit.kind === 'session' && cfg.sessionCapUsd != null) return usd(cfg.sessionCapUsd * pct / 100);
60
+ if (hit.kind === 'tokens' && cfg.capTokens != null) return `${Math.round(cfg.capTokens * pct / 100 / 1000)}k tokens`;
61
+ return `${pct}%`;
62
+ }
63
+
64
+ /** Exact user-facing pause line. Do not wrap this in hook-error language. */
65
+ export function pauseMessage(hit) {
66
+ if (hit.kind === 'usd' || hit.kind === 'session')
67
+ return `Lake Meter paused the run at ${usd(hit.amount)} (cap ${usd(hit.cap)})`;
68
+ if (hit.kind === 'tokens')
69
+ return `Lake Meter paused the run at ${Math.round(hit.amount / 1000)}k tokens (cap ${Math.round(hit.cap / 1000)}k)`;
70
+ if (hit.kind === 'fiveHour')
71
+ return `Lake Meter paused the run at ${Math.round(hit.amount)}% of the 5-hour window (cap ${Math.round(hit.cap)}%)`;
72
+ return `Lake Meter paused the run: ${hit.reason}`;
73
+ }
74
+
75
+ function applyHeadroom(cfg, run, s, t, kinds) {
76
+ const pct = cfg.extendPct / 100;
77
+ for (const kind of kinds) {
78
+ if (kind === 'usd' && cfg.capUsd != null) {
79
+ const target = Math.max(t.usd, cfg.capUsd + (run.extraUsd || 0)) + cfg.capUsd * pct;
80
+ run.extraUsd = target - cfg.capUsd;
81
+ }
82
+ if (kind === 'tokens' && cfg.capTokens != null) {
83
+ run.extraTokens = Math.max(t.tokens, cfg.capTokens + (run.extraTokens || 0)) + cfg.capTokens * pct - cfg.capTokens;
84
+ }
85
+ if (kind === 'fiveHour' && cfg.capFiveHourPct != null) {
86
+ run.extraPct = Math.max(0, (s.statusline?.fiveHourPct ?? cfg.capFiveHourPct) - cfg.capFiveHourPct) + 5;
87
+ }
88
+ if (kind === 'session' && cfg.sessionCapUsd != null) {
89
+ const current = cfg.sessionCapUsd + (s.extraSessionUsd || 0);
90
+ const target = Math.max(s.sessionUsd ?? 0, current) + cfg.sessionCapUsd * pct;
91
+ s.extraSessionUsd = target - cfg.sessionCapUsd;
92
+ }
93
+ }
94
+ }
95
+
96
+ /** /meter (and /meter status, /meter cap, …) is itself a UserPromptSubmit; it must not start a new run. */
97
+ export function isMeterCommand(prompt) {
98
+ const p = String(prompt || '').trim();
99
+ if (/^\/meter\b/i.test(p)) return true;
100
+ if (/<(?:command-name|command_name)>\s*\/?meter\b/i.test(p)) return true;
101
+ return false;
102
+ }
103
+
104
+ /** UserPromptSubmit: a new run starts, unless this prompt is the /meter slash command. */
53
105
  export function onUserPromptSubmit(input) {
54
106
  const s = loadSession(input.session_id);
55
107
  if (input.transcript_path) s.transcriptPath = input.transcript_path;
@@ -59,9 +111,12 @@ export function onUserPromptSubmit(input) {
59
111
  const { entries, offset } = scanFile(f, s.offsets[f] || 0);
60
112
  s.offsets[f] = offset;
61
113
  absorb((s.sessionSeen ||= {}), entries, 0);
114
+ if (s.run) absorb(s.run.seen, entries, s.run.start);
115
+ }
116
+ if (!isMeterCommand(input.prompt)) {
117
+ const now = Date.now();
118
+ s.run = { start: now, seen: {}, extraUsd: 0, extraTokens: 0, extraPct: 0, capHits: 0, warned: false, pendingAsk: null, pendingAskKind: null, startedAt: now };
62
119
  }
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
120
  saveSession(s);
66
121
  return null;
67
122
  }
@@ -90,22 +145,27 @@ export function onPreToolUse(input, prices = loadPrices()) {
90
145
  }
91
146
  }
92
147
 
93
- const caps = effectiveCaps(cfg, run);
94
- const reason = overCap(t, caps, s, cfg);
95
- if (reason) {
148
+ const caps = effectiveCaps(cfg, run, s);
149
+ const hit = overCap(t, caps, s);
150
+ if (hit) {
96
151
  run.capHits++;
97
- const ext = cfg.capUsd != null ? usd(cfg.capUsd * cfg.extendPct / 100) : `${cfg.extendPct}%`;
152
+ const ext = headroomLabel(hit, cfg);
98
153
  const unattended = cfg.onCap === 'stop' || UNATTENDED_MODES.has(input.permission_mode);
99
154
  if (unattended) {
155
+ const pause = pauseMessage(hit);
100
156
  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>.`;
157
+ out.stopReason = `${pause}. Reply "continue" to start a new run, or raise the cap with /meter cap <usd>.`;
158
+ // permissionDecision: deny is what actually blocks the tool in unattended modes.
159
+ // The reason must be the clear pause line — not "hook error" / "the user has been asked".
102
160
  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.`;
161
+ out.hookSpecificOutput.permissionDecisionReason = pause;
162
+ out.systemMessage = `${pause}\n${runSummary(t, { cap: caps.usd ?? caps.sessionUsd, capHits: run.capHits })}`;
104
163
  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
164
  } else {
106
165
  run.pendingAsk = input.tool_use_id || 'pending';
166
+ run.pendingAskKind = hit.kind;
107
167
  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.`;
168
+ out.hookSpecificOutput.permissionDecisionReason = `Lake Meter: ${hit.reason}. Approve to continue with +${ext} headroom. Deny to stop here. Or run /meter cap <usd> to set a new cap.`;
109
169
  }
110
170
  } else if (!run.warned && caps.usd && t.usd >= caps.usd * (cfg.warnPct / 100)) {
111
171
  run.warned = true;
@@ -115,7 +175,7 @@ export function onPreToolUse(input, prices = loadPrices()) {
115
175
 
116
176
  saveSession(s);
117
177
  if (ctx.length) out.hookSpecificOutput.additionalContext = ctx.join('\n');
118
- if (msgs.length) out.systemMessage = msgs.join('\n\n');
178
+ if (msgs.length) out.systemMessage = (out.systemMessage ? out.systemMessage + '\n\n' : '') + msgs.join('\n\n');
119
179
  const hso = out.hookSpecificOutput;
120
180
  if (!out.systemMessage && !hso.additionalContext && !hso.permissionDecision && out.continue === undefined) return null;
121
181
  return out;
@@ -163,13 +223,18 @@ export function onPostToolUse(input, prices = loadPrices()) {
163
223
  if (run.pendingAsk !== 'pending' && input.tool_use_id && input.tool_use_id !== run.pendingAsk) return null;
164
224
  const cfg = loadConfig(input.cwd);
165
225
  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;
226
+ // Session totals may have been computed on the last PreToolUse; keep them current if we have statusline/sessionSeen.
227
+ if (s.sessionUsd == null && s.sessionSeen) {
228
+ try { s.sessionUsd = totals(s.sessionSeen, prices).usd; } catch { /* ignore */ }
169
229
  }
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;
230
+ const kinds = new Set();
231
+ if (run.pendingAskKind) kinds.add(run.pendingAskKind);
232
+ const still = overCap(t, effectiveCaps(cfg, run, s), s);
233
+ if (still) kinds.add(still.kind);
234
+ if (!kinds.size && cfg.capUsd != null) kinds.add('usd');
235
+ applyHeadroom(cfg, run, s, t, kinds);
172
236
  run.pendingAsk = null;
237
+ run.pendingAskKind = null;
173
238
  run.warned = true; // the user just chose to continue; no extra heads-up for this extension
174
239
  saveSession(s);
175
240
  return null;
@@ -188,7 +253,7 @@ export async function onStop(input, prices = loadPrices(), { settleMs = 300 } =
188
253
  for (const f of sessionFiles(s.transcriptPath)) absorb(seen, scanFile(f, 0).entries, s.plan.createdAt);
189
254
  plan = { actualUsd: totals(seen, prices).usd, estimateUsd: s.plan.estimateUsd };
190
255
  }
191
- const caps = effectiveCaps(cfg, run);
256
+ const caps = effectiveCaps(cfg, run, s);
192
257
  const summary = runSummary(t, { cap: caps.usd, capHits: run.capHits, plan });
193
258
  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
259
  s.lastRun = { usd: t.usd, tokens: t.tokens, end: Date.now() };
@@ -206,7 +271,7 @@ export function onStatusLine(input, prices = loadPrices()) {
206
271
  s.sessionUsd = s.statusline.costUsd ?? s.sessionUsd ?? null;
207
272
  const t = s.run ? totals(s.run.seen, prices) : null;
208
273
  saveSession(s);
209
- const caps = s.run ? effectiveCaps(cfg, s.run) : { usd: cfg.capUsd };
274
+ const caps = s.run ? effectiveCaps(cfg, s.run, s) : { usd: cfg.capUsd };
210
275
  const parts = ['◒ Lake'];
211
276
  if (t) parts.push(`run ${usd(t.usd)}${caps.usd != null ? ` / ${usd(caps.usd)}` : ''}`);
212
277
  if (s.statusline.costUsd != null) parts.push(`session ${usd(s.statusline.costUsd)}`);
package/src/init.js CHANGED
@@ -46,7 +46,8 @@ export function init(opts = {}) {
46
46
  const cli = opts.cli || installRuntime();
47
47
  const t = targets(opts);
48
48
  const settings = readJson(t.settings);
49
- if (existsSync(t.settings)) copyFileSync(t.settings, `${t.settings}.lake-meter.bak`);
49
+ const bak = `${t.settings}.lake-meter.bak`;
50
+ if (existsSync(t.settings) && !existsSync(bak)) copyFileSync(t.settings, bak);
50
51
  settings.hooks ||= {};
51
52
  const add = (evt, group) => {
52
53
  settings.hooks[evt] = (settings.hooks[evt] || []).filter((g) => !isOurs(g));
package/src/mcp.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Minimal MCP server over stdio (JSON-RPC 2.0, newline-delimited), no dependencies.
2
2
  // Tools: estimate_plan (any MCP client: Claude Code, Cursor, ...) and meter_status (Claude Code sessions).
3
3
  import { createInterface } from 'node:readline';
4
+ import { readFileSync } from 'node:fs';
4
5
  import { loadPrices } from './pricing.js';
5
6
  import { analyzePlan } from './plan.js';
6
7
  import { planMarkdown, runSummary } from './format.js';
@@ -32,7 +33,7 @@ export function handle(msg, prices = loadPrices()) {
32
33
  const { id, method, params } = msg;
33
34
  const ok = (result) => ({ jsonrpc: '2.0', id, result });
34
35
  if (method === 'initialize') {
35
- return ok({ protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'lake-meter', version: '0.1.0' } });
36
+ return ok({ protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'lake-meter', version: JSON.parse(readFileSync(new URL('../package.json', import.meta.url))).version } });
36
37
  }
37
38
  if (method === 'notifications/initialized' || id === undefined) return null;
38
39
  if (method === 'ping') return ok({});
package/src/state.js CHANGED
@@ -15,6 +15,7 @@ export const DEFAULT_CONFIG = {
15
15
  extendPct: 50, // approving a cap prompt adds this % of the cap as headroom
16
16
  warnPct: 80, // one heads-up when a run passes this % of its cap
17
17
  provider: 'anthropic',
18
+ annotatePlans: true,
18
19
  };
19
20
 
20
21
  export function home() {
@@ -25,6 +26,21 @@ function readJson(p, fallback) {
25
26
  try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return fallback; }
26
27
  }
27
28
 
29
+ /** Read a JSON object file. On missing file, returns fallback. On parse failure, warns and returns fallback without mutating the file. */
30
+ export function readConfigFile(p, fallback, warn = defaultWarn) {
31
+ if (!existsSync(p)) return fallback;
32
+ try {
33
+ return JSON.parse(readFileSync(p, 'utf8'));
34
+ } catch (err) {
35
+ warn(`lake-meter: could not parse ${p}: ${err.message}. Ignoring this file and using defaults for its values.`);
36
+ return fallback;
37
+ }
38
+ }
39
+
40
+ function defaultWarn(msg) {
41
+ process.stderr.write(msg.endsWith('\n') ? msg : msg + '\n');
42
+ }
43
+
28
44
  export function writeJsonAtomic(p, data) {
29
45
  mkdirSync(join(p, '..'), { recursive: true });
30
46
  const tmp = `${p}.${process.pid}.${Date.now()}.tmp`;
@@ -32,16 +48,132 @@ export function writeJsonAtomic(p, data) {
32
48
  renameSync(tmp, p);
33
49
  }
34
50
 
51
+ /**
52
+ * Parse a user-supplied USD cap (CLI --cap, `lake-meter cap`).
53
+ * Accepts optional leading $ and commas: 10, $10, "$10", 1,000.50.
54
+ * 'off' / 'none' (case-insensitive) clears the cap when allowOff is true.
55
+ */
56
+ export function parseCapUsd(raw, { allowOff = false } = {}) {
57
+ if (raw == null) return { ok: false };
58
+ const s = String(raw).trim();
59
+ if (allowOff && /^(off|none)$/i.test(s)) return { ok: true, value: null };
60
+ const n = Number(s.replace(/^\$/, '').replace(/,/g, ''));
61
+ if (!Number.isFinite(n) || n <= 0) return { ok: false };
62
+ return { ok: true, value: n };
63
+ }
64
+
65
+ const NUMERIC_KEYS = new Set(['capUsd', 'capTokens', 'capFiveHourPct', 'sessionCapUsd', 'extendPct', 'warnPct']);
66
+ const NULLABLE_CAPS = new Set(['capUsd', 'capTokens', 'capFiveHourPct', 'sessionCapUsd']);
67
+
68
+ function coerceNumber(value) {
69
+ if (typeof value === 'number' && Number.isFinite(value)) return { ok: true, value, coerced: false };
70
+ if (typeof value === 'string' && value.trim() !== '') {
71
+ const n = Number(value.trim().replace(/^\$/, '').replace(/,/g, ''));
72
+ if (Number.isFinite(n)) return { ok: true, value: n, coerced: true };
73
+ }
74
+ return { ok: false };
75
+ }
76
+
77
+ /** Validate and coerce a raw config object. Invalid or missing fields fall back to `base` (defaults, or already-normalized user config). */
78
+ export function normalizeConfig(raw, warn = defaultWarn, source = 'config', base = DEFAULT_CONFIG) {
79
+ const out = { ...base };
80
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
81
+ warn(`lake-meter: ${source} is not a JSON object; using previous values.`);
82
+ return out;
83
+ }
84
+ for (const key of Object.keys(DEFAULT_CONFIG)) {
85
+ if (!(key in raw)) continue;
86
+ const v = raw[key];
87
+ if (NUMERIC_KEYS.has(key)) {
88
+ if (v == null) {
89
+ if (NULLABLE_CAPS.has(key)) { out[key] = null; continue; }
90
+ warn(`lake-meter: ${source}: ${key} cannot be null; using ${out[key]}.`);
91
+ continue;
92
+ }
93
+ const n = coerceNumber(v);
94
+ if (!n.ok) {
95
+ warn(`lake-meter: ${source}: invalid ${key} ${JSON.stringify(v)}; using ${out[key]}.`);
96
+ continue;
97
+ }
98
+ if (n.coerced) warn(`lake-meter: ${source}: ${key} should be a number, not a string; using ${n.value}.`);
99
+ if (key === 'extendPct') {
100
+ if (!(n.value > 0)) {
101
+ warn(`lake-meter: ${source}: extendPct must be greater than 0; using ${out.extendPct}.`);
102
+ continue;
103
+ }
104
+ out[key] = n.value;
105
+ continue;
106
+ }
107
+ if (key === 'warnPct') {
108
+ if (n.value < 0 || n.value > 100) {
109
+ warn(`lake-meter: ${source}: warnPct must be between 0 and 100; using ${out.warnPct}.`);
110
+ continue;
111
+ }
112
+ out[key] = n.value;
113
+ continue;
114
+ }
115
+ if (n.value <= 0) {
116
+ warn(`lake-meter: ${source}: ${key} must be a positive number; using ${out[key]}.`);
117
+ continue;
118
+ }
119
+ out[key] = n.value;
120
+ continue;
121
+ }
122
+ if (key === 'onCap') {
123
+ const s = String(v).toLowerCase();
124
+ if (s === 'ask' || s === 'stop') { out.onCap = s; continue; }
125
+ warn(`lake-meter: ${source}: invalid onCap ${JSON.stringify(v)}; using '${out.onCap}'.`);
126
+ continue;
127
+ }
128
+ if (key === 'provider') {
129
+ const s = String(v).toLowerCase();
130
+ if (s === 'anthropic' || s === 'openai') { out.provider = s; continue; }
131
+ warn(`lake-meter: ${source}: invalid provider ${JSON.stringify(v)}; using '${out.provider}'.`);
132
+ continue;
133
+ }
134
+ if (key === 'annotatePlans') {
135
+ if (typeof v === 'boolean') { out.annotatePlans = v; continue; }
136
+ if (v === 'true' || v === 'false') {
137
+ out.annotatePlans = v === 'true';
138
+ warn(`lake-meter: ${source}: annotatePlans should be a boolean, not a string; using ${out.annotatePlans}.`);
139
+ continue;
140
+ }
141
+ warn(`lake-meter: ${source}: invalid annotatePlans ${JSON.stringify(v)}; using ${out.annotatePlans}.`);
142
+ }
143
+ }
144
+ // Keep unknown keys out of the runtime config so they cannot poison comparisons.
145
+ return out;
146
+ }
147
+
35
148
  /** 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 };
149
+ export function loadConfig(cwd, warn = defaultWarn) {
150
+ const userPath = join(home(), 'config.json');
151
+ const user = normalizeConfig(readConfigFile(userPath, {}, warn), warn, userPath);
152
+ if (!cwd) return user;
153
+ const projPath = join(cwd, '.lake-meter.json');
154
+ if (!existsSync(projPath)) return user;
155
+ const projRaw = readConfigFile(projPath, null, warn);
156
+ if (projRaw == null) return user;
157
+ return normalizeConfig(projRaw, warn, projPath, user);
40
158
  }
41
159
 
42
- export function saveUserConfig(patch) {
160
+ export function saveUserConfig(patch, warn = defaultWarn) {
43
161
  const p = join(home(), 'config.json');
44
- const cur = readJson(p, {});
162
+ let cur = {};
163
+ if (existsSync(p)) {
164
+ try {
165
+ cur = JSON.parse(readFileSync(p, 'utf8'));
166
+ } catch (err) {
167
+ const msg = `lake-meter: refusing to overwrite unparseable ${p}: ${err.message}. Fix or remove the file, then retry.`;
168
+ warn(msg);
169
+ throw new Error(msg);
170
+ }
171
+ if (cur == null || typeof cur !== 'object' || Array.isArray(cur)) {
172
+ const msg = `lake-meter: refusing to overwrite ${p}: expected a JSON object.`;
173
+ warn(msg);
174
+ throw new Error(msg);
175
+ }
176
+ }
45
177
  writeJsonAtomic(p, { ...cur, ...patch });
46
178
  }
47
179