lakonai 0.16.4 → 0.17.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
@@ -42,19 +42,49 @@ Conservative - peaks go higher. `lakonai gain` shows your own.
42
42
 
43
43
  ---
44
44
 
45
- ## What it does - four fronts
45
+ ## What it does - five fronts
46
46
 
47
47
  | Front | Wasted tokens look like… | lakonai fixes it by… |
48
48
  | --------------------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------- |
49
49
  | **Output** (the model) | _"Great question! Let me explain…"_ | A terse-response rule - no preamble, no recap. |
50
50
  | **Input** (your shell) | `git log` dumping 1.8k tokens of metadata | Filtering **30 commands** (git/ls/grep/tests/lint/docker…) before they hit context. |
51
51
  | **Reads** (files) | `Read pnpm-lock.yaml` → 80k of nothing | A hook that blocks lockfiles/`node_modules`, caps huge files, and caps `Grep`. |
52
+ | **Overflow** (what's left) | A 4k-line build log that no filter knows | Parking it on disk and handing the agent a digest - `lakonai peek` reads it back. |
52
53
  | **Context** (every session) | MCP catalogs + your `CLAUDE.md`, re-paid every turn | Auto-compressing MCP catalogs; opt-in `compress-memory`. |
53
54
 
54
- Most tools stop at one front. lakonai works all four - and **gets better the more
55
+ Most tools stop at one front. lakonai works all five - and **gets better the more
55
56
  you use it**: it auto-learns new heavy commands and turns on a safe filter for them,
56
57
  no config. ([full reference →](docs/reference.md))
57
58
 
59
+ **Overflow, concretely.** Filters handle commands lakonai knows. When output is
60
+ still over budget after filtering, the full text goes to `~/.lakon/sandbox/` and
61
+ the agent sees a digest instead - head, tail, exit code, and how to query the rest:
62
+
63
+ ```
64
+ lakonai: 4000 lines / 249KB parked in sandbox 30930a0c — too big for context, kept out.
65
+ $ node build.js → exit 0
66
+
67
+ [build] compiling module 0 …
68
+ … 3980 lines elided …
69
+ [build] compiling module 3999 …
70
+
71
+ Full output is on disk, not lost. Query it without paying for the whole thing:
72
+ lakonai peek 30930a0c --grep "error"
73
+ ```
74
+
75
+ Measured on that example: **4000 lines / 120KB in, 29 lines out.** Nothing is
76
+ lost - it stops being re-paid on every turn. Set `LAKON_SPILL_TOKENS=0` to turn
77
+ it off.
78
+
79
+ This works on **any** tool that produces bulk output - not just the commands
80
+ lakonai knows. A `PostToolUse` hook sees the real result after the tool ran, so
81
+ `terraform plan`, `./deploy.sh`, a 3k-line `Grep`, a `WebFetch` of a huge page and
82
+ stderr are all covered, alongside `Read`. Structural results (`Edit`, `Write`,
83
+ `TodoWrite`) are left alone.
84
+
85
+ Filters still run first and handle the commands lakonai knows - `git log` becomes
86
+ three lines without ever touching the disk. The spill is the net for what's left.
87
+
58
88
  ---
59
89
 
60
90
  ## Quick start
@@ -131,6 +161,7 @@ weekly, at a TTY only). Both sides, one number.
131
161
  | `lakonai uninstall` / `revert` | Strip the lakonai block / restore from backup |
132
162
  | `lakonai shim [--off]` | Universal PATH shim - automatic shell filtering on every agent |
133
163
  | `lakonai compress-memory <file>` / `revert-memory <file>` | Shrink a memory file via your local AI CLI / undo |
164
+ | `lakonai peek [id]` | Read output parked in the sandbox (`--offset/--limit/--grep`) |
134
165
  | `lakonai gain` | Token savings - input (measured) and output (estimated) |
135
166
  | `lakonai doctor` | Per-platform health: CLI on PATH, rule, hooks |
136
167
 
@@ -142,7 +173,7 @@ Full flags, filters, env vars and internals: **[docs/reference.md](docs/referenc
142
173
 
143
174
  | Agent | Installs | Shell filter | Read/Grep guard | Auto-learn |
144
175
  | ------------------------- | ---------------------------------------------------- | :----------: | :-------------: | :--------: |
145
- | Claude Code | `~/.claude/CLAUDE.md` + 5 hooks + MCP compress | ✅ hook | ✅ tool + shell | ✅ |
176
+ | Claude Code | `~/.claude/CLAUDE.md` + 6 hooks + MCP compress | ✅ hook | ✅ tool + shell | ✅ |
146
177
  | Codex / Gemini | rule in `~/.codex/AGENTS.md` · `~/.gemini/GEMINI.md` | ✅ shim | ✅ shell reads | ✅ |
147
178
  | Cursor / Windsurf / Cline | per-project rule (`--here`) | ✅ shim | ✅ shell reads | ✅ |
148
179
 
package/bin/lakonai.js CHANGED
@@ -40,6 +40,12 @@ Usage:
40
40
  not just the ones with a hook API. Prepends
41
41
  ~/.lakon/shim to PATH in your shell rc.
42
42
 
43
+ lakonai peek [id] Read output that was parked in the sandbox. No id
44
+ lists what's parked. Flags: --offset N --limit N
45
+ --grep <regex>. Output too big for the context
46
+ budget is spilled to disk automatically and replaced
47
+ with a digest - this is how you read the rest.
48
+
43
49
  lakonai gain Show token savings - INPUT (shell output, measured)
44
50
  AND OUTPUT (how much terser the model writes; measured
45
51
  weekly via your local AI CLI, no API key)
@@ -67,6 +73,56 @@ Update notifications:
67
73
  Disable with LAKON_NO_UPDATE_CHECK=1.
68
74
  `;
69
75
 
76
+ // Returns what the agent should see: the filtered text when it fits the budget,
77
+ // otherwise a digest pointing at the parked full output. Falls back to the
78
+ // filtered text if the spill can't be written (read-only home, full disk).
79
+ function maybeSpill({ cmd, args, exitCode, filtered }) {
80
+ const sandbox = require('../src/sandbox');
81
+ const tokens = countTokensApprox(filtered);
82
+ if (!sandbox.shouldSpill(tokens, sandbox.spillThreshold())) return filtered;
83
+ const parked = sandbox.spill({ cmd, args, exitCode, text: filtered });
84
+ /* istanbul ignore next -- disk failure path */
85
+ if (!parked) return filtered;
86
+ return parked.digest;
87
+ }
88
+
89
+ function runPeek(rest) {
90
+ const sandbox = require('../src/sandbox');
91
+ const [id, ...flags] = rest;
92
+ if (!id) {
93
+ const recent = sandbox.list();
94
+ if (!recent.length) {
95
+ process.stdout.write('lakonai: no parked output yet.\n');
96
+ return;
97
+ }
98
+ process.stdout.write(
99
+ 'Parked output (newest first):\n' +
100
+ recent.map((s) => ` ${s.id} ${Math.round(s.bytes / 1024)}KB`).join('\n') +
101
+ '\n'
102
+ );
103
+ return;
104
+ }
105
+ let text;
106
+ try {
107
+ text = sandbox.read(id);
108
+ } catch {
109
+ process.stderr.write(`lakonai: no parked output with id ${id}. Try \`lakonai peek\` to list.\n`);
110
+ process.exit(1);
111
+ }
112
+ const flag = (name) => {
113
+ const i = flags.indexOf(name);
114
+ return i >= 0 ? flags[i + 1] : undefined;
115
+ };
116
+ const pattern = flag('--grep');
117
+ if (pattern != null) {
118
+ process.stdout.write(sandbox.grep(text, pattern) + '\n');
119
+ return;
120
+ }
121
+ const offset = Number(flag('--offset')) || 1;
122
+ const limit = Number(flag('--limit')) || 100;
123
+ process.stdout.write(sandbox.slice(text, { offset, limit }) + '\n');
124
+ }
125
+
70
126
  function runAndFilter(cmd, args) {
71
127
  // Universal Read-guard: refuse junk reads (lockfiles/node_modules) done via the
72
128
  // shell (`cat pnpm-lock.yaml`) on ANY agent that uses the shim - same deny rules
@@ -92,15 +148,21 @@ function runAndFilter(cmd, args) {
92
148
  /* istanbul ignore next -- defensive empty-stream fallbacks */
93
149
  const raw = merge ? (child.stdout || '') + (child.stderr || '') : child.stdout || '';
94
150
  const filtered = isSupported(cmd) ? filterCommand(cmd, args, raw) : raw;
95
- process.stdout.write(filtered);
151
+ // Last line of defence: the filters have already had their go, and it is STILL
152
+ // too big. Park it on disk and hand back a digest, so the bytes cost nothing
153
+ // per turn but stay one `lakonai peek` away.
154
+ const shown = maybeSpill({ cmd, args, exitCode: child.status, filtered });
155
+ process.stdout.write(shown);
96
156
  /* istanbul ignore next */
97
- if (filtered && !filtered.endsWith('\n')) process.stdout.write('\n');
157
+ if (shown && !shown.endsWith('\n')) process.stdout.write('\n');
98
158
 
99
159
  tracking.record({
100
160
  cmd,
101
161
  args,
102
162
  rawTokens: countTokensApprox(raw),
103
- filteredTokens: countTokensApprox(filtered),
163
+ // What the agent actually pays for is `shown`, not `filtered` — on a spill
164
+ // those differ by orders of magnitude, and `gain` must report the truth.
165
+ filteredTokens: countTokensApprox(shown),
104
166
  });
105
167
 
106
168
  // Auto-learning off the universal log (throttled hourly) - runs on EVERY agent,
@@ -401,6 +463,10 @@ async function main() {
401
463
  process.stdout.write(doctor.format(doctor.report()));
402
464
  return;
403
465
  }
466
+ if (first === 'peek') {
467
+ runPeek(rest);
468
+ return;
469
+ }
404
470
  /* istanbul ignore next -- long-running stdio MCP proxy; logic tested via src/mcp-shrink */
405
471
  if (first === '__mcp') {
406
472
  require('../src/mcp-shrink').runProxy(rest);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "0.16.4",
3
+ "version": "0.17.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",
@@ -31,7 +31,13 @@ function filterLog(raw) {
31
31
  pendingHash = null;
32
32
  }
33
33
  }
34
- return truncateLines(out.join('\n'), 50);
34
+ const joined = out.join('\n');
35
+ // This parser only recognises the verbose "commit <sha> / Author: / Date:"
36
+ // shape. `--oneline` and `--format=…` never emit it, so nothing matched and the
37
+ // join returned "" — swallowing the output whole. Those formats are already
38
+ // terse; hand them back untouched. Never answer a command with silence.
39
+ if (!joined && text.trim()) return truncateLines(text.replace(/\s+$/, ''), 50);
40
+ return truncateLines(joined, 50);
35
41
  }
36
42
 
37
43
  function filterStatus(raw) {
@@ -62,7 +68,18 @@ function filterStatus(raw) {
62
68
  const parts = [];
63
69
  if (changed.length) parts.push(`changed:\n${changed.join('\n')}`);
64
70
  if (untracked.length) parts.push(`untracked:\n${untracked.join('\n')}`);
65
- return parts.join('\n\n') || 'clean';
71
+ if (parts.length) return parts.join('\n\n');
72
+
73
+ // Nothing parsed. The section headers this parser keys on only exist in the
74
+ // LONG format — `--short`/`-s`/`--porcelain` emit bare `XY path` lines, so a
75
+ // blind `|| 'clean'` here reported a dirty tree as clean. Only ever say clean
76
+ // when git said so; otherwise hand back what git printed. The short formats are
77
+ // already terse, so passthrough costs nothing.
78
+ if (/nothing to commit|working tree clean|working directory clean/i.test(text)) return 'clean';
79
+ // Trailing-only trim: in porcelain the leading column is significant (" M" is
80
+ // unstaged, "M " is staged), so trimming the start would flip the meaning.
81
+ const rest = text.replace(/\s+$/, '');
82
+ return rest.trim() ? rest : 'clean';
66
83
  }
67
84
 
68
85
  function filterDiff(raw) {
@@ -79,7 +96,11 @@ function filterDiff(raw) {
79
96
  out.push(line);
80
97
  }
81
98
  }
82
- return truncateLines(out.join('\n'), 120);
99
+ const joined = out.join('\n');
100
+ // Same trap as filterLog: `--stat` and `--name-only` carry no hunk markers, so
101
+ // nothing matched and the output vanished. They are already terse — pass through.
102
+ if (!joined && text.trim()) return truncateLines(text.replace(/\s+$/, ''), 120);
103
+ return truncateLines(joined, 120);
83
104
  }
84
105
 
85
106
  function filter(subcmd, raw) {
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // PostToolUse: the universal net.
5
+ //
6
+ // bash-rewrite.js can only spill commands lakonai executes itself — the 34 in the
7
+ // allowlist, stdout only. This hook runs AFTER any tool and gets the real result,
8
+ // so it catches everything the rewrite can't: `terraform plan`, `./deploy.sh`,
9
+ // stderr, plus Read/Grep/WebFetch output that no filter ever sees.
10
+ //
11
+ // PostToolUse is the only hook that can replace a tool result
12
+ // (`updatedToolOutput`); PreToolUse fires before the output exists, so it can
13
+ // cap input but never park output.
14
+
15
+ const sandbox = require('../sandbox');
16
+ const { countTokensApprox } = require('../filters');
17
+
18
+ // Tools whose output is worth parking. Deliberately not everything: Edit/Write
19
+ // results are short, and TodoWrite & friends are structural.
20
+ const SPILLABLE_TOOLS = new Set(['Bash', 'Read', 'Grep', 'Glob', 'WebFetch', 'Task']);
21
+
22
+ // The result arrives as a string or as a structured object depending on the tool.
23
+ function extractText(data) {
24
+ const r = data.tool_response !== undefined ? data.tool_response : data.tool_output;
25
+ if (r == null) return null;
26
+ if (typeof r === 'string') return r;
27
+ // Read returns {file: {content}}; others vary. Prefer a real content field over
28
+ // stringifying the wrapper, which would park JSON noise instead of the payload.
29
+ if (typeof r === 'object') {
30
+ const content = r.content ?? r.file?.content ?? r.output ?? r.stdout;
31
+ if (typeof content === 'string') return content;
32
+ try {
33
+ return JSON.stringify(r);
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+ return null;
39
+ }
40
+
41
+ // bin/lakonai.js may already have parked this very output; re-parking a digest
42
+ // would nest one spill inside another and lose the original id.
43
+ function isAlreadyDigest(text) {
44
+ return /^lakonai: \d+ lines \/ \d+KB parked in sandbox /.test(text);
45
+ }
46
+
47
+ function decide({ toolName, text, threshold }) {
48
+ if (!SPILLABLE_TOOLS.has(toolName)) return null;
49
+ if (typeof text !== 'string' || !text) return null;
50
+ if (isAlreadyDigest(text)) return null;
51
+ const tokens = countTokensApprox(text);
52
+ if (!sandbox.shouldSpill(tokens, threshold)) return null;
53
+ return { tokens };
54
+ }
55
+
56
+ /* istanbul ignore next */
57
+ async function readStdin() {
58
+ let raw = '';
59
+ process.stdin.setEncoding('utf8');
60
+ for await (const chunk of process.stdin) raw += chunk;
61
+ return raw;
62
+ }
63
+
64
+ /* istanbul ignore next */
65
+ async function main() {
66
+ try {
67
+ const raw = await readStdin();
68
+ if (!raw.trim()) process.exit(0);
69
+ const data = JSON.parse(raw);
70
+
71
+ const toolName = data.tool_name;
72
+ const text = extractText(data);
73
+ if (!decide({ toolName, text, threshold: sandbox.spillThreshold() })) process.exit(0);
74
+
75
+ const label = toolName === 'Bash' ? data.tool_input?.command || 'Bash' : toolName;
76
+ const parked = sandbox.spill({ cmd: label, args: [], exitCode: null, text });
77
+ // Disk failure must leave the original result untouched, not blank it.
78
+ if (!parked) process.exit(0);
79
+
80
+ process.stdout.write(
81
+ JSON.stringify({
82
+ hookSpecificOutput: {
83
+ hookEventName: 'PostToolUse',
84
+ updatedToolOutput: parked.digest,
85
+ },
86
+ })
87
+ );
88
+ process.exit(0);
89
+ } catch {
90
+ // A broken net must never break the tool it is netting.
91
+ process.exit(0);
92
+ }
93
+ }
94
+
95
+ /* istanbul ignore next */
96
+ if (require.main === module) main();
97
+
98
+ module.exports = { extractText, isAlreadyDigest, decide, SPILLABLE_TOOLS };
@@ -67,6 +67,18 @@ const DENY_FILE_RE = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.
67
67
 
68
68
  const AUTO_CAP_LINES = 800;
69
69
 
70
+ // What a single Read may cost. Not a new policy: 800 lines of ordinary code
71
+ // (~40 bytes/line) is already ~8k tokens, so this makes the budget the line cap
72
+ // always implied explicit — and therefore enforceable on files whose lines are
73
+ // not ordinary. A 100-line × 5000-char JSON is 100 lines (under the line cap) and
74
+ // ~124k tokens (14× over the real budget); counting lines alone never saw it.
75
+ const READ_TOKEN_BUDGET = 8000;
76
+
77
+ // Counting lines by slurping the file defeats the point on the very files this
78
+ // guard exists for. Above this, sample and extrapolate.
79
+ const FULL_READ_LIMIT = 4 * 1024 * 1024;
80
+ const SAMPLE_BYTES = 64 * 1024;
81
+
70
82
  function isDeniedPath(p) {
71
83
  /* istanbul ignore next */
72
84
  if (typeof p !== 'string' || !p) return null;
@@ -84,6 +96,8 @@ function isDeniedPath(p) {
84
96
 
85
97
  function fileLineCount(p) {
86
98
  try {
99
+ const size = fs.statSync(p).size;
100
+ if (size > FULL_READ_LIMIT) return sampledLineCount(p, size);
87
101
  const data = fs.readFileSync(p, 'utf8');
88
102
  let n = 0;
89
103
  for (let i = 0; i < data.length; i++) if (data.charCodeAt(i) === 10) n++;
@@ -95,6 +109,60 @@ function fileLineCount(p) {
95
109
  }
96
110
  }
97
111
 
112
+ // Read a prefix and extrapolate. Exactness does not matter here: the number only
113
+ // feeds a cap decision, and a 500MB file is getting capped whatever the answer.
114
+ function sampledLineCount(p, size) {
115
+ let fd;
116
+ try {
117
+ fd = fs.openSync(p, 'r');
118
+ const len = Math.min(SAMPLE_BYTES, size);
119
+ const buf = Buffer.alloc(len);
120
+ fs.readSync(fd, buf, 0, len, 0);
121
+ let n = 0;
122
+ for (let i = 0; i < len; i++) if (buf[i] === 10) n++;
123
+ if (n === 0) return 1; // one enormous line
124
+ return Math.max(1, Math.round((n / len) * size));
125
+ /* istanbul ignore next */
126
+ } catch {
127
+ return null;
128
+ } finally {
129
+ /* istanbul ignore next */
130
+ if (fd !== undefined) {
131
+ try {
132
+ fs.closeSync(fd);
133
+ } catch {
134
+ /* already closed */
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ // The line limit a Read should get, or null when the file fits as-is.
141
+ // Two ceilings, whichever bites first: the line cap (many ordinary lines) and the
142
+ // byte budget (few enormous lines). Ordinary code hits the first and behaves
143
+ // exactly as before; wide-line files hit the second, which is the bug this fixes.
144
+ function capForFile(p) {
145
+ const lines = fileLineCount(p);
146
+ if (lines === null) return null;
147
+ let size;
148
+ try {
149
+ size = fs.statSync(p).size;
150
+ } catch {
151
+ /* istanbul ignore next */
152
+ return null;
153
+ }
154
+ const tokens = Math.round(size / 4);
155
+ if (lines <= AUTO_CAP_LINES && tokens <= READ_TOKEN_BUDGET) return null;
156
+ const avgLineBytes = Math.max(1, size / lines);
157
+ const byBudget = Math.floor((READ_TOKEN_BUDGET * 4) / avgLineBytes);
158
+ // Read slices by LINE, so a file whose single line already blows the budget
159
+ // (minified bundle, one-line JSON dump) cannot be capped at all — `limit: 1`
160
+ // would still hand over the whole thing. Deny and point at a tool that can cut
161
+ // inside a line.
162
+ if (byBudget < 1) return { deny: true, lines, tokens };
163
+ return { limit: Math.min(AUTO_CAP_LINES, byBudget), lines, tokens };
164
+ }
165
+
98
166
  function estimateTokensByBytes(p) {
99
167
  try {
100
168
  const size = fs.statSync(p).size;
@@ -145,10 +213,26 @@ async function main() {
145
213
  }
146
214
 
147
215
  if (input.limit == null && input.offset == null) {
148
- const n = fileLineCount(fp);
149
- if (n !== null && n > AUTO_CAP_LINES) {
216
+ const cap = capForFile(fp);
217
+ if (cap && cap.deny) {
218
+ const rawTokens = estimateTokensByBytes(fp);
219
+ trackRecord({ cmd: 'Read', args: [fp, 'deny-wide'], rawTokens, filteredTokens: 0 });
220
+ const response = {
221
+ hookSpecificOutput: {
222
+ hookEventName: 'PreToolUse',
223
+ permissionDecision: 'deny',
224
+ permissionDecisionReason:
225
+ `lakonai: ${cap.lines} line(s) but ~${cap.tokens} tokens — lines too wide to cap ` +
226
+ `(Read slices by line, so any limit still hands over the whole thing). ` +
227
+ `Cut inside the line instead: \`jq\` for JSON, or \`grep -o\` for a fragment.`,
228
+ },
229
+ };
230
+ process.stdout.write(JSON.stringify(response));
231
+ process.exit(0);
232
+ }
233
+ if (cap) {
150
234
  const rawTokens = estimateTokensByBytes(fp);
151
- const capRatio = AUTO_CAP_LINES / n;
235
+ const capRatio = cap.limit / cap.lines;
152
236
  const filteredTokens = Math.round(rawTokens * capRatio);
153
237
  trackRecord({
154
238
  cmd: 'Read',
@@ -163,9 +247,11 @@ async function main() {
163
247
  updatedInput: {
164
248
  ...input,
165
249
  offset: 1,
166
- limit: AUTO_CAP_LINES,
250
+ limit: cap.limit,
167
251
  },
168
- permissionDecisionReason: `lakonai: file has ${n} lines, capped at ${AUTO_CAP_LINES}. Read again with offset=${AUTO_CAP_LINES + 1} for more, or grep -n the symbol you need.`,
252
+ permissionDecisionReason:
253
+ `lakonai: file has ${cap.lines} lines / ~${cap.tokens} tokens, capped at ${cap.limit}. ` +
254
+ `Read again with offset=${cap.limit + 1} for more, or grep -n the symbol you need.`,
169
255
  },
170
256
  };
171
257
  process.stdout.write(JSON.stringify(response));
@@ -184,9 +270,13 @@ if (require.main === module) main();
184
270
  module.exports = {
185
271
  isDeniedPath,
186
272
  fileLineCount,
273
+ sampledLineCount,
274
+ capForFile,
187
275
  estimateTokensByBytes,
188
276
  lakonHome,
189
277
  trackRecord,
190
278
  DENY_DIRS,
191
279
  AUTO_CAP_LINES,
280
+ READ_TOKEN_BUDGET,
281
+ FULL_READ_LIMIT,
192
282
  };
@@ -24,6 +24,16 @@ const HOOKS = [
24
24
  event: 'PreToolUse',
25
25
  matcher: 'Grep',
26
26
  },
27
+ {
28
+ // The universal net: PostToolUse is the only event that can replace a tool
29
+ // result, so this is the one place Read/Grep/WebFetch/unrouted-Bash output
30
+ // can be parked. The PreToolUse hooks above cannot — they run before the
31
+ // output exists.
32
+ basename: 'lakon-output-spill.js',
33
+ src: path.join(__dirname, '..', 'hooks', 'output-spill.js'),
34
+ event: 'PostToolUse',
35
+ matcher: 'Bash|Read|Grep|Glob|WebFetch|Task',
36
+ },
27
37
  {
28
38
  basename: 'lakon-stop-hook.js',
29
39
  src: path.join(__dirname, '..', 'hooks', 'stop-hook.js'),
package/src/mem-llm.js CHANGED
@@ -11,6 +11,17 @@ const fs = require('fs');
11
11
  const path = require('path');
12
12
  const { spawnSync } = require('child_process');
13
13
 
14
+ // Hard wall-clock cap per CLI call so a hung agent (auth prompt, network stall)
15
+ // can never block the caller forever — `lakonai gain` fires 8 of these in a row.
16
+ // Override with LAKONAI_LLM_TIMEOUT_MS; 0/invalid disables the cap.
17
+ const DEFAULT_TIMEOUT_MS = 120000;
18
+ function defaultTimeout(env = process.env) {
19
+ const raw = env.LAKONAI_LLM_TIMEOUT_MS;
20
+ if (raw == null || raw === '') return DEFAULT_TIMEOUT_MS;
21
+ const n = Number(raw);
22
+ return Number.isFinite(n) && n >= 0 ? n : DEFAULT_TIMEOUT_MS;
23
+ }
24
+
14
25
  // Local agent CLIs that can run a one-shot, non-interactive prompt. Order is the
15
26
  // detection preference. `args(prompt)` builds argv; when `stdin` is true the
16
27
  // prompt is piped instead of passed as an argument. `modelFlag` (+ env
@@ -113,7 +124,7 @@ ${compressed}`;
113
124
  // Run the chosen agent CLI in non-interactive mode. `run` is injectable for tests
114
125
  // (production: spawnSync). Throws a clear error when the CLI is missing or returns
115
126
  // non-zero so the caller can surface it.
116
- function callAgent(prompt, { run = spawnSync, provider, model = process.env.LAKONAI_MEM_MODEL, systemPrompt, ruleFree, cwd } = {}) {
127
+ function callAgent(prompt, { run = spawnSync, provider, model = process.env.LAKONAI_MEM_MODEL, systemPrompt, ruleFree, cwd, timeout = defaultTimeout() } = {}) {
117
128
  const p = provider || pickProvider();
118
129
  // Prefer the CLI's real system-prompt flag (stronger behavioral effect); fall
119
130
  // back to prepending it to the prompt when the CLI has no such flag.
@@ -132,11 +143,18 @@ function callAgent(prompt, { run = spawnSync, provider, model = process.env.LAKO
132
143
  if (ruleFree && p.ruleFreeArgs) args.push(...p.ruleFreeArgs);
133
144
  const opts = { input: p.stdin ? effective : undefined, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 };
134
145
  if (cwd) opts.cwd = cwd;
146
+ if (timeout > 0) {
147
+ opts.timeout = timeout;
148
+ opts.killSignal = 'SIGKILL';
149
+ }
135
150
  const res = run(p.bin, args, opts);
136
151
  if (res.error) {
137
152
  if (res.error.code === 'ENOENT') {
138
153
  throw new Error(`\`${p.bin}\` (${p.platform}) not found on PATH.`);
139
154
  }
155
+ if (res.error.code === 'ETIMEDOUT') {
156
+ throw new Error(`${p.bin} timed out after ${timeout}ms (set LAKONAI_LLM_TIMEOUT_MS to adjust).`);
157
+ }
140
158
  throw new Error(`${p.bin} failed: ${res.error.message}`);
141
159
  }
142
160
  if (res.status !== 0) {
package/src/sandbox.js ADDED
@@ -0,0 +1,211 @@
1
+ 'use strict';
2
+
3
+ // Sandbox spill: when a command's output is too big to be worth its context
4
+ // cost, park the full text on disk and hand the agent a digest instead. The
5
+ // bytes stay one `lakonai peek` away, so nothing is lost — it just stops being
6
+ // paid for on every turn.
7
+ //
8
+ // This is the last line of defence, after src/filters/ has already had its go:
9
+ // a spill means even the FILTERED output was oversized.
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const crypto = require('crypto');
14
+ const { homedir } = require('./install/paths');
15
+
16
+ const DEFAULT_SPILL_TOKENS = 2000;
17
+ const HEAD_LINES = 5;
18
+ const TAIL_LINES = 15;
19
+ const KEEP_SPILLS = 50;
20
+ const MAX_AGE_MS = 24 * 60 * 60 * 1000;
21
+
22
+ function dataDir() {
23
+ return process.env.LAKON_HOME || path.join(homedir(), '.lakon');
24
+ }
25
+
26
+ function spillDir() {
27
+ return path.join(dataDir(), 'sandbox');
28
+ }
29
+
30
+ function spillPath(id) {
31
+ return path.join(spillDir(), `${id}.txt`);
32
+ }
33
+
34
+ // Env override lets a user opt out (0 = never spill) or tighten the budget.
35
+ function spillThreshold(env = process.env) {
36
+ const raw = env.LAKON_SPILL_TOKENS;
37
+ if (raw == null || raw === '') return DEFAULT_SPILL_TOKENS;
38
+ const n = Number(raw);
39
+ if (!Number.isFinite(n) || n < 0) return DEFAULT_SPILL_TOKENS;
40
+ return n;
41
+ }
42
+
43
+ function shouldSpill(tokens, threshold) {
44
+ if (threshold === 0) return false;
45
+ return tokens > threshold;
46
+ }
47
+
48
+ function newId() {
49
+ return crypto.randomBytes(4).toString('hex');
50
+ }
51
+
52
+ function splitLines(text) {
53
+ const lines = text.split('\n');
54
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
55
+ return lines;
56
+ }
57
+
58
+ // The only thing the model actually reads. Head+tail because failures land at
59
+ // the bottom (stack traces, "N tests failed") and the invocation at the top.
60
+ function digest({ id, cmd, args = [], exitCode, text }) {
61
+ const lines = splitLines(text);
62
+ const head = lines.slice(0, HEAD_LINES);
63
+ const tail = lines.length > HEAD_LINES + TAIL_LINES ? lines.slice(-TAIL_LINES) : [];
64
+ const elided = lines.length - head.length - tail.length;
65
+
66
+ // Report measured facts (lines, KB) rather than an estimated token count:
67
+ // countTokensApprox() splits on whitespace, which undercounts real tokenizer
68
+ // output by ~35% on prose and more on code. A tool that exists to be honest
69
+ // about token cost has no business quoting a number it can't stand behind.
70
+ const kb = Math.round(Buffer.byteLength(text) / 1024);
71
+ const label = [cmd, ...args].join(' ').trim();
72
+ const out = [];
73
+ out.push(
74
+ `lakonai: ${lines.length} lines / ${kb}KB parked in sandbox ${id} — too big for context, kept out.`
75
+ );
76
+ out.push(`$ ${label}${exitCode != null ? ` → exit ${exitCode}` : ''}`);
77
+ out.push('');
78
+ if (head.length) {
79
+ out.push(...head);
80
+ }
81
+ if (elided > 0) {
82
+ out.push(`… ${elided} lines elided …`);
83
+ }
84
+ if (tail.length) {
85
+ out.push(...tail);
86
+ }
87
+ out.push('');
88
+ out.push('Full output is on disk, not lost. Query it without paying for the whole thing:');
89
+ out.push(` lakonai peek ${id} # first 100 lines`);
90
+ out.push(` lakonai peek ${id} --offset 200 --limit 50`);
91
+ out.push(` lakonai peek ${id} --grep "error" # matching lines only`);
92
+ return out.join('\n');
93
+ }
94
+
95
+ function write({ id, text }) {
96
+ const dir = spillDir();
97
+ fs.mkdirSync(dir, { recursive: true });
98
+ const p = spillPath(id);
99
+ fs.writeFileSync(p, text);
100
+ return p;
101
+ }
102
+
103
+ // Best-effort: a full disk or a read-only home must never break the command the
104
+ // user actually ran.
105
+ function spill({ cmd, args, exitCode, text }) {
106
+ const id = newId();
107
+ try {
108
+ write({ id, text });
109
+ } catch {
110
+ return null;
111
+ }
112
+ try {
113
+ gc();
114
+ } catch {
115
+ /* gc is best-effort */
116
+ }
117
+ return { id, path: spillPath(id), digest: digest({ id, cmd, args, exitCode, text }) };
118
+ }
119
+
120
+ function read(id) {
121
+ return fs.readFileSync(spillPath(id), 'utf8');
122
+ }
123
+
124
+ function slice(text, { offset = 1, limit = 100 } = {}) {
125
+ const lines = splitLines(text);
126
+ const start = Math.max(0, offset - 1);
127
+ const picked = lines.slice(start, start + limit);
128
+ const end = start + picked.length;
129
+ const more = lines.length - end;
130
+ const out = picked.join('\n');
131
+ if (more > 0) {
132
+ return `${out}\n… ${more} more lines — lakonai peek <id> --offset ${end + 1}`;
133
+ }
134
+ return out;
135
+ }
136
+
137
+ function grep(text, pattern, { max = 50 } = {}) {
138
+ let re;
139
+ try {
140
+ re = new RegExp(pattern, 'i');
141
+ } catch {
142
+ return `lakonai: bad regex ${JSON.stringify(pattern)}`;
143
+ }
144
+ const lines = splitLines(text);
145
+ const hits = [];
146
+ for (let i = 0; i < lines.length && hits.length < max; i++) {
147
+ if (re.test(lines[i])) hits.push(`${i + 1}:${lines[i]}`);
148
+ }
149
+ if (!hits.length) return `lakonai: no match for ${JSON.stringify(pattern)}`;
150
+ const total = lines.filter((l) => re.test(l)).length;
151
+ const out = hits.join('\n');
152
+ return total > hits.length ? `${out}\n… ${total - hits.length} more matches` : out;
153
+ }
154
+
155
+ function list() {
156
+ let names;
157
+ try {
158
+ names = fs.readdirSync(spillDir());
159
+ } catch {
160
+ return [];
161
+ }
162
+ return names
163
+ .filter((n) => n.endsWith('.txt'))
164
+ .map((n) => {
165
+ const id = n.replace(/\.txt$/, '');
166
+ let st;
167
+ try {
168
+ st = fs.statSync(path.join(spillDir(), n));
169
+ } catch {
170
+ return null;
171
+ }
172
+ return { id, bytes: st.size, mtime: st.mtimeMs };
173
+ })
174
+ .filter(Boolean)
175
+ .sort((a, b) => b.mtime - a.mtime);
176
+ }
177
+
178
+ // Spills are disposable: a stale one has no value once the turn is over.
179
+ function gc({ keep = KEEP_SPILLS, maxAge = MAX_AGE_MS, now = Date.now() } = {}) {
180
+ const all = list();
181
+ const doomed = all.filter((s, i) => i >= keep || now - s.mtime > maxAge);
182
+ for (const s of doomed) {
183
+ try {
184
+ fs.unlinkSync(spillPath(s.id));
185
+ } catch {
186
+ /* already gone */
187
+ }
188
+ }
189
+ return doomed.length;
190
+ }
191
+
192
+ module.exports = {
193
+ dataDir,
194
+ spillDir,
195
+ spillPath,
196
+ spillThreshold,
197
+ shouldSpill,
198
+ newId,
199
+ digest,
200
+ spill,
201
+ read,
202
+ slice,
203
+ grep,
204
+ list,
205
+ gc,
206
+ splitLines,
207
+ DEFAULT_SPILL_TOKENS,
208
+ HEAD_LINES,
209
+ TAIL_LINES,
210
+ KEEP_SPILLS,
211
+ };