lakonai 1.4.1 → 1.5.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
@@ -276,7 +276,17 @@ Query it: lakonai peek 30930a0c --grep "error"
276
276
 
277
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
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.
279
+ The Bash hook rewrites `cmd` and `cd <dir> && cmd` to go through `lakonai`, and it never approves more than you already do:
280
+
281
+ | Command | What the hook does |
282
+ |---|---|
283
+ | Read-only (`git status/log/diff`, `ls`, `cat`, `grep`, `find` without `-exec`/`-delete`, `sed -n 'a,bp'`) | rewrites and approves |
284
+ | Matches one of your `allow` rules, or the session runs with `bypassPermissions` | rewrites and approves (you already did) |
285
+ | Matches one of your `deny`/`ask` rules | leaves it untouched, so the rule still fires |
286
+ | Anything else (`npm test`, `docker`, `git push`, …) | rewrites **without** approving: your prompt or auto mode still decides |
287
+ | Chains (`&&`, `;`, `||`), `$(…)`, redirects into files, pipes into anything but `head`/`tail` | runs unchanged |
288
+
289
+ On Codex, which requires an approval to rewrite, only read-only commands are rewritten.
280
290
 
281
291
  **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.
282
292
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "1.4.1",
3
+ "version": "1.5.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",
@@ -3,6 +3,7 @@
3
3
 
4
4
  const { supportedFirstWords } = require('../filters');
5
5
  const { topLevelOps, splitCdPrefix } = require('../shell');
6
+ const permissions = require('./permissions');
6
7
 
7
8
  const FILTERED_CMDS = supportedFirstWords();
8
9
 
@@ -56,16 +57,38 @@ function rewriteIfNeeded(command) {
56
57
  return rewriteSimple(trimmed);
57
58
  }
58
59
 
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
- };
60
+ // The PreToolUse answer. With `allow` the call skips the permission prompt;
61
+ // without a decision the rewritten command goes through the normal flow (the
62
+ // prompt, or auto mode's review). Codex accepts only the `allow` form.
63
+ function buildResponse(toolInput, rewritten, decision = 'allow') {
64
+ const out = { hookEventName: 'PreToolUse' };
65
+ if (decision === 'allow') out.permissionDecision = 'allow';
66
+ out.updatedInput = { ...toolInput, command: rewritten };
67
+ return { hookSpecificOutput: out };
68
+ }
69
+
70
+ // The command that actually runs, behind any `cd <dir> &&` prefixes.
71
+ function coreCommand(command) {
72
+ let s = command.trim();
73
+ for (let cd = splitCdPrefix(s); cd; cd = splitCdPrefix(s)) s = cd.rest;
74
+ return s;
75
+ }
76
+
77
+ // Full hook decision for one PreToolUse payload. Returns the JSON answer, or
78
+ // null to stay silent (the call proceeds untouched).
79
+ function respond(data, { env = process.env, rules } = {}) {
80
+ if (!data || data.tool_name !== 'Bash') return null;
81
+ const command = data.tool_input && data.tool_input.command;
82
+ const rewritten = rewriteIfNeeded(command);
83
+ if (!rewritten) return null;
84
+ const decision = permissions.decide({
85
+ core: coreCommand(command),
86
+ mode: data.permission_mode,
87
+ agent: env.LAKON_HOOK_AGENT === 'codex' ? 'codex' : 'claude',
88
+ rules: rules || permissions.loadRules({ cwd: data.cwd }),
89
+ });
90
+ if (decision === 'skip') return null;
91
+ return buildResponse(data.tool_input, rewritten, decision);
69
92
  }
70
93
 
71
94
  /* istanbul ignore next */
@@ -82,14 +105,8 @@ async function main() {
82
105
  const raw = await readStdin();
83
106
  if (!raw.trim()) process.exit(0);
84
107
 
85
- const data = JSON.parse(raw);
86
- if (data.tool_name !== 'Bash') process.exit(0);
87
-
88
- const command = data.tool_input && data.tool_input.command;
89
- const rewritten = rewriteIfNeeded(command);
90
- if (!rewritten) process.exit(0);
91
-
92
- process.stdout.write(JSON.stringify(buildResponse(data.tool_input, rewritten)));
108
+ const response = respond(JSON.parse(raw));
109
+ if (response) process.stdout.write(JSON.stringify(response));
93
110
  process.exit(0);
94
111
  } catch {
95
112
  process.exit(0);
@@ -99,4 +116,4 @@ async function main() {
99
116
  /* istanbul ignore next */
100
117
  if (require.main === module) main();
101
118
 
102
- module.exports = { rewriteIfNeeded, rewriteSimple, buildResponse, FILTERED_CMDS, PIPE_SINKS };
119
+ module.exports = { rewriteIfNeeded, rewriteSimple, buildResponse, coreCommand, respond, FILTERED_CMDS, PIPE_SINKS };
@@ -0,0 +1,152 @@
1
+ 'use strict';
2
+
3
+ // How much the Bash rewrite hook may approve.
4
+ //
5
+ // A PreToolUse answer of `permissionDecision: "allow"` skips the user's
6
+ // permission prompt (and auto mode's review). The hook only wants to add a
7
+ // `lakonai` prefix, never to approve something the user would have been asked
8
+ // about. So, per command:
9
+ //
10
+ // 'allow' — read-only, or already approved by one of the user's own allow
11
+ // rules (or the session runs in bypassPermissions): rewrite and
12
+ // answer allow, exactly what would have happened anyway.
13
+ // 'rewrite' — anything else: rewrite WITHOUT a decision, so the normal flow
14
+ // (prompt, or auto mode's classifier on the original) decides.
15
+ // 'skip' — matches a deny/ask rule: rules are evaluated against the
16
+ // rewritten command, and `lakonai git push` would slip past
17
+ // `Bash(git push:*)`; leave the original untouched. Also Codex for
18
+ // non-read-only commands: Codex rejects updatedInput without allow.
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const { claudeConfigDir, homedir } = require('../install/paths');
23
+ const gitFilter = require('../filters/git');
24
+
25
+ // Split a simple command into words, dropping quotes (flag detection only).
26
+ function words(command) {
27
+ const out = [];
28
+ const re = /'([^']*)'|"((?:\\.|[^"\\])*)"|(\S+)/g;
29
+ let m;
30
+ while ((m = re.exec(command))) out.push(m[1] ?? m[2] ?? m[3]);
31
+ return out;
32
+ }
33
+
34
+ const ALWAYS_READ_ONLY = new Set(['ls', 'tree', 'cat', 'head', 'tail', 'grep', 'ag']);
35
+
36
+ const GIT_READ_ONLY = new Set([
37
+ 'status', 'log', 'diff', 'show', 'blame', 'shortlog', 'describe', 'ls-files',
38
+ 'ls-tree', 'ls-remote', 'rev-parse', 'rev-list', 'cat-file', 'grep', 'reflog',
39
+ 'whatchanged', 'name-rev', 'merge-base', 'count-objects', 'check-ignore',
40
+ ]);
41
+
42
+ // `git branch` / `tag` / `remote` / `stash` are read-only only in their listing
43
+ // forms; any create/delete/move/annotate flag or a bare name makes them write.
44
+ const BRANCH_LIST_FLAGS = /^(-a|-r|-v|-vv|-l|--all|--remotes|--list|--verbose|--show-current|--no-color|--contains|--no-contains|--merged|--no-merged|--sort=.+|--format=.+)$/;
45
+ const hasList = (rest) => rest.includes('-l') || rest.includes('--list');
46
+ const TAG_WRITE = /^(-[dasfmFu]|--delete|--annotate|--sign|--force|--message.*|--file.*)$/;
47
+
48
+ const GIT_LISTING = {
49
+ branch: (rest) => rest.every((a) => BRANCH_LIST_FLAGS.test(a) || (hasList(rest) && !a.startsWith('-'))),
50
+ tag: (rest) => rest.length === 0 || (hasList(rest) && !rest.some((a) => TAG_WRITE.test(a))),
51
+ remote: (rest) => rest.every((a) => a === '-v' || a === '--verbose') || rest[0] === 'show' || rest[0] === 'get-url',
52
+ stash: (rest) => rest[0] === 'list' || rest[0] === 'show',
53
+ };
54
+
55
+ const FIND_ACTIONS = /^-(exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/;
56
+
57
+ // A sed script that only prints line ranges: `1,40p`, `10p;20,30p`, `$p`.
58
+ const SED_PRINT_ONLY = /^[\d,$;p\s]+$/;
59
+
60
+ function isReadOnly(command) {
61
+ const [cmd, ...args] = words(command);
62
+ if (ALWAYS_READ_ONLY.has(cmd)) return true;
63
+ if (cmd === 'rg') return !args.some((a) => a === '--pre' || a.startsWith('--pre='));
64
+ if (cmd === 'find') return !args.some((a) => FIND_ACTIONS.test(a));
65
+ if (cmd === 'sed') {
66
+ const flags = args.filter((a) => a.startsWith('-'));
67
+ const rest = args.filter((a) => !a.startsWith('-'));
68
+ return flags.every((f) => f === '-n') && rest.length >= 1 && SED_PRINT_ONLY.test(rest[0]);
69
+ }
70
+ if (cmd === 'git') {
71
+ if (args.some((a) => a.startsWith('--output') || a === '-c' || a.startsWith('--exec-path'))) return false;
72
+ const sub = gitFilter.subcommand(args);
73
+ if (GIT_READ_ONLY.has(sub)) return true;
74
+ const listing = GIT_LISTING[sub];
75
+ if (!listing) return false;
76
+ const rest = args.slice(args.indexOf(sub) + 1);
77
+ return listing(rest);
78
+ }
79
+ return false;
80
+ }
81
+
82
+ // --- the user's own permission rules -----------------------------------------
83
+
84
+ function readSettings(file) {
85
+ try {
86
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
87
+ return data && typeof data === 'object' ? data.permissions || {} : {};
88
+ } catch {
89
+ return {};
90
+ }
91
+ }
92
+
93
+ // Settings files that can hold Bash rules: the user's, then each `.claude/`
94
+ // from cwd up to the filesystem root (the project's lives in one of those).
95
+ function settingsFiles({ home, cwd }) {
96
+ const files = [];
97
+ const userDir = claudeConfigDir(home);
98
+ files.push(path.join(userDir, 'settings.json'), path.join(userDir, 'settings.local.json'));
99
+ let dir = cwd ? path.resolve(cwd) : null;
100
+ while (dir) {
101
+ const proj = path.join(dir, '.claude');
102
+ if (proj !== userDir) files.push(path.join(proj, 'settings.json'), path.join(proj, 'settings.local.json'));
103
+ const parent = path.dirname(dir);
104
+ dir = parent === dir ? null : parent;
105
+ }
106
+ return files;
107
+ }
108
+
109
+ function loadRules({ home = homedir(), cwd } = {}) {
110
+ const rules = { allow: [], deny: [], ask: [] };
111
+ for (const f of settingsFiles({ home, cwd })) {
112
+ const p = readSettings(f);
113
+ for (const kind of Object.keys(rules)) {
114
+ if (Array.isArray(p[kind])) rules[kind].push(...p[kind].filter((r) => typeof r === 'string'));
115
+ }
116
+ }
117
+ return rules;
118
+ }
119
+
120
+ const escapeRe = (s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
121
+
122
+ // Does a permission rule cover this (simple) Bash command?
123
+ // Bash / Bash(*) every command
124
+ // Bash(npm test:*) legacy prefix: `npm test` and `npm test …`
125
+ // Bash(git log *) glob, `*` matches anything
126
+ // Bash(npm test) exact
127
+ function matchesRule(command, rule) {
128
+ const m = /^Bash(?:\((.*)\))?$/.exec(String(rule).trim());
129
+ if (!m) return false;
130
+ const pattern = m[1];
131
+ if (pattern === undefined || pattern === '*' || pattern === '') return true;
132
+ const cmd = command.trim();
133
+ if (pattern.endsWith(':*')) {
134
+ const prefix = pattern.slice(0, -2);
135
+ return cmd === prefix || cmd.startsWith(prefix + ' ');
136
+ }
137
+ const re = new RegExp('^' + pattern.split('*').map(escapeRe).join('.*') + '$');
138
+ return re.test(cmd);
139
+ }
140
+
141
+ const anyRule = (command, list) => list.some((r) => matchesRule(command, r));
142
+
143
+ // core: the command behind any `cd <dir> &&` prefix (what actually runs).
144
+ function decide({ core, mode, agent, rules }) {
145
+ if (anyRule(core, rules.deny) || anyRule(core, rules.ask)) return 'skip';
146
+ if (isReadOnly(core)) return 'allow';
147
+ if (agent === 'codex') return 'skip';
148
+ if (mode === 'bypassPermissions' || anyRule(core, rules.allow)) return 'allow';
149
+ return 'rewrite';
150
+ }
151
+
152
+ module.exports = { words, isReadOnly, matchesRule, settingsFiles, loadRules, decide };
@@ -81,7 +81,7 @@ function installCodexHooks(home) {
81
81
  fs.mkdirSync(path.dirname(dest), { recursive: true });
82
82
  fs.writeFileSync(
83
83
  dest,
84
- `#!/usr/bin/env node\n// lakonai hook launcher (generated)\nrequire('module')._load(${JSON.stringify(h.src)}, null, true);\n`
84
+ `#!/usr/bin/env node\n// lakonai hook launcher (generated)\n// Codex rejects updatedInput without allow: the hook rewrites read-only commands only.\nprocess.env.LAKON_HOOK_AGENT = 'codex';\nrequire('module')._load(${JSON.stringify(h.src)}, null, true);\n`
85
85
  );
86
86
  fs.chmodSync(dest, 0o755);
87
87
  data.hooks[h.event] = data.hooks[h.event] || [];