lakonai 0.10.0 → 0.12.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/README.md +55 -81
- package/bin/lakonai.js +57 -74
- package/package.json +2 -4
- package/src/bench.js +76 -0
- package/src/install/claude-commands.js +1 -51
- package/src/install/claude-hook.js +0 -6
- package/src/install/index.js +70 -1
- package/src/install/mcp.js +87 -0
- package/src/install/platforms.js +3 -3
- package/src/mcp-shrink.js +98 -0
- package/src/mem-compress.js +138 -0
- package/src/mem-llm.js +152 -0
- package/src/rules/lakonai.md +1 -12
- package/src/tracking.js +10 -79
- package/src/compress.js +0 -0
- package/src/hooks/prompt-reinforce.js +0 -51
- package/src/install/claude-agents.js +0 -100
- package/src/mode.js +0 -47
- package/src/shell.js +0 -34
package/README.md
CHANGED
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
| `Read pnpm-lock.yaml` | ~56,000 | **blocked** | **-95%** |
|
|
44
44
|
| `Grep` (auto `head_limit`) | unbounded | 30 matches | **capped** |
|
|
45
45
|
|
|
46
|
-
Conservative numbers — peaks go higher in practice. Run `lakonai
|
|
46
|
+
Conservative numbers — peaks go higher in practice. Run `lakonai gain` to see your own savings stack up.
|
|
47
47
|
|
|
48
48
|
---
|
|
49
49
|
|
|
@@ -106,9 +106,32 @@ From the next session forward your agent:
|
|
|
106
106
|
5. **Is told to "think in code"** — for any count/filter/parse task, the rule pushes the agent toward a one-shot `node -e` (or `awk`) script that consumes the data so the agent consumes only the answer.
|
|
107
107
|
6. **Logs per-turn LLM token usage** — a `Stop` hook records `input_tokens` / `output_tokens` / `cache_read` after each model turn so `lakonai gain` shows model-side savings alongside shell-side savings.
|
|
108
108
|
7. **Tells you about new versions** — a `SessionStart` hook checks npm once per day and surfaces a `lakonai X.Y.Z available` notice inside the session (opt-out: `LAKON_NO_UPDATE_CHECK=1`).
|
|
109
|
+
8. **Auto-compresses MCP tool catalogs** — if you have MCP servers in `~/.claude.json`, install transparently wraps each stdio server so its tool/prompt/resource **descriptions** are compressed before they hit context (offline; backed up; reverted on `uninstall`; opt-out `LAKON_NO_MCP=1`). Requests and tool-call results are never touched.
|
|
109
110
|
|
|
110
111
|
You'll see savings stack up immediately in `lakonai gain`.
|
|
111
112
|
|
|
113
|
+
### Compress a memory file (opt-in)
|
|
114
|
+
|
|
115
|
+
Your `CLAUDE.md` (and other memory/notes) costs tokens **every session**. `lakonai compress-memory <file>` rewrites it tersely in place using **a local AI CLI you already have** — no API key to set up. A model rephrases and merges the prose (far higher savings than a regex pass: ~35% vs ~8% on a terse file), while headings, tables, fenced code, inline code, paths and URLs are preserved byte-for-byte.
|
|
116
|
+
|
|
117
|
+
It auto-detects, in order, whichever agent CLI is on your PATH:
|
|
118
|
+
|
|
119
|
+
| CLI binary | Platform | Headless call |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| `claude` | Claude Code | `claude --print` |
|
|
122
|
+
| `gemini` | Gemini CLI | `gemini -p` |
|
|
123
|
+
| `codex` | Codex | `codex exec -` |
|
|
124
|
+
| `cursor-agent` | Cursor | `cursor-agent -p` |
|
|
125
|
+
|
|
126
|
+
(Windsurf and Cline ship no headless one-shot CLI, so on those you just use whichever of the above you also have. Force a specific one with `LAKONAI_MEM_CLI=gemini`; pick a model with `LAKONAI_MEM_MODEL`.)
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
lakonai compress-memory CLAUDE.md # uses your local agent CLI; backup to CLAUDE.original.md
|
|
130
|
+
lakonai revert-memory CLAUDE.md # restore from the backup
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Unlike the MCP catalog above, this is **always manual and opt-in** — it edits text you authored, so a `CLAUDE.original.md` backup is written first, the result is **validated** (aborts untouched if any code/path/URL would be lost; one auto-fix pass first), and nothing happens unless you ask. Sensitive-looking filenames (`.env`, `*api-key*`, …) are refused since their bytes cross the model boundary. `lakonai install` offers a one-time prompt to compress a detected `CLAUDE.md`; declining leaves it alone.
|
|
134
|
+
|
|
112
135
|
> Hooks are currently Claude Code-only (the only platform with documented hook APIs). For Codex/Cursor/Windsurf/Cline/Gemini, the rule asks the model to grep-before-Read and use the `lakonai` prefix itself.
|
|
113
136
|
|
|
114
137
|
> **Worried?** Every install backs up the target file first. `lakonai revert` puts it back byte-for-byte.
|
|
@@ -142,64 +165,34 @@ lakonai gain
|
|
|
142
165
|
```
|
|
143
166
|
|
|
144
167
|
```
|
|
145
|
-
lakonai
|
|
146
|
-
|
|
147
|
-
shell + read/grep guards (tokens filtered before context)
|
|
148
|
-
win calls before after saved %
|
|
149
|
-
1h 12 1.2k tok 380 tok 820 tok 68%
|
|
150
|
-
24h 87 9.8k tok 3.1k tok 6.7k tok 68%
|
|
151
|
-
7d 512 54.2k tok 17.8k tok 36.4k tok 67%
|
|
152
|
-
30d 2104 241.0k tok 79.2k tok 161.8k tok 67%
|
|
153
|
-
all 2104 241.0k tok 79.2k tok 161.8k tok 67%
|
|
154
|
-
|
|
155
|
-
llm output (model tokens — terse style trims this side)
|
|
156
|
-
win turns input output cache-read
|
|
157
|
-
1h 4 2.1k tok 320 tok 48.7k tok
|
|
158
|
-
24h 38 18.4k tok 2.6k tok 412.2k tok
|
|
159
|
-
7d 210 102.5k tok 14.1k tok 2.3M tok
|
|
160
|
-
|
|
161
|
-
top commands (all time)
|
|
162
|
-
git 812x saved 124.3k tok 72%
|
|
163
|
-
ls 541x saved 18.2k tok 58%
|
|
164
|
-
grep 339x saved 12.0k tok 65%
|
|
165
|
-
```
|
|
168
|
+
lakonai — saved 161.8k tok (67% smaller) across 2104 commands
|
|
166
169
|
|
|
167
|
-
|
|
170
|
+
today 6.7k tok saved (68%)
|
|
171
|
+
this week 36.4k tok saved (67%)
|
|
168
172
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
```bash
|
|
172
|
-
lakonai inspect git log
|
|
173
|
+
top: git 124.3k tok · ls 18.2k tok · grep 12.0k tok
|
|
173
174
|
```
|
|
174
175
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
filtered: 187 tokens (1240 bytes)
|
|
179
|
-
saved: 85%
|
|
180
|
-
```
|
|
176
|
+
Simple and objective: one headline number, today/this-week, and your top commands.
|
|
177
|
+
Before you have any data, `gain` shows a sample benchmark so you see what the
|
|
178
|
+
filters do. Set `LAKON_COLOR=1`/`0` (or `NO_COLOR=1`) to force/disable ANSI colors.
|
|
181
179
|
|
|
182
180
|
---
|
|
183
181
|
|
|
184
182
|
## Commands
|
|
185
183
|
|
|
184
|
+
After `lakonai install`, everything is automatic — you rarely need anything but
|
|
185
|
+
`gain` (to see the savings) and `doctor` (to check it's active).
|
|
186
|
+
|
|
186
187
|
| Command | What it does |
|
|
187
188
|
|--------------------------------------|-----------------------------------------------------------------------|
|
|
188
|
-
| `lakonai install`
|
|
189
|
-
| `lakonai install --here` | Globals + per-project rules (Cursor/Windsurf/Cline) in current dir |
|
|
190
|
-
| `lakonai install --only <p>` | Install just one platform by id (any scope) |
|
|
189
|
+
| `lakonai install [--here] [--only <p>]` | Install rule + hooks (globals by default; `--here` adds per-project) |
|
|
191
190
|
| `lakonai uninstall` | Strip the lakonai block from each config (keeps your other content) |
|
|
192
191
|
| `lakonai revert [--only <p>]` | Restore each config to its pre-install state from backup |
|
|
193
192
|
| `lakonai backups` | Show backup history per platform |
|
|
194
|
-
| `lakonai
|
|
195
|
-
| `lakonai <cmd> [args]` | Run a command, filter its output, track savings |
|
|
196
|
-
| `lakonai gain` | Show savings by hour / day / week / month / all-time + session totals |
|
|
197
|
-
| `lakonai inspect <cmd>` | Run once and show raw-vs-filtered (no tracking) |
|
|
198
|
-
| `lakonai reset` | Wipe the savings log |
|
|
199
|
-
| `lakonai mode [lite\|full\|ultra]` | Show or set terse intensity (default `full`) |
|
|
200
|
-
| `lakonai compress <file> [--llm] [--dry-run]` | Shrink a memory `.md` (offline heuristic, or `--llm` via your `claude` CLI) |
|
|
193
|
+
| `lakonai gain` | Show savings by window + top commands (and a sample benchmark before you have data) |
|
|
201
194
|
| `lakonai doctor` | Per-platform health: CLI on PATH, rule installed, hooks registered |
|
|
202
|
-
| `lakonai
|
|
195
|
+
| `lakonai <cmd> [args]` | (internal) Run a command, filter its output, track savings |
|
|
203
196
|
| `lakonai version` / `--version` / `-v` | Print the installed lakonai version |
|
|
204
197
|
|
|
205
198
|
---
|
|
@@ -234,23 +227,6 @@ auto-filter is near-lossless (collapses repeated/blank lines, truncates only
|
|
|
234
227
|
with an announced marker) so it never hides a real error. Disable with
|
|
235
228
|
`LAKON_NO_LEARN=1`.
|
|
236
229
|
|
|
237
|
-
### Terse intensity + per-turn reinforcement
|
|
238
|
-
|
|
239
|
-
`lakonai mode lite|full|ultra` sets how terse the model is (default `full`;
|
|
240
|
-
`ultra` abbreviates and uses arrows for causality). A `UserPromptSubmit` hook
|
|
241
|
-
re-injects the active rule every turn so the model doesn't drift back to verbose
|
|
242
|
-
prose mid-session (opt out `LAKON_NO_REINFORCE=1`). Code, identifiers, paths and
|
|
243
|
-
security warnings stay verbatim at every level.
|
|
244
|
-
|
|
245
|
-
### Compress memory files
|
|
246
|
-
|
|
247
|
-
`lakonai compress <file>` shrinks the markdown an agent reloads every session
|
|
248
|
-
(CLAUDE.md, notes). Default is **offline and near-lossless** (collapses blank
|
|
249
|
-
lines / trailing whitespace, never touches code or words). `--llm` rewrites the
|
|
250
|
-
prose tersely using **your existing `claude` CLI** (`claude --print` — no separate
|
|
251
|
-
API key, no new dependency); `--dry-run` previews the savings. The original is
|
|
252
|
-
backed up to `<file>.bak`.
|
|
253
|
-
|
|
254
230
|
### Read tool guard (Claude Code)
|
|
255
231
|
|
|
256
232
|
The `Read` hook automatically:
|
|
@@ -302,7 +278,7 @@ Each profile gets its own independent install. `lakonai uninstall` / `lakonai re
|
|
|
302
278
|
|
|
303
279
|
| Agent | Scope | What `lakonai install` writes |
|
|
304
280
|
|-----------------|----------|--------------------------------------------------------------------------------------------------------|
|
|
305
|
-
| Claude Code¹ | global | Rule block in `~/.claude/CLAUDE.md` + **
|
|
281
|
+
| Claude Code¹ | global | Rule block in `~/.claude/CLAUDE.md` + **five** hooks in `~/.claude/settings.json` (`PreToolUse`: Bash rewrite + Read guard + Grep guard; `Stop`: session-usage log + auto-learning; `SessionStart`: update notify) + `/lakonai:gain` slash command |
|
|
306
282
|
| Codex CLI | global | Rule block in `~/.codex/AGENTS.md` |
|
|
307
283
|
| Gemini CLI | global | Rule block in `~/.gemini/GEMINI.md` |
|
|
308
284
|
| Cursor | project² | `.cursor/rules/lakonai.mdc` in the current dir |
|
|
@@ -312,23 +288,21 @@ Each profile gets its own independent install. `lakonai uninstall` / `lakonai re
|
|
|
312
288
|
### What each agent actually gets (honest capability matrix)
|
|
313
289
|
|
|
314
290
|
The powerful input-side features (shell-output filtering, Read/Grep guards,
|
|
315
|
-
auto-learning
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
|
323
|
-
|
|
|
324
|
-
|
|
|
325
|
-
|
|
|
326
|
-
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
wrapper. Run `lakonai doctor` to see, per platform, what's actually active on your
|
|
331
|
-
machine.
|
|
291
|
+
auto-learning) are **hooks — they run on Claude Code only**. Everywhere else,
|
|
292
|
+
lakonai delivers the terse rule and shell filtering happens by **the model
|
|
293
|
+
prefixing `lakonai`** (the rule tells it to). Honest matrix:
|
|
294
|
+
|
|
295
|
+
| Agent | Terse rule | Shell filter | Read/Grep guard | Auto-learning |
|
|
296
|
+
|-------------|:---------:|---------------------|:---------------:|:-------------:|
|
|
297
|
+
| Claude Code | ✅ | ✅ automatic (hook) | ✅ | ✅ |
|
|
298
|
+
| Codex CLI | ✅ | ⚠️ via rule (prefix) | ❌ | ❌ |
|
|
299
|
+
| Cursor | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
|
|
300
|
+
| Windsurf | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
|
|
301
|
+
| Cline | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
|
|
302
|
+
| Gemini CLI | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
|
|
303
|
+
|
|
304
|
+
⚠️ = the model has to cooperate (prefix `lakonai`). Run `lakonai doctor` to see,
|
|
305
|
+
per platform, what's actually active on your machine.
|
|
332
306
|
|
|
333
307
|
¹ "Claude Code" covers **every** Claude Code frontend — terminal CLI, VS Code extension, JetBrains plugin, desktop app. All read the same `~/.claude/CLAUDE.md` + `~/.claude/settings.json`, so one install lights up all of them.
|
|
334
308
|
|
|
@@ -354,7 +328,7 @@ Use `uninstall` to remove lakonai while keeping your other edits. Use `revert` w
|
|
|
354
328
|
|
|
355
329
|
## How tracking works
|
|
356
330
|
|
|
357
|
-
Every filtered command appends a JSON line to `~/.lakon/log.jsonl`. The `Stop` hook appends one line per model turn with token counts (`cmd: "session"`). `lakonai gain` reads that log and
|
|
331
|
+
Every filtered command appends a JSON line to `~/.lakon/log.jsonl`. The `Stop` hook appends one line per model turn with token counts (`cmd: "session"`). `lakonai gain` reads that log and shows a simple headline + per-window + top-commands summary.
|
|
358
332
|
|
|
359
333
|
The log stores: timestamp, command name, first few args, raw/filtered token counts (shell entries); timestamp, session id, `input_tokens` / `output_tokens` / `cache_read` / `cache_create` (session entries). **No file contents. No full arguments. No transcript content. No data ever leaves your machine** — except the one daily HEAD request to `registry.npmjs.org` for the update check (opt-out: `LAKON_NO_UPDATE_CHECK=1`).
|
|
360
334
|
|
|
@@ -400,7 +374,7 @@ npm run test:coverage:check # enforce the coverage threshold
|
|
|
400
374
|
node bin/lakonai.js --help
|
|
401
375
|
```
|
|
402
376
|
|
|
403
|
-
Suite: **
|
|
377
|
+
Suite: **261 tests**. Coverage gate: **100% lines / 100% branches / 100% functions / 100% statements**. Zero runtime dependencies. Node ≥ 18.
|
|
404
378
|
|
|
405
379
|
---
|
|
406
380
|
|
package/bin/lakonai.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
const { spawnSync } = require('child_process');
|
|
5
5
|
const { filterCommand, isSupported, needsStderr, countTokensApprox } = require('../src/filters');
|
|
6
|
-
const { install, uninstall, revert,
|
|
6
|
+
const { install, uninstall, revert, backupsReport } = require('../src/install');
|
|
7
7
|
const tracking = require('../src/tracking');
|
|
8
8
|
const versionCheck = require('../src/hooks/version-check');
|
|
9
9
|
|
|
@@ -21,14 +21,25 @@ Usage:
|
|
|
21
21
|
lakonai uninstall Strip the lakonai block (keeps rest of file)
|
|
22
22
|
lakonai revert [--only <p>] Restore files to pre-install state from backup
|
|
23
23
|
lakonai backups Show backup history per platform
|
|
24
|
-
|
|
24
|
+
|
|
25
|
+
lakonai compress-memory <file>
|
|
26
|
+
Compress a memory file (CLAUDE.md, notes) in place,
|
|
27
|
+
saving a <name>.original.md backup first. Manual &
|
|
28
|
+
opt-in — rewrites your authored text (lossy) using a
|
|
29
|
+
local AI CLI you already have (Claude/Gemini/Codex/
|
|
30
|
+
Cursor — no API key). Override with LAKONAI_MEM_CLI.
|
|
31
|
+
lakonai revert-memory <file>
|
|
32
|
+
Restore <file> from its .original.md backup.
|
|
25
33
|
|
|
26
34
|
lakonai gain Show token savings (hour / day / week / month / all)
|
|
27
|
-
lakonai
|
|
28
|
-
lakonai reset Wipe the savings log
|
|
35
|
+
lakonai doctor Per-platform health: CLI on PATH, rule, hooks
|
|
29
36
|
lakonai version Print the installed lakonai version
|
|
30
37
|
lakonai --help This help
|
|
31
38
|
|
|
39
|
+
After \`lakonai install\` everything is automatic — your agent's commands are
|
|
40
|
+
filtered, junk reads are blocked, and new noisy commands get learned. You rarely
|
|
41
|
+
need any command but \`gain\` (to see the savings) and \`doctor\` (to check it).
|
|
42
|
+
|
|
32
43
|
Supported filters:
|
|
33
44
|
files/search git (log/status/diff/show), ls, tree, cat, head, tail, grep, rg, ag, find
|
|
34
45
|
test runners jest, vitest, mocha, pytest, ava; npm/pnpm/yarn/bun test, go test, cargo test
|
|
@@ -71,27 +82,38 @@ function runAndFilter(cmd, args) {
|
|
|
71
82
|
process.exit(child.status ?? 0);
|
|
72
83
|
}
|
|
73
84
|
|
|
74
|
-
function
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
85
|
+
function runMemory(cmd, args) {
|
|
86
|
+
const mem = require('../src/mem-compress');
|
|
87
|
+
const file = args.find((a) => !a.startsWith('--'));
|
|
88
|
+
if (!file) {
|
|
89
|
+
process.stderr.write(`lakonai: ${cmd} needs a file path. e.g. \`lakonai ${cmd} CLAUDE.md\`\n`);
|
|
90
|
+
process.exit(1);
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
if (cmd === 'revert-memory') {
|
|
94
|
+
const { file: f, backup } = mem.revertFile(file);
|
|
95
|
+
process.stdout.write(`✅ restored ${f} from ${backup}\n`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
// The compressor is whichever local AI CLI the user has (no API key).
|
|
99
|
+
const llm = require('../src/mem-llm');
|
|
100
|
+
const provider = llm.pickProvider();
|
|
101
|
+
process.stdout.write(`compressing ${file} with ${provider.bin} (${provider.platform})…\n`);
|
|
102
|
+
const res = mem.compressFile(file, {
|
|
103
|
+
tokenize: countTokensApprox,
|
|
104
|
+
compress: (orig) => llm.compressWith(orig, { provider }),
|
|
105
|
+
fix: (orig, comp, missing) => llm.fixWith(orig, comp, missing, { provider }),
|
|
106
|
+
remote: true,
|
|
107
|
+
});
|
|
108
|
+
const pct = res.beforeTokens ? Math.round((1 - res.afterTokens / res.beforeTokens) * 100) : 0;
|
|
109
|
+
process.stdout.write(
|
|
110
|
+
`✅ compressed ${res.file}: ${res.beforeTokens} → ${res.afterTokens} tokens (~${pct}% smaller)\n` +
|
|
111
|
+
` backup: ${res.backup}\n undo: lakonai revert-memory ${res.file}\n`
|
|
112
|
+
);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
process.stderr.write(`lakonai: ${err.message}\n`);
|
|
115
|
+
process.exit(1);
|
|
78
116
|
}
|
|
79
|
-
const [cmd, ...args] = rest;
|
|
80
|
-
const merge = needsStderr(cmd, args);
|
|
81
|
-
const child = spawnSync(cmd, args, { encoding: 'utf8' });
|
|
82
|
-
/* istanbul ignore next -- defensive empty-stream fallbacks */
|
|
83
|
-
const raw = merge ? (child.stdout || '') + (child.stderr || '') : child.stdout || '';
|
|
84
|
-
const filtered = isSupported(cmd) ? filterCommand(cmd, args, raw) : raw;
|
|
85
|
-
const rawTokens = countTokensApprox(raw);
|
|
86
|
-
const newTokens = countTokensApprox(filtered);
|
|
87
|
-
/* istanbul ignore next */
|
|
88
|
-
const saved = rawTokens === 0 ? 0 : Math.round((1 - newTokens / rawTokens) * 100);
|
|
89
|
-
process.stdout.write(
|
|
90
|
-
`cmd: ${cmd} ${args.join(' ')}\n` +
|
|
91
|
-
`raw: ${rawTokens} tokens (${raw.length} bytes)\n` +
|
|
92
|
-
`filtered: ${newTokens} tokens (${filtered.length} bytes)\n` +
|
|
93
|
-
`saved: ${saved}%\n`
|
|
94
|
-
);
|
|
95
117
|
}
|
|
96
118
|
|
|
97
119
|
function printVersion() {
|
|
@@ -153,68 +175,29 @@ async function main() {
|
|
|
153
175
|
process.stdout.write(backupsReport());
|
|
154
176
|
return;
|
|
155
177
|
}
|
|
156
|
-
if (first === '
|
|
157
|
-
|
|
178
|
+
if (first === 'compress-memory' || first === 'revert-memory') {
|
|
179
|
+
runMemory(first, rest);
|
|
158
180
|
return;
|
|
159
181
|
}
|
|
160
182
|
if (first === 'gain' || first === 'stats') {
|
|
161
183
|
process.stdout.write(tracking.report());
|
|
184
|
+
// No real usage yet? Show the reproducible filter benchmark as a preview.
|
|
185
|
+
if (!tracking.readEntries().length) {
|
|
186
|
+
const bench = require('../src/bench');
|
|
187
|
+
process.stdout.write('\nWhat the filters do (sample benchmark):\n' + bench.format(bench.runBench()));
|
|
188
|
+
}
|
|
162
189
|
await versionCheck.checkForUpdate().catch(/* istanbul ignore next */ () => {});
|
|
163
190
|
maybePrintUpdateHint();
|
|
164
191
|
return;
|
|
165
192
|
}
|
|
166
|
-
if (first === 'inspect') {
|
|
167
|
-
inspectCmd(rest);
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
if (first === 'reset') {
|
|
171
|
-
const ok = tracking.reset();
|
|
172
|
-
process.stdout.write(ok ? 'lakonai: log cleared\n' : 'lakonai: nothing to clear\n');
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
if (first === 'mode') {
|
|
176
|
-
const { getMode, setMode, MODES } = require('../src/mode');
|
|
177
|
-
if (!rest.length) {
|
|
178
|
-
process.stdout.write(`lakonai mode: ${getMode()}\n`);
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
const m = setMode(rest[0]);
|
|
182
|
-
process.stdout.write(
|
|
183
|
-
m ? `lakonai mode set to ${m}\n` : `lakonai: unknown mode "${rest[0]}" (use ${MODES.join('/')})\n`
|
|
184
|
-
);
|
|
185
|
-
return;
|
|
186
|
-
}
|
|
187
|
-
if (first === 'compress') {
|
|
188
|
-
const { compressFile } = require('../src/compress');
|
|
189
|
-
const llm = rest.includes('--llm');
|
|
190
|
-
const dryRun = rest.includes('--dry-run');
|
|
191
|
-
const file = rest.find((a) => !a.startsWith('--'));
|
|
192
|
-
if (!file) {
|
|
193
|
-
process.stderr.write('lakonai compress: missing file\n');
|
|
194
|
-
process.exit(2);
|
|
195
|
-
}
|
|
196
|
-
const r = compressFile(file, { llm, dryRun });
|
|
197
|
-
const tail = r.written ? ' [written; backup .bak]' : ' [dry-run]';
|
|
198
|
-
process.stdout.write(`${r.file}: ${r.before} → ${r.after} tokens (-${r.saved}%, ${r.mode})${tail}\n`);
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
193
|
if (first === 'doctor') {
|
|
202
194
|
const doctor = require('../src/doctor');
|
|
203
195
|
process.stdout.write(doctor.format(doctor.report()));
|
|
204
196
|
return;
|
|
205
197
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
'# Add to your shell profile (~/.bashrc / ~/.zshrc), then set LAKON_SHELL=1\n' +
|
|
210
|
-
'# in the env your agent runs commands in. Experimental — read-only commands only.\n' +
|
|
211
|
-
snippet()
|
|
212
|
-
);
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
if (first === 'shell-uninit') {
|
|
216
|
-
const { MARK_BEGIN, MARK_END } = require('../src/shell');
|
|
217
|
-
process.stdout.write(`Remove the block between\n ${MARK_BEGIN}\n ${MARK_END}\nfrom your shell profile (or unset LAKON_SHELL).\n`);
|
|
198
|
+
/* istanbul ignore next -- long-running stdio MCP proxy; logic tested via src/mcp-shrink */
|
|
199
|
+
if (first === '__mcp') {
|
|
200
|
+
require('../src/mcp-shrink').runProxy(rest);
|
|
218
201
|
return;
|
|
219
202
|
}
|
|
220
203
|
|
|
@@ -229,4 +212,4 @@ if (require.main === module) {
|
|
|
229
212
|
});
|
|
230
213
|
}
|
|
231
214
|
|
|
232
|
-
module.exports = { runAndFilter,
|
|
215
|
+
module.exports = { runAndFilter, printVersion, main, HELP };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lakonai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "lakonai — save AI context tokens. Filters & compresses CLI output (git, ls, grep, find, test runners, lint/build, docker/kubectl/aws) before it reaches Claude Code, Codex, Cursor, Windsurf, Cline or Gemini — and learns to filter new commands automatically the more you use it.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude",
|
|
@@ -48,9 +48,7 @@
|
|
|
48
48
|
"test": "jest",
|
|
49
49
|
"test:coverage": "jest --coverage",
|
|
50
50
|
"test:coverage:check": "jest --coverage",
|
|
51
|
-
"bench": "node
|
|
52
|
-
"bench:output": "node scripts/bench-output.js",
|
|
53
|
-
"bench:measure": "node scripts/bench-measure.js"
|
|
51
|
+
"bench": "node -e \"process.stdout.write(require('./src/bench').format(require('./src/bench').runBench()))\""
|
|
54
52
|
},
|
|
55
53
|
"engines": {
|
|
56
54
|
"node": ">=18"
|
package/src/bench.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// `lakonai bench` — runs a fixed corpus of representative command outputs through
|
|
4
|
+
// the filters and prints the savings. Self-contained (sample outputs are built
|
|
5
|
+
// here, no external commands or shipped fixtures), deterministic, no LLM.
|
|
6
|
+
// tests/bench.test.js asserts each case clears its `minSaved` threshold so a
|
|
7
|
+
// filter regression fails CI.
|
|
8
|
+
|
|
9
|
+
const { filterCommand, countTokensApprox } = require('./filters');
|
|
10
|
+
|
|
11
|
+
function gitLogSample() {
|
|
12
|
+
let s = '';
|
|
13
|
+
for (let i = 0; i < 4; i++) {
|
|
14
|
+
s +=
|
|
15
|
+
`commit ${'a'.repeat(39)}${i}\n` +
|
|
16
|
+
`Author: Dev <dev@example.com>\n` +
|
|
17
|
+
`Date: Mon May 26 10:0${i}:00 2026 -0300\n\n` +
|
|
18
|
+
` fix: handle edge case ${i} in parser\n\n` +
|
|
19
|
+
`diff --git a/src/p${i}.js b/src/p${i}.js\n` +
|
|
20
|
+
`index 1111111..2222222 100644\n--- a/src/p${i}.js\n+++ b/src/p${i}.js\n` +
|
|
21
|
+
`@@ -1,5 +1,7 @@\n function parse(x){\n- return x;\n+ if(!x) return null;\n+ return x.trim();\n }\n`;
|
|
22
|
+
}
|
|
23
|
+
return s;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function npmTestSample() {
|
|
27
|
+
let s = '> app@1.0.0 test\n> jest\n\n';
|
|
28
|
+
for (let f = 0; f < 6; f++) {
|
|
29
|
+
s += `PASS src/mod${f}.test.js\n`;
|
|
30
|
+
for (let c = 0; c < 5; c++) s += ` ✓ case ${f}.${c} (${c + 1} ms)\n`;
|
|
31
|
+
}
|
|
32
|
+
return s + '\nTest Suites: 6 passed, 6 total\nTests: 30 passed, 30 total\nTime: 2.1 s\n';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function makeSample() {
|
|
36
|
+
let s = '';
|
|
37
|
+
for (let i = 0; i < 8; i++) {
|
|
38
|
+
s += `make[1]: Entering directory '/home/u/proj'\ngcc -O2 -c src/f${i}.c -o build/f${i}.o\n\nmake[1]: Leaving directory '/home/u/proj'\n`;
|
|
39
|
+
}
|
|
40
|
+
return s;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function grepSample() {
|
|
44
|
+
let s = '';
|
|
45
|
+
for (let i = 0; i < 60; i++) s += `src/file${i}.js:${i + 10}: const value = compute(${i});\n`;
|
|
46
|
+
return s;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const CASES = [
|
|
50
|
+
{ name: 'git log -p', cmd: 'git', args: ['log', '-p'], output: gitLogSample, minSaved: 60 },
|
|
51
|
+
{ name: 'npm test (passing)', cmd: 'npm', args: ['test'], output: npmTestSample, minSaved: 80 },
|
|
52
|
+
{ name: 'make', cmd: 'make', args: [], output: makeSample, minSaved: 30 },
|
|
53
|
+
{ name: 'grep (60 matches)', cmd: 'grep', args: ['-r', 'value', 'src/'], output: grepSample, minSaved: 60 },
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
function runBench() {
|
|
57
|
+
return CASES.map((c) => {
|
|
58
|
+
const raw = c.output();
|
|
59
|
+
const filtered = filterCommand(c.cmd, c.args, raw);
|
|
60
|
+
const before = countTokensApprox(raw);
|
|
61
|
+
const after = countTokensApprox(filtered);
|
|
62
|
+
/* istanbul ignore next -- samples are never empty; defensive divide-by-zero guard */
|
|
63
|
+
const saved = before === 0 ? 0 : Math.round((1 - after / before) * 100);
|
|
64
|
+
return { name: c.name, before, after, saved, minSaved: c.minSaved };
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function format(rows) {
|
|
69
|
+
const pad = (s, n) => String(s).padEnd(n);
|
|
70
|
+
const padN = (s, n) => String(s).padStart(n);
|
|
71
|
+
const lines = [pad('case', 22) + padN('raw', 8) + padN('filtered', 10) + padN('saved', 7), '-'.repeat(47)];
|
|
72
|
+
for (const r of rows) lines.push(pad(r.name, 22) + padN(r.before, 8) + padN(r.after, 10) + padN(r.saved + '%', 7));
|
|
73
|
+
return lines.join('\n') + '\n';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
module.exports = { runBench, format, CASES };
|
|
@@ -9,60 +9,10 @@ const COMMANDS = [
|
|
|
9
9
|
name: 'gain',
|
|
10
10
|
body: `---
|
|
11
11
|
description: Show lakonai token savings (raw vs filtered, per window and top commands).
|
|
12
|
-
allowed-tools: Bash(lakonai gain:*)
|
|
12
|
+
allowed-tools: Bash(lakonai gain:*)
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
Run \`lakonai gain\` and show the output verbatim. Do not summarize — the table is the answer.
|
|
16
|
-
`,
|
|
17
|
-
},
|
|
18
|
-
{
|
|
19
|
-
name: 'reset',
|
|
20
|
-
body: `---
|
|
21
|
-
description: Wipe the lakonai savings log.
|
|
22
|
-
allowed-tools: Bash(lakonai reset:*), Bash(lakon reset:*)
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
Run \`lakonai reset\` and show the output. Confirm with the user before running if they didn't explicitly ask to clear.
|
|
26
|
-
`,
|
|
27
|
-
},
|
|
28
|
-
{
|
|
29
|
-
name: 'inspect',
|
|
30
|
-
body: `---
|
|
31
|
-
description: Run a command once through lakonai and compare raw vs filtered token counts.
|
|
32
|
-
argument-hint: <command> [args...]
|
|
33
|
-
allowed-tools: Bash(lakonai inspect:*), Bash(lakon inspect:*)
|
|
34
|
-
---
|
|
35
|
-
|
|
36
|
-
Run \`lakonai inspect $ARGUMENTS\` and show the output verbatim.
|
|
37
|
-
`,
|
|
38
|
-
},
|
|
39
|
-
{
|
|
40
|
-
name: 'commit',
|
|
41
|
-
body: `---
|
|
42
|
-
description: Write a terse Conventional Commit for the staged changes.
|
|
43
|
-
allowed-tools: Bash(git diff:*), Bash(git status:*), Bash(git commit:*)
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
Write a commit message in terse lakonai style:
|
|
47
|
-
- Conventional Commits: \`type(scope): subject\`. Subject imperative, ≤50 chars, no trailing period.
|
|
48
|
-
- Drop "this commit does X", "I"/"we", "now"/"currently" — the diff says what changed.
|
|
49
|
-
- Body only for the non-obvious *why*, breaking changes, or migration notes.
|
|
50
|
-
- Reference issues at the end (\`Closes #42\`). No AI attribution lines.
|
|
51
|
-
`,
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
name: 'review',
|
|
55
|
-
body: `---
|
|
56
|
-
description: Review the current diff with one terse line per finding.
|
|
57
|
-
allowed-tools: Bash(git diff:*), Bash(lakonai git diff:*)
|
|
58
|
-
---
|
|
59
|
-
|
|
60
|
-
Review the diff. One line per finding, terse lakonai style:
|
|
61
|
-
- Format: \`<file>:L<line>: <severity>: <problem>. <fix>.\`
|
|
62
|
-
- Severity prefix: 🔴 bug / 🟡 risk / 🔵 nit / ❓ q.
|
|
63
|
-
- Keep exact line numbers and \`symbol\` names; give a concrete fix and the *why*.
|
|
64
|
-
- Drop "I noticed that…", "It seems…", "You might want to…".
|
|
65
|
-
- Switch to normal prose for security (CVE-class) findings.
|
|
66
16
|
`,
|
|
67
17
|
},
|
|
68
18
|
];
|
|
@@ -36,12 +36,6 @@ const HOOKS = [
|
|
|
36
36
|
event: 'SessionStart',
|
|
37
37
|
matcher: null,
|
|
38
38
|
},
|
|
39
|
-
{
|
|
40
|
-
basename: 'lakon-prompt-reinforce.js',
|
|
41
|
-
src: path.join(__dirname, '..', 'hooks', 'prompt-reinforce.js'),
|
|
42
|
-
event: 'UserPromptSubmit',
|
|
43
|
-
matcher: null,
|
|
44
|
-
},
|
|
45
39
|
];
|
|
46
40
|
|
|
47
41
|
const SUPPORT_FILES = [
|
package/src/install/index.js
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
const fs = require('fs');
|
|
4
4
|
const path = require('path');
|
|
5
|
+
const readline = require('readline');
|
|
5
6
|
const platforms = require('./platforms');
|
|
6
7
|
const { listBackups } = require('./backup');
|
|
7
8
|
const { homedir } = require('./paths');
|
|
9
|
+
const memCompress = require('../mem-compress');
|
|
8
10
|
|
|
9
11
|
const RULE_PATH = path.join(__dirname, '..', 'rules', 'lakonai.md');
|
|
10
12
|
|
|
@@ -82,6 +84,73 @@ async function install({ only, here = false } = {}) {
|
|
|
82
84
|
process.stdout.write(` ${BULLET} \`lakonai revert\` restores files to pre-install state from backup.\n`);
|
|
83
85
|
process.stdout.write(` ${BULLET} \`lakonai gain\` shows how many tokens you've saved.\n`);
|
|
84
86
|
process.stdout.write('\nRestart your AI agent (or open a new session) for the rule to take effect.\n');
|
|
87
|
+
|
|
88
|
+
await maybeOfferCompress({ cwd: process.cwd(), home });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// First existing memory file worth compressing: project CLAUDE.md, then the
|
|
92
|
+
// user-level one. Backups (*.original.md) are never offered.
|
|
93
|
+
function pickMemoryTarget(cwd, home) {
|
|
94
|
+
const candidates = [
|
|
95
|
+
path.join(cwd, 'CLAUDE.md'),
|
|
96
|
+
path.join(home, '.claude', 'CLAUDE.md'),
|
|
97
|
+
];
|
|
98
|
+
for (const c of candidates) {
|
|
99
|
+
if (memCompress.isBackup(c)) continue;
|
|
100
|
+
try {
|
|
101
|
+
if (fs.statSync(c).isFile()) return c;
|
|
102
|
+
} catch {
|
|
103
|
+
/* not present */
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/* istanbul ignore next -- thin interactive shell; promptYesNo logic is the testable part */
|
|
110
|
+
function promptYesNo(question, { input = process.stdin, output = process.stdout } = {}) {
|
|
111
|
+
return new Promise((resolve) => {
|
|
112
|
+
const rl = readline.createInterface({ input, output });
|
|
113
|
+
rl.question(question, (answer) => {
|
|
114
|
+
rl.close();
|
|
115
|
+
resolve(/^y(es)?$/i.test((answer || '').trim()));
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/* istanbul ignore next -- interactive; gated on TTY, exercised manually not in CI */
|
|
121
|
+
async function maybeOfferCompress({ cwd, home }) {
|
|
122
|
+
if (!process.stdin.isTTY) return; // never block CI / piped installs
|
|
123
|
+
const target = pickMemoryTarget(cwd, home);
|
|
124
|
+
if (!target) return;
|
|
125
|
+
|
|
126
|
+
const backup = memCompress.backupPath(target);
|
|
127
|
+
process.stdout.write(
|
|
128
|
+
`\n ${BULLET} Found memory file ${shortenPath(target)}.\n` +
|
|
129
|
+
` Compressing it shrinks the tokens it costs every session. A local AI CLI\n` +
|
|
130
|
+
` rewrites the prose (lossy), so a backup is saved to ${shortenPath(backup)}\n` +
|
|
131
|
+
` and you can undo with \`lakonai revert-memory ${shortenPath(target)}\`.\n`
|
|
132
|
+
);
|
|
133
|
+
const yes = await promptYesNo(' Compress it now with your local AI CLI? [y/N] ');
|
|
134
|
+
if (!yes) {
|
|
135
|
+
process.stdout.write(` Skipped. Run \`lakonai compress-memory ${shortenPath(target)}\` anytime.\n`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
const llm = require('../mem-llm');
|
|
140
|
+
const provider = llm.pickProvider();
|
|
141
|
+
process.stdout.write(` compressing with ${provider.bin} (${provider.platform})…\n`);
|
|
142
|
+
const res = memCompress.compressFile(target, {
|
|
143
|
+
compress: (orig) => llm.compressWith(orig, { provider }),
|
|
144
|
+
fix: (orig, comp, missing) => llm.fixWith(orig, comp, missing, { provider }),
|
|
145
|
+
remote: true,
|
|
146
|
+
});
|
|
147
|
+
const pct = res.beforeTokens ? Math.round((1 - res.afterTokens / res.beforeTokens) * 100) : 0;
|
|
148
|
+
process.stdout.write(
|
|
149
|
+
` ${OK} Compressed ${res.beforeTokens} ${ARROW} ${res.afterTokens} tokens (~${pct}% smaller). Backup: ${shortenPath(res.backup)}\n`
|
|
150
|
+
);
|
|
151
|
+
} catch (err) {
|
|
152
|
+
process.stdout.write(` ${FAIL} ${err.message}\n Run \`lakonai compress-memory ${shortenPath(target)}\` later to retry.\n`);
|
|
153
|
+
}
|
|
85
154
|
}
|
|
86
155
|
|
|
87
156
|
async function uninstall() {
|
|
@@ -156,4 +225,4 @@ function listPlatforms() {
|
|
|
156
225
|
});
|
|
157
226
|
}
|
|
158
227
|
|
|
159
|
-
module.exports = { install, uninstall, revert, listPlatforms, backupsReport };
|
|
228
|
+
module.exports = { install, uninstall, revert, listPlatforms, backupsReport, pickMemoryTarget };
|