@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.
- package/CHANGELOG.md +31 -0
- package/README.md +84 -12
- package/SECURITY.md +4 -0
- package/dist/cache.js +1 -1
- package/dist/cli.js +62 -2
- package/dist/compress.js +114 -9
- package/dist/config.js +17 -2
- package/dist/doctor.js +4 -0
- package/dist/explain.js +111 -0
- package/dist/handoff.js +97 -12
- package/dist/hooks/bashOutput.js +11 -66
- package/dist/hooks/prompt.js +17 -6
- package/dist/hooks/toolOutput.js +144 -44
- package/dist/init.js +4 -0
- package/dist/local.js +86 -0
- package/dist/mcpServer.js +4 -0
- package/dist/metrics.js +71 -2
- package/dist/pause.js +33 -0
- package/dist/report.js +70 -25
- package/dist/route.js +231 -0
- package/dist/seen.js +70 -0
- package/dist/statusline.js +7 -0
- package/dist/transcript.js +121 -3
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0 (2026-12-03)
|
|
4
|
+
|
|
5
|
+
Driven by a real-world A/B on chat, issue-tracker and wiki MCP tools, where chat (markdown inside JSON) and dense issue JSON were left untouched by the lossless default and invisible in the report.
|
|
6
|
+
|
|
7
|
+
**Visibility**
|
|
8
|
+
- `frugal report` lists every MCP and Bash tool seen: calls, changed, bytes in/out, how many were left alone and why (small, saving under threshold, write result, file contents, paused, …), and the fetch-back rate.
|
|
9
|
+
- `frugal_fetch` calls are counted per tool. A tool whose shortened output is fetched back more than 30% of the time has its lossy rules paused automatically (lossless pruning continues).
|
|
10
|
+
- The footer says what changed: fields and list items removed, texts shortened, items ranked or summarized.
|
|
11
|
+
- `frugal explain`: dry run on one saved result, stage by stage, without changing anything.
|
|
12
|
+
|
|
13
|
+
**Compression**
|
|
14
|
+
- Per-tool, opt-in `itemMaxChars`: caps prose per record, including records inside one long markdown string, so later results never vanish. Lines with ids, URLs, dates, numbers with units, errors, stack traces or code are always kept.
|
|
15
|
+
- Per-tool `maxItems`.
|
|
16
|
+
- Threshold is now "at least 10% **or** at least 4 KB saved" (`minSavingPct`, `minSavingBytes`).
|
|
17
|
+
- Results of write tools (create/update/delete/send/comment/transition …) are never changed.
|
|
18
|
+
- Identical MCP results already in context become a pointer (`compress.dedupe`), with the same compaction-aware rules as Bash.
|
|
19
|
+
|
|
20
|
+
Benchmarks: [docs/BENCHMARK-0.2.md](docs/BENCHMARK-0.2.md). No accuracy loss in any variant on Sonnet 5.5 or Opus 5.5. Per-item caps: −8% / −11% per chat-search task. Ranking cut tool output by 55–62% but often cost more because the model fetched the full output back, so it is marked experimental.
|
|
21
|
+
|
|
22
|
+
**Local-model routing (opt-in per tool, `route`; experimental)**
|
|
23
|
+
- `rank`: local embeddings rank items by relevance to the request; the top `routing.topK` stay in full, the rest become headlines with ids and links. Order is kept and no item disappears.
|
|
24
|
+
- `summarize`: a local ~4B model turns long prose items into bullets, accepted only if every URL, id, hash, number and quoted/code string of the original appears in the summary.
|
|
25
|
+
- Time budget with fallback to the rules; loopback only; input redacted.
|
|
26
|
+
- `frugal setup-local [--yes]`: checks Ollama and memory, pulls missing models on request, times them, and suggests a config.
|
|
27
|
+
|
|
28
|
+
**Long sessions**
|
|
29
|
+
- `PreCompact` hook: tells Claude Code's compaction summary which facts to keep verbatim and saves a handoff draft. Optional `SessionStart` reinjection after compaction (`compaction.reinject`).
|
|
30
|
+
- `frugal handoff`: fixed template with commands that worked and links/ids; the local model may add Decisions and Open questions, and lines with unverifiable facts are dropped.
|
|
31
|
+
- Bloat note names what is large ("3 mcp__slack__search results ≈ 41%").
|
|
32
|
+
- `frugal pause` / `frugal resume`, shown in the status line.
|
|
33
|
+
|
|
3
34
|
## 0.1.1 (2026-12-03)
|
|
4
35
|
|
|
5
36
|
- `frugal init` now reads your settings and prints ready-to-run commands instead of snippets to paste: one command merges frugal into `settings.json` (with a backup, keeping an existing status line alongside frugal's), one adds the MCP server. Steps already done are skipped. New `frugal init --settings` prints the merged file. frugal still never writes Claude Code's config itself (S9).
|
package/README.md
CHANGED
|
@@ -31,6 +31,8 @@ frugal doctor # checks config, permissions, Ollama and your Claude Code setup
|
|
|
31
31
|
1) Add to ~/.claude/settings.json (a backup goes to settings.json.bak-frugal):
|
|
32
32
|
+ PostToolUse hook (shrinks MCP and Bash output)
|
|
33
33
|
+ UserPromptSubmit hook (drift and context warnings)
|
|
34
|
+
+ PreCompact hook (keeps key facts through compaction)
|
|
35
|
+
+ SessionStart hook (restores saved facts after compaction, if you turn it on)
|
|
34
36
|
+ status line (spend and context meter)
|
|
35
37
|
|
|
36
38
|
( mkdir -p "$HOME/.claude" && cd "$HOME/.claude" && frugal init --settings > settings.json.frugal-new && cp settings.json settings.json.bak-frugal && mv settings.json.frugal-new settings.json )
|
|
@@ -76,9 +78,26 @@ By default frugal is **lossless about content**: it removes noise and never shor
|
|
|
76
78
|
4. Apply the per-tool `keepFields` allow list, if you configure one.
|
|
77
79
|
5. Strip ANSI codes, collapse whitespace and write JSON compactly.
|
|
78
80
|
|
|
79
|
-
|
|
81
|
+
frugal changes a result only if that saves at least 10% (`minSavingPct`) **or** at least 4 KB (`minSavingBytes`); on large results a small percentage is still many tokens. Otherwise the result is left untouched, and `frugal report` says so (see below).
|
|
80
82
|
|
|
81
|
-
|
|
83
|
+
Always left exact, whatever the config:
|
|
84
|
+
|
|
85
|
+
- **Results of write tools** (`create…`, `update…`, `delete…`, `send…`, `add…Comment`, `transition…`, …): they are confirmations, and ids in them get used next.
|
|
86
|
+
- **File contents** (`read_file`, `get_file_contents`, …): Claude copies exact text from them into edits.
|
|
87
|
+
- `frugal_fetch` itself.
|
|
88
|
+
|
|
89
|
+
**Repeats.** If an MCP tool returns exactly the same result again in a session while the first copy is still in context, Claude gets a one-line pointer to it instead (same rules as Bash repeat-skip below; `compress.dedupe`).
|
|
90
|
+
|
|
91
|
+
**Shortening is opt-in, per tool** (`compress.tools`, matched by name or `prefix*`):
|
|
92
|
+
|
|
93
|
+
| Rule | What it does | Good for |
|
|
94
|
+
|---|---|---|
|
|
95
|
+
| `keepFields: [...]` | keep only these fields per record | dense JSON (issue search) |
|
|
96
|
+
| `itemMaxChars: 400` | cap the **prose** in each record to N chars. Lines with ids, URLs, dates, numbers with units, errors, stack traces or code are always kept whole. Inside one long text (e.g. a chat search returning markdown in JSON) every record gets its own budget, so later results never disappear. | chat search, wiki excerpts |
|
|
97
|
+
| `maxItems: 30` | keep the first N items of each list, mark the rest `…N more` | very long lists |
|
|
98
|
+
| `route: "rank" \| "summarize" \| "both"` | local-model routing, see below | search results, long pages |
|
|
99
|
+
|
|
100
|
+
The global `maxBytes` cap still exists, but a per-item cap is safer: a single size cap on a whole result cuts it from the end, so the last records vanish. When a cap is set and pruning can't get under it, `summarize: true` makes the local model summarize instead.
|
|
82
101
|
|
|
83
102
|
Measured with the default lossless settings:
|
|
84
103
|
|
|
@@ -92,16 +111,48 @@ Measured with the default lossless settings:
|
|
|
92
111
|
|
|
93
112
|
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.
|
|
94
113
|
|
|
95
|
-
When frugal changes an output, it adds one line:
|
|
114
|
+
When frugal changes an output, it adds one line saying what changed:
|
|
96
115
|
|
|
97
116
|
```
|
|
98
|
-
[frugal: compressed
|
|
117
|
+
[frugal: compressed 41.2KB → 12.9KB (−69%); removed 212 empty/noise fields; shortened prose in 20 texts (ids, links, dates, errors and code kept). Some content is shortened (marked …); if you need every item or the full text, Full output: call frugal_fetch with id "<sha256>"]
|
|
99
118
|
```
|
|
100
119
|
|
|
120
|
+
**Round-trip budget.** Every `frugal_fetch` is counted per tool. If the model fetches a tool's full output back more than 30% of the time (at least 5 shortened results in the last 7 days), frugal stops applying that tool's lossy rules and falls back to lossless pruning, because saved tokens that are re-read are not savings. `frugal report` flags it.
|
|
121
|
+
|
|
101
122
|
`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.
|
|
102
123
|
|
|
103
124
|
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.
|
|
104
125
|
|
|
126
|
+
### Local-model routing (opt-in, `route`)
|
|
127
|
+
|
|
128
|
+
> **Experimental.** Measured in [docs/BENCHMARK-0.2.md](docs/BENCHMARK-0.2.md): ranking cut chat and issue search output by 55–62% with no accuracy loss, but when a question covers *every* item the model often fetched the full result back, which made the task cost more. Use `rank` for tools where you ask about a few items, and watch the fetch-back column in `frugal report` (frugal switches a tool's lossy rules off by itself above 30%). For chat search, `itemMaxChars` was the measured win (−8% Sonnet, −11% Opus per task, no fetch-backs).
|
|
129
|
+
|
|
130
|
+
Local tokens cost nothing and never leave the machine, so frugal can use a small local model for work that rules can't do. Each step is cheaper than the next, and each falls back to the step before it:
|
|
131
|
+
|
|
132
|
+
1. **Rules** (always): noise pruning above. Free and exact.
|
|
133
|
+
2. **Rank** (`route: "rank"`, embeddings): frugal embeds what was asked (the tool's query fields plus your latest prompt) and each result item. The `routing.topK` (5) most relevant items stay in full; the others become **headlines**: their ids, title, status, dates and links, marked as such. Items keep their original order and none disappear.
|
|
134
|
+
3. **Summarize** (`route: "summarize"`, ~4B chat model): long prose items (over `routing.summarizeMinChars`, 1,500 chars) become 3–5 bullets. **Verify before replace:** every URL, issue key, hash, number and quoted or code string in the original must appear in the summary, or the original is kept. Code, stack traces and structured data are never summarized.
|
|
135
|
+
4. The paid model gets the result.
|
|
136
|
+
|
|
137
|
+
`route: "both"` ranks, then summarizes what is still long. Safety rules:
|
|
138
|
+
|
|
139
|
+
- Loopback only; Ollama cloud models and local aliases of them are refused (S1). Input is redacted first (S2).
|
|
140
|
+
- A time budget (`routing.budgetMs`, 12 s) for the whole step, inside the hook's own limit. If the model is slow, missing or wrong, the rules output is used.
|
|
141
|
+
- Results under `minBytes` never reach the model.
|
|
142
|
+
|
|
143
|
+
Get the models and time them on your machine:
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
frugal setup-local # checks Ollama, memory and models, then times embeddings and a summary
|
|
147
|
+
frugal setup-local --yes # also asks your local Ollama to download missing models (several GB)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
On machines with under 12 GB of memory it suggests ranking only. Then try a rule on a real result before turning it on:
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
frugal explain result.json --tool mcp__slack__slack_search_messages --local --query "what did the payments team decide"
|
|
154
|
+
```
|
|
155
|
+
|
|
105
156
|
### Bash output (same hook)
|
|
106
157
|
|
|
107
158
|
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:
|
|
@@ -132,11 +183,18 @@ The first prompt of a session becomes its goal. Later prompts are compared to th
|
|
|
132
183
|
- **With Ollama:** cosine similarity of `nomic-embed-text` embeddings, threshold `driftThreshold`.
|
|
133
184
|
- **Without Ollama:** keyword Jaccard similarity, threshold `jaccardThreshold`.
|
|
134
185
|
|
|
135
|
-
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).
|
|
186
|
+
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%. It says what is large, for example `Largest: 3 mcp__slack__search results ≈ 41%`. The hook never blocks: it always exits 0 within its time budget (300 ms without Ollama, 1.5 s with it).
|
|
187
|
+
|
|
188
|
+
### Handoff and compaction (`frugal handoff`, `frugal hook pre-compact`)
|
|
136
189
|
|
|
137
|
-
|
|
190
|
+
`frugal handoff` prints a fixed-template summary of the current project's latest session, ready to paste into a fresh one: goal, last request, files changed, commands that worked, links and ids, open TODOs, recent progress and last error. These come straight from the transcript. With Ollama, a local model adds **Decisions** and **Open questions**, and any line whose ids, numbers or links don't appear in the facts is dropped. It prints to stdout only.
|
|
138
191
|
|
|
139
|
-
|
|
192
|
+
Before Claude Code compacts a session, the `PreCompact` hook:
|
|
193
|
+
|
|
194
|
+
- tells the compaction summary which facts to keep verbatim (goal, files, open TODOs, commands that worked, ids and links, last error) and to drop raw tool output that has already been used. Claude Code uses a PreCompact hook's output as extra instructions for its summary.
|
|
195
|
+
- saves a handoff draft for the session in frugal's data dir (expires with the cache TTL).
|
|
196
|
+
|
|
197
|
+
With `compaction.reinject: true`, the `SessionStart` hook puts those saved facts back into context right after compaction (off by default: it adds up to 4 KB).
|
|
140
198
|
|
|
141
199
|
```bash
|
|
142
200
|
frugal handoff # latest session for the current directory
|
|
@@ -147,7 +205,10 @@ frugal handoff --session <id>
|
|
|
147
205
|
|
|
148
206
|
| Command | What it does |
|
|
149
207
|
|---|---|
|
|
150
|
-
| `frugal report [--days 30]` | Spend per day, and
|
|
208
|
+
| `frugal report [--days 30]` | Spend per day, and **every** MCP and Bash tool seen: calls, how many were changed, bytes in and out, how many were left alone and why (small, saving under threshold, write result, file contents, paused…), and how often the full output was fetched back |
|
|
209
|
+
| `frugal explain <file\|-> [--tool name] [--id id] [--query text] [--local] [--print]` | Dry run on one saved result (raw text, MCP content, or a hook payload): what each stage would remove and how much, and whether the hook would replace it. Changes nothing. Use it as an A/B on a single result |
|
|
210
|
+
| `frugal pause [--minutes N]` / `frugal resume` | Pass all output through unchanged, without editing settings (a flag in frugal's data dir; the status line shows `paused`) |
|
|
211
|
+
| `frugal setup-local [--yes]` | Check, pull and time the local models |
|
|
151
212
|
| `frugal doctor` | Read-only checks: Node version, config, permissions, Ollama, hooks/status line/MCP registration, managed-settings locks, Vertex/Bedrock |
|
|
152
213
|
| `frugal init` | Prints ready-to-run setup commands (`--settings`: your settings.json with frugal merged in) |
|
|
153
214
|
| `frugal purge --yes` | Deletes all frugal data |
|
|
@@ -181,8 +242,14 @@ Many companies launch Claude Code through a wrapper that injects settings and cr
|
|
|
181
242
|
"ollama": { "url": "http://127.0.0.1:11434", "chatModel": "qwen3:4b", "embedModel": "nomic-embed-text", "enabled": true },
|
|
182
243
|
"compress": {
|
|
183
244
|
"minBytes": 2048, "maxBytes": 0, "maxArrayItems": 0, "summarize": false, "denyKeys": [],
|
|
184
|
-
"
|
|
245
|
+
"minSavingPct": 10, "minSavingBytes": 4096, "dedupe": true,
|
|
246
|
+
"tools": {
|
|
247
|
+
"mcp__jira__*": { "keepFields": ["key", "summary", "status", "name", "assignee", "displayName", "updated"] },
|
|
248
|
+
"mcp__slack__*": { "itemMaxChars": 600, "route": "rank" }
|
|
249
|
+
}
|
|
185
250
|
},
|
|
251
|
+
"routing": { "topK": 5, "budgetMs": 12000, "summarizeMinChars": 1500, "maxSummaries": 6 },
|
|
252
|
+
"compaction": { "instructions": true, "reinject": false },
|
|
186
253
|
"cache": { "ttlHours": 24, "maxMB": 200 },
|
|
187
254
|
"bash": { "enabled": true, "dedupe": true, "cleanup": true, "minBytes": 1024, "maxAgeMinutes": 60 }
|
|
188
255
|
}
|
|
@@ -191,7 +258,8 @@ Many companies launch Claude Code through a wrapper that injects settings and cr
|
|
|
191
258
|
- Price keys match the model id by longest prefix, with `default` as the fallback. Prices default to 0, and frugal never ships guessed prices.
|
|
192
259
|
- `ollama.url` must be a loopback address, or frugal refuses to start.
|
|
193
260
|
- `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.
|
|
194
|
-
- `compress.tools` keys are exact MCP tool names or prefixes ending in
|
|
261
|
+
- `compress.tools` keys are exact MCP tool names or prefixes ending in `*` (the longest matching prefix wins). `{"skip": true}` turns compression off for that tool.
|
|
262
|
+
- **A/B without restarting:** in our testing, edits to hooks in `settings.json` were picked up by a running Claude Code session. Claude Code doesn't document this, so check with `/hooks`. `frugal pause` / `frugal resume` is the supported way to compare with and without frugal mid-session.
|
|
195
263
|
|
|
196
264
|
## Data and privacy
|
|
197
265
|
|
|
@@ -200,9 +268,13 @@ Stored in `~/.local/share/frugal/` (`$XDG_DATA_HOME` is honoured). Directories a
|
|
|
200
268
|
| Path | Contents |
|
|
201
269
|
|---|---|
|
|
202
270
|
| `cache/<sha256>.json` | Redacted original tool outputs for `frugal_fetch` (TTL plus size cap) |
|
|
203
|
-
| `sessions/<id>.json` | Session goal (redacted), keywords and embedding (TTL) |
|
|
271
|
+
| `sessions/<id>.json` | Session goal (redacted), keywords and embedding; hashes of results already shown, for repeat-skip (TTL) |
|
|
272
|
+
| `handoffs/<id>.md` | Handoff draft saved before compaction (redacted, TTL) |
|
|
273
|
+
| `paused.json` | Present while `frugal pause` is on |
|
|
204
274
|
| `spend.json` | Per-session and per-day cost totals |
|
|
205
|
-
| `metrics.jsonl` | Numbers only: timestamp, kind, tool name, bytes, tokens, cost. No prompt or tool content. |
|
|
275
|
+
| `metrics.jsonl` | Numbers only: timestamp, kind, outcome (from a fixed list), tool name, bytes, counts of removed fields/items/texts, tokens, cost, durations. No prompt or tool content. |
|
|
276
|
+
|
|
277
|
+
`frugal setup-local --yes` asks your local Ollama to download models; the download is done by the Ollama daemon, not by frugal, which still only talks to loopback.
|
|
206
278
|
|
|
207
279
|
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.
|
|
208
280
|
|
package/SECURITY.md
CHANGED
|
@@ -12,6 +12,7 @@ confirmed high-severity issues within 14 days.
|
|
|
12
12
|
|
|
13
13
|
| Version | Supported |
|
|
14
14
|
|---|---|
|
|
15
|
+
| 0.2.x | ✓ |
|
|
15
16
|
| 0.1.x | ✓ |
|
|
16
17
|
|
|
17
18
|
## Security design
|
|
@@ -32,6 +33,9 @@ frugal's release-blocking requirements (from the v0.1 spec, §7):
|
|
|
32
33
|
|
|
33
34
|
## Threat notes
|
|
34
35
|
|
|
36
|
+
- Local-model routing (opt-in) sends redacted tool output to the loopback Ollama only. A local summary replaces original text only if every URL, id, hash, number and quoted/code string of the original appears in it; otherwise the original is kept.
|
|
37
|
+
- `frugal setup-local --yes` asks the local Ollama daemon to download models. frugal itself still talks only to loopback.
|
|
38
|
+
|
|
35
39
|
- 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
40
|
- `frugal_fetch` ids are validated as 64 hex characters before any file access (no path traversal).
|
|
37
41
|
- Cached originals are redacted, so `frugal_fetch` never returns a secret that the redaction patterns recognise.
|
package/dist/cache.js
CHANGED
|
@@ -24,7 +24,7 @@ export function getOriginal(id) {
|
|
|
24
24
|
export function pruneStore(ttlHours, maxMB, now = Date.now()) {
|
|
25
25
|
let removed = 0;
|
|
26
26
|
const ttlMs = ttlHours * 3600_000;
|
|
27
|
-
for (const sub of ["cache", "sessions"]) {
|
|
27
|
+
for (const sub of ["cache", "sessions", "handoffs"]) {
|
|
28
28
|
const dir = dataPath(sub);
|
|
29
29
|
let names;
|
|
30
30
|
try {
|
package/dist/cli.js
CHANGED
|
@@ -11,10 +11,17 @@ const HELP = `frugal ${VERSION}: local-only cost helper for Claude Code
|
|
|
11
11
|
Usage:
|
|
12
12
|
frugal hook tool-output PostToolUse hook: shrink MCP tool output
|
|
13
13
|
frugal hook prompt UserPromptSubmit hook: drift and context warnings
|
|
14
|
+
frugal hook pre-compact PreCompact hook: tell the compaction summary which facts to keep
|
|
15
|
+
frugal hook session-start SessionStart hook: after compaction, restore saved facts (opt-in)
|
|
14
16
|
frugal statusline status line command: spend and context meter
|
|
15
17
|
frugal mcp stdio MCP server providing frugal_fetch
|
|
16
18
|
frugal handoff [--session <id>] [--transcript <path>]
|
|
17
|
-
frugal report [--days 30]
|
|
19
|
+
frugal report [--days 30] spend, and every tool seen: changed, left alone (why), fetched back
|
|
20
|
+
frugal explain [file|-] [--tool <name>] [--id <id>] [--query <text>] [--local] [--print]
|
|
21
|
+
dry run: what frugal would do to one tool result
|
|
22
|
+
frugal pause [--minutes N] pass all tool output through unchanged (no settings edit)
|
|
23
|
+
frugal resume
|
|
24
|
+
frugal setup-local [--yes] check/pull the local models and time them on this machine
|
|
18
25
|
frugal doctor check config, Ollama, permissions, Claude Code setup
|
|
19
26
|
frugal init print ready-to-run setup commands (never edits files)
|
|
20
27
|
frugal init --settings print your settings.json with frugal added (stdout only)
|
|
@@ -48,7 +55,27 @@ async function main(argv) {
|
|
|
48
55
|
return handleToolOutput(input, loadConfig());
|
|
49
56
|
});
|
|
50
57
|
}
|
|
51
|
-
|
|
58
|
+
if (sub === "pre-compact") {
|
|
59
|
+
// stdout becomes extra instructions for Claude Code's compaction summary
|
|
60
|
+
return failOpen(20_000, async () => {
|
|
61
|
+
const input = parseJsonObject(await readStdin());
|
|
62
|
+
if (!input)
|
|
63
|
+
return undefined;
|
|
64
|
+
const { preCompact } = await import("./handoff.js");
|
|
65
|
+
const t = await preCompact(input, loadConfig());
|
|
66
|
+
return t ? t + "\n" : undefined;
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
if (sub === "session-start") {
|
|
70
|
+
return failOpen(2000, async () => {
|
|
71
|
+
const input = parseJsonObject(await readStdin());
|
|
72
|
+
if (!input)
|
|
73
|
+
return undefined;
|
|
74
|
+
const { sessionStart } = await import("./handoff.js");
|
|
75
|
+
return sessionStart(input, loadConfig());
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
process.stderr.write("usage: frugal hook <prompt|tool-output|pre-compact|session-start>\n");
|
|
52
79
|
return 0; // never break Claude Code over a bad registration
|
|
53
80
|
}
|
|
54
81
|
case "statusline":
|
|
@@ -75,6 +102,39 @@ async function main(argv) {
|
|
|
75
102
|
process.stdout.write(report(loadConfig(), days) + "\n");
|
|
76
103
|
return 0;
|
|
77
104
|
}
|
|
105
|
+
case "explain": {
|
|
106
|
+
const { values, positionals } = parseArgs({
|
|
107
|
+
args: rest,
|
|
108
|
+
allowPositionals: true,
|
|
109
|
+
options: { tool: { type: "string" }, id: { type: "string" }, query: { type: "string" }, local: { type: "boolean", default: false }, print: { type: "boolean", default: false } }
|
|
110
|
+
});
|
|
111
|
+
const file = positionals[0];
|
|
112
|
+
if (!file && !values.id && process.stdin.isTTY) {
|
|
113
|
+
process.stderr.write("usage: frugal explain <file|-> [--tool <name>] [--query <text>] [--local] [--print] (or --id <frugal id>)\n");
|
|
114
|
+
return 2;
|
|
115
|
+
}
|
|
116
|
+
const { explain } = await import("./explain.js");
|
|
117
|
+
const stdin = !values.id && (!file || file === "-") ? await readStdin() : undefined;
|
|
118
|
+
process.stdout.write((await explain(loadConfig(), { ...values, file, stdin })) + "\n");
|
|
119
|
+
return 0;
|
|
120
|
+
}
|
|
121
|
+
case "pause": {
|
|
122
|
+
const { values } = parseArgs({ args: rest, options: { minutes: { type: "string" } } });
|
|
123
|
+
const { pause } = await import("./pause.js");
|
|
124
|
+
const m = values.minutes ? Number.parseInt(values.minutes, 10) : undefined;
|
|
125
|
+
process.stdout.write(pause(Number.isFinite(m) ? m : undefined) + "\n");
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
case "resume": {
|
|
129
|
+
const { resume } = await import("./pause.js");
|
|
130
|
+
process.stdout.write(resume() + "\n");
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
case "setup-local": {
|
|
134
|
+
const { values } = parseArgs({ args: rest, options: { yes: { type: "boolean", default: false } } });
|
|
135
|
+
const { setupLocal } = await import("./local.js");
|
|
136
|
+
return setupLocal(loadConfig(), values.yes ?? false, (...s) => process.stdout.write(s.join("\n") + "\n"));
|
|
137
|
+
}
|
|
78
138
|
case "doctor": {
|
|
79
139
|
const { doctor } = await import("./doctor.js");
|
|
80
140
|
const r = await doctor();
|
package/dist/compress.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Deterministic pruning pipeline for MCP tool output (spec §4.1 steps 1-7).
|
|
2
2
|
import { htmlToText, looksLikeHtml } from "./html.js";
|
|
3
|
+
export const newStats = () => ({ fields: 0, items: 0, strings: 0 });
|
|
3
4
|
export const DEFAULT_DENY = ["avatarUrls", "self", "_links", "iconUrl", "expand", "node_id"];
|
|
4
5
|
// eslint-disable-next-line no-control-regex -- matching ANSI escapes is the point
|
|
5
6
|
const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g;
|
|
@@ -25,8 +26,12 @@ function isAllZero(v) {
|
|
|
25
26
|
function prune(v, o, deny, keep) {
|
|
26
27
|
if (Array.isArray(v)) {
|
|
27
28
|
const items = v.map((x) => prune(x, o, deny, keep)).filter((x) => !isEmpty(x));
|
|
29
|
+
if (o.stats)
|
|
30
|
+
o.stats.items += v.length - items.length;
|
|
28
31
|
if (o.maxArrayItems > 0 && items.length > o.maxArrayItems) {
|
|
29
32
|
const extra = items.length - o.maxArrayItems;
|
|
33
|
+
if (o.stats)
|
|
34
|
+
o.stats.items += extra;
|
|
30
35
|
return [...items.slice(0, o.maxArrayItems), `…${extra} more`];
|
|
31
36
|
}
|
|
32
37
|
return items;
|
|
@@ -37,29 +42,124 @@ function prune(v, o, deny, keep) {
|
|
|
37
42
|
// A human-readable identifier makes a numeric surrogate id redundant (GitHub number/login, Jira key).
|
|
38
43
|
const hasHumanId = ["number", "key", "login", "slug"].some((k) => typeof src[k] === "string" || typeof src[k] === "number");
|
|
39
44
|
const out = {};
|
|
45
|
+
const drop = () => {
|
|
46
|
+
if (o.stats)
|
|
47
|
+
o.stats.fields++;
|
|
48
|
+
};
|
|
40
49
|
for (const [k, x] of Object.entries(src)) {
|
|
41
|
-
if (deny.has(k))
|
|
50
|
+
if (deny.has(k)) {
|
|
51
|
+
drop();
|
|
42
52
|
continue;
|
|
43
|
-
|
|
53
|
+
}
|
|
54
|
+
if (hasHtmlUrl && k !== "html_url" && (k.endsWith("_url") || k === "url")) {
|
|
55
|
+
drop();
|
|
44
56
|
continue;
|
|
45
|
-
|
|
57
|
+
}
|
|
58
|
+
if (hasHumanId && k === "id" && (typeof x === "number" || (typeof x === "string" && /^\d+$/.test(x)))) {
|
|
59
|
+
drop();
|
|
46
60
|
continue;
|
|
61
|
+
}
|
|
47
62
|
const isContainer = typeof x === "object" && x !== null;
|
|
48
|
-
if (keep && !keep.has(k) && !isContainer)
|
|
63
|
+
if (keep && !keep.has(k) && !isContainer) {
|
|
64
|
+
drop();
|
|
49
65
|
continue;
|
|
66
|
+
}
|
|
50
67
|
const p = prune(x, o, deny, keep);
|
|
51
|
-
if (keep && !keep.has(k) && isContainer && isEmpty(p))
|
|
68
|
+
if (keep && !keep.has(k) && isContainer && isEmpty(p)) {
|
|
69
|
+
drop();
|
|
52
70
|
continue;
|
|
53
|
-
|
|
71
|
+
}
|
|
72
|
+
if (isEmpty(p) || isAllZero(p)) {
|
|
73
|
+
drop();
|
|
54
74
|
continue;
|
|
75
|
+
}
|
|
55
76
|
out[k] = p;
|
|
56
77
|
}
|
|
57
78
|
return out;
|
|
58
79
|
}
|
|
59
80
|
if (typeof v === "string")
|
|
60
|
-
return cleanText(looksLikeHtml(v) ? htmlToText(v) : v);
|
|
81
|
+
return capProseItems(cleanText(looksLikeHtml(v) ? htmlToText(v) : v), o);
|
|
61
82
|
return v;
|
|
62
83
|
}
|
|
84
|
+
// ---- accuracy guard + per-item caps (opt-in) ----
|
|
85
|
+
/** A line that carries facts the model may need verbatim: never shortened. */
|
|
86
|
+
const FACT_LINE = /https?:\/\/|\b[A-Z][A-Z0-9_]+-\d+\b|\b[0-9a-f]{7,40}\b|\b\d{4}-\d{2}-\d{2}|\b\d{9,}(?:\.\d+)?\b|\b(?:error|exception|failed|failure|fatal|traceback|panic)\b|^\s+at\s|`|^\s*[{}[\]]|^\s*[-*]?\s*\**(?:id|key|ts|channel|user|author|from|date|time|status|state|url|link|permalink|assignee|priority|version)\**\s*[:=]|\b\d+(?:\.\d+)?\s?(?:ms|s|kb|mb|gb|%|usd|\$)\b|\bv?\d+\.\d+\.\d+\b|\b\d{1,2}:\d{2}\b|#\d{2,}\b/i;
|
|
87
|
+
export function isFactLine(line) {
|
|
88
|
+
return FACT_LINE.test(line);
|
|
89
|
+
}
|
|
90
|
+
/** Lines that start a new record inside a long text result (search hits, messages, pages). */
|
|
91
|
+
const RECORD_START = /^(?:#{1,4}\s|-{3,}\s*$|={3,}\s*$|\*\*\d+[.)]|\d+[.)]\s|\[\d+\]\s|(?:result|message|match|hit|page)\s*#?\d+\b)/i;
|
|
92
|
+
export function splitRecords(text) {
|
|
93
|
+
const lines = text.split("\n");
|
|
94
|
+
const out = [[]];
|
|
95
|
+
let inFence = false;
|
|
96
|
+
for (const l of lines) {
|
|
97
|
+
if (/^\s*```/.test(l))
|
|
98
|
+
inFence = !inFence;
|
|
99
|
+
if (!inFence && RECORD_START.test(l) && out[out.length - 1].some((x) => x.trim()))
|
|
100
|
+
out.push([]);
|
|
101
|
+
out[out.length - 1].push(l);
|
|
102
|
+
}
|
|
103
|
+
return out.map((r) => r.join("\n"));
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Keep every fact line and code block; spend at most `budget` chars on prose lines, cutting the
|
|
107
|
+
* line that crosses the budget at a word boundary. Returns the text and how many chars were cut.
|
|
108
|
+
*/
|
|
109
|
+
export function capProse(text, budget) {
|
|
110
|
+
const out = [];
|
|
111
|
+
let used = 0;
|
|
112
|
+
let cut = 0;
|
|
113
|
+
let inFence = false;
|
|
114
|
+
for (const l of text.split("\n")) {
|
|
115
|
+
const fence = /^\s*```/.test(l);
|
|
116
|
+
if (fence)
|
|
117
|
+
inFence = !inFence;
|
|
118
|
+
if (fence || inFence || !l.trim() || isFactLine(l) || /^#{1,6}\s/.test(l)) {
|
|
119
|
+
out.push(l);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (used >= budget) {
|
|
123
|
+
cut += l.length + 1;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (used + l.length <= budget) {
|
|
127
|
+
out.push(l);
|
|
128
|
+
used += l.length;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
let keep = l.slice(0, budget - used);
|
|
132
|
+
const sp = keep.lastIndexOf(" ");
|
|
133
|
+
if (sp > keep.length * 0.6)
|
|
134
|
+
keep = keep.slice(0, sp);
|
|
135
|
+
cut += l.length - keep.length;
|
|
136
|
+
used = budget;
|
|
137
|
+
out.push(keep);
|
|
138
|
+
}
|
|
139
|
+
let t = out.join("\n").replace(/\n{3,}/g, "\n\n");
|
|
140
|
+
if (cut > 0)
|
|
141
|
+
t += ` …[+${cut} chars]`;
|
|
142
|
+
return { text: t, cut };
|
|
143
|
+
}
|
|
144
|
+
/** Per-item cap: each record inside a long string gets its own prose budget, so later records never vanish. */
|
|
145
|
+
function capProseItems(s, o) {
|
|
146
|
+
const max = o.itemMaxChars ?? 0;
|
|
147
|
+
if (max <= 0 || s.length <= max)
|
|
148
|
+
return s;
|
|
149
|
+
let changed = false;
|
|
150
|
+
const recs = splitRecords(s).map((r) => {
|
|
151
|
+
if (r.length <= max)
|
|
152
|
+
return r;
|
|
153
|
+
const c = capProse(r, max);
|
|
154
|
+
if (c.cut > 0) {
|
|
155
|
+
changed = true;
|
|
156
|
+
if (o.stats)
|
|
157
|
+
o.stats.strings++;
|
|
158
|
+
}
|
|
159
|
+
return c.text;
|
|
160
|
+
});
|
|
161
|
+
return changed ? recs.join("\n") : s;
|
|
162
|
+
}
|
|
63
163
|
/**
|
|
64
164
|
* Conservative, content-preserving cleanup: ANSI codes, CRLF, trailing whitespace, runs of 3+
|
|
65
165
|
* blank lines. Never touches spacing inside a line, so code indentation and alignment survive.
|
|
@@ -98,11 +198,16 @@ export function pruneText(text, o) {
|
|
|
98
198
|
// not JSON, fall through
|
|
99
199
|
}
|
|
100
200
|
}
|
|
101
|
-
return cleanText(looksLikeHtml(text) ? htmlToText(text) : text);
|
|
201
|
+
return capProseItems(cleanText(looksLikeHtml(text) ? htmlToText(text) : text), o);
|
|
102
202
|
}
|
|
103
203
|
function shrink(v, maxStr, maxItems) {
|
|
104
204
|
if (typeof v === "string") {
|
|
105
|
-
|
|
205
|
+
if (v.length <= maxStr)
|
|
206
|
+
return v;
|
|
207
|
+
// Multi-record text: cap each record's prose instead of cutting the string head-first.
|
|
208
|
+
if (splitRecords(v).length >= 3)
|
|
209
|
+
return capProseItems(v, { maxBytes: 0, maxArrayItems: 0, denyKeys: [], itemMaxChars: Math.max(maxStr, 200) });
|
|
210
|
+
return `${v.slice(0, maxStr)}…[+${v.length - maxStr} chars]`;
|
|
106
211
|
}
|
|
107
212
|
if (Array.isArray(v)) {
|
|
108
213
|
const isMarker = (x) => typeof x === "string" && /^…\d+ more$/.test(x);
|
package/dist/config.js
CHANGED
|
@@ -12,7 +12,9 @@ export const DEFAULTS = {
|
|
|
12
12
|
jaccardThreshold: 0.08,
|
|
13
13
|
ollama: { url: "http://127.0.0.1:11434", chatModel: "qwen3:4b", embedModel: "nomic-embed-text", enabled: true },
|
|
14
14
|
// Lossless-by-default: no caps. Set maxBytes / maxArrayItems > 0 to opt in to shortening.
|
|
15
|
-
compress: { minBytes: 2048, maxBytes: 0, maxArrayItems: 0, summarize: false, denyKeys: [], tools: {} },
|
|
15
|
+
compress: { minBytes: 2048, maxBytes: 0, maxArrayItems: 0, summarize: false, denyKeys: [], tools: {}, minSavingPct: 10, minSavingBytes: 4096, dedupe: true },
|
|
16
|
+
routing: { topK: 5, budgetMs: 12000, summarizeMinChars: 1500, maxSummaries: 6 },
|
|
17
|
+
compaction: { instructions: true, reinject: false },
|
|
16
18
|
cache: { ttlHours: 24, maxMB: 200 },
|
|
17
19
|
bash: { enabled: true, dedupe: true, cleanup: true, minBytes: 1024, maxAgeMinutes: 60 }
|
|
18
20
|
};
|
|
@@ -34,8 +36,13 @@ const SCHEMA = {
|
|
|
34
36
|
maxArrayItems: "number",
|
|
35
37
|
summarize: "boolean",
|
|
36
38
|
denyKeys: "string[]",
|
|
37
|
-
tools: ["record", { keepFields: "string[]", skip: "boolean" }]
|
|
39
|
+
tools: ["record", { keepFields: "string[]", skip: "boolean", itemMaxChars: "number", maxItems: "number", route: ["enum", ["rank", "summarize", "both"]] }],
|
|
40
|
+
minSavingPct: "number",
|
|
41
|
+
minSavingBytes: "number",
|
|
42
|
+
dedupe: "boolean"
|
|
38
43
|
},
|
|
44
|
+
routing: { topK: "number", budgetMs: "number", summarizeMinChars: "number", maxSummaries: "number" },
|
|
45
|
+
compaction: { instructions: "boolean", reinject: "boolean" },
|
|
39
46
|
cache: { ttlHours: "number", maxMB: "number" },
|
|
40
47
|
bash: { enabled: "boolean", dedupe: "boolean", cleanup: "boolean", minBytes: "number", maxAgeMinutes: "number" }
|
|
41
48
|
};
|
|
@@ -101,6 +108,14 @@ export function validateConfig(raw) {
|
|
|
101
108
|
if (isRemoteOllamaModel(cfg.ollama[k]))
|
|
102
109
|
throw new ConfigError(`config.ollama.${k}: "${cfg.ollama[k]}" is an Ollama cloud model, which sends data to ollama.com. Use a local model.`);
|
|
103
110
|
}
|
|
111
|
+
if (cfg.compress.minSavingPct > 100)
|
|
112
|
+
throw new ConfigError("config.compress.minSavingPct must be between 0 and 100");
|
|
113
|
+
for (const [k, r] of Object.entries(cfg.compress.tools)) {
|
|
114
|
+
if (r.itemMaxChars !== undefined && r.itemMaxChars !== 0 && r.itemMaxChars < 80)
|
|
115
|
+
throw new ConfigError(`config.compress.tools.${k}.itemMaxChars must be 0 (off) or at least 80`);
|
|
116
|
+
}
|
|
117
|
+
if (cfg.routing.budgetMs > 25000)
|
|
118
|
+
throw new ConfigError("config.routing.budgetMs must be at most 25000 (the hook's own time limit)");
|
|
104
119
|
if (cfg.driftThreshold > 1 || cfg.jaccardThreshold > 1)
|
|
105
120
|
throw new ConfigError("config: thresholds must be between 0 and 1");
|
|
106
121
|
if (cfg.compress.maxBytes !== 0 && cfg.compress.maxBytes < 512)
|
package/dist/doctor.js
CHANGED
|
@@ -117,6 +117,7 @@ export async function doctor(cwd = process.cwd()) {
|
|
|
117
117
|
const settingsFiles = [path.join(ccDir, "settings.json"), path.join(cwd, ".claude", "settings.json"), path.join(cwd, ".claude", "settings.local.json")];
|
|
118
118
|
let hasPrompt = false;
|
|
119
119
|
let hasTool = false;
|
|
120
|
+
let hasCompact = false;
|
|
120
121
|
let statusCmd;
|
|
121
122
|
for (const f of settingsFiles) {
|
|
122
123
|
const s = readJson(f);
|
|
@@ -126,12 +127,15 @@ export async function doctor(cwd = process.cwd()) {
|
|
|
126
127
|
hasPrompt = true;
|
|
127
128
|
if (hookCommands(s, "PostToolUse").some((c) => c.includes("frugal") && c.includes("tool-output")))
|
|
128
129
|
hasTool = true;
|
|
130
|
+
if (hookCommands(s, "PreCompact").some((c) => c.includes("frugal") && c.includes("pre-compact")))
|
|
131
|
+
hasCompact = true;
|
|
129
132
|
const sl = s.statusLine;
|
|
130
133
|
if (typeof sl?.command === "string")
|
|
131
134
|
statusCmd = sl.command;
|
|
132
135
|
}
|
|
133
136
|
L.push(hasTool ? { level: "ok", msg: "PostToolUse hook registered (MCP compression)" } : { level: "warn", msg: "PostToolUse hook not found in settings: run `frugal init`" });
|
|
134
137
|
L.push(hasPrompt ? { level: "ok", msg: "UserPromptSubmit hook registered (drift/bloat)" } : { level: "warn", msg: "UserPromptSubmit hook not found in settings: run `frugal init`" });
|
|
138
|
+
L.push(hasCompact ? { level: "ok", msg: "PreCompact hook registered (keeps key facts through compaction)" } : { level: "info", msg: "PreCompact hook not found: run `frugal init` to keep key facts through compaction (optional)" });
|
|
135
139
|
if (!statusCmd)
|
|
136
140
|
L.push({ level: "warn", msg: "no statusLine configured: run `frugal init`" });
|
|
137
141
|
else if (!statusCmd.includes("frugal"))
|