lakonai 1.2.8 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,7 +20,7 @@
20
20
  <img src="https://img.shields.io/badge/node-%E2%89%A518-0F0F0F" alt="node ≥18" />
21
21
  <img src="https://img.shields.io/badge/deps-0-0F0F0F" alt="zero dependencies" />
22
22
  <img src="https://img.shields.io/badge/agents-6-0F0F0F" alt="6 AI agents" />
23
- <img src="https://img.shields.io/badge/tests-895-0F0F0F" alt="895 tests" />
23
+ <img src="https://img.shields.io/badge/tests-1075-0F0F0F" alt="1075 tests" />
24
24
  </p>
25
25
 
26
26
  <p align="center">
@@ -39,6 +39,22 @@
39
39
 
40
40
  ## Real savings, measured
41
41
 
42
+ ### End-to-end, reproducible
43
+
44
+ <p align="center">
45
+ <img src="./docs/assets/savings-e2e.svg" width="820" alt="lakonai e2e: 86.3% fewer tokens overall across 10 real commands on a fixture repo — grep 96.9%, git diff 88.8%, git log 86.6%, ls 80%, git status 36.2%, find 31.5%, make 15%, sed read 0%" />
46
+ </p>
47
+
48
+ `tests/savings-e2e.test.js` builds a git repository on disk and runs each command
49
+ twice — raw, and through the real CLI (or the real PreToolUse hook + `sh` for the
50
+ `cd … &&` row). CI fails if a command drops below its floor **or** loses a line
51
+ that matters (the newest commit, the changed lines, the build warning). File
52
+ reads (`sed -n`, `cat`) are content the agent asked for, so they stay ~untouched.
53
+ Numbers and method: [docs/benchmark-e2e.md](./docs/benchmark-e2e.md). Regenerate the
54
+ chart with `npm run bench:e2e`.
55
+
56
+ ### From live projects
57
+
42
58
  All numbers from live projects using `lakonai@1.1.1`.
43
59
 
44
60
  **CLI filters** — output compressed before it reaches the model (React + TipTap + Yjs microfrontend, 2,185 files):
@@ -83,6 +99,7 @@ All numbers from live projects using `lakonai@1.1.1`.
83
99
  | Front | What it fixes | How |
84
100
  |-------|--------------|-----|
85
101
  | **Output** | _"Great question! Let me explain…"_ | Terse-response rule — no preamble, no recap. Auto-clarity for edge cases. |
102
+ | **Answer length** | A correct answer too long to read | Answer budget restated every turn: summary first, depth only when you ask (`lakonai depth on`) |
86
103
  | **Shell input** | `git log` dumping 1.8k tokens of metadata | Filters **30+ commands** (git/ls/grep/tests/lint/docker/kubectl/aws…) before they hit context |
87
104
  | **Reads** | `Read pnpm-lock.yaml` → 80k of nothing | Hook blocks lockfiles/`node_modules`, caps huge files and `Grep` |
88
105
  | **Overflow** | 4k-line build logs no filter knows | Parks on disk, hands the agent a digest — `lakonai peek` reads it back |
@@ -247,7 +264,7 @@ Query it: lakonai peek 30930a0c --grep "error"
247
264
 
248
265
  | Feature | Claude Code | Codex | Cursor / Windsurf / Cline | Gemini |
249
266
  |---------|:-----------:|:-----:|:-------------------------:|:------:|
250
- | CLI filters | ✅ hook | ✅ shim | ✅ shim | ✅ shim |
267
+ | CLI filters | ✅ hook | ✅ hook ¹ | ✅ shim | ✅ shim |
251
268
  | Read/Grep guard | ✅ | ✅ shim | ✅ shim | ✅ shim |
252
269
  | Overflow sandbox | ✅ | — | — | — |
253
270
  | Proxy compression | ✅ | — | — | — |
@@ -255,6 +272,11 @@ Query it: lakonai peek 30930a0c --grep "error"
255
272
  | Pixel (skill PNG) | ✅ | ✅ | — | — |
256
273
  | MCP catalog compression | ✅ | — | — | — |
257
274
  | Auto-learn new commands | ✅ | ✅ | ✅ | ✅ |
275
+ | Answer budget (per-turn) | ✅ hook | ✅ proxy | ✅ proxy | ✅ proxy |
276
+
277
+ ¹ Codex CLI 0.16x+ runs the same PreToolUse hook from `~/.codex/hooks.json`. Codex skips new hooks until you trust them once with `/hooks`.
278
+
279
+ The Bash hook rewrites `cmd` and `cd <dir> && cmd` to go through `lakonai`. It answers "allow", so it only rewrites a command it can fully see: chains (`&&`, `;`, `||`), `$(…)`, redirects into files, and pipes into anything but `head`/`tail` run unchanged through your normal permission rules.
258
280
 
259
281
  **Primary target: Claude Code.** The proxy and graph layers intercept the Anthropic protocol and are Claude-Code-specific. CLI filters and the universal shim work on every agent. Every install is idempotent and reversible.
260
282
 
@@ -268,6 +290,8 @@ After `lakonai install`, these are available in Claude Code:
268
290
  |---------|--------------|
269
291
  | `/lakonai:gain` | Token savings — input (measured) and output (estimated) |
270
292
  | `/lakonai:stats` | All layers: filters + proxy breakdown by content type |
293
+ | `/lakonai:deep` | Lift the answer budget for one reply, then back to brief |
294
+ | `/lakonai:brief` | Cancel a pending depth grant — back to summary-first |
271
295
 
272
296
  ---
273
297
 
@@ -283,6 +307,7 @@ After `lakonai install`, these are available in Claude Code:
283
307
  | `lakonai pixel [--dry-run\|--revert\|--agent]` | Convert skill files to PNG |
284
308
  | `lakonai compress-memory <file>` | Shrink a memory file via your local AI CLI |
285
309
  | `lakonai peek [id]` | Read output parked in sandbox (`--grep/--offset/--limit`) |
310
+ | `lakonai depth [on\|off\|status]` | Answer budget: `on` buys one long reply, `off` cancels, `status` reports |
286
311
  | `lakonai gain` | Token savings across all measured fronts |
287
312
  | `lakonai inspect <cmd>` | Debug what filter applies to a command |
288
313
  | `lakonai mcp [wrap\|unwrap]` | MCP catalog compression status/lifecycle |
@@ -342,16 +367,16 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
342
367
 
343
368
  ## Test suite
344
369
 
345
- 895 tests across 58 suites — all passing, no mocks on I/O boundaries.
370
+ 1075 tests across 68 suites — all passing, no mocks on I/O boundaries.
346
371
 
347
372
  | Type | Suites | Tests |
348
373
  |------|--------|-------|
349
- | Unit | 13 | 170 |
350
- | Integration (module + real FS) | 33 | 530 |
351
- | E2E / CLI (spawn + real process) | 2 | 51 |
352
- | **Total** | **48** | **751** |
374
+ | Unit | 16 | 218 |
375
+ | Integration (module + real FS / real HTTP) | 36 | 642 |
376
+ | E2E / CLI (spawn + real process) | 16 | 215 |
377
+ | **Total** | **68** | **1075** |
353
378
 
354
- Coverage: **95% statements · 89% branches · 97% functions**
379
+ Coverage: **90% statements · 86% branches · 93% functions** (gate: 80% global; target 100% per new file)
355
380
 
356
381
  Branch ceiling is ~90% — the remaining gaps are canvas-native rendering, platform-specific `fs.watch` fallback, and the HTTPS transport branch (all marked `/* istanbul ignore next */` with justification).
357
382
 
package/bin/lakonai.js CHANGED
@@ -46,6 +46,13 @@ Usage:
46
46
  budget is spilled to disk automatically and replaced
47
47
  with a digest - this is how you read the rest.
48
48
 
49
+ lakonai depth [on|off|status]
50
+ Output-side brevity. Answers are summary-first by
51
+ default (a line budget restated every turn); \`on\`
52
+ buys ONE long answer, \`off\` cancels it, \`status\`
53
+ reports the current mode. Saying "detalha" /
54
+ "more detail" in a prompt does the same as \`on\`.
55
+
49
56
  lakonai gain Show token savings - INPUT (shell output, measured)
50
57
  AND OUTPUT (how much terser the model writes; measured
51
58
  weekly via your local AI CLI, no API key)
@@ -539,6 +546,35 @@ function drainPendingWork() {
539
546
  try { require('../src/install/pending').drain(); } catch { /* best-effort */ }
540
547
  }
541
548
 
549
+ // Output-side brevity control. `on` grants one long answer, `off` revokes,
550
+ // `status` reports. The grant is written under the global key because a slash
551
+ // command cannot learn the session id.
552
+ function runDepth(rest) {
553
+ const depth = require('../src/depth');
554
+ const sub = rest[0] || 'status';
555
+
556
+ if (sub === 'on') {
557
+ depth.grantDepth(null, 1);
558
+ process.stdout.write('lakonai depth: ON - the next answer may run long, then reverts to brief.\n');
559
+ return;
560
+ }
561
+ if (sub === 'off') {
562
+ const had = depth.revokeDepth(null);
563
+ process.stdout.write(`lakonai depth: OFF - brief mode${had ? ' (pending grant cleared)' : ''}.\n`);
564
+ return;
565
+ }
566
+ if (sub === 'status') {
567
+ const active = depth.depthActive(null);
568
+ const b = depth.BUDGETS;
569
+ process.stdout.write(
570
+ `lakonai depth: ${active ? 'ON (one long answer pending)' : 'OFF - brief mode'}\n` +
571
+ ` budget: factual <=${b.factual} lines | explanation <=${b.explanation} | plan/review <=${b.plan}\n`
572
+ );
573
+ return;
574
+ }
575
+ process.stdout.write(`lakonai depth: unknown subcommand "${sub}" (use on|off|status)\n`);
576
+ }
577
+
542
578
  async function main() {
543
579
  const argv = process.argv.slice(2);
544
580
  drainPendingWork();
@@ -587,6 +623,10 @@ async function main() {
587
623
  runUpgrade();
588
624
  return;
589
625
  }
626
+ if (first === 'depth') {
627
+ runDepth(rest);
628
+ return;
629
+ }
590
630
  if (first === 'gain' || first === 'stats') {
591
631
  process.stdout.write(tracking.report());
592
632
  // Output side: measure how much terser the model writes (weekly, TTY-only,
@@ -644,4 +684,4 @@ if (require.main === module) {
644
684
  });
645
685
  }
646
686
 
647
- module.exports = { runAndFilter, printVersion, main, runProxy, runMcp, HELP };
687
+ module.exports = { runAndFilter, printVersion, main, runProxy, runMcp, runDepth, HELP };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "1.2.8",
3
+ "version": "1.4.1",
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",
@@ -50,7 +50,8 @@
50
50
  "test:e2e": "jest --testPathPattern='(cli|e2e-proxy|integration)\\.test\\.js$'",
51
51
  "test:coverage": "jest --coverage",
52
52
  "test:coverage:check": "jest --coverage",
53
- "bench": "node -e \"process.stdout.write(require('./src/bench').format(require('./src/bench').runBench()))\""
53
+ "bench": "node -e \"process.stdout.write(require('./src/bench').format(require('./src/bench').runBench()))\"",
54
+ "bench:e2e": "node scripts/savings-chart.js"
54
55
  },
55
56
  "engines": {
56
57
  "node": ">=18"
package/src/depth.js ADDED
@@ -0,0 +1,212 @@
1
+ 'use strict';
2
+
3
+ // Output-side brevity: lakonai's filters shrink what the model *reads*; this
4
+ // module shrinks what it *writes*. The contract is summary-first — every answer
5
+ // stays inside a line budget unless the user explicitly asks to go deeper.
6
+ //
7
+ // Depth is opt-in and consumable: one request for detail buys one long answer,
8
+ // not a permanently verbose session.
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { homedir } = require('./install/paths');
13
+
14
+ function dataDir() {
15
+ /* istanbul ignore next -- LAKON_HOME is always set under test */
16
+ return process.env.LAKON_HOME || path.join(homedir(), '.lakon');
17
+ }
18
+
19
+ function statePath() {
20
+ return path.join(dataDir(), 'depth.json');
21
+ }
22
+
23
+ // A granted depth token outlives a couple of turns but not a whole day — a
24
+ // stale flag would silently turn brevity off for a session that never asked.
25
+ const TTL_MS = 2 * 60 * 60 * 1000;
26
+
27
+ // Line budgets by answer shape. These are caps on prose lines, never on code
28
+ // blocks, diffs or verbatim output (rule 6 outranks rule 8).
29
+ const BUDGETS = {
30
+ factual: 3,
31
+ explanation: 10,
32
+ plan: 20,
33
+ review: 20,
34
+ };
35
+
36
+ const DEFAULT_BUDGET = BUDGETS.explanation;
37
+
38
+ function budgetFor(kind) {
39
+ return BUDGETS[kind] || DEFAULT_BUDGET;
40
+ }
41
+
42
+ // Phrases that mean "open it up". Portuguese and English, since the rule block
43
+ // ships to users in both.
44
+ const DEPTH_TRIGGERS = [
45
+ /\bdetalh(a|e|ar|es|ando)\b/i,
46
+ /\baprofund(a|e|ar|ando)\b/i,
47
+ /\bexplica(\s+melhor|\s+direito|\s+tudo)\b/i,
48
+ /\bmais\s+(detalhes?|contexto|profundidade)\b/i,
49
+ /\bpor\s+extenso\b/i,
50
+ /\bsem\s+resumir\b/i,
51
+ /\b(be\s+)?verbose\b/i,
52
+ /\bin\s+(full|detail)\b/i,
53
+ /\bdeep\s*dive\b/i,
54
+ /\bwalk\s+me\s+through\b/i,
55
+ /\bmore\s+detail(s)?\b/i,
56
+ /\bexplain\s+(fully|in\s+depth)\b/i,
57
+ /\bdon'?t\s+summarize\b/i,
58
+ ];
59
+
60
+ // Phrases that mean "back to short" — an explicit way out of a depth grant.
61
+ const BRIEF_TRIGGERS = [
62
+ /\bresum(e|a|ido|idamente)\b/i,
63
+ /\bmais\s+curto\b/i,
64
+ /\bs(e|ê|eja)\s+objetiv[oa]\b/i,
65
+ /\bbrief(ly)?\b/i,
66
+ /\bshorter\b/i,
67
+ /\btl;?dr\b/i,
68
+ ];
69
+
70
+ function matchesAny(patterns, text) {
71
+ if (!text || typeof text !== 'string') return false;
72
+ return patterns.some((re) => re.test(text));
73
+ }
74
+
75
+ function wantsDepth(text) {
76
+ return matchesAny(DEPTH_TRIGGERS, text);
77
+ }
78
+
79
+ function wantsBrief(text) {
80
+ return matchesAny(BRIEF_TRIGGERS, text);
81
+ }
82
+
83
+ function readState() {
84
+ try {
85
+ const parsed = JSON.parse(fs.readFileSync(statePath(), 'utf8'));
86
+ if (!parsed || typeof parsed !== 'object' || !parsed.sessions) return { sessions: {} };
87
+ return parsed;
88
+ } catch {
89
+ return { sessions: {} };
90
+ }
91
+ }
92
+
93
+ function writeState(state) {
94
+ try {
95
+ fs.mkdirSync(dataDir(), { recursive: true });
96
+ fs.writeFileSync(statePath(), JSON.stringify(state), 'utf8');
97
+ return true;
98
+ /* istanbul ignore next -- never let a flag write break a hook */
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // Drop expired grants so the file cannot grow without bound across sessions.
105
+ function prune(state, now = Date.now()) {
106
+ for (const [id, entry] of Object.entries(state.sessions)) {
107
+ if (!entry || typeof entry.t !== 'number' || now - entry.t > TTL_MS) {
108
+ delete state.sessions[id];
109
+ }
110
+ }
111
+ return state;
112
+ }
113
+
114
+ const GLOBAL_KEY = 'default';
115
+
116
+ function sessionKey(sessionId) {
117
+ return sessionId || GLOBAL_KEY;
118
+ }
119
+
120
+ // A grant can be addressed to this session, or made globally by the CLI
121
+ // (`lakonai depth on`) — the slash command has no way to learn the session id,
122
+ // so it writes the global key and any session honours it.
123
+ function candidateKeys(sessionId) {
124
+ const own = sessionKey(sessionId);
125
+ return own === GLOBAL_KEY ? [GLOBAL_KEY] : [own, GLOBAL_KEY];
126
+ }
127
+
128
+ // Grant depth for the next `turns` answers in this session.
129
+ function grantDepth(sessionId, turns = 1) {
130
+ const state = prune(readState());
131
+ state.sessions[sessionKey(sessionId)] = { turns: Math.max(1, turns), t: Date.now() };
132
+ writeState(state);
133
+ return turns;
134
+ }
135
+
136
+ // Revoking clears the session's own grant *and* the global one — "resume isso"
137
+ // must not leave a CLI grant standing behind it.
138
+ function revokeDepth(sessionId) {
139
+ const state = prune(readState());
140
+ let had = false;
141
+ for (const key of candidateKeys(sessionId)) {
142
+ if (state.sessions[key]) had = true;
143
+ delete state.sessions[key];
144
+ }
145
+ writeState(state);
146
+ return had;
147
+ }
148
+
149
+ // Is depth active right now? Read-only — does not spend the grant.
150
+ function depthActive(sessionId, now = Date.now()) {
151
+ const state = readState();
152
+ return candidateKeys(sessionId).some((key) => {
153
+ const entry = state.sessions[key];
154
+ if (!entry || typeof entry.t !== 'number') return false;
155
+ if (now - entry.t > TTL_MS) return false;
156
+ return (entry.turns || 0) > 0;
157
+ });
158
+ }
159
+
160
+ // Spend one turn of the grant. Returns true if this turn is allowed to be long.
161
+ function consumeDepth(sessionId) {
162
+ const state = prune(readState());
163
+ for (const key of candidateKeys(sessionId)) {
164
+ const entry = state.sessions[key];
165
+ if (!entry || (entry.turns || 0) <= 0) continue;
166
+ entry.turns -= 1;
167
+ if (entry.turns <= 0) delete state.sessions[key];
168
+ writeState(state);
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+
174
+ // The per-turn reminder injected into context. Deliberately tiny — it is paid
175
+ // on every single turn, so spending 40 lines to ask for brevity would be
176
+ // self-defeating.
177
+ function briefReminder() {
178
+ return [
179
+ 'lakonai brief mode — answer budget:',
180
+ ` factual ≤${BUDGETS.factual} lines · explanation ≤${BUDGETS.explanation} · plan/review ≤${BUDGETS.plan}`,
181
+ ' Summary first. Depth only when asked.',
182
+ ' Code, diffs, identifiers and verbatim output do not count and are never truncated.',
183
+ ' Cut something the user may want? End with one line: → ask "detalha" to expand.',
184
+ ].join('\n');
185
+ }
186
+
187
+ function depthNotice() {
188
+ return 'lakonai depth mode — this one answer may run long. Reverts to brief next turn.';
189
+ }
190
+
191
+ module.exports = {
192
+ BUDGETS,
193
+ GLOBAL_KEY,
194
+ candidateKeys,
195
+ DEFAULT_BUDGET,
196
+ DEPTH_TRIGGERS,
197
+ BRIEF_TRIGGERS,
198
+ TTL_MS,
199
+ budgetFor,
200
+ wantsDepth,
201
+ wantsBrief,
202
+ grantDepth,
203
+ revokeDepth,
204
+ depthActive,
205
+ consumeDepth,
206
+ readState,
207
+ writeState,
208
+ prune,
209
+ statePath,
210
+ briefReminder,
211
+ depthNotice,
212
+ };
package/src/doctor.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // `lakonai doctor` — per-platform health check: is the CLI on PATH, is the rule
4
- // installed, and (for Claude Code) are the hooks registered? Gives an honest,
4
+ // installed, and (for Claude Code and Codex) are the hooks registered? Gives an honest,
5
5
  // per-platform view of what's actually active.
6
6
 
7
7
  const fs = require('fs');
@@ -37,7 +37,7 @@ function report(home) {
37
37
  detected: !!p.detect(h),
38
38
  ruleInstalled: platforms.hasBlock(p.rulePath(h)),
39
39
  };
40
- if (p.hasHooks) row.hooksInstalled = hooksInstalled(h);
40
+ if (p.hasHooks) row.hooksInstalled = p.hooksInstalled ? p.hooksInstalled(h) : hooksInstalled(h);
41
41
  return row;
42
42
  });
43
43
  return { cli: cliOnPath(), platforms: rows };
@@ -55,6 +55,7 @@ module.exports = [
55
55
  match: '^make\\b',
56
56
  stripLines: ['^make\\[\\d+\\]:', '^\\s*$', '^Nothing to be done'],
57
57
  maxLines: 60,
58
+ pinLines: ['\\b(error|warning|Error|Warning|ERROR|WARNING|undefined reference)\\b', '^make(\\[\\d+\\])?: \\*\\*\\*'],
58
59
  onEmpty: 'make: ok',
59
60
  },
60
61
  {
@@ -38,6 +38,7 @@ function compileDef(def) {
38
38
  headLines: def.headLines || null,
39
39
  tailLines: def.tailLines || null,
40
40
  maxLines: def.maxLines || null,
41
+ pinLines: (def.pinLines || []).map((p) => new RegExp(p)),
41
42
  onEmpty: def.onEmpty != null ? def.onEmpty : '',
42
43
  filterStderr: !!def.filterStderr,
43
44
  };
@@ -87,6 +88,14 @@ function applyDef(def, raw) {
87
88
  .join('\n');
88
89
  }
89
90
 
91
+ // A line cap keeps the head, but a build log puts its verdict at the end.
92
+ // Lines matching pinLines survive any cap: they are re-appended after the
93
+ // truncation marker, in order, so a warning on line 400 is never cut.
94
+ const cap = def.headLines || (!def.tailLines && def.maxLines) || null;
95
+ const pinned = cap && def.pinLines.length
96
+ ? text.split('\n').slice(cap).filter((l) => def.pinLines.some((re) => re.test(l)))
97
+ : [];
98
+
90
99
  if (def.headLines) {
91
100
  text = truncateLines(text, def.headLines);
92
101
  } else if (def.tailLines) {
@@ -98,6 +107,7 @@ function applyDef(def, raw) {
98
107
  }
99
108
 
100
109
  if (def.maxLines) text = truncateLines(text, def.maxLines);
110
+ if (pinned.length) text += '\n' + pinned.join('\n');
101
111
 
102
112
  return text.trim() === '' ? def.onEmpty : text;
103
113
  }
@@ -103,6 +103,26 @@ function filterDiff(raw) {
103
103
  return truncateLines(joined, 120);
104
104
  }
105
105
 
106
+ // Global options that sit between `git` and its subcommand. Agents run
107
+ // `git -C <repo> diff` constantly; reading args[0] saw "-C" and the diff
108
+ // filter never ran. Options listed in WITH_VALUE consume the next argument.
109
+ const WITH_VALUE = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']);
110
+
111
+ function subcommand(args) {
112
+ if (!Array.isArray(args)) return undefined;
113
+ for (let i = 0; i < args.length; i++) {
114
+ const a = args[i];
115
+ if (typeof a !== 'string') return undefined;
116
+ if (WITH_VALUE.has(a)) {
117
+ i++;
118
+ continue;
119
+ }
120
+ if (a.startsWith('-')) continue; // --no-pager, -P, --git-dir=…, --bare
121
+ return a;
122
+ }
123
+ return undefined;
124
+ }
125
+
106
126
  function filter(subcmd, raw) {
107
127
  switch (subcmd) {
108
128
  case 'log': return filterLog(raw);
@@ -113,4 +133,4 @@ function filter(subcmd, raw) {
113
133
  }
114
134
  }
115
135
 
116
- module.exports = { filter, filterLog, filterStatus, filterDiff };
136
+ module.exports = { filter, subcommand, filterLog, filterStatus, filterDiff };
@@ -12,12 +12,16 @@ const learn = require('../learn');
12
12
  const { countTokensApprox } = require('./utils');
13
13
 
14
14
  const HANDLERS = {
15
- git: (args, raw) => git.filter(args[0], raw),
15
+ git: (args, raw) => git.filter(git.subcommand(args), raw),
16
16
  ls: (_args, raw) => ls.filter(raw),
17
17
  tree: (_args, raw) => ls.filter(raw),
18
18
  cat: (_args, raw) => cat.filter(raw),
19
19
  head: (_args, raw) => cat.filter(raw, { maxLines: 50 }),
20
20
  tail: (_args, raw) => cat.filter(raw, { maxLines: 50 }),
21
+ // `sed -n 'a,bp' file` is how Codex and Claude read a slice of a file. The
22
+ // range is the agent's explicit choice, so never truncate it (the output
23
+ // spill still parks a runaway read); only ANSI and blank runs go.
24
+ sed: (_args, raw) => cat.filter(raw, { maxLines: Infinity }),
21
25
  grep: (_args, raw) => grep.filter(raw),
22
26
  rg: (_args, raw) => grep.filter(raw),
23
27
  ag: (_args, raw) => grep.filter(raw),
@@ -2,17 +2,70 @@
2
2
  'use strict';
3
3
 
4
4
  const { supportedFirstWords } = require('../filters');
5
+ const { topLevelOps, splitCdPrefix } = require('../shell');
5
6
 
6
7
  const FILTERED_CMDS = supportedFirstWords();
7
8
 
9
+ // Commands that may sit after a `|` without changing what the filter is for:
10
+ // they only cut the (already filtered) display. `| wc -l`, `| jq`, `| sh` or
11
+ // `| git apply` would consume filtered bytes as if they were the real output.
12
+ const PIPE_SINKS = new Set(['head', 'tail']);
13
+
14
+ // Redirections that never capture the filtered stdout into a file.
15
+ const HARMLESS_OPS = new Set(['dup', 'null']);
16
+
17
+ // Forms whose output is empty: rewriting them saves nothing, and the hook
18
+ // answers "allow", so leave them to the normal permission flow.
19
+ function isNoOutputForm(firstWord, rest) {
20
+ if (firstWord === 'sed') return /(^|\s)(-i|--in-place)/.test(rest);
21
+ return false;
22
+ }
23
+
24
+ // Rewrite a single command (no `cd` prefix). The hook approves what it
25
+ // rewrites, so it must only ever rewrite the command it can see: anything that
26
+ // chains another command (`&&`, `;`, `||`, `&`, newline), substitutes one
27
+ // (`$(…)`, backticks), writes the filtered output to a file (`>`), or pipes it
28
+ // into a consumer other than head/tail is left alone.
29
+ function rewriteSimple(command) {
30
+ const firstWord = command.split(/\s+/)[0];
31
+ if (!FILTERED_CMDS.has(firstWord)) return null;
32
+ if (isNoOutputForm(firstWord, command.slice(firstWord.length))) return null;
33
+ const ops = topLevelOps(command);
34
+ if (!ops) return null;
35
+ for (const { op, i } of ops) {
36
+ if (HARMLESS_OPS.has(op)) continue;
37
+ if (op !== '|') return null;
38
+ const sink = command.slice(i + 1).trim().split(/\s+/)[0];
39
+ if (!PIPE_SINKS.has(sink)) return null;
40
+ }
41
+ return `lakonai ${command}`;
42
+ }
43
+
8
44
  function rewriteIfNeeded(command) {
9
45
  if (typeof command !== 'string') return null;
10
46
  const trimmed = command.trim();
11
47
  if (!trimmed) return null;
12
48
  if (/^lakonai(\s|$)/.test(trimmed)) return null;
13
- const firstWord = trimmed.split(/\s+/)[0];
14
- if (!FILTERED_CMDS.has(firstWord)) return null;
15
- return `lakonai ${trimmed}`;
49
+ // `cd <dir> && cmd` is the dominant shape agents emit. Rewrite the command
50
+ // behind the prefix; `cd` itself has nothing to filter.
51
+ const cd = splitCdPrefix(trimmed);
52
+ if (cd) {
53
+ const inner = rewriteIfNeeded(cd.rest);
54
+ return inner ? `cd ${cd.dir} ${cd.op} ${inner}` : null;
55
+ }
56
+ return rewriteSimple(trimmed);
57
+ }
58
+
59
+ // The PreToolUse answer. Claude Code and Codex CLI share this shape: `allow`
60
+ // plus `updatedInput` (Codex rejects `updatedInput` without `allow`).
61
+ function buildResponse(toolInput, rewritten) {
62
+ return {
63
+ hookSpecificOutput: {
64
+ hookEventName: 'PreToolUse',
65
+ permissionDecision: 'allow',
66
+ updatedInput: { ...toolInput, command: rewritten },
67
+ },
68
+ };
16
69
  }
17
70
 
18
71
  /* istanbul ignore next */
@@ -36,17 +89,7 @@ async function main() {
36
89
  const rewritten = rewriteIfNeeded(command);
37
90
  if (!rewritten) process.exit(0);
38
91
 
39
- const response = {
40
- hookSpecificOutput: {
41
- hookEventName: 'PreToolUse',
42
- permissionDecision: 'allow',
43
- updatedInput: {
44
- ...data.tool_input,
45
- command: rewritten,
46
- },
47
- },
48
- };
49
- process.stdout.write(JSON.stringify(response));
92
+ process.stdout.write(JSON.stringify(buildResponse(data.tool_input, rewritten)));
50
93
  process.exit(0);
51
94
  } catch {
52
95
  process.exit(0);
@@ -56,4 +99,4 @@ async function main() {
56
99
  /* istanbul ignore next */
57
100
  if (require.main === module) main();
58
101
 
59
- module.exports = { rewriteIfNeeded, FILTERED_CMDS };
102
+ module.exports = { rewriteIfNeeded, rewriteSimple, buildResponse, FILTERED_CMDS, PIPE_SINKS };
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // UserPromptSubmit: the enforcement point for output-side brevity.
5
+ //
6
+ // The rule block in ~/.claude/CLAUDE.md states the budget once, at session
7
+ // start, and then drifts out of attention as the context fills. This hook
8
+ // restates it on every single turn, which is the only way the contract survives
9
+ // a long session — and it is also where a depth request ("detalha") is detected
10
+ // and spent.
11
+
12
+ const depth = require('../depth');
13
+
14
+ /* istanbul ignore next -- I/O shell */
15
+ async function readStdin() {
16
+ let raw = '';
17
+ process.stdin.setEncoding('utf8');
18
+ for await (const chunk of process.stdin) raw += chunk;
19
+ return raw;
20
+ }
21
+
22
+ // Pure decision: given a prompt, say which mode this turn runs in and what
23
+ // context to inject. No I/O beyond the depth flag file.
24
+ function decide({ sessionId, prompt }) {
25
+ if (process.env.LAKON_NO_BRIEF === '1') return { mode: 'off', context: null };
26
+
27
+ // An explicit "resume isso" cancels a standing grant before it is spent.
28
+ if (depth.wantsBrief(prompt)) depth.revokeDepth(sessionId);
29
+ else if (depth.wantsDepth(prompt)) depth.grantDepth(sessionId, 1);
30
+
31
+ if (depth.consumeDepth(sessionId)) {
32
+ return { mode: 'depth', context: depth.depthNotice() };
33
+ }
34
+ return { mode: 'brief', context: depth.briefReminder() };
35
+ }
36
+
37
+ function buildResponse(decision) {
38
+ if (!decision.context) return null;
39
+ return {
40
+ hookSpecificOutput: {
41
+ hookEventName: 'UserPromptSubmit',
42
+ additionalContext: decision.context,
43
+ },
44
+ };
45
+ }
46
+
47
+ /* istanbul ignore next -- process entry point; decide()/buildResponse() are unit-tested */
48
+ async function main() {
49
+ try {
50
+ const raw = await readStdin();
51
+ if (!raw.trim()) process.exit(0);
52
+ const data = JSON.parse(raw);
53
+ const decision = decide({ sessionId: data.session_id, prompt: data.prompt || '' });
54
+ const response = buildResponse(decision);
55
+ if (response) process.stdout.write(JSON.stringify(response));
56
+ process.exit(0);
57
+ } catch {
58
+ // Never block a prompt because brevity bookkeeping failed.
59
+ process.exit(0);
60
+ }
61
+ }
62
+
63
+ /* istanbul ignore next */
64
+ if (require.main === module) main();
65
+
66
+ module.exports = { decide, buildResponse };