@frugalhq/frugal 0.0.0 → 0.1.1

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.
@@ -0,0 +1,166 @@
1
+ // PostToolUse for Claude Code's Bash tool. Two lossless steps, never on file contents' text:
2
+ // 1. Repeat-skip: if this exact output was already shown earlier in the session (and is still in
3
+ // context), replace it with a short pointer to that earlier result.
4
+ // 2. Light cleanup (not for file-reading commands): apply carriage-return overwrites the way a
5
+ // terminal would, strip ANSI codes and trailing spaces, fold runs of identical lines.
6
+ // Observed tool_response shape (Claude Code 2.1.x): {stdout, stderr, interrupted, isImage, noOutputExpected}.
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import { createHash } from "node:crypto";
10
+ import { byteLen, fmtKB } from "../compress.js";
11
+ import { dataPath, readPrivateJson, writePrivateFile } from "../paths.js";
12
+ import { redact } from "../redact.js";
13
+ import { record } from "../metrics.js";
14
+ import { faultPoint, obj, str } from "../io.js";
15
+ const SESSION_RE = /^[A-Za-z0-9_-]{1,128}$/;
16
+ const MAX_SEEN = 300;
17
+ // Commands whose output is file content Claude may copy into an edit: never rewrite their text.
18
+ const FILE_READERS = new Set(["cat", "bat", "sed", "awk", "head", "tail", "nl", "less", "more", "xxd", "od", "strings", "tac", "cut"]);
19
+ /** First real program in a command line, skipping `cd x &&`, env assignments, sudo/time/env. */
20
+ export function mainProgram(cmd) {
21
+ let rest = cmd.trim();
22
+ // drop leading `cd ... &&` / `cd ...;` segments
23
+ for (;;) {
24
+ const m = /^cd\s+(?:"[^"]*"|'[^']*'|[^;&|]+?)\s*(?:&&|;)\s*/.exec(rest);
25
+ if (!m)
26
+ break;
27
+ rest = rest.slice(m[0].length);
28
+ }
29
+ const words = rest.split(/\s+/).filter(Boolean);
30
+ let i = 0;
31
+ while (i < words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || ["sudo", "time", "env", "nice", "command"].includes(words[i])))
32
+ i++;
33
+ return path.basename(words[i] ?? "");
34
+ }
35
+ export function isFileRead(cmd) {
36
+ const prog = mainProgram(cmd);
37
+ if (FILE_READERS.has(prog))
38
+ return true;
39
+ // git show <rev>:<path> prints a file verbatim
40
+ return prog === "git" && /\bgit\s+show\s+\S*:\S+/.test(cmd);
41
+ }
42
+ /** What a terminal would display: each \r returns to line start, later text overwrites earlier. */
43
+ function applyCarriageReturns(line) {
44
+ if (!line.includes("\r"))
45
+ return line;
46
+ const parts = line.split("\r");
47
+ let shown = "";
48
+ for (const p of parts)
49
+ shown = p + shown.slice(p.length);
50
+ return shown;
51
+ }
52
+ // eslint-disable-next-line no-control-regex -- matching ANSI escapes is the point
53
+ const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[()][A-Za-z0-9]/g;
54
+ export function cleanTerminalText(text) {
55
+ const lines = text.replace(/\r\n/g, "\n").split("\n").map((l) => applyCarriageReturns(l).replace(ANSI, "").replace(/[ \t]+$/, ""));
56
+ const out = [];
57
+ for (let i = 0; i < lines.length;) {
58
+ let j = i + 1;
59
+ while (j < lines.length && lines[j] === lines[i])
60
+ j++;
61
+ const run = j - i;
62
+ out.push(lines[i]);
63
+ if (run >= 3 && lines[i] !== "")
64
+ out.push(`[frugal: previous line repeated ${run - 1} more times]`);
65
+ else
66
+ for (let k = 1; k < run; k++)
67
+ out.push(lines[i]);
68
+ i = j;
69
+ }
70
+ return out.join("\n");
71
+ }
72
+ const CLEARED_MARKERS = ["compact_boundary", "Old tool result content cleared"];
73
+ /** Was the transcript compacted, or were old tool results cleared, after byte offset `at`? */
74
+ function contextChangedSince(transcript, at) {
75
+ if (!transcript)
76
+ return true;
77
+ let fd;
78
+ try {
79
+ fd = fs.openSync(transcript, "r");
80
+ }
81
+ catch {
82
+ return true;
83
+ }
84
+ try {
85
+ const size = fs.fstatSync(fd).size;
86
+ if (size < at)
87
+ return true; // rewritten
88
+ const len = Math.min(size - at, 64 * 1024 * 1024);
89
+ const buf = Buffer.alloc(len);
90
+ fs.readSync(fd, buf, 0, len, at);
91
+ const s = buf.toString("utf8");
92
+ return CLEARED_MARKERS.some((m) => s.includes(m));
93
+ }
94
+ finally {
95
+ fs.closeSync(fd);
96
+ }
97
+ }
98
+ function transcriptSize(transcript) {
99
+ try {
100
+ return transcript ? fs.statSync(transcript).size : 0;
101
+ }
102
+ catch {
103
+ return 0;
104
+ }
105
+ }
106
+ export async function handleBashOutput(input, cfg, now = Date.now()) {
107
+ if (!cfg.bash.enabled)
108
+ return undefined;
109
+ const resp = obj(input.tool_response);
110
+ const stdout = str(resp?.stdout);
111
+ if (!resp || stdout === undefined)
112
+ return undefined;
113
+ const stderr = str(resp.stderr) ?? "";
114
+ if (resp.isImage === true)
115
+ return undefined;
116
+ const bytesIn = byteLen(stdout) + byteLen(stderr);
117
+ if (bytesIn < cfg.bash.minBytes)
118
+ return undefined;
119
+ faultPoint("bash");
120
+ const cmd = str(obj(input.tool_input)?.command) ?? "";
121
+ const session = str(input.session_id);
122
+ const transcript = str(input.transcript_path);
123
+ const started = Date.now();
124
+ // ---- 1. repeat-skip ----
125
+ if (cfg.bash.dedupe && session && SESSION_RE.test(session)) {
126
+ const file = path.join(dataPath("sessions"), `${session}.bash.json`);
127
+ const st = readPrivateJson(file);
128
+ const state = st && st.v === 1 && typeof st.seen === "object" ? st : { v: 1, seen: {} };
129
+ const key = createHash("sha256").update(stdout).update("\u0000").update(stderr).digest("hex");
130
+ const prev = state.seen[key];
131
+ const fresh = prev && now - prev.ts <= cfg.bash.maxAgeMinutes * 60_000 && !contextChangedSince(transcript, prev.at);
132
+ if (fresh) {
133
+ const stub = `[frugal: identical to the output of an earlier command in this session (\`${prev.cmd}\`, ${fmtKB(bytesIn)}). That result is still above; refer to it.]`;
134
+ recordSafe("Bash.repeat", bytesIn, byteLen(stub), started);
135
+ return JSON.stringify({
136
+ hookSpecificOutput: { hookEventName: "PostToolUse", updatedToolOutput: { ...resp, stdout: stub, stderr: "" } }
137
+ });
138
+ }
139
+ state.seen[key] = { cmd: redact(cmd).replace(/\s+/g, " ").slice(0, 120), ts: now, at: transcriptSize(transcript) };
140
+ const keys = Object.keys(state.seen);
141
+ if (keys.length > MAX_SEEN)
142
+ for (const k of keys.slice(0, keys.length - MAX_SEEN))
143
+ delete state.seen[k];
144
+ writePrivateFile(file, JSON.stringify(state));
145
+ }
146
+ // ---- 2. light cleanup (never for file contents) ----
147
+ if (!cfg.bash.cleanup || isFileRead(cmd))
148
+ return undefined;
149
+ const out = cleanTerminalText(stdout);
150
+ const err = cleanTerminalText(stderr);
151
+ const bytesOut = byteLen(out) + byteLen(err);
152
+ if (bytesOut > bytesIn * 0.9)
153
+ return undefined; // not worth changing
154
+ recordSafe("Bash.clean", bytesIn, bytesOut, started);
155
+ return JSON.stringify({
156
+ hookSpecificOutput: { hookEventName: "PostToolUse", updatedToolOutput: { ...resp, stdout: out, stderr: err } }
157
+ });
158
+ }
159
+ function recordSafe(tool, bytesIn, bytesOut, started) {
160
+ try {
161
+ record({ ts: Date.now(), kind: "compress", tool, bytesIn, bytesOut, durationMs: Date.now() - started });
162
+ }
163
+ catch {
164
+ // best-effort
165
+ }
166
+ }
@@ -0,0 +1,115 @@
1
+ // UserPromptSubmit hook: topic drift + context bloat. Never blocks; only adds a note.
2
+ import * as path from "node:path";
3
+ import { dataPath, readPrivateJson, writePrivateFile } from "../paths.js";
4
+ import { redact } from "../redact.js";
5
+ import { cosine, embed } from "../ollama.js";
6
+ import { lastContextTokens } from "../transcript.js";
7
+ import { faultPoint, str } from "../io.js";
8
+ import { ktok } from "../statusline.js";
9
+ const SESSION_RE = /^[A-Za-z0-9_-]{1,128}$/;
10
+ const RECENT = 3;
11
+ const DRIFT_COOLDOWN_MS = 30 * 60_000;
12
+ const STOP = new Set(("the and for are but not you all any can had her was one our out day get has him his how man new now old see two way who boy did its let put say she too use " +
13
+ "this that with have from they will would there their what about which when make like time just know take into year your good some could them than then look only come over think also back after work first well even want because these give most " +
14
+ "please help need should does doing done here where while being been were more very much many each other such using used file files code fix add make sure let's lets okay ok yes thanks thank can't don't it's i'm").split(" "));
15
+ export function keywords(text) {
16
+ const words = text
17
+ .toLowerCase()
18
+ .replace(/```[\s\S]*?```/g, " ")
19
+ .split(/[^a-z0-9_]+/)
20
+ .filter((w) => w.length >= 3 && !STOP.has(w) && !/^\d+$/.test(w))
21
+ .map((w) => (w.length > 4 && w.endsWith("s") ? w.slice(0, -1) : w));
22
+ return [...new Set(words)];
23
+ }
24
+ export function jaccard(a, b) {
25
+ if (!a.length || !b.length)
26
+ return 0;
27
+ const A = new Set(a);
28
+ const B = new Set(b);
29
+ let inter = 0;
30
+ for (const x of A)
31
+ if (B.has(x))
32
+ inter++;
33
+ return inter / (A.size + B.size - inter);
34
+ }
35
+ function sessionFile(id) {
36
+ return path.join(dataPath("sessions"), `${id}.json`);
37
+ }
38
+ export const DRIFT_NOTE = 'frugal: this looks like a new topic. Run "frugal handoff" and start a fresh session to save context.';
39
+ export function bloatNote(tokens) {
40
+ return `frugal: context is ${ktok(tokens)} tokens. Consider "frugal handoff" and a fresh session (or /compact).`;
41
+ }
42
+ export async function handlePrompt(input, cfg, now = Date.now()) {
43
+ faultPoint("prompt");
44
+ const session = str(input.session_id);
45
+ const prompt = str(input.prompt);
46
+ if (!session || !SESSION_RE.test(session) || !prompt)
47
+ return undefined;
48
+ const trimmed = prompt.trim();
49
+ if (!trimmed || trimmed.startsWith("/") || trimmed.startsWith("!"))
50
+ return undefined;
51
+ const file = sessionFile(session);
52
+ const st = readPrivateJson(file);
53
+ const kw = keywords(trimmed);
54
+ const notes = [];
55
+ const ctxNotes = [];
56
+ const embBudget = 900;
57
+ if (!st || st.v !== 1) {
58
+ const goal = redact(trimmed).slice(0, 2000);
59
+ const fresh = { v: 1, goal, goalKw: kw, recent: [], created: now };
60
+ if (cfg.ollama.enabled) {
61
+ const e = await embed(cfg, [goal], embBudget);
62
+ if (e?.[0])
63
+ fresh.goalEmb = e[0];
64
+ }
65
+ writePrivateFile(file, JSON.stringify(fresh));
66
+ return undefined;
67
+ }
68
+ // ---- drift ----
69
+ let drift;
70
+ let emb;
71
+ const longEnough = kw.length >= 4;
72
+ if (longEnough) {
73
+ if (cfg.ollama.enabled && st.goalEmb) {
74
+ const e = await embed(cfg, [trimmed], embBudget);
75
+ emb = e?.[0];
76
+ }
77
+ if (emb && st.goalEmb) {
78
+ const sims = [cosine(emb, st.goalEmb), ...st.recent.filter((r) => r.emb).map((r) => cosine(emb, r.emb))];
79
+ drift = Math.max(...sims) < cfg.driftThreshold;
80
+ }
81
+ else {
82
+ const sims = [jaccard(kw, st.goalKw), ...st.recent.map((r) => jaccard(kw, r.kw))];
83
+ drift = Math.max(...sims) < cfg.jaccardThreshold;
84
+ }
85
+ if (drift && (!st.lastDriftWarn || now - st.lastDriftWarn > DRIFT_COOLDOWN_MS)) {
86
+ notes.push(DRIFT_NOTE);
87
+ ctxNotes.push("frugal (local cost tool) note: the user's new prompt looks unrelated to this session's original goal. Handle the request normally. In one short sentence at the end, you may suggest running `frugal handoff` and starting a fresh session to save context.");
88
+ st.lastDriftWarn = now;
89
+ }
90
+ if (!drift) {
91
+ st.recent = [...st.recent, { kw, ...(emb ? { emb } : {}) }].slice(-RECENT);
92
+ }
93
+ }
94
+ // ---- bloat ----
95
+ const tp = str(input.transcript_path);
96
+ const tokens = tp ? lastContextTokens(tp) : undefined;
97
+ if (tokens !== undefined && tokens > cfg.contextWarnTokens) {
98
+ const last = st.lastBloatWarnTokens ?? 0;
99
+ if (tokens > last * 1.2) {
100
+ notes.push(bloatNote(tokens));
101
+ ctxNotes.push(`frugal (local cost tool) note: ${bloatNote(tokens).slice(8)}`);
102
+ st.lastBloatWarnTokens = tokens;
103
+ }
104
+ }
105
+ writePrivateFile(file, JSON.stringify(st));
106
+ if (!notes.length)
107
+ return undefined;
108
+ return JSON.stringify({
109
+ systemMessage: notes.join("\n"),
110
+ hookSpecificOutput: {
111
+ hookEventName: "UserPromptSubmit",
112
+ additionalContext: ctxNotes.join("\n")
113
+ }
114
+ });
115
+ }
@@ -0,0 +1,168 @@
1
+ // PostToolUse hook: shrink MCP tool output before the paid model reads it.
2
+ // Works for every MCP transport (stdio, HTTP, wrapper-injected) because Claude Code
3
+ // hands us the result after the call. Any failure => no output => original result kept.
4
+ import * as fs from "node:fs";
5
+ import * as path from "node:path";
6
+ import { claudeConfigDir } from "../paths.js";
7
+ import { byteLen, capBytes, fmtKB, pruneText } from "../compress.js";
8
+ import { putOriginal, pruneStore } from "../cache.js";
9
+ import { record } from "../metrics.js";
10
+ import { redact } from "../redact.js";
11
+ import { chat, SUMMARIZE_SYSTEM } from "../ollama.js";
12
+ import { faultPoint, obj, str } from "../io.js";
13
+ function isTextBlock(b) {
14
+ const o = obj(b);
15
+ return !!o && o.type === "text" && typeof o.text === "string";
16
+ }
17
+ /** Find the text blocks in whatever shape Claude Code hands us, and a way to rebuild that shape. */
18
+ function unpack(resp) {
19
+ if (Array.isArray(resp))
20
+ return { blocks: resp, rebuild: (b) => b };
21
+ const o = obj(resp);
22
+ if (o && Array.isArray(o.content))
23
+ return { blocks: o.content, rebuild: (b) => ({ ...o, content: b }) };
24
+ if (typeof resp === "string")
25
+ return { blocks: [{ type: "text", text: resp }], rebuild: (b) => b[0].text };
26
+ return undefined;
27
+ }
28
+ /** Claude Code's MCP output limit (env MAX_MCP_OUTPUT_TOKENS, documented default 25,000). */
29
+ export function mcpOutputTokenLimit() {
30
+ const n = Number.parseInt(process.env.MAX_MCP_OUTPUT_TOKENS ?? "", 10);
31
+ return Number.isFinite(n) && n > 0 ? n : 25_000;
32
+ }
33
+ const SPILL_RE = /^Error: result \([\d,]+ characters[^)]*\) exceeds maximum allowed tokens\. Output has been saved to (\/.+?)\.?\n/;
34
+ const MAX_SPILL_BYTES = 64 * 1024 * 1024;
35
+ /**
36
+ * Claude Code (observed on 2.1.x) replaces MCP results above its token limit with
37
+ * "Error: result (N characters …) exceeds maximum allowed tokens. Output has been saved to <path>."
38
+ * Read that file back, but only from this session's own tool-results dir, never via symlink.
39
+ */
40
+ export function readSpilledOutput(resp, input) {
41
+ const m = SPILL_RE.exec(resp);
42
+ if (!m)
43
+ return undefined;
44
+ const file = path.resolve(m[1]);
45
+ const tp = str(input.transcript_path);
46
+ const sid = str(input.session_id);
47
+ const anchors = [path.join(claudeConfigDir(), "projects")];
48
+ if (tp && sid && /^[A-Za-z0-9_-]{1,128}$/.test(sid))
49
+ anchors.unshift(path.join(path.dirname(path.resolve(tp)), sid, "tool-results"));
50
+ const inside = (dir) => file.startsWith(dir + path.sep) && file.split(path.sep).includes("tool-results");
51
+ if (!anchors.some(inside))
52
+ return undefined;
53
+ const st = fs.lstatSync(file);
54
+ if (!st.isFile() || st.size > MAX_SPILL_BYTES)
55
+ return undefined;
56
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
57
+ try {
58
+ return fs.readFileSync(fd, "utf8");
59
+ }
60
+ finally {
61
+ fs.closeSync(fd);
62
+ }
63
+ }
64
+ /**
65
+ * MCP tools whose output is file content (filesystem servers, GitHub get_file_contents, …).
66
+ * Claude can copy exact text from these into edits, so frugal never rewrites them.
67
+ */
68
+ export function returnsFileContents(tool) {
69
+ const name = tool.split("__").pop() ?? tool;
70
+ return /(^|_)(read|get|cat|view|open|show|download)_?(text_|media_|multiple_)?(files?|file_contents?|contents?|blob|source|raw)(_|$)/i.test(name) ||
71
+ /^(read|cat|view)$/i.test(name);
72
+ }
73
+ function matchRule(cfg, tool) {
74
+ if (cfg.compress.tools[tool])
75
+ return cfg.compress.tools[tool];
76
+ for (const [pat, rule] of Object.entries(cfg.compress.tools)) {
77
+ if (pat.endsWith("*") && tool.startsWith(pat.slice(0, -1)))
78
+ return rule;
79
+ }
80
+ return undefined;
81
+ }
82
+ export async function handleToolOutput(input, cfg) {
83
+ const started = Date.now();
84
+ const tool = str(input.tool_name) ?? "";
85
+ if (!tool.startsWith("mcp__"))
86
+ return undefined;
87
+ if (tool.endsWith("__frugal_fetch"))
88
+ 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)
93
+ return undefined;
94
+ let resp = input.tool_response ?? input.tool_result;
95
+ // Oversized results: Claude Code saves them to a file first and hands the hook a pointer.
96
+ const spilled = typeof resp === "string" ? readSpilledOutput(resp, input) : undefined;
97
+ if (spilled !== undefined)
98
+ resp = spilled;
99
+ 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;
105
+ const original = texts.join("\n");
106
+ const bytesIn = byteLen(original);
107
+ if (bytesIn <= cfg.compress.minBytes)
108
+ return undefined;
109
+ faultPoint("compress");
110
+ const safeOriginal = redact(original);
111
+ const opts = {
112
+ maxBytes: cfg.compress.maxBytes,
113
+ maxArrayItems: cfg.compress.maxArrayItems,
114
+ denyKeys: cfg.compress.denyKeys,
115
+ keepFields: rule?.keepFields
116
+ };
117
+ // Compress each text block, preserving non-text blocks (images etc.) as-is.
118
+ const textOf = (o2) => u.blocks
119
+ .filter(isTextBlock)
120
+ .map((b) => pruneText(redact(b.text), o2))
121
+ .join("\n");
122
+ let joined = textOf(opts);
123
+ if (cfg.compress.summarize && cfg.compress.maxBytes > 0) {
124
+ // Summarize when pruning alone (before fitting to size) cannot get under maxBytes.
125
+ const full = textOf({ ...opts, maxBytes: Number.MAX_SAFE_INTEGER });
126
+ if (byteLen(full) > cfg.compress.maxBytes) {
127
+ const s = await chat(cfg, SUMMARIZE_SYSTEM, full.slice(0, 200_000), 15_000);
128
+ if (s)
129
+ joined = s;
130
+ }
131
+ }
132
+ const finalText = capBytes(joined, cfg.compress.maxBytes);
133
+ const bytesOut = byteLen(finalText);
134
+ // Never inline more than Claude Code itself would: if a spilled result is still over the
135
+ // MCP output limit after cleanup, keep Claude Code's file pointer instead.
136
+ if (spilled !== undefined && bytesOut / 3.5 > mcpOutputTokenLimit())
137
+ return undefined;
138
+ if (bytesOut >= bytesIn * 0.9)
139
+ return undefined; // not worth it; leave untouched
140
+ const id = putOriginal(tool, safeOriginal);
141
+ const shortened = /…\d+ more"|…\[\+\d+ chars\]|…\[frugal: truncated\]/.test(finalText);
142
+ const tagCount = (t) => (t.match(/<\/?[a-z][a-z0-9:-]*[\s>/]/gi) ?? []).length;
143
+ 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
+ }
157
+ try {
158
+ record({ ts: Date.now(), kind: "compress", tool, bytesIn, bytesOut, durationMs: Date.now() - started });
159
+ if (Math.random() < 0.05)
160
+ pruneStore(cfg.cache.ttlHours, cfg.cache.maxMB);
161
+ }
162
+ catch {
163
+ // metrics are best-effort
164
+ }
165
+ return JSON.stringify({
166
+ hookSpecificOutput: { hookEventName: "PostToolUse", updatedMCPToolOutput: u.rebuild(out) }
167
+ });
168
+ }
package/dist/html.js ADDED
@@ -0,0 +1,62 @@
1
+ // Deterministic HTML → text for markup-heavy tool output (e.g. Confluence storage format,
2
+ // Jira rendered fields, raw web pages). Keeps all visible text, link targets and code;
3
+ // drops tags, attributes, styles and scripts. No parsing library, no execution.
4
+ // Private-use placeholder protects "<" inside CDATA from tag stripping.
5
+ const LT = "\uE000";
6
+ const ENTITIES = {
7
+ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "–", mdash: "—",
8
+ hellip: "…", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“", bull: "•", middot: "·", copy: "©", reg: "®", trade: "™"
9
+ };
10
+ function decodeEntities(s) {
11
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
12
+ if (e[0] === "#") {
13
+ const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
14
+ return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : m;
15
+ }
16
+ return ENTITIES[e.toLowerCase()] ?? m;
17
+ });
18
+ }
19
+ const TAG = /<\/?[a-z][a-z0-9:-]*(?:\s[^<>]*)?\/?>/gi;
20
+ /** Heuristic: is this string mostly HTML markup? */
21
+ export function looksLikeHtml(s) {
22
+ if (s.length < 200)
23
+ return false;
24
+ const tags = s.match(TAG);
25
+ if (!tags || tags.length < 5)
26
+ return false;
27
+ const markup = tags.reduce((a, t) => a + t.length, 0);
28
+ return markup / s.length > 0.15;
29
+ }
30
+ export function htmlToText(html) {
31
+ let s = html;
32
+ // CDATA (Confluence code macros) keeps its content verbatim.
33
+ s = s.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_m, body) => "\n```\n" + body.replace(/</g, LT) + "\n```\n");
34
+ s = s.replace(/<!--[\s\S]*?-->/g, "");
35
+ // Confluence: user mentions and status lozenges carry meaning; keep them as text.
36
+ s = s.replace(/<ri:user\b[^>]*?ri:(?:account-id|userkey|username)\s*=\s*["']([^"']+)["'][^>]*\/?>/gi, " @user:$1 ");
37
+ s = s.replace(/<ac:structured-macro\b[^>]*ac:name=["']status["'][^>]*>[\s\S]*?<ac:parameter ac:name=["']title["']>([\s\S]*?)<\/ac:parameter>[\s\S]*?<\/ac:structured-macro>/gi, " [status: $1] ");
38
+ // Tables: one line per row, cells joined with " | ".
39
+ s = s.replace(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi, (_m, row) => {
40
+ const cells = [...row.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((c) => c[1].replace(/<(br|\/p|\/div|\/li)\b[^>]*>/gi, " ").replace(TAG, "").replace(/\s+/g, " ").trim());
41
+ return `\n| ${cells.join(" | ")} |\n`;
42
+ });
43
+ s = s.replace(/<(script|style|noscript|svg|head)\b[\s\S]*?<\/\1>/gi, "");
44
+ // Links: keep text and target.
45
+ s = s.replace(/<a\b[^>]*?href\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, (_m, href, text) => {
46
+ const t = text.replace(TAG, "").trim();
47
+ return t && t !== href ? `${t} (${href})` : href;
48
+ });
49
+ s = s.replace(/<img\b[^>]*?alt\s*=\s*["']([^"']+)["'][^>]*>/gi, "[image: $1]");
50
+ s = s.replace(/<h([1-6])\b[^>]*>/gi, (_m, n) => "\n" + "#".repeat(Number(n)) + " ");
51
+ s = s.replace(/<li\b[^>]*>/gi, "\n- ");
52
+ s = s.replace(/<(br|hr)\b[^>]*\/?>/gi, "\n");
53
+ s = s.replace(/<\/?(p|div|tr|table|ul|ol|section|article|blockquote|pre|h[1-6]|ac:[a-z-]+|ri:[a-z-]+)\b[^>]*>/gi, "\n");
54
+ s = s.replace(TAG, "");
55
+ s = decodeEntities(s).replaceAll(LT, "<");
56
+ return s
57
+ .replace(/[ \t]+\n/g, "\n")
58
+ .replace(/\n[ \t]+/g, "\n")
59
+ .replace(/[ \t]{2,}/g, " ")
60
+ .replace(/\n{3,}/g, "\n\n")
61
+ .trim();
62
+ }
package/dist/init.js ADDED
@@ -0,0 +1,146 @@
1
+ // `frugal init`: reads your Claude Code settings and prints ready-to-run commands.
2
+ // frugal itself never edits any file (S9): you run the commands, so you see every change.
3
+ import * as fs from "node:fs";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import { claudeConfigDir, configPath } from "./paths.js";
7
+ const TOOL_CMD = "frugal hook tool-output";
8
+ const PROMPT_CMD = "frugal hook prompt";
9
+ const STATUS_CMD = "frugal statusline";
10
+ 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
+ /** POSIX single-quote a string for a shell command line. */
12
+ export function shq(s) {
13
+ return "'" + s.replace(/'/g, "'\\''") + "'";
14
+ }
15
+ /** A status line that runs `existing` and frugal on the same stdin, side by side. */
16
+ export function chainStatus(existing) {
17
+ // `existing` lands inside sh -c '...': escape its single quotes for that layer.
18
+ const inner = `( ${existing} )`.replace(/'/g, "'\\''");
19
+ return CHAIN.replace("YOUR_EXISTING_COMMAND", inner);
20
+ }
21
+ function hookCommands(settings, event) {
22
+ const groups = settings.hooks?.[event];
23
+ if (!Array.isArray(groups))
24
+ return [];
25
+ const out = [];
26
+ for (const g of groups) {
27
+ const hs = g?.hooks;
28
+ if (Array.isArray(hs))
29
+ for (const h of hs)
30
+ if (typeof h?.command === "string")
31
+ out.push(h.command);
32
+ }
33
+ return out;
34
+ }
35
+ /** Add frugal's hooks and status line to a settings object. Keeps everything else as it was. */
36
+ export function mergeSettings(input) {
37
+ const s = structuredClone(input);
38
+ const changes = [];
39
+ const addHook = (event, group, cmd, label) => {
40
+ if (hookCommands(s, event).some((c) => c.includes("frugal") && c.includes(cmd.slice("frugal ".length))))
41
+ return;
42
+ const hooks = (typeof s.hooks === "object" && s.hooks !== null && !Array.isArray(s.hooks) ? s.hooks : (s.hooks = {}));
43
+ const list = Array.isArray(hooks[event]) ? hooks[event] : (hooks[event] = []);
44
+ list.push(group);
45
+ changes.push(label);
46
+ };
47
+ addHook("PostToolUse", { matcher: "mcp__.*|Bash", hooks: [{ type: "command", command: TOOL_CMD, timeout: 30 }] }, TOOL_CMD, "PostToolUse hook (shrinks MCP and Bash output)");
48
+ addHook("UserPromptSubmit", { hooks: [{ type: "command", command: PROMPT_CMD, timeout: 5 }] }, PROMPT_CMD, "UserPromptSubmit hook (drift and context warnings)");
49
+ const sl = s.statusLine;
50
+ const cur = typeof sl?.command === "string" ? sl.command.trim() : "";
51
+ if (!cur) {
52
+ s.statusLine = { type: "command", command: STATUS_CMD, padding: 0 };
53
+ changes.push("status line (spend and context meter)");
54
+ }
55
+ else if (!cur.includes("frugal")) {
56
+ s.statusLine = { ...sl, type: "command", command: chainStatus(cur) };
57
+ changes.push("status line: your existing one and frugal's, side by side");
58
+ }
59
+ return { settings: s, changes };
60
+ }
61
+ /** A directory for the printed command: "$HOME/..." when under home and safe to double-quote, else single-quoted. */
62
+ function shellDir(dir) {
63
+ const home = os.homedir();
64
+ if ((dir === home || dir.startsWith(home + path.sep)) && !/["$`\\!]/.test(dir))
65
+ return `"$HOME${dir.slice(home.length)}"`;
66
+ return shq(dir);
67
+ }
68
+ function tilde(p) {
69
+ const home = os.homedir();
70
+ return p.startsWith(home + path.sep) ? "~" + p.slice(home.length) : p;
71
+ }
72
+ function settingsTarget() {
73
+ let file = path.join(claudeConfigDir(), "settings.json");
74
+ try {
75
+ if (fs.lstatSync(file).isSymbolicLink())
76
+ file = fs.realpathSync(file); // edit the real file, keep the link
77
+ }
78
+ catch {
79
+ return { file, exists: false, settings: {} };
80
+ }
81
+ try {
82
+ const v = JSON.parse(fs.readFileSync(file, "utf8"));
83
+ if (typeof v !== "object" || v === null || Array.isArray(v))
84
+ return { file, exists: true, error: "is not a JSON object" };
85
+ return { file, exists: true, settings: v };
86
+ }
87
+ catch (e) {
88
+ return { file, exists: true, error: `could not be read as JSON (${e.message})` };
89
+ }
90
+ }
91
+ function mcpConfigured() {
92
+ try {
93
+ const p = path.join(process.env.CLAUDE_CONFIG_DIR ?? os.homedir(), ".claude.json");
94
+ const v = JSON.parse(fs.readFileSync(p, "utf8"));
95
+ return !!v.mcpServers?.frugal;
96
+ }
97
+ catch {
98
+ return false;
99
+ }
100
+ }
101
+ /** `frugal init --settings`: the merged settings.json on stdout (used by the printed command). */
102
+ export function mergedSettingsText() {
103
+ const t = settingsTarget();
104
+ if (!t.settings)
105
+ return { text: `frugal: ${t.file} ${t.error ?? "could not be read"}; not printing a merged copy`, ok: false };
106
+ return { text: JSON.stringify(mergeSettings(t.settings).settings, null, 2), ok: true };
107
+ }
108
+ export function initText() {
109
+ const t = settingsTarget();
110
+ const out = ["frugal init: copy and run the commands below. frugal never edits your files itself.", ""];
111
+ let step = 0;
112
+ if (!t.settings) {
113
+ out.push(`${++step}) ${t.file} ${t.error}. Fix it, then run \`frugal init\` again. Or add this by hand:`, "");
114
+ out.push(JSON.stringify(mergeSettings({}).settings, null, 2), "");
115
+ }
116
+ else {
117
+ const { changes } = mergeSettings(t.settings);
118
+ if (changes.length === 0)
119
+ out.push(`✓ hooks and status line already set in ${tilde(t.file)}`, "");
120
+ else {
121
+ const dir = shellDir(path.dirname(t.file));
122
+ const base = path.basename(t.file); // "settings.json", or a symlink's target name
123
+ const q = (x) => (/^[\w.@%+=:,-]+$/.test(x) ? x : shq(x));
124
+ const cmd = [
125
+ `mkdir -p ${dir}`,
126
+ `cd ${dir}`,
127
+ // pin the config dir so the command reads the same file even outside a wrapper session
128
+ `${process.env.CLAUDE_CONFIG_DIR ? `CLAUDE_CONFIG_DIR=${shellDir(process.env.CLAUDE_CONFIG_DIR)} ` : ""}frugal init --settings > ${q(base + ".frugal-new")}`,
129
+ ...(t.exists ? [`cp ${q(base)} ${q(base + ".bak-frugal")}`] : []),
130
+ `mv ${q(base + ".frugal-new")} ${q(base)}`
131
+ ].join(" && ");
132
+ // in a subshell, so the `cd` does not move the user's shell
133
+ out.push(`${++step}) Add to ${tilde(t.file)}${t.exists ? " (a backup goes to settings.json.bak-frugal)" : ""}:`);
134
+ for (const c of changes)
135
+ out.push(` + ${c}`);
136
+ out.push("", ` ( ${cmd} )`, "");
137
+ }
138
+ }
139
+ if (mcpConfigured())
140
+ out.push("✓ frugal MCP server already added", "");
141
+ else
142
+ out.push(`${++step}) Add the frugal_fetch MCP server (lets Claude get full output back when it needs it):`, "", " claude mcp add --scope user frugal -- frugal mcp", "");
143
+ out.push(step ? `${step + 1}) Restart Claude Code, then check: frugal doctor` : "All set. Check anytime with: frugal doctor", "");
144
+ out.push(`Optional: set your company's prices and a monthly cap in ${tilde(configPath())}`, ` ${JSON.stringify({ monthlyCap: 250, prices: { default: { inputPerMTok: 0, outputPerMTok: 0, cacheReadPerMTok: 0, cacheWritePerMTok: 0 } } })}`, "Using a company wrapper that sets CLAUDE_CONFIG_DIR? Run `frugal init` inside a wrapper session so the paths above are right.");
145
+ return out.join("\n");
146
+ }