lake-meter 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/package.json +2 -2
- package/src/cli.js +3 -3
- package/src/hooks.js +31 -6
- package/src/init.js +15 -1
- package/src/state.js +28 -6
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# lake-meter
|
|
2
2
|
|
|
3
|
-
**A model for every step, and a
|
|
3
|
+
**A model for every step, and a cap that stops and asks. For Claude Code.**
|
|
4
4
|
|
|
5
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
6
|
|
|
@@ -168,7 +168,7 @@ Step titles are stored locally in `~/.lake-meter`, along with config and a run l
|
|
|
168
168
|
|
|
169
169
|
## Verification
|
|
170
170
|
|
|
171
|
-
- `npm test`:
|
|
171
|
+
- `npm test`: 54 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).
|
|
172
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.
|
|
173
173
|
- The screens in [What you see](#what-you-see) were captured from an interactive Claude Code session driven against the same mock.
|
|
174
174
|
|
|
@@ -180,7 +180,7 @@ npm run demo # simulated session: plan breakdown → cap prompt → recei
|
|
|
180
180
|
|
|
181
181
|
## Teams
|
|
182
182
|
|
|
183
|
-
Works with [lake-gate](https://getlake.
|
|
183
|
+
Works with [lake-gate](https://getlake.dev/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.dev/lake-meter/#waitlist).
|
|
184
184
|
|
|
185
185
|
## License
|
|
186
186
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lake-meter",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Per-step model picks and a
|
|
3
|
+
"version": "0.1.4",
|
|
4
|
+
"description": "Per-step model picks and a cap that stops and asks for Claude Code. Hooks + MCP, local only, no telemetry.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"lake-meter": "bin/lake-meter.js"
|
package/src/cli.js
CHANGED
|
@@ -4,12 +4,12 @@ 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, parseCapUsd } from './state.js';
|
|
7
|
+
import { loadConfig, saveUserConfig, loadSession, latestSessionId, readRuns, uniqueRuns, 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';
|
|
11
11
|
|
|
12
|
-
const HELP = `lake-meter · per-step model picks and a
|
|
12
|
+
const HELP = `lake-meter · per-step model picks and a per-run cap that stops and asks for Claude Code
|
|
13
13
|
|
|
14
14
|
npx lake-meter init [--project] [--cap 5] [--no-agents] [--statusline] install hooks, statusline, /meter
|
|
15
15
|
lake-meter plan <file.md> [--openai] [--why] plan breakdown: complexity, model per step, cost ranges
|
|
@@ -61,7 +61,7 @@ function setCap(v) {
|
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
function report() {
|
|
64
|
-
const runs = readRuns().slice(-15);
|
|
64
|
+
const runs = uniqueRuns(readRuns()).slice(-15);
|
|
65
65
|
if (!runs.length) return 'No finished runs yet.';
|
|
66
66
|
const lines = ['Lake Meter · last runs (measured tokens, list-price $)', ''];
|
|
67
67
|
for (const r of runs) {
|
package/src/hooks.js
CHANGED
|
@@ -9,6 +9,21 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
9
9
|
|
|
10
10
|
const UNATTENDED_MODES = new Set(['bypassPermissions', 'dontAsk']);
|
|
11
11
|
|
|
12
|
+
function defaultWarn(msg) {
|
|
13
|
+
process.stderr.write(msg.endsWith('\n') ? msg : msg + '\n');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Load config and, once per session, return a user-visible notice for parse/validation warnings (M-22). */
|
|
17
|
+
function loadConfigNotices(cwd, s) {
|
|
18
|
+
const warnings = [];
|
|
19
|
+
const cfg = loadConfig(cwd, (m) => { defaultWarn(m); warnings.push(m); });
|
|
20
|
+
if (!warnings.length) return { cfg, notice: null };
|
|
21
|
+
if (s.configNoticeShown) return { cfg, notice: null };
|
|
22
|
+
s.configNoticeShown = true;
|
|
23
|
+
return { cfg, notice: warnings.join('\n') };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
12
27
|
function ensureRun(s, now) {
|
|
13
28
|
if (!s.run) s.run = { start: 0, seen: {}, extraUsd: 0, extraTokens: 0, capHits: 0, warned: false, pendingAsk: null, startedAt: now };
|
|
14
29
|
return s.run;
|
|
@@ -123,8 +138,8 @@ export function onUserPromptSubmit(input) {
|
|
|
123
138
|
|
|
124
139
|
/** PreToolUse (all tools): enforce the cap; on ExitPlanMode also produce the plan breakdown. */
|
|
125
140
|
export function onPreToolUse(input, prices = loadPrices()) {
|
|
126
|
-
const cfg = loadConfig(input.cwd);
|
|
127
141
|
const s = loadSession(input.session_id);
|
|
142
|
+
const { cfg, notice } = loadConfigNotices(input.cwd, s);
|
|
128
143
|
const t = refresh(s, input, prices);
|
|
129
144
|
const run = s.run;
|
|
130
145
|
const out = { hookSpecificOutput: { hookEventName: 'PreToolUse' } };
|
|
@@ -153,6 +168,8 @@ export function onPreToolUse(input, prices = loadPrices()) {
|
|
|
153
168
|
const unattended = cfg.onCap === 'stop' || UNATTENDED_MODES.has(input.permission_mode);
|
|
154
169
|
if (unattended) {
|
|
155
170
|
const pause = pauseMessage(hit);
|
|
171
|
+
// continue:false is required to end the turn. Without it, bypass mode keeps
|
|
172
|
+
// calling tools and -p result is "Done.", not the pause line (M-26 / Claude Code).
|
|
156
173
|
out.continue = false;
|
|
157
174
|
out.stopReason = `${pause}. Reply "continue" to start a new run, or raise the cap with /meter cap <usd>.`;
|
|
158
175
|
// permissionDecision: deny is what actually blocks the tool in unattended modes.
|
|
@@ -160,7 +177,8 @@ export function onPreToolUse(input, prices = loadPrices()) {
|
|
|
160
177
|
out.hookSpecificOutput.permissionDecision = 'deny';
|
|
161
178
|
out.hookSpecificOutput.permissionDecisionReason = pause;
|
|
162
179
|
out.systemMessage = `${pause}\n${runSummary(t, { cap: caps.usd ?? caps.sessionUsd, capHits: run.capHits })}`;
|
|
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 })
|
|
180
|
+
if (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 }))
|
|
181
|
+
run.logged = true;
|
|
164
182
|
} else {
|
|
165
183
|
run.pendingAsk = input.tool_use_id || 'pending';
|
|
166
184
|
run.pendingAskKind = hit.kind;
|
|
@@ -173,6 +191,7 @@ export function onPreToolUse(input, prices = loadPrices()) {
|
|
|
173
191
|
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.`);
|
|
174
192
|
}
|
|
175
193
|
|
|
194
|
+
if (notice) msgs.push(notice);
|
|
176
195
|
saveSession(s);
|
|
177
196
|
if (ctx.length) out.hookSpecificOutput.additionalContext = ctx.join('\n');
|
|
178
197
|
if (msgs.length) out.systemMessage = (out.systemMessage ? out.systemMessage + '\n\n' : '') + msgs.join('\n\n');
|
|
@@ -243,8 +262,8 @@ export function onPostToolUse(input, prices = loadPrices()) {
|
|
|
243
262
|
/** Stop: end-of-run summary (shown to the user, never blocks). */
|
|
244
263
|
export async function onStop(input, prices = loadPrices(), { settleMs = 300 } = {}) {
|
|
245
264
|
if (settleMs) await new Promise((r) => setTimeout(r, settleMs)); // transcript is written asynchronously
|
|
246
|
-
const cfg = loadConfig(input.cwd);
|
|
247
265
|
const s = loadSession(input.session_id);
|
|
266
|
+
const { cfg, notice } = loadConfigNotices(input.cwd, s);
|
|
248
267
|
const t = refresh(s, input, prices);
|
|
249
268
|
const run = s.run;
|
|
250
269
|
let plan = null;
|
|
@@ -255,11 +274,17 @@ export async function onStop(input, prices = loadPrices(), { settleMs = 300 } =
|
|
|
255
274
|
}
|
|
256
275
|
const caps = effectiveCaps(cfg, run, s);
|
|
257
276
|
const summary = runSummary(t, { cap: caps.usd, capHits: run.capHits, plan });
|
|
258
|
-
|
|
277
|
+
const record = { 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 };
|
|
278
|
+
// /meter and a second Stop after an unattended cap must not record or re-print the receipt (M-23).
|
|
279
|
+
if (run.logged || appendRun(record) === false) {
|
|
280
|
+
saveSession(s);
|
|
281
|
+
return notice ? { systemMessage: notice } : null;
|
|
282
|
+
}
|
|
283
|
+
run.logged = true;
|
|
259
284
|
s.lastRun = { usd: t.usd, tokens: t.tokens, end: Date.now() };
|
|
260
285
|
saveSession(s);
|
|
261
|
-
if (!t.requests) return null;
|
|
262
|
-
return { systemMessage: summary };
|
|
286
|
+
if (!t.requests) return notice ? { systemMessage: notice } : null;
|
|
287
|
+
return { systemMessage: [summary, notice].filter(Boolean).join('\n\n') };
|
|
263
288
|
}
|
|
264
289
|
|
|
265
290
|
/** statusLine command: show the meter, and keep Claude Code's own session cost + rate-limit % for cap checks. */
|
package/src/init.js
CHANGED
|
@@ -40,6 +40,19 @@ export function installRuntime() {
|
|
|
40
40
|
return join(rt, 'bin', 'lake-meter.js');
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
|
|
44
|
+
/** Cap display: $1,000.50 (not $1000.5). */
|
|
45
|
+
function formatCapUsd(n) {
|
|
46
|
+
if (n == null) return 'off';
|
|
47
|
+
const [ints, frac] = Number(n).toFixed(2).split('.');
|
|
48
|
+
return `$${ints.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}.${frac}`;
|
|
49
|
+
}
|
|
50
|
+
function capExample(n) {
|
|
51
|
+
if (n == null) return '10';
|
|
52
|
+
const v = Number(n);
|
|
53
|
+
return Number.isInteger(v) ? String(v) : v.toFixed(2);
|
|
54
|
+
}
|
|
55
|
+
|
|
43
56
|
export function init(opts = {}) {
|
|
44
57
|
const log = opts.log || console.log;
|
|
45
58
|
const node = opts.node || process.execPath;
|
|
@@ -106,7 +119,8 @@ You implement one step of an approved plan. Stay inside the step's scope, follow
|
|
|
106
119
|
log(`✓ Lake Meter installed in ${t.settings}`);
|
|
107
120
|
log(` hooks: UserPromptSubmit, PreToolUse, PostToolUse, Stop · ${statusNote}`);
|
|
108
121
|
log(` /meter skill: ${t.skillDir}${opts.agents !== false ? ` · subagents lake-light (haiku), lake-standard (sonnet) in ${t.agentsDir}` : ''}`);
|
|
109
|
-
|
|
122
|
+
const capVal = opts.capUsd ?? JSON.parse(readFileSync(join(home(), 'config.json'), 'utf8')).capUsd;
|
|
123
|
+
log(` per-run cap: ${formatCapUsd(capVal)} (change with: npx lake-meter cap ${capExample(capVal)})`);
|
|
110
124
|
log(' Restart Claude Code (or open /hooks) to load it. No data leaves your machine.');
|
|
111
125
|
return t;
|
|
112
126
|
}
|
package/src/state.js
CHANGED
|
@@ -164,14 +164,11 @@ export function saveUserConfig(patch, warn = defaultWarn) {
|
|
|
164
164
|
try {
|
|
165
165
|
cur = JSON.parse(readFileSync(p, 'utf8'));
|
|
166
166
|
} catch (err) {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
throw new Error(msg);
|
|
167
|
+
// Throw only (no warn): callers print the message once (M-25).
|
|
168
|
+
throw new Error(`lake-meter: refusing to overwrite unparseable ${p}: ${err.message}. Fix or remove the file, then retry.`);
|
|
170
169
|
}
|
|
171
170
|
if (cur == null || typeof cur !== 'object' || Array.isArray(cur)) {
|
|
172
|
-
|
|
173
|
-
warn(msg);
|
|
174
|
-
throw new Error(msg);
|
|
171
|
+
throw new Error(`lake-meter: refusing to overwrite ${p}: expected a JSON object.`);
|
|
175
172
|
}
|
|
176
173
|
}
|
|
177
174
|
writeJsonAtomic(p, { ...cur, ...patch });
|
|
@@ -204,9 +201,34 @@ export function latestSessionId() {
|
|
|
204
201
|
return best;
|
|
205
202
|
}
|
|
206
203
|
|
|
204
|
+
/** Identity of a recorded run: same session + same run start ⇒ the same run (M-23). */
|
|
205
|
+
export function runKey(record) {
|
|
206
|
+
if (record?.session && record.start) return `${record.session}:${record.start}`;
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Dedupe by session+start so /meter or a later Stop cannot double-count the same run. Returns false if skipped. */
|
|
207
211
|
export function appendRun(record) {
|
|
212
|
+
const key = runKey(record);
|
|
213
|
+
if (key && readRuns().some((r) => runKey(r) === key)) return false;
|
|
208
214
|
mkdirSync(home(), { recursive: true });
|
|
209
215
|
appendFileSync(join(home(), 'runs.jsonl'), JSON.stringify(record) + '\n');
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** First occurrence of each session+start, in file order (the original Stop, not a later /meter recopy). */
|
|
220
|
+
export function uniqueRuns(runs) {
|
|
221
|
+
const seen = new Set();
|
|
222
|
+
const out = [];
|
|
223
|
+
for (const r of runs) {
|
|
224
|
+
const k = runKey(r);
|
|
225
|
+
if (k) {
|
|
226
|
+
if (seen.has(k)) continue;
|
|
227
|
+
seen.add(k);
|
|
228
|
+
}
|
|
229
|
+
out.push(r);
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
210
232
|
}
|
|
211
233
|
|
|
212
234
|
export function readRuns() {
|