@frugalhq/frugal 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-12-02)
4
+
5
+ First release. Benchmarks on Claude Code 2.1.334 with Sonnet 5.5 and Opus 5.5 (MCP and Bash A/B, MCPMark, Terminal-Bench 2.1, SWE-bench Verified): [docs/BENCHMARK.md](docs/BENCHMARK.md).
6
+
7
+ - `frugal hook tool-output`: a `PostToolUse` hook that removes noise from MCP tool output: nulls and empties, noise keys, duplicate API URLs, surrogate ids, all-zero counters, ANSI codes and whitespace. It works with any MCP transport and is lossless by default. Size caps (structural fit) and local summarization are opt-in.
8
+ - Bash output (same `PostToolUse` hook, matcher `mcp__.*|Bash`): exact repeats within a session become a pointer to the earlier result, which must still be in context (compaction-aware). Light terminal cleanup is applied, never to file contents.
9
+ - `frugal mcp`: stdio MCP server with `frugal_fetch`, which returns cached originals (redacted), paged.
10
+ - `frugal statusline`: today and month spend against `monthlyCap`, plus context size. Session costs are counted by increase only, with a transcript-based fallback priced from your own table. Vertex and Bedrock model ids are normalised.
11
+ - `frugal hook prompt`: topic drift (Ollama embeddings or keyword Jaccard) and context-bloat notes. Never blocks a prompt.
12
+ - `frugal handoff`, `report`, `doctor`, `init` and `purge`.
13
+ - Security: loopback-only networking (Ollama cloud models and remote-served aliases are refused), secret redaction, 0700/0600 storage with symlink refusal, fail-open hooks, zero runtime dependencies.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 frugal contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,5 +1,228 @@
1
- # @frugalhq/frugal (placeholder)
1
+ # frugal
2
2
 
3
- This 0.0.0 version only exists so npm trusted publishing can be configured.
4
- Real releases (0.1.0 and later) are published from GitHub Actions with provenance:
5
- https://github.com/rushi209/frugal
3
+ A local copilot for your AI copilot. frugal plugs into **Claude Code** through its hooks, status line and MCP config to cut wasted spend:
4
+
5
+ 1. **Shrinks MCP tool output** (Jira, Datadog, Slack, …) before the paid model reads it, and can always return the original.
6
+ 2. **Shows spend and context size** in the status line, with colours at 70% and 90% of your monthly cap.
7
+ 3. **Detects topic drift and context bloat** on each prompt and suggests a fresh session.
8
+ 4. **Writes a handoff note** so the fresh session starts with a short summary.
9
+
10
+ **No data leaves your machine.** frugal makes no network calls except, optionally, to a local [Ollama](https://ollama.com) on `127.0.0.1`. No telemetry, no update checks, no third-party models.
11
+
12
+ **Measured** on Claude Code 2.1.334 with Sonnet 5.5 and Opus 5.5: on MCP tasks with noisy payloads (Jira/Datadog/Slack, Confluence HTML) frugal cut cost **17–35% per task** with every answer still correct; across all five MCP scenarios −20% (Sonnet) and −12% (Opus). On MCPMark, Terminal-Bench 2.1 and SWE-bench Verified it solved as many tasks as Claude Code alone, or more. Details, raw data and caveats: [docs/BENCHMARK.md](docs/BENCHMARK.md).
13
+
14
+ ![Mean cost per MCP task, without vs with frugal](docs/benchmark.svg)
15
+
16
+ It never wraps, launches or patches Claude Code, never blocks a prompt, and never writes to your repo or your Claude Code settings. If frugal fails, Claude Code carries on as if it weren't installed.
17
+
18
+ ## Install
19
+
20
+ Requires **Node 22 or later**. (Node 20 reached end of life in April 2026.)
21
+
22
+ ```bash
23
+ npm install -g @frugalhq/frugal
24
+ frugal init # prints snippets to paste; edits nothing
25
+ frugal doctor # checks config, permissions, Ollama and your Claude Code setup
26
+ ```
27
+
28
+ `frugal init` prints three things for you to paste:
29
+
30
+ ```jsonc
31
+ // ~/.claude/settings.json (or $CLAUDE_CONFIG_DIR/settings.json)
32
+ {
33
+ "hooks": {
34
+ "PostToolUse": [
35
+ { "matcher": "mcp__.*|Bash", "hooks": [{ "type": "command", "command": "frugal hook tool-output", "timeout": 30 }] }
36
+ ],
37
+ "UserPromptSubmit": [
38
+ { "hooks": [{ "type": "command", "command": "frugal hook prompt", "timeout": 5 }] }
39
+ ]
40
+ },
41
+ "statusLine": { "type": "command", "command": "frugal statusline", "padding": 0 }
42
+ }
43
+ ```
44
+
45
+ ```bash
46
+ claude mcp add --scope user frugal -- frugal mcp # provides frugal_fetch
47
+ ```
48
+
49
+ If you already have a status line, `frugal init` prints a one-line `sh -c` command that runs both.
50
+
51
+ ## How it works
52
+
53
+ ### MCP output compression (`frugal hook tool-output`)
54
+
55
+ frugal is registered as a `PostToolUse` hook for `mcp__*` tools. Claude Code hands it each MCP result after the call. frugal returns a smaller version through `updatedMCPToolOutput`, and Claude Code passes that version to the model instead. Because this happens after the call, it works the same for **stdio, HTTP/SSE and wrapper- or admin-managed MCP servers**, and your MCP config stays as it is.
56
+
57
+ By default frugal is **lossless about content**: it removes noise and never shortens data. Outputs over `minBytes` (2 KB) go through these steps:
58
+
59
+ 1. Parse JSON. Non-JSON text skips to step 5.
60
+ 2. Drop `null`, `""`, `[]` and `{}`.
61
+ 3. Drop noise:
62
+ - keys `avatarUrls`, `self`, `_links`, `iconUrl`, `expand` and `node_id`, plus your own `denyKeys`
63
+ - API links (`url`, `*_url`) when an `html_url` sibling exists
64
+ - numeric surrogate `id`s next to a human-readable id (`number`, `key`, `login`, `slug`)
65
+ - counter blocks that are all zero, such as unused reaction counts
66
+ 4. Apply the per-tool `keepFields` allow list, if you configure one.
67
+ 5. Strip ANSI codes, collapse whitespace and write JSON compactly.
68
+
69
+ If the result isn't at least 10% smaller, frugal leaves the output untouched.
70
+
71
+ Shortening is **opt-in**. Set `maxBytes` and optionally `maxArrayItems` above 0 and frugal fits the JSON under that size by shortening long strings first, then keeping as many whole records as fit (marked `…N more`). Every record then still has its ids and titles. With a cap set, `summarize: true` makes the local model summarize instead.
72
+
73
+ Measured with the default lossless settings:
74
+
75
+ | Payload | Raw | Sent to the model | Saved |
76
+ |---|---|---|---|
77
+ | Jira-style search (fixture, compact JSON) | 81.6 KB | 25.9 KB | 68% |
78
+ | Datadog-style logs (fixture, compact JSON) | 38.0 KB | 33.6 KB | 12% |
79
+ | Slack-style history (fixture, compact JSON) | 17.3 KB | 14.9 KB | 14% |
80
+ | GitHub MCP `search_issues` (real) | 135.7 KB | 86.8 KB | 36% |
81
+ | GitHub MCP `list_issues`, `list_commits`, `list_pull_requests` (real) | 38–77 KB | unchanged | under 10%, left untouched |
82
+
83
+ Savings depend on how much noise a server sends. Raw REST passthroughs (typical of Jira and Confluence tools) shrink a lot. Servers that already trim their output (like GitHub's official one) shrink little, and frugal leaves them alone. Servers that pretty-print JSON gain another 30–45% from compact JSON.
84
+
85
+ When frugal changes an output, it adds one line:
86
+
87
+ ```
88
+ [frugal: compressed 116.6KB → 25.9KB. Full output: call frugal_fetch with id "<sha256>"]
89
+ ```
90
+
91
+ `frugal_fetch` is served by `frugal mcp`, a tiny stdio MCP server. It returns the original output, paged for large outputs. Originals are kept for 24 h (`cache.ttlHours`), up to 200 MB.
92
+
93
+ Secrets are redacted before anything is cached, so `frugal_fetch` returns the original with secrets replaced by `[REDACTED:…]`. The compressed view the model sees is redacted too.
94
+
95
+ ### Bash output (same hook)
96
+
97
+ Bash is where most tool output comes from (72% of tool-output volume in one developer's history of 1,169 sessions; MCP was 7%). Most of it is content Claude asked for, so frugal does only two things:
98
+
99
+ 1. **Repeat-skip.** If a command produces exactly the same output as an earlier one in the session (tests re-run with the same result, `git status`, listings, re-reading an unchanged file), Claude gets one line instead: `[frugal: identical to the output of an earlier command in this session (`npm test`, 16.0KB). That result is still above; refer to it.]`. frugal only does this when the earlier copy is still in context. It checks the transcript and won't point back past a `/compact`, an automatic compaction, or Claude Code clearing old tool results, and it gives up after `bash.maxAgeMinutes` (60). Only hashes and a redacted command line are stored, never the output.
100
+ 2. **Light cleanup** of terminal noise: progress-bar redraws (`\r`) resolved the way a terminal shows them, ANSI codes, trailing spaces, and runs of 3+ identical lines folded into one line with a count. This never applies to file contents (`cat`, `sed`, `head`, `tail`, `git show rev:path`, …), because Claude copies exact text from those into edits.
101
+
102
+ Replayed over that same history (1,020 sessions, 15.9 MB of Bash output), repeat-skip would have removed 13.0% of Bash output *bytes* and cleanup 0.2%. Claude Code already strips most terminal noise itself. In live tests with current models the cost effect is small: Sonnet 5.5 and Opus 5.5 usually re-check with `| head` or `| grep`, so full repeats are rare (see [section 3 of the benchmark](docs/BENCHMARK.md#3-bash-heavy-tasks-own-ab-harness)). Treat it as a safe extra, not the main saving. Limitation: two identical commands run *in parallel* in one step are not deduplicated.
103
+
104
+ ### Spend meter (`frugal statusline`)
105
+
106
+ ```
107
+ frugal ▸ $12.40 today · $186/$250 month (74%) · ctx 88k
108
+ ```
109
+
110
+ Where the cost comes from (`costSource`):
111
+
112
+ - **`auto`** (default): Claude Code's own `cost.total_cost_usd`. If that is missing, transcript token usage priced from your price table.
113
+ - **`transcript`**: always your price table. Use this when your company's negotiated rates differ from list price (common on Vertex AI or Bedrock).
114
+ - **`statusline`**: only Claude Code's figure.
115
+
116
+ Claude Code reports a *cumulative* cost per session on every refresh. frugal keeps the last value for each session and adds only the increase, so totals don't double-count. Vertex (`claude-…@20250929`) and Bedrock (`us.anthropic.…-v1:0`) model ids are mapped to plain ids before the price lookup.
117
+
118
+ ### Drift and bloat (`frugal hook prompt`)
119
+
120
+ The first prompt of a session becomes its goal. Later prompts are compared to the goal and the last few on-topic prompts:
121
+
122
+ - **With Ollama:** cosine similarity of `nomic-embed-text` embeddings, threshold `driftThreshold`.
123
+ - **Without Ollama:** keyword Jaccard similarity, threshold `jaccardThreshold`.
124
+
125
+ Short follow-ups ("yes do it"), slash commands and `!` commands are ignored. A drift note shows at most once every 30 minutes. A bloat note shows when context passes `contextWarnTokens`, and again only after it grows by another 20%. The hook never blocks: it always exits 0 within its time budget (300 ms without Ollama, 1.5 s with it).
126
+
127
+ ### Handoff (`frugal handoff`)
128
+
129
+ Prints a short summary of the current project's latest session: goal, files changed, open TODOs, recent progress and last error. With Ollama, the summary is at most 15 lines. It prints to stdout only.
130
+
131
+ ```bash
132
+ frugal handoff # latest session for the current directory
133
+ frugal handoff --session <id>
134
+ ```
135
+
136
+ ### Other commands
137
+
138
+ | Command | What it does |
139
+ |---|---|
140
+ | `frugal report [--days 30]` | Spend per day, and bytes saved per MCP tool |
141
+ | `frugal doctor` | Read-only checks: Node version, config, permissions, Ollama, hooks/status line/MCP registration, managed-settings locks, Vertex/Bedrock |
142
+ | `frugal init` | Prints snippets to paste |
143
+ | `frugal purge --yes` | Deletes all frugal data |
144
+
145
+ ## Using frugal behind a company wrapper
146
+
147
+ Many companies launch Claude Code through a wrapper that injects settings and credentials (for example, a unified key for Vertex-hosted models). frugal doesn't touch the wrapper, the key or the model route. Claude Code itself runs frugal's hooks, whatever launched it. Things to check, all of which `frugal doctor` reports:
148
+
149
+ - **`CLAUDE_CONFIG_DIR`**: if the wrapper moves Claude Code's config, run `frugal init` and `frugal doctor` *inside a wrapper session* so they look at the right directory. frugal reads transcript paths from Claude Code's hook input and never guesses them.
150
+ - **Managed settings** (`allowManagedHooksOnly`, `disableAllHooks`, `allowedMcpServers`, `managed-mcp.json`): if your admins lock these, ask them to allow frugal's hooks or the `frugal` MCP server. Compression keeps working even if `frugal_fetch` is blocked.
151
+ - **The wrapper's own `--settings` file** can't be inspected by frugal. If the wrapper sets a `statusLine`, use the chaining command from `frugal init`.
152
+ - **Pricing on Vertex**: Claude Code's cost figure is a list-price estimate. Set `costSource: "transcript"` and your rate card in `prices`.
153
+ - **Other agents** (opencode, Codex CLI, …) on the same key are not counted. The meter shows Claude Code spend only.
154
+
155
+ ## Configuration
156
+
157
+ `~/.config/frugal/config.json` (`$XDG_CONFIG_HOME` is honoured). The file is optional, and unknown keys are an error.
158
+
159
+ ```json
160
+ {
161
+ "monthlyCap": 250,
162
+ "currency": "USD",
163
+ "costSource": "auto",
164
+ "prices": {
165
+ "default": { "inputPerMTok": 0, "outputPerMTok": 0, "cacheReadPerMTok": 0, "cacheWritePerMTok": 0 },
166
+ "claude-opus": { "inputPerMTok": 0, "outputPerMTok": 0, "cacheReadPerMTok": 0, "cacheWritePerMTok": 0 }
167
+ },
168
+ "contextWarnTokens": 120000,
169
+ "driftThreshold": 0.35,
170
+ "jaccardThreshold": 0.08,
171
+ "ollama": { "url": "http://127.0.0.1:11434", "chatModel": "qwen3:4b", "embedModel": "nomic-embed-text", "enabled": true },
172
+ "compress": {
173
+ "minBytes": 2048, "maxBytes": 0, "maxArrayItems": 0, "summarize": false, "denyKeys": [],
174
+ "tools": { "mcp__jira__*": { "keepFields": ["key", "summary", "status", "name", "assignee", "displayName", "updated"] } }
175
+ },
176
+ "cache": { "ttlHours": 24, "maxMB": 200 },
177
+ "bash": { "enabled": true, "dedupe": true, "cleanup": true, "minBytes": 1024, "maxAgeMinutes": 60 }
178
+ }
179
+ ```
180
+
181
+ - Price keys match the model id by longest prefix, with `default` as the fallback. Prices default to 0, and frugal never ships guessed prices.
182
+ - `ollama.url` must be a loopback address, or frugal refuses to start.
183
+ - `ollama.chatModel` and `ollama.embedModel` can be any **local** Ollama model. Ollama cloud models (names like `gpt-oss:120b-cloud`) are refused, because the local Ollama sends their prompts to ollama.com. Local aliases of cloud models are detected and refused too, and `frugal doctor` reports them.
184
+ - `compress.tools` keys are exact MCP tool names or prefixes ending in `*`. `{"skip": true}` turns compression off for that tool.
185
+
186
+ ## Data and privacy
187
+
188
+ Stored in `~/.local/share/frugal/` (`$XDG_DATA_HOME` is honoured). Directories are `0700` and files `0600`. Symlinks are refused.
189
+
190
+ | Path | Contents |
191
+ |---|---|
192
+ | `cache/<sha256>.json` | Redacted original tool outputs for `frugal_fetch` (TTL plus size cap) |
193
+ | `sessions/<id>.json` | Session goal (redacted), keywords and embedding (TTL) |
194
+ | `spend.json` | Per-session and per-day cost totals |
195
+ | `metrics.jsonl` | Numbers only: timestamp, kind, tool name, bytes, tokens, cost. No prompt or tool content. |
196
+
197
+ Secret patterns (AWS keys, GitHub/GitLab/Slack tokens, Google API keys, JWTs, `Bearer`/`Basic` auth, private key blocks, `password=`/`api_key=`/`secret=` values) are redacted before anything is cached, logged or sent to Ollama.
198
+
199
+ ## Verifying a release
200
+
201
+ Releases are built by GitHub Actions from the tag, published to npm through trusted publishing (OIDC, so there is no stored npm token) with [provenance](https://docs.npmjs.com/generating-provenance-statements), and the GitHub release includes a CycloneDX SBOM and `SHA256SUMS`.
202
+
203
+ ```bash
204
+ npm audit signatures # verifies npm provenance and registry signatures
205
+ sha256sum -c SHA256SUMS --ignore-missing # after downloading the release assets
206
+ ```
207
+
208
+ frugal has **zero runtime dependencies** (the package contains only `dist/`). Dev dependencies are pinned to exact versions and the lockfile is committed.
209
+
210
+ ## Development
211
+
212
+ ```bash
213
+ npm ci && npm run lint && npm test
214
+ ```
215
+
216
+ Tests run offline. A guard in `test/setup.ts` makes any non-loopback `fetch` throw. The `frugal_fetch` integration test uses the official MCP SDK client against `frugal mcp`.
217
+
218
+ ## Changes from the original v0.1 spec
219
+
220
+ - **Compression is done in a `PostToolUse` hook, not a stdio `mcp-proxy`.** The proxy only covered stdio servers you configure yourself. The hook covers remote HTTP servers (Atlassian, Datadog and Slack ship these) and servers injected by wrappers or admins. Because frugal no longer launches any process, there is no `child_process` anywhere in the code.
221
+ - **Zero runtime dependencies** instead of `@modelcontextprotocol/sdk`. The SDK brings in express, hono and others. `frugal mcp` implements the few JSON-RPC methods it needs, and the SDK is used in tests to check compatibility.
222
+ - **Lossless by default.** The spec's defaults (20 array items, 12 KB cap) cut real data: on GitHub's `search_issues`, only 1 of 30 issues stayed visible. Caps are now opt-in (`0` = off), and with a cap set, frugal shortens strings and drops whole records rather than cutting bytes.
223
+ - Config: `proxy` is renamed `compress`. Added `costSource`, `jaccardThreshold` and `prices.*.cacheWritePerMTok`. `monthlyCap` defaults to 0 (unset), not 250.
224
+ - Requires Node 22 or later instead of 20.
225
+
226
+ ## License
227
+
228
+ MIT
package/SECURITY.md ADDED
@@ -0,0 +1,37 @@
1
+ # Security policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Please report vulnerabilities privately through **GitHub's private vulnerability reporting**:
6
+ the repository's **Security** tab → **Report a vulnerability**. Do not open a public issue.
7
+
8
+ We aim to acknowledge reports within 3 working days and to ship a fix or mitigation for
9
+ confirmed high-severity issues within 14 days.
10
+
11
+ ## Supported versions
12
+
13
+ | Version | Supported |
14
+ |---|---|
15
+ | 0.1.x | ✓ |
16
+
17
+ ## Security design
18
+
19
+ frugal's release-blocking requirements (from the v0.1 spec, §7):
20
+
21
+ | # | Requirement | How it is enforced |
22
+ |---|---|---|
23
+ | S1 | No outbound network except loopback | All network I/O goes through `src/net.ts` (`loopbackFetch`), which refuses non-loopback URLs and redirects. ESLint bans `http`, `https`, `net`. `scripts/check-urls.mjs` fails CI on non-loopback URLs in `src/`. Tests run with a guard that throws on non-loopback `fetch`. Ollama cloud models, and local aliases Ollama serves remotely, are refused in config validation and checked again before each call, because the local daemon would forward the data to ollama.com. |
24
+ | S2 | Secret redaction before cache, logs, Ollama | `src/redact.ts`, applied to cached originals, session goals, handoff output and all Ollama inputs. Covered by fixture tests. |
25
+ | S3 | Never execute content | No `child_process`, `eval`, `Function` or `vm` anywhere in `src/` (ESLint rules plus a static test). frugal spawns no processes. |
26
+ | S4 | 0700/0600 permissions, symlinks refused | `src/paths.ts`: `O_NOFOLLOW`, `lstat` checks, atomic writes. Covered by tests. |
27
+ | S5 | Fail open | Hooks and the status line run in `failOpen()`: any error or timeout exits 0 with no output, so Claude Code keeps the original prompt or tool result. Covered by fault-injection tests. |
28
+ | S6 | Supply chain | Zero runtime dependencies. Exact-pinned dev dependencies, committed lockfile, `npm ci --ignore-scripts`, `npm audit --audit-level=high` in CI, GitHub Actions pinned by commit SHA. |
29
+ | S7 | Release integrity | Built in GitHub Actions from the tag behind an approval-gated `release` environment. Published with npm trusted publishing (OIDC, no long-lived npm token) and provenance. CycloneDX SBOM and SHA256SUMS attached to the release. |
30
+ | S8 | No telemetry, analytics or update checks | Code review plus the S1 controls. |
31
+ | S9 | Never modifies Claude Code config or repo files | `init` only prints and `doctor` only reads (tested). All writes stay inside frugal's data dir. |
32
+
33
+ ## Threat notes
34
+
35
+ - Tool output is untrusted. frugal parses it as JSON or text only, never executes it, and the local summarization prompt tells the model to ignore instructions in the content.
36
+ - `frugal_fetch` ids are validated as 64 hex characters before any file access (no path traversal).
37
+ - Cached originals are redacted, so `frugal_fetch` never returns a secret that the redaction patterns recognise.
package/dist/cache.js ADDED
@@ -0,0 +1,69 @@
1
+ // Original tool outputs for frugal_fetch, plus TTL/size pruning (spec §6).
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { dataPath, ensurePrivateDir, readPrivateJson, writePrivateFile } from "./paths.js";
6
+ const ID_RE = /^[0-9a-f]{64}$/;
7
+ export function cacheDir() {
8
+ return dataPath("cache");
9
+ }
10
+ export function putOriginal(tool, text) {
11
+ const id = createHash("sha256").update(text).digest("hex");
12
+ const entry = { v: 1, ts: Date.now(), tool, text };
13
+ ensurePrivateDir(cacheDir());
14
+ writePrivateFile(path.join(cacheDir(), `${id}.json`), JSON.stringify(entry));
15
+ return id;
16
+ }
17
+ export function getOriginal(id) {
18
+ if (!ID_RE.test(id))
19
+ return undefined;
20
+ const e = readPrivateJson(path.join(cacheDir(), `${id}.json`));
21
+ return e && typeof e.text === "string" ? e : undefined;
22
+ }
23
+ /** Delete entries older than the TTL, then oldest-first until under maxMB. Also expires session files. */
24
+ export function pruneStore(ttlHours, maxMB, now = Date.now()) {
25
+ let removed = 0;
26
+ const ttlMs = ttlHours * 3600_000;
27
+ for (const sub of ["cache", "sessions"]) {
28
+ const dir = dataPath(sub);
29
+ let names;
30
+ try {
31
+ names = fs.readdirSync(dir);
32
+ }
33
+ catch {
34
+ continue;
35
+ }
36
+ const files = [];
37
+ for (const n of names) {
38
+ const p = path.join(dir, n);
39
+ const st = fs.lstatSync(p);
40
+ if (!st.isFile())
41
+ continue;
42
+ if (now - st.mtimeMs > ttlMs) {
43
+ fs.rmSync(p, { force: true });
44
+ removed++;
45
+ }
46
+ else
47
+ files.push({ p, mtime: st.mtimeMs, size: st.size });
48
+ }
49
+ if (sub === "cache") {
50
+ let total = files.reduce((a, f) => a + f.size, 0);
51
+ const cap = maxMB * 1024 * 1024;
52
+ files.sort((a, b) => a.mtime - b.mtime);
53
+ for (const f of files) {
54
+ if (total <= cap)
55
+ break;
56
+ fs.rmSync(f.p, { force: true });
57
+ total -= f.size;
58
+ removed++;
59
+ }
60
+ }
61
+ }
62
+ return { removed };
63
+ }
64
+ export function sliceText(text, offset, limit) {
65
+ const total = text.length;
66
+ const start = Math.max(0, Math.min(offset, total));
67
+ const end = Math.min(total, start + limit);
68
+ return { chunk: text.slice(start, end), next: end < total ? end : undefined, total };
69
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+ // frugal: a local copilot for your AI copilot. No data leaves your machine.
3
+ import { parseArgs } from "node:util";
4
+ import * as fs from "node:fs";
5
+ import { loadConfig } from "./config.js";
6
+ import { failOpen, parseJsonObject, readStdin } from "./io.js";
7
+ import { dataDir } from "./paths.js";
8
+ import { VERSION } from "./version.js";
9
+ const HELP = `frugal ${VERSION}: local-only cost helper for Claude Code
10
+
11
+ Usage:
12
+ frugal hook tool-output PostToolUse hook: shrink MCP tool output
13
+ frugal hook prompt UserPromptSubmit hook: drift and context warnings
14
+ frugal statusline status line command: spend and context meter
15
+ frugal mcp stdio MCP server providing frugal_fetch
16
+ frugal handoff [--session <id>] [--transcript <path>]
17
+ frugal report [--days 30]
18
+ frugal doctor check config, Ollama, permissions, Claude Code setup
19
+ frugal init print config snippets to paste (never edits files)
20
+ frugal purge --yes delete all frugal data (${"$"}XDG_DATA_HOME/frugal)
21
+ frugal --version
22
+ `;
23
+ async function main(argv) {
24
+ const [cmd, ...rest] = argv;
25
+ switch (cmd) {
26
+ case "hook": {
27
+ const sub = rest[0];
28
+ if (sub === "prompt") {
29
+ return failOpen(1400, async () => {
30
+ const input = parseJsonObject(await readStdin());
31
+ if (!input)
32
+ return undefined;
33
+ const { handlePrompt } = await import("./hooks/prompt.js");
34
+ return handlePrompt(input, loadConfig());
35
+ });
36
+ }
37
+ if (sub === "tool-output") {
38
+ return failOpen(25_000, async () => {
39
+ const input = parseJsonObject(await readStdin());
40
+ if (!input)
41
+ return undefined;
42
+ if (input.tool_name === "Bash") {
43
+ const { handleBashOutput } = await import("./hooks/bashOutput.js");
44
+ return handleBashOutput(input, loadConfig());
45
+ }
46
+ const { handleToolOutput } = await import("./hooks/toolOutput.js");
47
+ return handleToolOutput(input, loadConfig());
48
+ });
49
+ }
50
+ process.stderr.write("usage: frugal hook <prompt|tool-output>\n");
51
+ return 0; // never break Claude Code over a bad registration
52
+ }
53
+ case "statusline":
54
+ return failOpen(2000, async () => {
55
+ const input = parseJsonObject(await readStdin()) ?? {};
56
+ const { renderStatus } = await import("./statusline.js");
57
+ return renderStatus(input, loadConfig(), Date.now(), !process.env.NO_COLOR) + "\n";
58
+ });
59
+ case "mcp": {
60
+ const { runMcpServer } = await import("./mcpServer.js");
61
+ await runMcpServer();
62
+ return 0;
63
+ }
64
+ case "handoff": {
65
+ const { values } = parseArgs({ args: rest, options: { session: { type: "string" }, transcript: { type: "string" } } });
66
+ const { handoff } = await import("./handoff.js");
67
+ process.stdout.write((await handoff(loadConfig(), { session: values.session, transcript: values.transcript, cwd: process.cwd() })) + "\n");
68
+ return 0;
69
+ }
70
+ case "report": {
71
+ const { values } = parseArgs({ args: rest, options: { days: { type: "string", default: "30" } } });
72
+ const days = Math.max(1, Math.min(366, Number.parseInt(values.days ?? "30", 10) || 30));
73
+ const { report } = await import("./report.js");
74
+ process.stdout.write(report(loadConfig(), days) + "\n");
75
+ return 0;
76
+ }
77
+ case "doctor": {
78
+ const { doctor } = await import("./doctor.js");
79
+ const r = await doctor();
80
+ process.stdout.write(r.text + "\n");
81
+ return r.ok ? 0 : 1;
82
+ }
83
+ case "init": {
84
+ const { initText } = await import("./init.js");
85
+ process.stdout.write(initText() + "\n");
86
+ return 0;
87
+ }
88
+ case "purge": {
89
+ const { values } = parseArgs({ args: rest, options: { yes: { type: "boolean", default: false } } });
90
+ const dir = dataDir();
91
+ if (!values.yes) {
92
+ process.stdout.write(`This deletes everything in ${dir}. Re-run with --yes to confirm.\n`);
93
+ return 1;
94
+ }
95
+ let st;
96
+ try {
97
+ st = fs.lstatSync(dir);
98
+ }
99
+ catch {
100
+ process.stdout.write("nothing to purge\n");
101
+ return 0;
102
+ }
103
+ if (st.isSymbolicLink()) {
104
+ process.stderr.write(`refusing: ${dir} is a symlink\n`);
105
+ return 1;
106
+ }
107
+ fs.rmSync(dir, { recursive: true, force: true });
108
+ process.stdout.write(`purged ${dir}\n`);
109
+ return 0;
110
+ }
111
+ case "--version":
112
+ case "-v":
113
+ case "version":
114
+ process.stdout.write(VERSION + "\n");
115
+ return 0;
116
+ case undefined:
117
+ case "help":
118
+ case "--help":
119
+ case "-h":
120
+ process.stdout.write(HELP);
121
+ return 0;
122
+ default:
123
+ process.stderr.write(`unknown command: ${cmd}\n\n${HELP}`);
124
+ return 2;
125
+ }
126
+ }
127
+ main(process.argv.slice(2)).then((code) => {
128
+ process.exitCode = code;
129
+ }, (e) => {
130
+ process.stderr.write(`frugal: ${e.message}\n`);
131
+ process.exitCode = 1;
132
+ });
@@ -0,0 +1,149 @@
1
+ // Deterministic pruning pipeline for MCP tool output (spec §4.1 steps 1-7).
2
+ import { htmlToText, looksLikeHtml } from "./html.js";
3
+ export const DEFAULT_DENY = ["avatarUrls", "self", "_links", "iconUrl", "expand", "node_id"];
4
+ // eslint-disable-next-line no-control-regex -- matching ANSI escapes is the point
5
+ const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g;
6
+ export function byteLen(s) {
7
+ return Buffer.byteLength(s, "utf8");
8
+ }
9
+ function isEmpty(v) {
10
+ if (v === null || v === undefined || v === "")
11
+ return true;
12
+ if (Array.isArray(v))
13
+ return v.length === 0;
14
+ if (typeof v === "object")
15
+ return Object.keys(v).length === 0;
16
+ return false;
17
+ }
18
+ /** Counter blocks where nothing happened, e.g. {"+1":0,"-1":0,"heart":0,...}: at least 3 keys, all 0/false. */
19
+ function isAllZero(v) {
20
+ if (typeof v !== "object" || v === null || Array.isArray(v))
21
+ return false;
22
+ const vals = Object.values(v);
23
+ return vals.length >= 3 && vals.every((x) => x === 0 || x === false);
24
+ }
25
+ function prune(v, o, deny, keep) {
26
+ if (Array.isArray(v)) {
27
+ const items = v.map((x) => prune(x, o, deny, keep)).filter((x) => !isEmpty(x));
28
+ if (o.maxArrayItems > 0 && items.length > o.maxArrayItems) {
29
+ const extra = items.length - o.maxArrayItems;
30
+ return [...items.slice(0, o.maxArrayItems), `…${extra} more`];
31
+ }
32
+ return items;
33
+ }
34
+ if (typeof v === "object" && v !== null) {
35
+ const src = v;
36
+ const hasHtmlUrl = "html_url" in src;
37
+ // A human-readable identifier makes a numeric surrogate id redundant (GitHub number/login, Jira key).
38
+ const hasHumanId = ["number", "key", "login", "slug"].some((k) => typeof src[k] === "string" || typeof src[k] === "number");
39
+ const out = {};
40
+ for (const [k, x] of Object.entries(src)) {
41
+ if (deny.has(k))
42
+ continue;
43
+ if (hasHtmlUrl && k !== "html_url" && (k.endsWith("_url") || k === "url"))
44
+ continue;
45
+ if (hasHumanId && k === "id" && (typeof x === "number" || (typeof x === "string" && /^\d+$/.test(x))))
46
+ continue;
47
+ const isContainer = typeof x === "object" && x !== null;
48
+ if (keep && !keep.has(k) && !isContainer)
49
+ continue;
50
+ const p = prune(x, o, deny, keep);
51
+ if (keep && !keep.has(k) && isContainer && isEmpty(p))
52
+ continue;
53
+ if (isEmpty(p) || isAllZero(p))
54
+ continue;
55
+ out[k] = p;
56
+ }
57
+ return out;
58
+ }
59
+ if (typeof v === "string")
60
+ return cleanText(looksLikeHtml(v) ? htmlToText(v) : v);
61
+ return v;
62
+ }
63
+ /**
64
+ * Conservative, content-preserving cleanup: ANSI codes, CRLF, trailing whitespace, runs of 3+
65
+ * blank lines. Never touches spacing inside a line, so code indentation and alignment survive.
66
+ */
67
+ export function cleanText(s) {
68
+ return s
69
+ .replace(ANSI, "")
70
+ .replace(/\r\n?/g, "\n")
71
+ .replace(/[ \t\f\v]+\n/g, "\n")
72
+ .replace(/[ \t\f\v]+$/, "")
73
+ .replace(/\n{4,}/g, "\n\n\n");
74
+ }
75
+ export function capBytes(s, max) {
76
+ if (max <= 0 || byteLen(s) <= max)
77
+ return s;
78
+ const marker = "\n…[frugal: truncated]";
79
+ const budget = Math.max(0, max - byteLen(marker));
80
+ // Cut on a UTF-8 boundary.
81
+ const buf = Buffer.from(s, "utf8").subarray(0, budget);
82
+ let cut = buf.toString("utf8");
83
+ if (cut.endsWith("�"))
84
+ cut = cut.slice(0, -1);
85
+ return cut + marker;
86
+ }
87
+ /** Steps 1-6. Returns the pruned text (before the byte cap). */
88
+ export function pruneText(text, o) {
89
+ const deny = new Set([...DEFAULT_DENY, ...o.denyKeys]);
90
+ const keep = o.keepFields && o.keepFields.length ? new Set(o.keepFields) : undefined;
91
+ const trimmed = text.trim();
92
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
93
+ try {
94
+ const parsed = JSON.parse(trimmed);
95
+ return fitJson(prune(parsed, o, deny, keep) ?? null, o);
96
+ }
97
+ catch {
98
+ // not JSON, fall through
99
+ }
100
+ }
101
+ return cleanText(looksLikeHtml(text) ? htmlToText(text) : text);
102
+ }
103
+ function shrink(v, maxStr, maxItems) {
104
+ if (typeof v === "string") {
105
+ return v.length > maxStr ? `${v.slice(0, maxStr)}…[+${v.length - maxStr} chars]` : v;
106
+ }
107
+ if (Array.isArray(v)) {
108
+ const isMarker = (x) => typeof x === "string" && /^…\d+ more$/.test(x);
109
+ const real = v.filter((x) => !isMarker(x));
110
+ const prevExtra = v.filter(isMarker).reduce((a, x) => a + Number(/\d+/.exec(x)[0]), 0);
111
+ const kept = real.slice(0, maxItems).map((x) => shrink(x, maxStr, maxItems));
112
+ const extra = real.length - kept.length + prevExtra;
113
+ return extra > 0 ? [...kept, `…${extra} more`] : kept;
114
+ }
115
+ if (typeof v === "object" && v !== null) {
116
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, shrink(x, maxStr, maxItems)]));
117
+ }
118
+ return v;
119
+ }
120
+ /**
121
+ * Step 7 for JSON: fit under maxBytes structurally instead of cutting bytes, so every
122
+ * record keeps its ids/titles. Shorten long strings first, then thin arrays.
123
+ */
124
+ export function fitJson(v, o) {
125
+ let s = JSON.stringify(v);
126
+ if (o.maxBytes <= 0 || byteLen(s) <= o.maxBytes)
127
+ return s;
128
+ const cap = o.maxArrayItems > 0 ? o.maxArrayItems : 1000;
129
+ // 1) shorten long strings, keeping every record
130
+ for (const maxStr of [2000, 600, 240, 120, 80]) {
131
+ s = JSON.stringify(shrink(v, maxStr, cap));
132
+ if (byteLen(s) <= o.maxBytes)
133
+ return s;
134
+ }
135
+ // 2) then keep as many records as fit (largest n first)
136
+ for (let n = Math.min(cap, 100) - 1; n >= 1; n--) {
137
+ s = JSON.stringify(shrink(v, 80, n));
138
+ if (byteLen(s) <= o.maxBytes)
139
+ return s;
140
+ }
141
+ return s; // compressText's byte cap is the last resort
142
+ }
143
+ /** Full deterministic pipeline: steps 1-7. */
144
+ export function compressText(text, o) {
145
+ return capBytes(pruneText(text, o), o.maxBytes);
146
+ }
147
+ export function fmtKB(bytes) {
148
+ return `${(bytes / 1024).toFixed(1)}KB`;
149
+ }