lakonai 0.12.1 → 0.14.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 CHANGED
@@ -32,16 +32,16 @@
32
32
 
33
33
  ## At a glance — measured savings
34
34
 
35
- | Command | Raw tokens | Filtered | Saved |
36
- |----------------------------------|-----------:|---------:|--------:|
37
- | `git log -p -10` | 10,497 | 78 | **-94%** |
38
- | `ls -laR` (deep directory) | 23,624 | 117 | **-94%** |
39
- | `git diff HEAD~5` | 13,230 | 798 | **-89%** |
40
- | `git log --stat -50` | 4,845 | 439 | **-86%** |
41
- | `git status` | 17 | 1 | **-89%** |
42
- | `npm test` (passing suite) | 4,451 | 358 | **-92%** |
43
- | `Read pnpm-lock.yaml` | ~56,000 | **blocked** | **-95%** |
44
- | `Grep` (auto `head_limit`) | unbounded | 30 matches | **capped** |
35
+ | Command | Raw tokens | Filtered | Saved |
36
+ | -------------------------- | ---------: | ----------: | ---------: |
37
+ | `git log -p -10` | 10,497 | 78 | **-94%** |
38
+ | `ls -laR` (deep directory) | 23,624 | 117 | **-94%** |
39
+ | `git diff HEAD~5` | 13,230 | 798 | **-89%** |
40
+ | `git log --stat -50` | 4,845 | 439 | **-86%** |
41
+ | `git status` | 17 | 1 | **-89%** |
42
+ | `npm test` (passing suite) | 4,451 | 358 | **-92%** |
43
+ | `Read pnpm-lock.yaml` | ~56,000 | **blocked** | **-95%** |
44
+ | `Grep` (auto `head_limit`) | unbounded | 30 matches | **capped** |
45
45
 
46
46
  Conservative numbers — peaks go higher in practice. Run `lakonai gain` to see your own savings stack up.
47
47
 
@@ -51,15 +51,15 @@ Conservative numbers — peaks go higher in practice. Run `lakonai gain` to see
51
51
 
52
52
  In 346 BC, Philip II of Macedon — father of Alexander the Great — sent the Spartans a message:
53
53
 
54
- > *"If I invade Lakonía, I will raze your cities to the ground."*
54
+ > _"If I invade Lakonía, I will raze your cities to the ground."_
55
55
 
56
56
  The Spartans replied with a single word:
57
57
 
58
- > *"If."*
58
+ > _"If."_
59
59
 
60
60
  That region was **Lakonía**. Its people gave the English language the word **laconic** — using as few words as possible. They didn't waste breath, didn't waste arrows, didn't waste anything.
61
61
 
62
- Your AI coding agent does. It opens with *"Sure! I'd be happy to help…"*, repeats your question back, and explains what the diff already shows. It reads `git log` in full when one line per commit would do. Every wasted token is a soldier you didn't need to send.
62
+ Your AI coding agent does. It opens with _"Sure! I'd be happy to help…"_, repeats your question back, and explains what the diff already shows. It reads `git log` in full when one line per commit would do. Every wasted token is a soldier you didn't need to send.
63
63
 
64
64
  **lakonai trims both sides.**
65
65
 
@@ -67,22 +67,23 @@ Your AI coding agent does. It opens with *"Sure! I'd be happy to help…"*, repe
67
67
 
68
68
  ## Four fronts. One install.
69
69
 
70
- | Front | Wasted tokens look like… | lakonai fixes it by… |
71
- |--------------------------------|-------------------------------------------------------|-------------------------------------------------------------------------------------|
72
- | **Output** (the model) | *"Great question! Let me explain…"* | Installing a terse-response rule. No preamble, no recap, no restating. |
73
- | **Input** (your shell tools) | `git log` dumping 1.8 k tokens of author metadata | Wrapping **30 commands** — `git`/`ls`/`grep`/`cat`/`find`, **test runners** (jest/pytest/go/cargo), **lint/build** (tsc/eslint/ruff/make), **docker/kubectl/aws** — and compressing before context. |
74
- | **Reads** (file ingestion) | Agent runs `Read` on `pnpm-lock.yaml` → 80 k of nothing | A `PreToolUse` hook on `Read` blocks lockfiles & `node_modules`, caps files >800 lines. |
75
- | **Search** (Grep tool) | `Grep` returns 800 matches and you re-read every one | A `PreToolUse` hook on `Grep` auto-caps `head_limit` at 30 with a one-shot hint. |
76
- | **Context** (every session) | MCP tool catalogs + your `CLAUDE.md`, re-paid every single session | **Auto-compressing MCP catalogs** on install; **opt-in `compress-memory`** for your memory files. |
77
- | **Analysis** (the rule) | `Read` 5k of logs to count errors in your head | "Think in code" — write `node -e '…filter…count'`, consume only the answer. |
70
+ | Front | Wasted tokens look like… | lakonai fixes it by… |
71
+ | ---------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
72
+ | **Output** (the model) | _"Great question! Let me explain…"_ | Installing a terse-response rule. No preamble, no recap, no restating. |
73
+ | **Input** (your shell tools) | `git log` dumping 1.8 k tokens of author metadata | Wrapping **30 commands** — `git`/`ls`/`grep`/`cat`/`find`, **test runners** (jest/pytest/go/cargo), **lint/build** (tsc/eslint/ruff/make), **docker/kubectl/aws** — and compressing before context. |
74
+ | **Reads** (file ingestion) | Agent runs `Read` on `pnpm-lock.yaml` → 80 k of nothing | A `PreToolUse` hook on `Read` blocks lockfiles & `node_modules`, caps files >800 lines. |
75
+ | **Search** (Grep tool) | `Grep` returns 800 matches and you re-read every one | A `PreToolUse` hook on `Grep` auto-caps `head_limit` at 30 with a one-shot hint. |
76
+ | **Context** (every session) | MCP tool catalogs + your `CLAUDE.md`, re-paid every single session | **Auto-compressing MCP catalogs** on install; **opt-in `compress-memory`** for your memory files. |
77
+ | **Analysis** (the rule) | `Read` 5k of logs to count errors in your head | "Think in code" — write `node -e '…filter…count'`, consume only the answer. |
78
78
 
79
79
  Most tools stop at one front. lakonai works all four transparently — your agent doesn't have to remember anything.
80
80
 
81
81
  > **Two that are easy to miss:**
82
- > - **MCP catalogs, compressed automatically.** Connect MCP servers and their tool/prompt/resource *descriptions* load into context every session. On install, lakonai wraps each stdio server and shrinks those descriptions offline — no manual config (caveman's equivalent is hand-wired). Reversible; opt-out `LAKON_NO_MCP=1`.
83
- > - **Your `CLAUDE.md`, compressed on command — no API key.** `lakonai compress-memory CLAUDE.md` rewrites your memory file using **a local AI CLI you already have** (`claude`/`gemini`/`codex`/`cursor-agent`). Backs up first, validates every code span / path / URL survives byte-for-byte. *(new in 0.12.0)*
82
+ >
83
+ > - **MCP catalogs, compressed automatically.** Connect MCP servers and their tool/prompt/resource _descriptions_ load into context every session. On install, lakonai wraps each stdio server and shrinks those descriptions offline — no manual config (caveman's equivalent is hand-wired). Reversible; opt-out `LAKON_NO_MCP=1`.
84
+ > - **Your `CLAUDE.md`, compressed on command — no API key.** `lakonai compress-memory CLAUDE.md` rewrites your memory file using **a local AI CLI you already have** (`claude`/`gemini`/`codex`/`cursor-agent`). Backs up first, validates every code span / path / URL survives byte-for-byte. _(new in 0.12.0)_
84
85
 
85
- > **★ It gets better the more you use it.** lakonai watches your session history and, when an unfiltered command keeps showing up with heavy output, it **turns on a safe filter for that command automatically** — no config, no manual rules. Similar tools only *report* what you're missing; lakonai just fixes it. (Near-lossless: it collapses repetition and truncates with a marker, never silently dropping a line that could be an error. Opt out with `LAKON_NO_LEARN=1`.)
86
+ > **★ It gets better the more you use it.** lakonai watches your session history and, when an unfiltered command keeps showing up with heavy output, it **turns on a safe filter for that command automatically** — no config, no manual rules. Similar tools only _report_ what you're missing; lakonai just fixes it. (Near-lossless: it collapses repetition and truncates with a marker, never silently dropping a line that could be an error. Opt out with `LAKON_NO_LEARN=1`.)
86
87
 
87
88
  ---
88
89
 
@@ -115,18 +116,39 @@ From the next session forward your agent:
115
116
 
116
117
  You'll see savings stack up immediately in `lakonai gain`.
117
118
 
119
+ ### Make shell filtering automatic on _every_ agent (`lakonai shim`)
120
+
121
+ The hooks above are Claude-Code-only — they're the only platform whose hook API
122
+ can transparently rewrite a tool call. To get **automatic** shell-output
123
+ filtering on Codex, Cursor, Windsurf, Cline and Gemini CLI too, run:
124
+
125
+ ```bash
126
+ lakonai shim # prepend ~/.lakon/shim to PATH; lakonai shim --off to undo
127
+ ```
128
+
129
+ This drops tiny executable wrappers for `ls`/`grep`/`rg`/`ag`/`find`/`cat`/`tree`/`head`
130
+ into `~/.lakon/shim/` and prepends that dir to your shell's PATH. Now **any** agent
131
+ that runs one of those commands through a shell gets its output filtered through
132
+ lakonai — no hook API, no model cooperation. `git` is deliberately excluded (its
133
+ subcommands open editors / stream), and the wrappers only shadow read-only,
134
+ single-shot commands so they can never break an interactive invocation.
135
+
136
+ It's **opt-in** because it edits your shell rc (`.zshrc`/`.bashrc`) and shadows
137
+ system commands on PATH. Caveat: it only reaches agents that inherit your shell's
138
+ PATH (terminal-launched CLIs do; some GUI apps with their own environment may not).
139
+
118
140
  ### Compress a memory file (opt-in)
119
141
 
120
- 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.
142
+ 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 — measured **~59%** on a verbose file, **~2%** on an already-terse one), while headings, tables, fenced code, inline code, paths and URLs are preserved byte-for-byte.
121
143
 
122
144
  It auto-detects, in order, whichever agent CLI is on your PATH:
123
145
 
124
- | CLI binary | Platform | Headless call |
125
- |---|---|---|
126
- | `claude` | Claude Code | `claude --print` |
127
- | `gemini` | Gemini CLI | `gemini -p` |
128
- | `codex` | Codex | `codex exec -` |
129
- | `cursor-agent` | Cursor | `cursor-agent -p` |
146
+ | CLI binary | Platform | Headless call |
147
+ | -------------- | ----------- | ----------------- |
148
+ | `claude` | Claude Code | `claude --print` |
149
+ | `gemini` | Gemini CLI | `gemini -p` |
150
+ | `codex` | Codex | `codex exec -` |
151
+ | `cursor-agent` | Cursor | `cursor-agent -p` |
130
152
 
131
153
  (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`.)
132
154
 
@@ -189,34 +211,37 @@ filters do. Set `LAKON_COLOR=1`/`0` (or `NO_COLOR=1`) to force/disable ANSI colo
189
211
  After `lakonai install`, everything is automatic — you rarely need anything but
190
212
  `gain` (to see the savings) and `doctor` (to check it's active).
191
213
 
192
- | Command | What it does |
193
- |--------------------------------------|-----------------------------------------------------------------------|
194
- | `lakonai install [--here] [--only <p>]` | Install rule + hooks (globals by default; `--here` adds per-project) |
195
- | `lakonai uninstall` | Strip the lakonai block from each config (keeps your other content) |
196
- | `lakonai revert [--only <p>]` | Restore each config to its pre-install state from backup |
197
- | `lakonai backups` | Show backup history per platform |
198
- | `lakonai gain` | Show savings by window + top commands (and a sample benchmark before you have data) |
199
- | `lakonai doctor` | Per-platform health: CLI on PATH, rule installed, hooks registered |
200
- | `lakonai <cmd> [args]` | (internal) Run a command, filter its output, track savings |
201
- | `lakonai version` / `--version` / `-v` | Print the installed lakonai version |
214
+ | Command | What it does |
215
+ | --------------------------------------- | ----------------------------------------------------------------------------------- |
216
+ | `lakonai install [--here] [--only <p>]` | Install rule + hooks (globals by default; `--here` adds per-project) |
217
+ | `lakonai uninstall` | Strip the lakonai block from each config (keeps your other content) |
218
+ | `lakonai revert [--only <p>]` | Restore each config to its pre-install state from backup |
219
+ | `lakonai backups` | Show backup history per platform |
220
+ | `lakonai shim [--off]` | Enable/disable the universal PATH shim — automatic shell filtering on _every_ agent |
221
+ | `lakonai compress-memory <file>` | Shrink an authored memory file with your local agent CLI (opt-in, backed up, validated) |
222
+ | `lakonai revert-memory <file>` | Restore a memory file from its `.original.md` backup |
223
+ | `lakonai gain` | Show savings by window + top commands (and a sample benchmark before you have data) |
224
+ | `lakonai doctor` | Per-platform health: CLI on PATH, rule installed, hooks registered |
225
+ | `lakonai <cmd> [args]` | (internal) Run a command, filter its output, track savings |
226
+ | `lakonai version` / `--version` / `-v` | Print the installed lakonai version |
202
227
 
203
228
  ---
204
229
 
205
230
  ## Supported filters
206
231
 
207
- | Command | What it does |
208
- |------------------------|-------------------------------------------------------------------|
209
- | `git log` | One line per commit (`<hash> <subject>`), capped at 50 |
210
- | `git status` | Drops hint paragraphs, separates changed vs untracked |
211
- | `git diff` / `show` | Only `+`/`-`/`@@` lines, drops `index`/`---`/`+++`, cap 120 lines |
212
- | `ls -la` / `tree` | `<size>\t<name>` (drops perms / dates / link targets), cap 60 |
213
- | `cat` | Collapses blank-line runs, cap 200 lines |
214
- | `head` / `tail` | Cap 50 lines |
215
- | `grep` / `rg` / `ag` | Cap 15 matches with "tighten the pattern" hint |
216
- | `find` | Groups matched paths by directory, drops permission-denied noise |
217
- | test runners | jest/vitest/mocha/pytest/ava, `npm/pnpm/yarn/bun test`, `go test`, `cargo test` — collapse passes, keep failures + summary |
218
- | lint / build | `tsc`, `eslint`, `ruff`, `cargo clippy`, `make` — strip noise, "ok" when clean |
219
- | pkg / cloud | `npm/pnpm/yarn/bun install`, `diff`, `docker`, `kubectl`, `aws` — strip progress/noise, cap |
232
+ | Command | What it does |
233
+ | -------------------- | -------------------------------------------------------------------------------------------------------------------------- |
234
+ | `git log` | One line per commit (`<hash> <subject>`), capped at 50 |
235
+ | `git status` | Drops hint paragraphs, separates changed vs untracked |
236
+ | `git diff` / `show` | Only `+`/`-`/`@@` lines, drops `index`/`---`/`+++`, cap 120 lines |
237
+ | `ls -la` / `tree` | `<size>\t<name>` (drops perms / dates / link targets), cap 60 |
238
+ | `cat` | Collapses blank-line runs, cap 200 lines |
239
+ | `head` / `tail` | Cap 50 lines |
240
+ | `grep` / `rg` / `ag` | Cap 15 matches with "tighten the pattern" hint |
241
+ | `find` | Groups matched paths by directory, drops permission-denied noise |
242
+ | test runners | jest/vitest/mocha/pytest/ava, `npm/pnpm/yarn/bun test`, `go test`, `cargo test` — collapse passes, keep failures + summary |
243
+ | lint / build | `tsc`, `eslint`, `ruff`, `cargo clippy`, `make` — strip noise, "ok" when clean |
244
+ | pkg / cloud | `npm/pnpm/yarn/bun install`, `diff`, `docker`, `kubectl`, `aws` — strip progress/noise, cap |
220
245
 
221
246
  The last three groups are powered by a declarative engine (`src/filters/defs.js`)
222
247
  plus a couple of structured filters; adding a new command is usually one data entry.
@@ -272,7 +297,7 @@ If you use wrapper aliases like `claude-my=CLAUDE_CONFIG_DIR=$HOME/.claude-my cl
272
297
 
273
298
  ```bash
274
299
  CLAUDE_CONFIG_DIR=$HOME/.claude-my lakonai install
275
- CLAUDE_CONFIG_DIR=$HOME/.claude-arco lakonai install
300
+ CLAUDE_CONFIG_DIR=$HOME/.claude-company lakonai install
276
301
  ```
277
302
 
278
303
  Each profile gets its own independent install. `lakonai uninstall` / `lakonai revert` respect the same env var.
@@ -281,33 +306,40 @@ Each profile gets its own independent install. `lakonai uninstall` / `lakonai re
281
306
 
282
307
  ## Supported AI agents
283
308
 
284
- | Agent | Scope | What `lakonai install` writes |
285
- |-----------------|----------|--------------------------------------------------------------------------------------------------------|
286
- | 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 |
287
- | Codex CLI | global | Rule block in `~/.codex/AGENTS.md` |
288
- | Gemini CLI | global | Rule block in `~/.gemini/GEMINI.md` |
289
- | Cursor | project² | `.cursor/rules/lakonai.mdc` in the current dir |
290
- | Windsurf | project² | `.windsurf/rules/lakonai.md` in the current dir |
291
- | Cline | project² | `.clinerules/lakonai.md` in the current dir |
309
+ | Agent | Scope | What `lakonai install` writes |
310
+ | ------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
311
+ | 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 |
312
+ | Codex CLI | global | Rule block in `~/.codex/AGENTS.md` |
313
+ | Gemini CLI | global | Rule block in `~/.gemini/GEMINI.md` |
314
+ | Cursor | project² | `.cursor/rules/lakonai.mdc` in the current dir |
315
+ | Windsurf | project² | `.windsurf/rules/lakonai.md` in the current dir |
316
+ | Cline | project² | `.clinerules/lakonai.md` in the current dir |
292
317
 
293
318
  ### What each agent actually gets (honest capability matrix)
294
319
 
295
- The powerful input-side features (shell-output filtering, Read/Grep guards,
296
- auto-learning) are **hooks — they run on Claude Code only**. Everywhere else,
297
- lakonai delivers the terse rule and shell filtering happens by **the model
298
- prefixing `lakonai`** (the rule tells it to). Honest matrix:
299
-
300
- | Agent | Terse rule | Shell filter | Read/Grep guard | Auto-learning |
301
- |-------------|:---------:|---------------------|:---------------:|:-------------:|
302
- | Claude Code | ✅ | ✅ automatic (hook) | ✅ | ✅ |
303
- | Codex CLI | ✅ | ⚠️ via rule (prefix) | ❌ | ❌ |
304
- | Cursor | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
305
- | Windsurf | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
306
- | Cline | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
307
- | Gemini CLI | ✅ | ⚠️ via rule (prefix) | ❌ (rule) | ❌ |
308
-
309
- ⚠️ = the model has to cooperate (prefix `lakonai`). Run `lakonai doctor` to see,
310
- per platform, what's actually active on your machine.
320
+ Once you run `lakonai shim` (see above), the **shell-mediated** features are
321
+ automatic on every agent — they work at the PATH level, no hook API and no model
322
+ cooperation needed. **Shell filtering** routes every wrapped command through
323
+ lakonai, and the **Read-guard** refuses junk reads done via the shell
324
+ (`cat pnpm-lock.yaml`, `head node_modules/…`). What the shim *can't* see is an
325
+ agent's own non-shell Read tool and its full command stream — guarding that tool
326
+ and auto-learning need a call-rewriting hook, which today only Claude Code
327
+ exposes. Honest matrix:
328
+
329
+ | Agent | Terse rule | Shell filter | Read/Grep guard | Auto-learning |
330
+ | ----------- | :--------: | -------------------- | --------------------- | :-----------: |
331
+ | Claude Code | ✅ | ✅ automatic (hook) | ✅ tool + shell | ✅ |
332
+ | Codex CLI | ✅ | ✅ automatic (shim¹) | ✅ shell reads (shim²) | ❌³ |
333
+ | Cursor | ✅ | ✅ automatic (shim¹) | ✅ shell reads (shim²) | ❌³ |
334
+ | Windsurf | ✅ | ✅ automatic (shim¹) | ✅ shell reads (shim²) | ❌³ |
335
+ | Cline | ✅ | ✅ automatic (shim¹) | ✅ shell reads (shim²) | ❌³ |
336
+ | Gemini CLI | ✅ | ✅ automatic (shim¹) | ✅ shell reads (shim²) | ❌³ |
337
+
338
+ Run `lakonai doctor` to see, per platform, what's actually active on your machine.
339
+
340
+ ¹ `lakonai shim` prepends `~/.lakon/shim` to PATH so `ls`/`grep`/`rg`/`ag`/`find`/`cat`/`tree`/`head` filter automatically for any agent that runs them through a shell (opt-in — it edits your shell rc; `git` is excluded for safety). Without it, those commands filter only when the model prefixes `lakonai` itself.
341
+ ² The shim refuses junk reads (lockfiles, `node_modules/…`, build artifacts) done through the shell with `cat`/`head`/`tail`/`less` — same deny rules as the Claude Read hook. An agent's *own* internal Read tool (not via the shell) still needs a hook, so capping/blocking it is automatic only on Claude Code. Codex's hook [can't yet rewrite a tool call](https://github.com/openai/codex/issues/18491); Cursor's can deny but not cap; Gemini's `BeforeTool` could (installer planned, pending schema validation against the real CLI).
342
+ ³ Auto-learning needs to observe the agent's full command stream (an end-of-turn hook), so it's Claude-Code-only — and largely moot elsewhere, since the shim already filters the standard heavy commands without needing to learn them.
311
343
 
312
344
  ¹ "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.
313
345
 
@@ -345,23 +377,23 @@ Override the location with `LAKON_HOME=/path`. Disable per-command logging with
345
377
 
346
378
  ## Configuration
347
379
 
348
- | Env var | Effect |
349
- |-------------------------|------------------------------------------------------------------------------|
350
- | `LAKON_HOME` | Where to keep the log + backups + version cache (default `~/.lakon`) |
351
- | `LAKON_NO_TRACK` | Set to `1` to disable per-command logging |
352
- | `LAKON_NO_UPDATE_CHECK` | Set to `1` to disable the `SessionStart` npm check + terminal hint |
353
- | `LAKON_REGISTRY_URL` | Override the npm registry URL used by the update check (testing) |
354
- | `LAKON_COLOR` | `1` forces ANSI colors in `lakonai gain`; `0` disables; unset = TTY auto-detect |
355
- | `NO_COLOR` | Standard. Disables ANSI colors when set to any non-empty value. |
380
+ | Env var | Effect |
381
+ | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
382
+ | `LAKON_HOME` | Where to keep the log + backups + version cache (default `~/.lakon`) |
383
+ | `LAKON_NO_TRACK` | Set to `1` to disable per-command logging |
384
+ | `LAKON_NO_UPDATE_CHECK` | Set to `1` to disable the `SessionStart` npm check + terminal hint |
385
+ | `LAKON_REGISTRY_URL` | Override the npm registry URL used by the update check (testing) |
386
+ | `LAKON_COLOR` | `1` forces ANSI colors in `lakonai gain`; `0` disables; unset = TTY auto-detect |
387
+ | `NO_COLOR` | Standard. Disables ANSI colors when set to any non-empty value. |
356
388
  | `CLAUDE_CONFIG_DIR` | When set during `lakonai install` / `uninstall`, hooks + rule land in that dir instead of `~/.claude/`. Used for multi-profile setups. |
357
389
 
358
390
  ---
359
391
 
360
392
  ## Philosophy
361
393
 
362
- > *"Brevity is the soul of wit."* — Shakespeare, *Hamlet*
363
- > *"Vēnī, vīdī, vīcī."* — Julius Caesar, three words to describe winning a war.
364
- > *"If."* — Spartans, refusing to be intimidated by a single conditional.
394
+ > _"Brevity is the soul of wit."_ — Shakespeare, _Hamlet_
395
+ > _"Vēnī, vīdī, vīcī."_ — Julius Caesar, three words to describe winning a war.
396
+ > _"If."_ — Spartans, refusing to be intimidated by a single conditional.
365
397
 
366
398
  Every token your agent emits or reads is paid for — in latency, in money, in context budget. The fastest way to think clearly is to speak briefly. lakonai doesn't make your agent dumber; it makes it Spartan.
367
399
 
package/bin/lakonai.js CHANGED
@@ -31,6 +31,12 @@ Usage:
31
31
  lakonai revert-memory <file>
32
32
  Restore <file> from its .original.md backup.
33
33
 
34
+ lakonai shim [--off] Enable (or disable) the universal PATH shim — makes
35
+ ls/grep/rg/ag/find/cat/tree/head filtering AUTOMATIC
36
+ for EVERY agent (Codex/Cursor/Windsurf/Cline/Gemini),
37
+ not just the ones with a hook API. Prepends
38
+ ~/.lakon/shim to PATH in your shell rc.
39
+
34
40
  lakonai gain Show token savings (hour / day / week / month / all)
35
41
  lakonai doctor Per-platform health: CLI on PATH, rule, hooks
36
42
  lakonai version Print the installed lakonai version
@@ -57,9 +63,23 @@ Update notifications:
57
63
  `;
58
64
 
59
65
  function runAndFilter(cmd, args) {
66
+ // Universal Read-guard: refuse junk reads (lockfiles/node_modules) done via the
67
+ // shell (`cat pnpm-lock.yaml`) on ANY agent that uses the shim — same deny rules
68
+ // as the Claude Read hook, no platform hook required.
69
+ const denied = require('../src/shim-guard').check(cmd, args);
70
+ if (denied) {
71
+ process.stdout.write(`lakonai: skipped ${denied.path} — ${denied.reason}\n`);
72
+ tracking.record({ cmd, args, rawTokens: 0, filteredTokens: 0 });
73
+ process.exit(0);
74
+ }
75
+
60
76
  const merge = needsStderr(cmd, args);
61
77
  const stdio = merge ? ['inherit', 'pipe', 'pipe'] : ['inherit', 'pipe', 'inherit'];
62
- const child = spawnSync(cmd, args, { encoding: 'utf8', stdio });
78
+ // Strip the shim dir from PATH so spawning `cmd` resolves the real system
79
+ // binary, not the lakonai shim that may have invoked us (prevents recursion).
80
+ const { pathWithoutShim } = require('../src/install/shim');
81
+ const env = { ...process.env, PATH: pathWithoutShim(process.env) };
82
+ const child = spawnSync(cmd, args, { encoding: 'utf8', stdio, env });
63
83
  if (child.error) {
64
84
  process.stderr.write(`lakonai: ${child.error.message}\n`);
65
85
  process.exit(127);
@@ -82,6 +102,31 @@ function runAndFilter(cmd, args) {
82
102
  process.exit(child.status ?? 0);
83
103
  }
84
104
 
105
+ function runShim(args) {
106
+ const shim = require('../src/install/shim');
107
+ const off = args.includes('--off');
108
+ if (off) {
109
+ const { touched } = shim.uninstall();
110
+ process.stdout.write(`✅ shim removed (${shim.shimDir()})\n`);
111
+ if (touched.length) process.stdout.write(` cleaned PATH block from: ${touched.join(', ')}\n`);
112
+ process.stdout.write(' Restart your shell (or your agent) for it to take effect.\n');
113
+ return;
114
+ }
115
+ const { dir, touched } = shim.install();
116
+ process.stdout.write(
117
+ `✅ universal shim enabled — ${shim.WRAPPED.join('/')} now filtered for ANY agent that inherits PATH.\n` +
118
+ ` shims: ${dir}\n`
119
+ );
120
+ if (touched.length) {
121
+ process.stdout.write(` PATH prepended in: ${touched.join(', ')}\n`);
122
+ } else {
123
+ process.stdout.write(` PATH block already present.\n`);
124
+ }
125
+ process.stdout.write(
126
+ ' Restart your shell (or your agent) for it to take effect. Disable: `lakonai shim --off`.\n'
127
+ );
128
+ }
129
+
85
130
  function runMemory(cmd, args) {
86
131
  const mem = require('../src/mem-compress');
87
132
  const file = args.find((a) => !a.startsWith('--'));
@@ -179,6 +224,10 @@ async function main() {
179
224
  runMemory(first, rest);
180
225
  return;
181
226
  }
227
+ if (first === 'shim') {
228
+ runShim(rest);
229
+ return;
230
+ }
182
231
  if (first === 'gain' || first === 'stats') {
183
232
  process.stdout.write(tracking.report());
184
233
  // No real usage yet? Show the reproducible filter benchmark as a preview.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "0.12.1",
3
+ "version": "0.14.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",
@@ -83,6 +83,10 @@ async function install({ only, here = false } = {}) {
83
83
  process.stdout.write(` ${BULLET} \`lakonai uninstall\` removes only the lakonai block (keeps your other content).\n`);
84
84
  process.stdout.write(` ${BULLET} \`lakonai revert\` restores files to pre-install state from backup.\n`);
85
85
  process.stdout.write(` ${BULLET} \`lakonai gain\` shows how many tokens you've saved.\n`);
86
+ process.stdout.write(
87
+ ` ${BULLET} \`lakonai shim\` makes ls/grep/find/… filtering AUTOMATIC on EVERY agent\n` +
88
+ ` (Codex/Cursor/Windsurf/Cline/Gemini — not just Claude Code). Prepends ~/.lakon/shim to PATH.\n`
89
+ );
86
90
  process.stdout.write('\nRestart your AI agent (or open a new session) for the rule to take effect.\n');
87
91
 
88
92
  await maybeOfferCompress({ cwd: process.cwd(), home });
@@ -0,0 +1,166 @@
1
+ 'use strict';
2
+
3
+ // Universal PATH shim — the one mechanism that makes shell-output filtering
4
+ // AUTOMATIC on every agent, not just the ones with a tool-interception hook
5
+ // (Claude Code, Gemini CLI). It drops tiny executable wrappers into
6
+ // `~/.lakon/shim/` and prepends that dir to PATH, so any command an agent runs
7
+ // through a shell that inherits PATH is routed through `lakonai` transparently —
8
+ // no model cooperation, no per-platform hook API required.
9
+ //
10
+ // Scope is deliberately limited to read-only, output-only commands (no `git` —
11
+ // `git commit` opens an editor; no `tail` — `-f` streams) so shadowing a system
12
+ // binary can never break an interactive or long-running invocation.
13
+ //
14
+ // Recursion: a shim `grep` execs `lakonai grep`, which itself spawns the real
15
+ // `grep`. `pathWithoutShim()` strips the shim dir from the child's PATH so that
16
+ // spawn resolves the system binary instead of the shim again. (See bin/lakonai.js.)
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const os = require('os');
21
+ const { homedir } = require('./paths');
22
+
23
+ const MARK_BEGIN = '# lakonai:shim:begin';
24
+ const MARK_END = '# lakonai:shim:end';
25
+
26
+ // Safe to shadow system-wide: read-only, single-shot, output-only.
27
+ const WRAPPED = ['ls', 'grep', 'rg', 'ag', 'find', 'cat', 'tree', 'head'];
28
+
29
+ function lakonHome() {
30
+ return process.env.LAKON_HOME || path.join(homedir(), '.lakon');
31
+ }
32
+
33
+ function shimDir() {
34
+ return path.join(lakonHome(), 'shim');
35
+ }
36
+
37
+ function shimScript(cmd) {
38
+ // POSIX sh; `exec` replaces the process so exit code passes through.
39
+ return `#!/bin/sh\n# lakonai shim — filters \`${cmd}\` output via lakonai.\nexec lakonai ${cmd} "$@"\n`;
40
+ }
41
+
42
+ // Create the shim dir and one executable per wrapped command. Idempotent.
43
+ function writeShims(dir = shimDir()) {
44
+ fs.mkdirSync(dir, { recursive: true });
45
+ for (const cmd of WRAPPED) {
46
+ const p = path.join(dir, cmd);
47
+ fs.writeFileSync(p, shimScript(cmd), { mode: 0o755 });
48
+ fs.chmodSync(p, 0o755); // ensure +x even if the file pre-existed
49
+ }
50
+ return dir;
51
+ }
52
+
53
+ function removeShims(dir = shimDir()) {
54
+ for (const cmd of WRAPPED) {
55
+ try {
56
+ fs.unlinkSync(path.join(dir, cmd));
57
+ } catch {
58
+ /* already gone */
59
+ }
60
+ }
61
+ }
62
+
63
+ // The block we add to a shell rc file to put the shim dir first on PATH.
64
+ function rcBlock(dir = shimDir()) {
65
+ return [
66
+ MARK_BEGIN,
67
+ '# Routes read-only commands through lakonai for any agent that inherits PATH.',
68
+ '# Remove this block to disable (or run `lakonai shim --off`).',
69
+ `export PATH="${dir}:$PATH"`,
70
+ MARK_END,
71
+ '',
72
+ ].join('\n');
73
+ }
74
+
75
+ function hasBlock(content) {
76
+ return content.includes(MARK_BEGIN);
77
+ }
78
+
79
+ function stripBlock(content) {
80
+ const re = new RegExp(`\\n?${MARK_BEGIN}[\\s\\S]*?${MARK_END}\\n?`, 'g');
81
+ return content.replace(re, '\n').replace(/\n{3,}/g, '\n\n');
82
+ }
83
+
84
+ // Append the PATH block to a shell rc file (idempotent). Returns true if written.
85
+ function addToRc(rcPath, dir = shimDir()) {
86
+ let content = '';
87
+ try {
88
+ content = fs.readFileSync(rcPath, 'utf8');
89
+ } catch {
90
+ /* file may not exist yet */
91
+ }
92
+ if (hasBlock(content)) return false;
93
+ const sep = content && !content.endsWith('\n') ? '\n' : '';
94
+ fs.writeFileSync(rcPath, content + sep + rcBlock(dir));
95
+ return true;
96
+ }
97
+
98
+ function removeFromRc(rcPath) {
99
+ let content;
100
+ try {
101
+ content = fs.readFileSync(rcPath, 'utf8');
102
+ } catch {
103
+ return false;
104
+ }
105
+ if (!hasBlock(content)) return false;
106
+ fs.writeFileSync(rcPath, stripBlock(content));
107
+ return true;
108
+ }
109
+
110
+ // Candidate rc files in the user's home (only those that exist, plus .zshrc/.bashrc
111
+ // which we create if absent since agents commonly source them).
112
+ function rcCandidates(home = homedir()) {
113
+ return ['.zshrc', '.bashrc', '.profile'].map((f) => path.join(home, f));
114
+ }
115
+
116
+ // PATH with the shim dir removed — used when lakonai spawns the real command so
117
+ // it resolves the system binary, not the shim (prevents infinite recursion).
118
+ function pathWithoutShim(env = process.env) {
119
+ const dir = shimDir();
120
+ const sep = path.delimiter;
121
+ const parts = (env.PATH || '').split(sep).filter((p) => p && p !== dir);
122
+ return parts.join(sep);
123
+ }
124
+
125
+ // Install: write shims + prepend PATH in shells that exist (always ensure .zshrc
126
+ // and .bashrc so terminal-launched agents pick it up). Returns the touched files.
127
+ function install({ home = homedir() } = {}) {
128
+ const dir = writeShims();
129
+ const touched = [];
130
+ for (const rc of rcCandidates(home)) {
131
+ // .profile only if it already exists; .zshrc/.bashrc always (create on demand).
132
+ const base = path.basename(rc);
133
+ const exists = fs.existsSync(rc);
134
+ if (base === '.profile' && !exists) continue;
135
+ if (addToRc(rc, dir)) touched.push(rc);
136
+ }
137
+ return { dir, touched };
138
+ }
139
+
140
+ function uninstall({ home = homedir() } = {}) {
141
+ removeShims();
142
+ const touched = [];
143
+ for (const rc of rcCandidates(home)) {
144
+ if (removeFromRc(rc)) touched.push(rc);
145
+ }
146
+ return { touched };
147
+ }
148
+
149
+ module.exports = {
150
+ WRAPPED,
151
+ MARK_BEGIN,
152
+ MARK_END,
153
+ shimDir,
154
+ shimScript,
155
+ writeShims,
156
+ removeShims,
157
+ rcBlock,
158
+ hasBlock,
159
+ stripBlock,
160
+ addToRc,
161
+ removeFromRc,
162
+ rcCandidates,
163
+ pathWithoutShim,
164
+ install,
165
+ uninstall,
166
+ };
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ // Universal Read-guard for the shell path. The Read-guard hook only fires on
4
+ // Claude Code's Read tool, but EVERY agent reads files through the shell too
5
+ // (`cat pnpm-lock.yaml`, `head node_modules/...`). Those go through the shim →
6
+ // `lakonai cat ...`, so we can refuse junk reads here and the protection becomes
7
+ // automatic on every agent that uses the shim — no per-platform hook needed.
8
+ //
9
+ // Reuses the exact deny rules from the Claude Read-guard so behaviour matches.
10
+
11
+ const { isDeniedPath } = require('./hooks/read-guard');
12
+
13
+ // Commands whose non-flag arguments are file paths we should guard.
14
+ const READ_CMDS = new Set(['cat', 'head', 'tail', 'less', 'more', 'bat']);
15
+
16
+ // Return { path, reason } for the first denied path argument, or null. Args that
17
+ // start with `-` are flags; `--` ends option parsing.
18
+ function check(cmd, args) {
19
+ if (!READ_CMDS.has(cmd) || !Array.isArray(args)) return null;
20
+ let optsEnded = false;
21
+ for (const a of args) {
22
+ if (typeof a !== 'string') continue;
23
+ if (!optsEnded && a === '--') {
24
+ optsEnded = true;
25
+ continue;
26
+ }
27
+ if (!optsEnded && a.startsWith('-')) continue; // flag (e.g. -n, -20)
28
+ const reason = isDeniedPath(a);
29
+ if (reason) return { path: a, reason };
30
+ }
31
+ return null;
32
+ }
33
+
34
+ module.exports = { check, READ_CMDS };