@frugalhq/frugal 0.1.1 → 0.2.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.
@@ -4,12 +4,16 @@
4
4
  import * as fs from "node:fs";
5
5
  import * as path from "node:path";
6
6
  import { claudeConfigDir } from "../paths.js";
7
- import { byteLen, capBytes, fmtKB, pruneText } from "../compress.js";
7
+ import { byteLen, capBytes, fmtKB, newStats, pruneText } from "../compress.js";
8
8
  import { putOriginal, pruneStore } from "../cache.js";
9
- import { record } from "../metrics.js";
9
+ import { fetchBackRate, recordSafe } from "../metrics.js";
10
10
  import { redact } from "../redact.js";
11
11
  import { chat, SUMMARIZE_SYSTEM } from "../ollama.js";
12
12
  import { faultPoint, obj, str } from "../io.js";
13
+ import { isPaused } from "../pause.js";
14
+ import { checkRepeat, contentKey } from "../seen.js";
15
+ import { routeText } from "../route.js";
16
+ import { lastUserPrompt } from "../transcript.js";
13
17
  function isTextBlock(b) {
14
18
  const o = obj(b);
15
19
  return !!o && o.type === "text" && typeof o.text === "string";
@@ -70,14 +74,57 @@ export function returnsFileContents(tool) {
70
74
  return /(^|_)(read|get|cat|view|open|show|download)_?(text_|media_|multiple_)?(files?|file_contents?|contents?|blob|source|raw)(_|$)/i.test(name) ||
71
75
  /^(read|cat|view)$/i.test(name);
72
76
  }
73
- function matchRule(cfg, tool) {
77
+ const VERB_WRITE = new Set("create add insert post send reply update edit patch put set delete remove archive move assign transition merge close reopen upload write comment react publish approve reject submit schedule invite cancel rename".split(" "));
78
+ const VERB_READ = new Set("get list search find fetch read query lookup view show describe count browse retrieve export download".split(" "));
79
+ /** Tools that change something (create/update/delete/send …). Their results are confirmations: always exact. */
80
+ export function isWriteTool(tool) {
81
+ const name = tool.split("__").pop() ?? tool;
82
+ const words = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().split(/[^a-z0-9]+/);
83
+ for (const w of words) {
84
+ if (VERB_READ.has(w))
85
+ return false;
86
+ if (VERB_WRITE.has(w))
87
+ return true;
88
+ }
89
+ return false;
90
+ }
91
+ export function matchRule(cfg, tool) {
74
92
  if (cfg.compress.tools[tool])
75
93
  return cfg.compress.tools[tool];
94
+ let best;
76
95
  for (const [pat, rule] of Object.entries(cfg.compress.tools)) {
77
- if (pat.endsWith("*") && tool.startsWith(pat.slice(0, -1)))
78
- return rule;
96
+ if (pat.endsWith("*") && tool.startsWith(pat.slice(0, -1)) && (!best || pat.length > best[0].length))
97
+ best = [pat, rule];
79
98
  }
80
- return undefined;
99
+ return best?.[1];
100
+ }
101
+ /** What the model asked for: the tool's own query fields plus the user's latest prompt. */
102
+ function requestText(input) {
103
+ const parts = [];
104
+ const ti = obj(input.tool_input);
105
+ if (ti)
106
+ for (const [k, v] of Object.entries(ti))
107
+ if (typeof v === "string" && /query|jql|cql|search|text|q$|keywords|question|filter/i.test(k))
108
+ parts.push(v);
109
+ const tp = str(input.transcript_path);
110
+ const p = tp ? lastUserPrompt(tp) : undefined;
111
+ if (p)
112
+ parts.push(p.slice(0, 2000));
113
+ return parts.join("\n");
114
+ }
115
+ const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
116
+ export function footer(bytesIn, bytesOut, st, r, id, extra) {
117
+ const parts = [`compressed ${fmtKB(bytesIn)} → ${fmtKB(bytesOut)} (−${Math.round((1 - bytesOut / bytesIn) * 100)}%)`];
118
+ const removed = [st.fields ? plural(st.fields, "empty/noise field") : "", st.items ? plural(st.items, "empty or extra list item") : ""].filter(Boolean);
119
+ if (removed.length)
120
+ parts.push(`removed ${removed.join(", ")}`);
121
+ if (st.strings)
122
+ parts.push(`shortened prose in ${plural(st.strings, "text")} (ids, links, dates, errors and code kept)`);
123
+ if (r?.headlines)
124
+ parts.push(`all ${r.ranked + r.headlines} items are listed in their original order: the ${r.ranked} most relevant to the request in full, the other ${r.headlines} as headlines that keep their ids, titles, status, people, dates, issue keys and links (only their prose is omitted)`);
125
+ if (r?.summarized)
126
+ parts.push(`${plural(r.summarized, "long item")} summarized locally (facts verified)`);
127
+ return `[frugal: ${parts.join("; ")}.${extra} Full output: call frugal_fetch with id "${id}"]`;
81
128
  }
82
129
  export async function handleToolOutput(input, cfg) {
83
130
  const started = Date.now();
@@ -86,40 +133,82 @@ export async function handleToolOutput(input, cfg) {
86
133
  return undefined;
87
134
  if (tool.endsWith("__frugal_fetch"))
88
135
  return undefined; // never compress our own escape hatch
89
- if (returnsFileContents(tool))
90
- return undefined; // Claude may copy exact text from these into edits
91
- const rule = matchRule(cfg, tool);
92
- if (rule?.skip)
136
+ let bytesIn = 0;
137
+ const leave = (outcome, bytesOut) => {
138
+ recordSafe({ ts: Date.now(), kind: "seen", outcome, tool, bytesIn, bytesOut: bytesOut ?? bytesIn, durationMs: Date.now() - started });
93
139
  return undefined;
140
+ };
94
141
  let resp = input.tool_response ?? input.tool_result;
95
142
  // Oversized results: Claude Code saves them to a file first and hands the hook a pointer.
96
143
  const spilled = typeof resp === "string" ? readSpilledOutput(resp, input) : undefined;
97
144
  if (spilled !== undefined)
98
145
  resp = spilled;
99
146
  const u = unpack(resp);
100
- if (!u)
101
- return undefined;
102
- const texts = u.blocks.filter(isTextBlock).map((b) => b.text);
103
- if (texts.length === 0)
104
- return undefined;
147
+ const texts = u ? u.blocks.filter(isTextBlock).map((b) => b.text) : [];
105
148
  const original = texts.join("\n");
106
- const bytesIn = byteLen(original);
149
+ bytesIn = byteLen(original);
150
+ if (isPaused())
151
+ return leave("paused");
152
+ if (isWriteTool(tool))
153
+ return leave("write");
154
+ if (returnsFileContents(tool))
155
+ return leave("file"); // Claude may copy exact text from these into edits
156
+ const rule = matchRule(cfg, tool);
157
+ if (rule?.skip)
158
+ return leave("rule-skip");
159
+ if (!u || texts.length === 0)
160
+ return leave("not-text");
107
161
  if (bytesIn <= cfg.compress.minBytes)
108
- return undefined;
162
+ return leave("small");
109
163
  faultPoint("compress");
110
164
  const safeOriginal = redact(original);
165
+ const rebuildWith = (text) => {
166
+ // Single text block replaces all original text blocks (in the position of the first one).
167
+ const out = [];
168
+ let placed = false;
169
+ for (const b of u.blocks) {
170
+ if (isTextBlock(b)) {
171
+ if (!placed)
172
+ out.push({ type: "text", text });
173
+ placed = true;
174
+ }
175
+ else
176
+ out.push(b);
177
+ }
178
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", updatedMCPToolOutput: u.rebuild(out) } });
179
+ };
180
+ // ---- identical result already in context this session: pointer instead of a second copy ----
181
+ if (cfg.compress.dedupe) {
182
+ const prev = checkRepeat("mcp", str(input.session_id), str(input.transcript_path), contentKey(tool, original), tool, cfg.bash.maxAgeMinutes * 60_000);
183
+ if (prev) {
184
+ const id = putOriginal(tool, safeOriginal);
185
+ const stub = `[frugal: identical to an earlier ${tool.split("__").pop()} result in this session (${fmtKB(bytesIn)}), which is still above in context; refer to it. Full output: call frugal_fetch with id "${id}"]`;
186
+ recordSafe({ ts: Date.now(), kind: "compress", outcome: "repeat", tool, bytesIn, bytesOut: byteLen(stub), durationMs: Date.now() - started });
187
+ return rebuildWith(stub);
188
+ }
189
+ }
190
+ // Round-trip budget: if the model keeps fetching this tool's full output back, the lossy rule
191
+ // costs more than it saves. Fall back to lossless pruning for it (and say so in the footer).
192
+ let relaxed = false;
193
+ if (rule && (rule.itemMaxChars || rule.maxItems || rule.route)) {
194
+ const fb = fetchBackRate(tool, Date.now() - 7 * 86400_000);
195
+ relaxed = fb.changed >= 5 && fb.fetched / fb.changed > 0.3;
196
+ }
197
+ const lossy = relaxed ? undefined : rule;
198
+ const stats = newStats();
111
199
  const opts = {
112
200
  maxBytes: cfg.compress.maxBytes,
113
- maxArrayItems: cfg.compress.maxArrayItems,
201
+ maxArrayItems: lossy?.maxItems ?? cfg.compress.maxArrayItems,
114
202
  denyKeys: cfg.compress.denyKeys,
115
- keepFields: rule?.keepFields
203
+ keepFields: rule?.keepFields,
204
+ itemMaxChars: lossy?.itemMaxChars ?? 0
116
205
  };
117
206
  // Compress each text block, preserving non-text blocks (images etc.) as-is.
118
- const textOf = (o2) => u.blocks
207
+ const textOf = (o2, st) => u.blocks
119
208
  .filter(isTextBlock)
120
- .map((b) => pruneText(redact(b.text), o2))
209
+ .map((b) => pruneText(redact(b.text), { ...o2, stats: st }))
121
210
  .join("\n");
122
- let joined = textOf(opts);
211
+ let joined = textOf(opts, stats);
123
212
  if (cfg.compress.summarize && cfg.compress.maxBytes > 0) {
124
213
  // Summarize when pruning alone (before fitting to size) cannot get under maxBytes.
125
214
  const full = textOf({ ...opts, maxBytes: Number.MAX_SAFE_INTEGER });
@@ -129,40 +218,51 @@ export async function handleToolOutput(input, cfg) {
129
218
  joined = s;
130
219
  }
131
220
  }
221
+ // ---- local-model routing (opt-in per tool) ----
222
+ let routed;
223
+ if (lossy?.route && cfg.ollama.enabled) {
224
+ const r = await routeText(joined, lossy.route, redact(requestText(input)), cfg, started + cfg.routing.budgetMs);
225
+ if (r) {
226
+ joined = r.text;
227
+ routed = r.stats;
228
+ }
229
+ }
132
230
  const finalText = capBytes(joined, cfg.compress.maxBytes);
133
231
  const bytesOut = byteLen(finalText);
134
232
  // Never inline more than Claude Code itself would: if a spilled result is still over the
135
233
  // MCP output limit after cleanup, keep Claude Code's file pointer instead.
136
234
  if (spilled !== undefined && bytesOut / 3.5 > mcpOutputTokenLimit())
137
- return undefined;
138
- if (bytesOut >= bytesIn * 0.9)
139
- return undefined; // not worth it; leave untouched
235
+ return leave("over-limit", bytesOut);
236
+ const saved = bytesIn - bytesOut - 260; // the footer costs bytes too
237
+ const worth = saved > 0 && (saved >= (bytesIn * cfg.compress.minSavingPct) / 100 || saved >= cfg.compress.minSavingBytes);
238
+ if (!worth)
239
+ return leave("low-gain", bytesOut); // not worth it; leave untouched
140
240
  const id = putOriginal(tool, safeOriginal);
141
- const shortened = /…\d+ more"|…\[\+\d+ chars\]|…\[frugal: truncated\]/.test(finalText);
241
+ const shortened = stats.strings > 0 || /…\d+ more"|…\[\+\d+ chars\]|…\[frugal: truncated\]/.test(finalText);
142
242
  const tagCount = (t) => (t.match(/<\/?[a-z][a-z0-9:-]*[\s>/]/gi) ?? []).length;
143
243
  const htmlConverted = tagCount(original) >= 10 && tagCount(finalText) < tagCount(original) / 2;
144
- const note = `[frugal: compressed ${fmtKB(bytesIn)} → ${fmtKB(bytesOut)}.${shortened ? " Some lists/strings are shortened (marked …); if you need every item or full text," : ""}${htmlConverted ? " HTML was converted to text; before editing or re-saving this content, fetch the original markup." : ""} Full output: call frugal_fetch with id "${id}"]`;
145
- // Single text block replaces all original text blocks (in the position of the first one).
146
- const out = [];
147
- let placed = false;
148
- for (const b of u.blocks) {
149
- if (isTextBlock(b)) {
150
- if (!placed)
151
- out.push({ type: "text", text: `${finalText}\n${note}` });
152
- placed = true;
153
- }
154
- else
155
- out.push(b);
156
- }
244
+ const extra = `${relaxed ? " (This tool's lossy rule is paused: its output was fetched back over 30% of the time this week.)" : ""}${shortened ? " Some content is shortened (marked …); if you need every item or the full text," : ""}${routed && !shortened ? " Fetch the original only if you need the full prose of a headline item." : ""}${htmlConverted ? " HTML was converted to text; before editing or re-saving this content, fetch the original markup." : ""}`;
245
+ const note = footer(bytesIn, bytesOut, stats, routed, id, extra);
246
+ const outcome = routed?.summarized ? "summarized" : routed?.headlines ? "ranked" : shortened ? "capped" : "lossless";
247
+ recordSafe({
248
+ ts: Date.now(),
249
+ kind: "compress",
250
+ outcome,
251
+ tool,
252
+ bytesIn,
253
+ bytesOut,
254
+ durationMs: Date.now() - started,
255
+ fields: stats.fields,
256
+ items: stats.items,
257
+ strings: stats.strings,
258
+ localMs: routed?.localMs
259
+ });
157
260
  try {
158
- record({ ts: Date.now(), kind: "compress", tool, bytesIn, bytesOut, durationMs: Date.now() - started });
159
261
  if (Math.random() < 0.05)
160
262
  pruneStore(cfg.cache.ttlHours, cfg.cache.maxMB);
161
263
  }
162
264
  catch {
163
- // metrics are best-effort
265
+ // best-effort
164
266
  }
165
- return JSON.stringify({
166
- hookSpecificOutput: { hookEventName: "PostToolUse", updatedMCPToolOutput: u.rebuild(out) }
167
- });
267
+ return rebuildWith(`${finalText}\n${note}`);
168
268
  }
package/dist/init.js CHANGED
@@ -6,6 +6,8 @@ import * as path from "node:path";
6
6
  import { claudeConfigDir, configPath } from "./paths.js";
7
7
  const TOOL_CMD = "frugal hook tool-output";
8
8
  const PROMPT_CMD = "frugal hook prompt";
9
+ const COMPACT_CMD = "frugal hook pre-compact";
10
+ const START_CMD = "frugal hook session-start";
9
11
  const STATUS_CMD = "frugal statusline";
10
12
  export const CHAIN = "sh -c 'in=$(cat); a=$(printf %s \"$in\" | YOUR_EXISTING_COMMAND); b=$(printf %s \"$in\" | frugal statusline); printf \"%s %s\\n\" \"$a\" \"$b\"'";
11
13
  /** POSIX single-quote a string for a shell command line. */
@@ -46,6 +48,8 @@ export function mergeSettings(input) {
46
48
  };
47
49
  addHook("PostToolUse", { matcher: "mcp__.*|Bash", hooks: [{ type: "command", command: TOOL_CMD, timeout: 30 }] }, TOOL_CMD, "PostToolUse hook (shrinks MCP and Bash output)");
48
50
  addHook("UserPromptSubmit", { hooks: [{ type: "command", command: PROMPT_CMD, timeout: 5 }] }, PROMPT_CMD, "UserPromptSubmit hook (drift and context warnings)");
51
+ addHook("PreCompact", { hooks: [{ type: "command", command: COMPACT_CMD, timeout: 30 }] }, COMPACT_CMD, "PreCompact hook (keeps key facts through compaction)");
52
+ addHook("SessionStart", { matcher: "compact", hooks: [{ type: "command", command: START_CMD, timeout: 5 }] }, START_CMD, "SessionStart hook (restores saved facts after compaction, if you turn it on)");
49
53
  const sl = s.statusLine;
50
54
  const cur = typeof sl?.command === "string" ? sl.command.trim() : "";
51
55
  if (!cur) {
package/dist/local.js ADDED
@@ -0,0 +1,86 @@
1
+ // `frugal setup-local`: get the local models ready and measure them on this machine.
2
+ // Talks only to the local Ollama daemon (loopback). Pulling a model makes the daemon download it;
3
+ // that only happens with --yes.
4
+ import * as os from "node:os";
5
+ import { loopbackFetch } from "./net.js";
6
+ import { chat, embed, ollamaAvailable } from "./ollama.js";
7
+ import { verifySummary } from "./route.js";
8
+ const SAMPLE = "PROJ-4821 Checkout fails for EU cards. Opened 2026-11-30 by the payments team. Customers using cards issued in the EU see a generic error at the last step of checkout. The logs show HTTP 502 from the card gateway in 18% of attempts since release 4.12.0, starting right after the deploy. The team suspects the new 3-D Secure redirect, which was rolled out to all EU traffic at once instead of gradually. A rollback was discussed but rejected because it also removes the fraud-rule fix that went out in the same release. Next step agreed: put the redirect behind a feature flag and roll it out to 5% of traffic. Details: http://localhost:8080/browse/PROJ-4821";
9
+ async function timed(f) {
10
+ const t = Date.now();
11
+ const v = await f();
12
+ return { v, ms: Date.now() - t };
13
+ }
14
+ async function pull(cfg, model) {
15
+ try {
16
+ const r = await loopbackFetch(`${cfg.ollama.url.replace(/\/+$/, "")}/api/pull`, {
17
+ method: "POST",
18
+ headers: { "content-type": "application/json" },
19
+ body: JSON.stringify({ model, stream: false }),
20
+ timeoutMs: 60 * 60_000
21
+ });
22
+ return r.ok;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ export async function setupLocal(cfg, yes, log) {
29
+ if (!cfg.ollama.enabled) {
30
+ log("ollama.enabled is false in your frugal config: local models are off. Set it to true to use them.");
31
+ return 1;
32
+ }
33
+ const memGB = os.totalmem() / 1024 ** 3;
34
+ const chatOk = memGB >= 12;
35
+ log(`Memory: ${memGB.toFixed(0)} GB. ${chatOk ? "Enough for embeddings and a ~4B chat model." : "Under 12 GB: embeddings only is recommended (leave route at \"rank\")."}`);
36
+ const t = await ollamaAvailable(cfg, 1500);
37
+ if (!t.ok) {
38
+ log(`Ollama is not reachable at ${cfg.ollama.url}. Install it from the Ollama website, start it (\`ollama serve\`), then run this again.`);
39
+ return 1;
40
+ }
41
+ const have = (m) => t.models.some((x) => x === m || x === `${m}:latest`);
42
+ // Already have a small local chat model? Use it instead of downloading the default.
43
+ const local = t.models.filter((m) => !t.remote.includes(m));
44
+ const altChat = !have(cfg.ollama.chatModel) ? local.find((m) => /qwen|llama|gemma|phi|mistral/i.test(m) && /(^|[:-])(\d+(\.\d+)?)b\b/i.test(m) && Number(/(\d+(?:\.\d+)?)b\b/i.exec(m)[1]) <= 14) : undefined;
45
+ if (altChat) {
46
+ log(`Using ${altChat}, which you already have, for summaries (set ollama.chatModel to "${altChat}" to keep it).`);
47
+ cfg = { ...cfg, ollama: { ...cfg.ollama, chatModel: altChat } };
48
+ }
49
+ const want = [cfg.ollama.embedModel, ...(chatOk ? [cfg.ollama.chatModel] : [])];
50
+ const missing = want.filter((m) => !have(m));
51
+ if (missing.length) {
52
+ if (!yes) {
53
+ log(`Missing models: ${missing.join(", ")}. Run \`frugal setup-local --yes\` to have Ollama download them (several GB), or \`ollama pull <model>\` yourself.`);
54
+ return 1;
55
+ }
56
+ for (const m of missing) {
57
+ log(`Pulling ${m} through your local Ollama (this can take a while)…`);
58
+ if (!(await pull(cfg, m))) {
59
+ log(`Could not pull ${m}. Try \`ollama pull ${m}\`.`);
60
+ return 1;
61
+ }
62
+ }
63
+ }
64
+ log("", "Self-test (timings on this machine):");
65
+ const e1 = await timed(() => embed(cfg, ["warm up"], 60_000));
66
+ const e2 = await timed(() => embed(cfg, Array.from({ length: 20 }, (_, i) => `${SAMPLE} ${i}`), 30_000));
67
+ if (!e1.v || !e2.v) {
68
+ log(`- embeddings (${cfg.ollama.embedModel}): FAILED`);
69
+ return 1;
70
+ }
71
+ log(`- embeddings: first call ${(e1.ms / 1000).toFixed(1)}s (loads the model), 20 items ${(e2.ms / 1000).toFixed(1)}s`);
72
+ let summaryMs;
73
+ if (chatOk) {
74
+ await timed(() => chat(cfg, "Reply with OK.", "ping", 120_000));
75
+ const s = await timed(() => chat(cfg, "Write 3 short bullets. Copy every identifier, number, date and URL exactly. No preamble.", SAMPLE, 60_000));
76
+ if (!s.v)
77
+ log(`- summary (${cfg.ollama.chatModel}): FAILED`);
78
+ else {
79
+ summaryMs = s.ms;
80
+ log(`- summary: ${(s.ms / 1000).toFixed(1)}s per long item; fact check ${verifySummary(SAMPLE, s.v) ? "passed" : "failed (frugal would keep the original)"}`);
81
+ }
82
+ }
83
+ const route = summaryMs !== undefined && summaryMs < 6000 ? "both" : "rank";
84
+ log("", "Ready. The measured win is per-item caps on chat search (no local model needed):", JSON.stringify({ ...(altChat ? { ollama: { chatModel: altChat } } : {}), compress: { tools: { "mcp__slack__*": { itemMaxChars: 400 } } } }, null, 2), `Experimental: add "route": "${route}" to a tool where you usually ask about a few items, then watch its fetch-back rate in \`frugal report\`.`, route === "rank" ? "(Summaries look slow here, so ranking only is suggested.)" : "", "Try a rule on a saved result first: frugal explain result.json --local --query \"what you asked\"");
85
+ return 0;
86
+ }
package/dist/mcpServer.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import * as readline from "node:readline";
4
4
  import { getOriginal, sliceText } from "./cache.js";
5
5
  import { VERSION } from "./version.js";
6
+ import { recordSafe } from "./metrics.js";
6
7
  const SUPPORTED = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
7
8
  const PAGE = 50_000;
8
9
  export const FETCH_TOOL = {
@@ -53,6 +54,9 @@ export function handleRpc(req) {
53
54
  content: [{ type: "text", text: `frugal: no cached output for id "${id}" (expired, purged, or wrong id).` }]
54
55
  });
55
56
  }
57
+ // Fetch-back rate per tool: saved tokens that get re-read are not savings.
58
+ if (offset === 0)
59
+ recordSafe({ ts: Date.now(), kind: "fetch", tool: entry.tool, bytesOut: entry.text.length });
56
60
  const { chunk, next, total } = sliceText(entry.text, offset, limit);
57
61
  const tail = next !== undefined ? `\n[frugal: showing ${offset}-${next} of ${total} chars; call frugal_fetch with offset ${next} for more]` : "";
58
62
  return reply({ content: [{ type: "text", text: chunk + tail }] });
package/dist/metrics.js CHANGED
@@ -1,7 +1,24 @@
1
1
  // Append-only numeric metrics (spec §6). Never records prompt or tool content.
2
2
  import * as fs from "node:fs";
3
3
  import { appendPrivateFile, dataPath, readPrivateFile } from "./paths.js";
4
- const ALLOWED = new Set(["ts", "kind", "tool", "session", "bytesIn", "bytesOut", "tokens", "costUsd", "durationMs"]);
4
+ export const OUTCOMES = [
5
+ "lossless", // pruned noise only
6
+ "capped", // opt-in per-item caps / size fit
7
+ "ranked", // local relevance ranking (opt-in)
8
+ "summarized", // local summaries, verified (opt-in)
9
+ "repeat", // identical to an earlier result still in context
10
+ "small", // under minBytes
11
+ "low-gain", // saving under the threshold
12
+ "write", // result of a create/update/delete-style tool: always exact
13
+ "file", // file contents: always exact
14
+ "rule-skip", // config says skip
15
+ "paused", // frugal pause
16
+ "over-limit", // still above Claude Code's MCP limit after cleanup
17
+ "not-text" // no text blocks
18
+ ];
19
+ const ALLOWED = new Set(["ts", "kind", "outcome", "tool", "session", "bytesIn", "bytesOut", "tokens", "costUsd", "durationMs", "fields", "items", "strings", "localMs"]);
20
+ const KINDS = new Set(["compress", "cost", "seen", "fetch"]);
21
+ const OUTCOME_SET = new Set(OUTCOMES);
5
22
  const SAFE_NAME = /^[A-Za-z0-9_.:@\-/]{1,200}$/;
6
23
  export function metricsFile() {
7
24
  return dataPath("metrics.jsonl");
@@ -13,12 +30,25 @@ export function record(ev) {
13
30
  continue;
14
31
  if ((k === "tool" || k === "session") && (typeof v !== "string" || !SAFE_NAME.test(v)))
15
32
  continue;
16
- if (k !== "kind" && k !== "tool" && k !== "session" && (typeof v !== "number" || !Number.isFinite(v)))
33
+ if (k === "kind" && !KINDS.has(v))
34
+ continue;
35
+ if (k === "outcome" && !OUTCOME_SET.has(v))
36
+ continue;
37
+ if (k !== "kind" && k !== "outcome" && k !== "tool" && k !== "session" && (typeof v !== "number" || !Number.isFinite(v)))
17
38
  continue;
18
39
  clean[k] = v;
19
40
  }
20
41
  appendPrivateFile(metricsFile(), JSON.stringify(clean) + "\n");
21
42
  }
43
+ /** record() that never throws: metrics are best-effort and must not change hook behaviour. */
44
+ export function recordSafe(ev) {
45
+ try {
46
+ record(ev);
47
+ }
48
+ catch {
49
+ // best-effort
50
+ }
51
+ }
22
52
  export function readMetrics(sinceTs = 0) {
23
53
  let text;
24
54
  try {
@@ -44,6 +74,45 @@ export function readMetrics(sinceTs = 0) {
44
74
  }
45
75
  return out;
46
76
  }
77
+ /** Recent compress/fetch counts for one tool, from the tail of the metrics file (cheap enough for a hook). */
78
+ export function fetchBackRate(tool, sinceTs, tailBytes = 512 * 1024) {
79
+ let text;
80
+ try {
81
+ const fd = fs.openSync(metricsFile(), "r");
82
+ try {
83
+ const size = fs.fstatSync(fd).size;
84
+ const start = Math.max(0, size - tailBytes);
85
+ const buf = Buffer.alloc(size - start);
86
+ fs.readSync(fd, buf, 0, buf.length, start);
87
+ text = buf.toString("utf8");
88
+ }
89
+ finally {
90
+ fs.closeSync(fd);
91
+ }
92
+ }
93
+ catch {
94
+ return { changed: 0, fetched: 0 };
95
+ }
96
+ let changed = 0;
97
+ let fetched = 0;
98
+ for (const line of text.split("\n")) {
99
+ if (!line.includes(tool))
100
+ continue;
101
+ try {
102
+ const e = JSON.parse(line);
103
+ if (e.tool !== tool || e.ts < sinceTs)
104
+ continue;
105
+ if (e.kind === "compress" && e.outcome !== "lossless" && e.outcome !== "repeat")
106
+ changed++;
107
+ else if (e.kind === "fetch")
108
+ fetched++;
109
+ }
110
+ catch {
111
+ // partial first line
112
+ }
113
+ }
114
+ return { changed, fetched };
115
+ }
47
116
  export function metricsSize() {
48
117
  try {
49
118
  return fs.statSync(metricsFile()).size;
package/dist/pause.js ADDED
@@ -0,0 +1,33 @@
1
+ // `frugal pause` / `frugal resume`: turn frugal's hooks into no-ops without editing any settings.
2
+ // The flag lives in frugal's own data dir.
3
+ import * as fs from "node:fs";
4
+ import { dataPath, readPrivateJson, writePrivateFile } from "./paths.js";
5
+ function flagFile() {
6
+ return dataPath("paused.json");
7
+ }
8
+ export function pausedUntil(now = Date.now()) {
9
+ let f;
10
+ try {
11
+ f = readPrivateJson(flagFile());
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ if (!f || f.v !== 1 || typeof f.until !== "number")
17
+ return undefined;
18
+ if (f.until !== 0 && f.until <= now)
19
+ return undefined;
20
+ return f.until;
21
+ }
22
+ export function isPaused(now = Date.now()) {
23
+ return pausedUntil(now) !== undefined;
24
+ }
25
+ export function pause(minutes, now = Date.now()) {
26
+ const until = minutes && minutes > 0 ? now + minutes * 60_000 : 0;
27
+ writePrivateFile(flagFile(), JSON.stringify({ v: 1, until }));
28
+ return until ? `frugal paused until ${new Date(until).toLocaleTimeString()}. Tool output is passed through unchanged.` : "frugal paused. Tool output is passed through unchanged. Run `frugal resume` to turn it back on.";
29
+ }
30
+ export function resume() {
31
+ fs.rmSync(flagFile(), { force: true });
32
+ return "frugal resumed.";
33
+ }
package/dist/report.js CHANGED
@@ -6,6 +6,51 @@ function table(rows) {
6
6
  const w = rows[0].map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length)));
7
7
  return rows.map((r) => r.map((c, i) => (i === 0 ? c.padEnd(w[i]) : c.padStart(w[i]))).join(" ")).join("\n");
8
8
  }
9
+ /** Older versions logged Bash as "Bash.repeat" / "Bash.clean". */
10
+ function toolName(e) {
11
+ return (e.tool ?? "?").replace(/^Bash\.(repeat|clean)$/, "Bash");
12
+ }
13
+ export function toolRows(events) {
14
+ const per = new Map();
15
+ const get = (t) => {
16
+ let r = per.get(t);
17
+ if (!r)
18
+ per.set(t, (r = { calls: 0, changed: 0, inB: 0, outB: 0, fetched: 0, skipped: new Map(), changedIn: 0 }));
19
+ return r;
20
+ };
21
+ for (const e of events) {
22
+ if (!e.tool)
23
+ continue;
24
+ const r = get(toolName(e));
25
+ if (e.kind === "fetch")
26
+ r.fetched++;
27
+ else if (e.kind === "compress") {
28
+ r.calls++;
29
+ r.changed++;
30
+ r.inB += e.bytesIn ?? 0;
31
+ r.outB += e.bytesOut ?? 0;
32
+ r.changedIn += e.bytesIn ?? 0;
33
+ }
34
+ else if (e.kind === "seen") {
35
+ r.calls++;
36
+ r.inB += e.bytesIn ?? 0;
37
+ r.outB += e.bytesIn ?? 0; // left alone: the model saw every byte
38
+ const why = e.outcome ?? "other";
39
+ r.skipped.set(why, (r.skipped.get(why) ?? 0) + 1);
40
+ }
41
+ }
42
+ return per;
43
+ }
44
+ const WHY = {
45
+ "low-gain": "saving under threshold",
46
+ small: "small",
47
+ write: "write result (kept exact)",
48
+ file: "file contents (kept exact)",
49
+ "rule-skip": "skipped by config",
50
+ paused: "paused",
51
+ "over-limit": "over Claude Code's limit",
52
+ "not-text": "no text"
53
+ };
9
54
  export function report(cfg, days, now = Date.now()) {
10
55
  const out = [];
11
56
  const ledger = loadLedger();
@@ -21,32 +66,32 @@ export function report(cfg, days, now = Date.now()) {
21
66
  }
22
67
  out.push(`Spend, last ${days} days (${cfg.currency})`);
23
68
  out.push(rows.length > 1 ? table([...rows, ["total", money(total)]]) : "(no spend recorded yet)");
24
- const since = now - days * 86400_000;
25
- const per = new Map();
26
- for (const e of readMetrics(since)) {
27
- if (e.kind !== "compress" || !e.tool)
28
- continue;
29
- const t = per.get(e.tool) ?? { calls: 0, inB: 0, outB: 0 };
30
- t.calls++;
31
- t.inB += e.bytesIn ?? 0;
32
- t.outB += e.bytesOut ?? 0;
33
- per.set(e.tool, t);
69
+ const per = toolRows(readMetrics(now - days * 86400_000));
70
+ out.push("", "Tool output (every MCP and Bash call frugal saw)");
71
+ if (per.size === 0) {
72
+ out.push("(no tool calls seen yet; is the PostToolUse hook installed? run `frugal doctor`)");
73
+ return out.join("\n");
34
74
  }
35
- out.push("", "MCP output compression");
36
- if (per.size === 0)
37
- out.push("(no compressed tool calls yet)");
38
- else {
39
- const r = [["tool", "calls", "in", "out", "saved"]];
40
- let ti = 0;
41
- let to = 0;
42
- for (const [tool, t] of [...per.entries()].sort((a, b) => b[1].inB - b[1].outB - (a[1].inB - a[1].outB))) {
43
- ti += t.inB;
44
- to += t.outB;
45
- r.push([tool, String(t.calls), fmtKB(t.inB), fmtKB(t.outB), `${Math.round((1 - t.outB / t.inB) * 100)}%`]);
46
- }
47
- r.push(["total", "", fmtKB(ti), fmtKB(to), `${Math.round((1 - to / ti) * 100)}%`]);
48
- out.push(table(r));
49
- out.push(`≈ ${Math.round((ti - to) / 4).toLocaleString("en-US")} tokens kept out of context (bytes/4 estimate)`);
75
+ const r = [["tool", "calls", "changed", "in", "out", "saved", "fetched back", "left alone (why)"]];
76
+ let ti = 0;
77
+ let to = 0;
78
+ let fetchedTotal = 0;
79
+ let changedTotal = 0;
80
+ const sorted = [...per.entries()].sort((a, b) => b[1].inB - b[1].outB - (a[1].inB - a[1].outB) || b[1].inB - a[1].inB);
81
+ for (const [tool, t] of sorted) {
82
+ ti += t.inB;
83
+ to += t.outB;
84
+ fetchedTotal += t.fetched;
85
+ changedTotal += t.changed;
86
+ const why = [...t.skipped.entries()].sort((a, b) => b[1] - a[1]).map(([k, n]) => `${n} ${WHY[k] ?? k}`).join(", ");
87
+ const fb = t.changed ? `${t.fetched} (${Math.round((t.fetched / t.changed) * 100)}%)` : t.fetched ? String(t.fetched) : "";
88
+ r.push([tool, String(t.calls), String(t.changed), fmtKB(t.inB), fmtKB(t.outB), t.inB ? `${Math.round((1 - t.outB / t.inB) * 100)}%` : "", fb, why]);
50
89
  }
90
+ r.push(["total", "", String(changedTotal), fmtKB(ti), fmtKB(to), ti ? `${Math.round((1 - to / ti) * 100)}%` : "", String(fetchedTotal), ""]);
91
+ out.push(table(r));
92
+ out.push(`≈ ${Math.round((ti - to) / 4).toLocaleString("en-US")} tokens kept out of context (bytes/4 estimate; real token counts vary by content)`);
93
+ const noisy = sorted.filter(([, t]) => t.changed >= 5 && t.fetched / t.changed > 0.3).map(([k]) => k);
94
+ if (noisy.length)
95
+ out.push(`! fetched back more than 30% of the time: ${noisy.join(", ")}. Those savings are partly re-spent; consider a lighter rule for them (frugal explain).`);
51
96
  return out.join("\n");
52
97
  }