lakonai 1.3.0 → 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 +38 -8
- package/package.json +3 -2
- package/src/doctor.js +2 -2
- package/src/filters/defs.js +1 -0
- package/src/filters/engine.js +10 -0
- package/src/filters/git.js +21 -1
- package/src/filters/index.js +5 -1
- package/src/hooks/bash-rewrite.js +82 -22
- package/src/hooks/permissions.js +152 -0
- package/src/install/codex-hook.js +128 -0
- package/src/install/platforms.js +16 -2
- package/src/learn-report.js +2 -1
- package/src/learn.js +46 -6
- package/src/shell.js +141 -0
- package/src/tracking.js +36 -1
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-
|
|
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):
|
|
@@ -248,7 +264,7 @@ Query it: lakonai peek 30930a0c --grep "error"
|
|
|
248
264
|
|
|
249
265
|
| Feature | Claude Code | Codex | Cursor / Windsurf / Cline | Gemini |
|
|
250
266
|
|---------|:-----------:|:-----:|:-------------------------:|:------:|
|
|
251
|
-
| CLI filters | ✅ hook | ✅
|
|
267
|
+
| CLI filters | ✅ hook | ✅ hook ¹ | ✅ shim | ✅ shim |
|
|
252
268
|
| Read/Grep guard | ✅ | ✅ shim | ✅ shim | ✅ shim |
|
|
253
269
|
| Overflow sandbox | ✅ | — | — | — |
|
|
254
270
|
| Proxy compression | ✅ | — | — | — |
|
|
@@ -258,6 +274,20 @@ Query it: lakonai peek 30930a0c --grep "error"
|
|
|
258
274
|
| Auto-learn new commands | ✅ | ✅ | ✅ | ✅ |
|
|
259
275
|
| Answer budget (per-turn) | ✅ hook | ✅ proxy | ✅ proxy | ✅ proxy |
|
|
260
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`, 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.
|
|
290
|
+
|
|
261
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.
|
|
262
292
|
|
|
263
293
|
---
|
|
@@ -347,16 +377,16 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
|
|
|
347
377
|
|
|
348
378
|
## Test suite
|
|
349
379
|
|
|
350
|
-
|
|
380
|
+
1075 tests across 68 suites — all passing, no mocks on I/O boundaries.
|
|
351
381
|
|
|
352
382
|
| Type | Suites | Tests |
|
|
353
383
|
|------|--------|-------|
|
|
354
|
-
| Unit |
|
|
355
|
-
| Integration (module + real FS / real HTTP) |
|
|
356
|
-
| E2E / CLI (spawn + real process) |
|
|
357
|
-
| **Total** | **
|
|
384
|
+
| Unit | 16 | 218 |
|
|
385
|
+
| Integration (module + real FS / real HTTP) | 36 | 642 |
|
|
386
|
+
| E2E / CLI (spawn + real process) | 16 | 215 |
|
|
387
|
+
| **Total** | **68** | **1075** |
|
|
358
388
|
|
|
359
|
-
Coverage: **90% statements ·
|
|
389
|
+
Coverage: **90% statements · 86% branches · 93% functions** (gate: 80% global; target 100% per new file)
|
|
360
390
|
|
|
361
391
|
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).
|
|
362
392
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lakonai",
|
|
3
|
-
"version": "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",
|
|
@@ -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/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 };
|
package/src/filters/defs.js
CHANGED
|
@@ -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
|
{
|
package/src/filters/engine.js
CHANGED
|
@@ -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
|
}
|
package/src/filters/git.js
CHANGED
|
@@ -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 };
|
package/src/filters/index.js
CHANGED
|
@@ -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
|
|
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,93 @@
|
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
const { supportedFirstWords } = require('../filters');
|
|
5
|
+
const { topLevelOps, splitCdPrefix } = require('../shell');
|
|
6
|
+
const permissions = require('./permissions');
|
|
5
7
|
|
|
6
8
|
const FILTERED_CMDS = supportedFirstWords();
|
|
7
9
|
|
|
10
|
+
// Commands that may sit after a `|` without changing what the filter is for:
|
|
11
|
+
// they only cut the (already filtered) display. `| wc -l`, `| jq`, `| sh` or
|
|
12
|
+
// `| git apply` would consume filtered bytes as if they were the real output.
|
|
13
|
+
const PIPE_SINKS = new Set(['head', 'tail']);
|
|
14
|
+
|
|
15
|
+
// Redirections that never capture the filtered stdout into a file.
|
|
16
|
+
const HARMLESS_OPS = new Set(['dup', 'null']);
|
|
17
|
+
|
|
18
|
+
// Forms whose output is empty: rewriting them saves nothing, and the hook
|
|
19
|
+
// answers "allow", so leave them to the normal permission flow.
|
|
20
|
+
function isNoOutputForm(firstWord, rest) {
|
|
21
|
+
if (firstWord === 'sed') return /(^|\s)(-i|--in-place)/.test(rest);
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Rewrite a single command (no `cd` prefix). The hook approves what it
|
|
26
|
+
// rewrites, so it must only ever rewrite the command it can see: anything that
|
|
27
|
+
// chains another command (`&&`, `;`, `||`, `&`, newline), substitutes one
|
|
28
|
+
// (`$(…)`, backticks), writes the filtered output to a file (`>`), or pipes it
|
|
29
|
+
// into a consumer other than head/tail is left alone.
|
|
30
|
+
function rewriteSimple(command) {
|
|
31
|
+
const firstWord = command.split(/\s+/)[0];
|
|
32
|
+
if (!FILTERED_CMDS.has(firstWord)) return null;
|
|
33
|
+
if (isNoOutputForm(firstWord, command.slice(firstWord.length))) return null;
|
|
34
|
+
const ops = topLevelOps(command);
|
|
35
|
+
if (!ops) return null;
|
|
36
|
+
for (const { op, i } of ops) {
|
|
37
|
+
if (HARMLESS_OPS.has(op)) continue;
|
|
38
|
+
if (op !== '|') return null;
|
|
39
|
+
const sink = command.slice(i + 1).trim().split(/\s+/)[0];
|
|
40
|
+
if (!PIPE_SINKS.has(sink)) return null;
|
|
41
|
+
}
|
|
42
|
+
return `lakonai ${command}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
8
45
|
function rewriteIfNeeded(command) {
|
|
9
46
|
if (typeof command !== 'string') return null;
|
|
10
47
|
const trimmed = command.trim();
|
|
11
48
|
if (!trimmed) return null;
|
|
12
49
|
if (/^lakonai(\s|$)/.test(trimmed)) return null;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
50
|
+
// `cd <dir> && cmd` is the dominant shape agents emit. Rewrite the command
|
|
51
|
+
// behind the prefix; `cd` itself has nothing to filter.
|
|
52
|
+
const cd = splitCdPrefix(trimmed);
|
|
53
|
+
if (cd) {
|
|
54
|
+
const inner = rewriteIfNeeded(cd.rest);
|
|
55
|
+
return inner ? `cd ${cd.dir} ${cd.op} ${inner}` : null;
|
|
56
|
+
}
|
|
57
|
+
return rewriteSimple(trimmed);
|
|
58
|
+
}
|
|
59
|
+
|
|
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);
|
|
16
92
|
}
|
|
17
93
|
|
|
18
94
|
/* istanbul ignore next */
|
|
@@ -29,24 +105,8 @@ async function main() {
|
|
|
29
105
|
const raw = await readStdin();
|
|
30
106
|
if (!raw.trim()) process.exit(0);
|
|
31
107
|
|
|
32
|
-
const
|
|
33
|
-
if (
|
|
34
|
-
|
|
35
|
-
const command = data.tool_input && data.tool_input.command;
|
|
36
|
-
const rewritten = rewriteIfNeeded(command);
|
|
37
|
-
if (!rewritten) process.exit(0);
|
|
38
|
-
|
|
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));
|
|
108
|
+
const response = respond(JSON.parse(raw));
|
|
109
|
+
if (response) process.stdout.write(JSON.stringify(response));
|
|
50
110
|
process.exit(0);
|
|
51
111
|
} catch {
|
|
52
112
|
process.exit(0);
|
|
@@ -56,4 +116,4 @@ async function main() {
|
|
|
56
116
|
/* istanbul ignore next */
|
|
57
117
|
if (require.main === module) main();
|
|
58
118
|
|
|
59
|
-
module.exports = { rewriteIfNeeded, FILTERED_CMDS };
|
|
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 };
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Codex CLI hooks. Codex (0.16x+) reads Claude-compatible hooks from
|
|
4
|
+
// `~/.codex/hooks.json`: a PreToolUse handler matched on `Bash` gets
|
|
5
|
+
// `tool_input.command` and may answer `permissionDecision: "allow"` with
|
|
6
|
+
// `updatedInput.command`, which is exactly what bash-rewrite emits. So Codex
|
|
7
|
+
// gets the same automatic `lakonai` prefix as Claude Code, with no PATH shim.
|
|
8
|
+
//
|
|
9
|
+
// Codex only runs a non-managed hook after the user reviews and trusts it
|
|
10
|
+
// (`/hooks` in the TUI); until then it is skipped, never half-applied.
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const { backupFile } = require('./backup');
|
|
15
|
+
const { writeFileAtomic } = require('./atomic');
|
|
16
|
+
|
|
17
|
+
const HOOKS = [
|
|
18
|
+
{
|
|
19
|
+
basename: 'lakon-bash-rewrite.js',
|
|
20
|
+
src: path.join(__dirname, '..', 'hooks', 'bash-rewrite.js'),
|
|
21
|
+
event: 'PreToolUse',
|
|
22
|
+
matcher: '^Bash$',
|
|
23
|
+
},
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
const BASENAMES = HOOKS.map((h) => h.basename);
|
|
27
|
+
|
|
28
|
+
function codexDir(home) {
|
|
29
|
+
return path.join(home, '.codex');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function hooksJsonPath(home) {
|
|
33
|
+
return path.join(codexDir(home), 'hooks.json');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function launcherPath(home, basename) {
|
|
37
|
+
return path.join(codexDir(home), 'hooks', basename);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function readHooksJson(home) {
|
|
41
|
+
const p = hooksJsonPath(home);
|
|
42
|
+
if (!fs.existsSync(p)) return { ok: true, data: {} };
|
|
43
|
+
try {
|
|
44
|
+
const data = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
45
|
+
return { ok: true, data: data && typeof data === 'object' ? data : {} };
|
|
46
|
+
} catch (err) {
|
|
47
|
+
return { ok: false, error: err.message };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const ownsHandler = (h) => !!h && typeof h.command === 'string' && BASENAMES.some((b) => h.command.includes(b));
|
|
52
|
+
|
|
53
|
+
// Drop every lakonai handler; returns the cleaned data (empty groups removed).
|
|
54
|
+
function stripOurs(data) {
|
|
55
|
+
if (!data.hooks || typeof data.hooks !== 'object') return data;
|
|
56
|
+
for (const event of Object.keys(data.hooks)) {
|
|
57
|
+
if (!Array.isArray(data.hooks[event])) continue;
|
|
58
|
+
data.hooks[event] = data.hooks[event]
|
|
59
|
+
.map((group) => {
|
|
60
|
+
if (!group || !Array.isArray(group.hooks)) return group;
|
|
61
|
+
const keep = group.hooks.filter((h) => !ownsHandler(h));
|
|
62
|
+
return keep.length ? { ...group, hooks: keep } : null;
|
|
63
|
+
})
|
|
64
|
+
.filter(Boolean);
|
|
65
|
+
if (!data.hooks[event].length) delete data.hooks[event];
|
|
66
|
+
}
|
|
67
|
+
if (!Object.keys(data.hooks).length) delete data.hooks;
|
|
68
|
+
return data;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function installCodexHooks(home) {
|
|
72
|
+
const { ok, data, error } = readHooksJson(home);
|
|
73
|
+
if (!ok) return { installed: false, note: `hooks.json could not be parsed (${error})` };
|
|
74
|
+
const p = hooksJsonPath(home);
|
|
75
|
+
if (fs.existsSync(p)) backupFile('codex', p);
|
|
76
|
+
|
|
77
|
+
stripOurs(data); // idempotent: re-install replaces, never duplicates
|
|
78
|
+
data.hooks = data.hooks || {};
|
|
79
|
+
for (const h of HOOKS) {
|
|
80
|
+
const dest = launcherPath(home, h.basename);
|
|
81
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
82
|
+
fs.writeFileSync(
|
|
83
|
+
dest,
|
|
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
|
+
);
|
|
86
|
+
fs.chmodSync(dest, 0o755);
|
|
87
|
+
data.hooks[h.event] = data.hooks[h.event] || [];
|
|
88
|
+
data.hooks[h.event].push({
|
|
89
|
+
matcher: h.matcher,
|
|
90
|
+
hooks: [{ type: 'command', command: dest, timeout: 10 }],
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
writeFileAtomic(p, JSON.stringify(data, null, 2) + '\n');
|
|
94
|
+
return { installed: true, path: p };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function uninstallCodexHooks(home) {
|
|
98
|
+
const { ok, data } = readHooksJson(home);
|
|
99
|
+
const p = hooksJsonPath(home);
|
|
100
|
+
if (ok && fs.existsSync(p)) {
|
|
101
|
+
stripOurs(data);
|
|
102
|
+
if (Object.keys(data).length) writeFileAtomic(p, JSON.stringify(data, null, 2) + '\n');
|
|
103
|
+
else fs.unlinkSync(p);
|
|
104
|
+
}
|
|
105
|
+
for (const b of BASENAMES) {
|
|
106
|
+
try {
|
|
107
|
+
fs.unlinkSync(launcherPath(home, b));
|
|
108
|
+
} catch {
|
|
109
|
+
/* already gone */
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function codexHooksInstalled(home) {
|
|
115
|
+
const { ok, data } = readHooksJson(home);
|
|
116
|
+
if (!ok || !data.hooks) return false;
|
|
117
|
+
return JSON.stringify(data.hooks).includes('lakon-bash-rewrite.js');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = {
|
|
121
|
+
installCodexHooks,
|
|
122
|
+
uninstallCodexHooks,
|
|
123
|
+
codexHooksInstalled,
|
|
124
|
+
hooksJsonPath,
|
|
125
|
+
launcherPath,
|
|
126
|
+
stripOurs,
|
|
127
|
+
HOOKS,
|
|
128
|
+
};
|
package/src/install/platforms.js
CHANGED
|
@@ -5,6 +5,7 @@ const path = require('path');
|
|
|
5
5
|
const { backupFile, restoreAllBackups } = require('./backup');
|
|
6
6
|
const { installHook, uninstallHook } = require('./claude-hook');
|
|
7
7
|
const { installCommands, uninstallCommands } = require('./claude-commands');
|
|
8
|
+
const { installCodexHooks, uninstallCodexHooks, codexHooksInstalled } = require('./codex-hook');
|
|
8
9
|
const { wrapMcp, unwrapMcp } = require('./mcp');
|
|
9
10
|
const { writeFileAtomic } = require('./atomic');
|
|
10
11
|
const { claudeConfigDir } = require('./paths');
|
|
@@ -113,9 +114,22 @@ const PLATFORMS = [
|
|
|
113
114
|
label: 'Codex CLI',
|
|
114
115
|
scope: 'global',
|
|
115
116
|
rulePath: (home) => path.join(home, '.codex', 'AGENTS.md'),
|
|
117
|
+
hasHooks: true,
|
|
118
|
+
hooksInstalled: (home) => codexHooksInstalled(home),
|
|
116
119
|
detect: (home) => dirExists(path.join(home, '.codex')),
|
|
117
|
-
install: ({ home, rule, id }) =>
|
|
118
|
-
|
|
120
|
+
install: ({ home, rule, id }) => {
|
|
121
|
+
const rulePath = upsertBlock(id, path.join(home, '.codex', 'AGENTS.md'), rule);
|
|
122
|
+
const hooks = installCodexHooks(home);
|
|
123
|
+
/* istanbul ignore next -- the parse-failure note is covered in codex-hook tests */
|
|
124
|
+
const suffix = hooks.installed
|
|
125
|
+
? '+ PreToolUse hook (trust it once with /hooks in Codex)'
|
|
126
|
+
: `(hook: ${hooks.note})`;
|
|
127
|
+
return `${rulePath} ${suffix}`;
|
|
128
|
+
},
|
|
129
|
+
uninstall: ({ home }) => {
|
|
130
|
+
uninstallCodexHooks(home);
|
|
131
|
+
return stripBlock(path.join(home, '.codex', 'AGENTS.md'));
|
|
132
|
+
},
|
|
119
133
|
},
|
|
120
134
|
{
|
|
121
135
|
id: 'cursor',
|
package/src/learn-report.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const fs = require('fs');
|
|
4
4
|
const path = require('path');
|
|
5
5
|
const os = require('os');
|
|
6
|
+
const { isLearnable } = require('./learn');
|
|
6
7
|
|
|
7
8
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
8
9
|
const REPORT_TTL_MS = DAY_MS;
|
|
@@ -61,7 +62,7 @@ function readLogSinks() {
|
|
|
61
62
|
function readUnfilteredSinks(isBuiltin) {
|
|
62
63
|
const stats = readJson(statsPath(), {});
|
|
63
64
|
return Object.entries(stats)
|
|
64
|
-
.filter(([cmd]) => !isBuiltin(cmd))
|
|
65
|
+
.filter(([cmd]) => !isBuiltin(cmd) && isLearnable(cmd))
|
|
65
66
|
.map(([cmd, s]) => ({
|
|
66
67
|
cmd,
|
|
67
68
|
calls: s.count,
|
package/src/learn.js
CHANGED
|
@@ -15,6 +15,7 @@ const fs = require('fs');
|
|
|
15
15
|
const path = require('path');
|
|
16
16
|
const os = require('os');
|
|
17
17
|
const { countTokensApprox } = require('./filters/utils');
|
|
18
|
+
const { splitCdPrefix } = require('./shell');
|
|
18
19
|
|
|
19
20
|
const MIN_CALLS = Number(process.env.LAKON_LEARN_MIN_CALLS) || 3;
|
|
20
21
|
const MIN_AVG_TOKENS = Number(process.env.LAKON_LEARN_MIN_TOKENS) || 300;
|
|
@@ -44,12 +45,44 @@ function writeJson(file, data) {
|
|
|
44
45
|
}
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
//
|
|
48
|
+
// A learnable command is a bare executable name. Paths, quoted fragments,
|
|
49
|
+
// flags and split-up arguments (`Support/…` from an unquoted
|
|
50
|
+
// `Application Support`, `-n`, `foo;`) were landing in learned.json.
|
|
51
|
+
const VALID_NAME = /^[A-Za-z0-9_][\w.+-]*$/;
|
|
52
|
+
|
|
53
|
+
// Never learned, even when they are loud:
|
|
54
|
+
// - shell builtins / keywords and lakonai itself — nothing to filter, or
|
|
55
|
+
// the output is already filtered;
|
|
56
|
+
// - agent tool names logged by the guards (Read, Grep, …);
|
|
57
|
+
// - interpreters and file mutators — a learned command is rewritten by the
|
|
58
|
+
// PreToolUse hook, which answers "allow", and `node -e …` or `rm` must
|
|
59
|
+
// keep going through the user's own permission rules.
|
|
60
|
+
const NEVER_LEARN = new Set([
|
|
61
|
+
'cd', 'echo', 'printf', 'export', 'source', 'set', 'unset', 'eval', 'exec', 'exit',
|
|
62
|
+
'command', 'builtin', 'type', 'which', 'alias', 'true', 'false', 'test',
|
|
63
|
+
'for', 'while', 'until', 'if', 'then', 'else', 'fi', 'do', 'done', 'case', 'esac',
|
|
64
|
+
'sleep', 'wait', 'read', 'pwd', 'time', 'lakonai',
|
|
65
|
+
'Read', 'Grep', 'Glob', 'Bash', 'Edit', 'Write',
|
|
66
|
+
'node', 'python', 'python3', 'ruby', 'perl', 'php', 'deno', 'bun',
|
|
67
|
+
'bash', 'sh', 'zsh', 'fish', 'osascript',
|
|
68
|
+
'rm', 'mv', 'cp', 'ln', 'chmod', 'chown', 'mkdir', 'rmdir', 'touch', 'kill', 'pkill',
|
|
69
|
+
'dd', 'tee', 'xargs', 'sudo', 'env',
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
function isLearnable(cmd) {
|
|
73
|
+
return typeof cmd === 'string' && VALID_NAME.test(cmd) && !NEVER_LEARN.has(cmd);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Base command of a shell string: skips `cd <dir> &&` prefixes, env
|
|
77
|
+
// assignments and sudo/env, and returns '' for anything that is not learnable.
|
|
48
78
|
function baseCommand(command) {
|
|
49
|
-
|
|
79
|
+
let s = String(command).trim();
|
|
80
|
+
for (let cd = splitCdPrefix(s); cd; cd = splitCdPrefix(s)) s = cd.rest;
|
|
81
|
+
const tokens = s.split(/\s+/);
|
|
50
82
|
let i = 0;
|
|
51
83
|
while (i < tokens.length && (/^\w+=/.test(tokens[i]) || tokens[i] === 'sudo' || tokens[i] === 'env')) i++;
|
|
52
|
-
|
|
84
|
+
const cmd = tokens[i] || '';
|
|
85
|
+
return isLearnable(cmd) ? cmd : '';
|
|
53
86
|
}
|
|
54
87
|
|
|
55
88
|
// Parse a Claude Code transcript (JSONL) into [{ cmd, tokens }] for every Bash
|
|
@@ -97,7 +130,7 @@ function promote(stats, isBuiltin) {
|
|
|
97
130
|
const learned = new Set(readJson(learnedPath(), []));
|
|
98
131
|
let changed = false;
|
|
99
132
|
for (const [cmd, s] of Object.entries(stats)) {
|
|
100
|
-
if (learned.has(cmd) || isBuiltin(cmd)) continue;
|
|
133
|
+
if (learned.has(cmd) || isBuiltin(cmd) || !isLearnable(cmd)) continue;
|
|
101
134
|
if (s.count >= MIN_CALLS && s.tokens / s.count >= MIN_AVG_TOKENS) {
|
|
102
135
|
learned.add(cmd);
|
|
103
136
|
changed = true;
|
|
@@ -154,7 +187,7 @@ function analyzeLog(isBuiltin) {
|
|
|
154
187
|
continue;
|
|
155
188
|
}
|
|
156
189
|
const cmd = e && typeof e.cmd === 'string' ? e.cmd : null;
|
|
157
|
-
if (!cmd || cmd === 'session' || isBuiltin(cmd)) continue;
|
|
190
|
+
if (!cmd || cmd === 'session' || isBuiltin(cmd) || !isLearnable(cmd)) continue;
|
|
158
191
|
const s = stats[cmd] || { count: 0, tokens: 0 };
|
|
159
192
|
s.count += 1;
|
|
160
193
|
s.tokens += e.raw || 0;
|
|
@@ -179,7 +212,12 @@ function maybeLearnFromLog(isBuiltin, now = Date.now()) {
|
|
|
179
212
|
|
|
180
213
|
let _learnedCache;
|
|
181
214
|
function learnedCommands() {
|
|
182
|
-
|
|
215
|
+
// Filter on read, so entries learned by older versions (paths, `node`)
|
|
216
|
+
// stop being rewritten without anyone editing learned.json by hand.
|
|
217
|
+
if (_learnedCache === undefined) {
|
|
218
|
+
const raw = readJson(learnedPath(), []);
|
|
219
|
+
_learnedCache = new Set(Array.isArray(raw) ? raw.filter(isLearnable) : []);
|
|
220
|
+
}
|
|
183
221
|
return _learnedCache;
|
|
184
222
|
}
|
|
185
223
|
function isLearned(cmd) {
|
|
@@ -192,6 +230,8 @@ function _resetCache() {
|
|
|
192
230
|
|
|
193
231
|
module.exports = {
|
|
194
232
|
baseCommand,
|
|
233
|
+
isLearnable,
|
|
234
|
+
NEVER_LEARN,
|
|
195
235
|
extractBashUsage,
|
|
196
236
|
promote,
|
|
197
237
|
analyzeTranscript,
|
package/src/shell.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// A deliberately small shell lexer. lakonai never executes or rewrites shell
|
|
4
|
+
// syntax it does not understand: these helpers only answer two questions about
|
|
5
|
+
// a command string — "which control operators appear at the top level (outside
|
|
6
|
+
// quotes)?" and "does it start with a `cd <dir> &&` prefix?". Anything the
|
|
7
|
+
// lexer cannot account for (an unbalanced quote) makes the caller back off.
|
|
8
|
+
|
|
9
|
+
// Operators reported at the top level of a command:
|
|
10
|
+
// '&&' '||' ';' '&' '\n' '|' — command separators / pipes
|
|
11
|
+
// '$(' '`' — command substitution (also inside "…")
|
|
12
|
+
// '>' '<' — a redirection that touches a file
|
|
13
|
+
// 'dup' — an fd duplication such as `2>&1`
|
|
14
|
+
// 'null' — a redirection to /dev/null
|
|
15
|
+
// Returns [{ op, i }] in source order, or null for an unbalanced quote.
|
|
16
|
+
function topLevelOps(s) {
|
|
17
|
+
const ops = [];
|
|
18
|
+
let i = 0;
|
|
19
|
+
let quote = null;
|
|
20
|
+
while (i < s.length) {
|
|
21
|
+
const c = s[i];
|
|
22
|
+
if (quote === "'") {
|
|
23
|
+
if (c === "'") quote = null;
|
|
24
|
+
i++;
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (quote === '"') {
|
|
28
|
+
if (c === '\\') {
|
|
29
|
+
i += 2;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (c === '"') quote = null;
|
|
33
|
+
else if (c === '`') ops.push({ op: '`', i });
|
|
34
|
+
else if (c === '$' && s[i + 1] === '(') ops.push({ op: '$(', i });
|
|
35
|
+
i++;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (c === '\\') {
|
|
39
|
+
i += 2;
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (c === "'" || c === '"') {
|
|
43
|
+
quote = c;
|
|
44
|
+
i++;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (c === '`') {
|
|
48
|
+
ops.push({ op: '`', i });
|
|
49
|
+
i++;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (c === '$' && s[i + 1] === '(') {
|
|
53
|
+
ops.push({ op: '$(', i });
|
|
54
|
+
i += 2;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (c === ';' || c === '\n') {
|
|
58
|
+
ops.push({ op: c, i });
|
|
59
|
+
i++;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (c === '&' || c === '|') {
|
|
63
|
+
if (s[i + 1] === c) {
|
|
64
|
+
ops.push({ op: c + c, i });
|
|
65
|
+
i += 2;
|
|
66
|
+
} else {
|
|
67
|
+
ops.push({ op: c, i });
|
|
68
|
+
i++;
|
|
69
|
+
}
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (c === '>') {
|
|
73
|
+
const rest = s.slice(i + 1);
|
|
74
|
+
const dup = /^&[0-9]/.exec(rest);
|
|
75
|
+
if (dup && /[0-9]/.test(s[i - 1] || '')) {
|
|
76
|
+
ops.push({ op: 'dup', i });
|
|
77
|
+
i += 1 + dup[0].length;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const devnull = /^\s*\/dev\/null(?=\s|$)/.exec(rest);
|
|
81
|
+
if (devnull) {
|
|
82
|
+
ops.push({ op: 'null', i });
|
|
83
|
+
i += 1 + devnull[0].length;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
ops.push({ op: '>', i });
|
|
87
|
+
i++;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (c === '<') {
|
|
91
|
+
ops.push({ op: '<', i });
|
|
92
|
+
i++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
i++;
|
|
96
|
+
}
|
|
97
|
+
return quote ? null : ops;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// True when `s` is exactly one shell word: no top-level whitespace, quotes
|
|
101
|
+
// balanced. `"my dir"` and `my\ dir` are one word; `a b` is two.
|
|
102
|
+
function isSingleWord(s) {
|
|
103
|
+
if (!s) return false;
|
|
104
|
+
let quote = null;
|
|
105
|
+
for (let i = 0; i < s.length; i++) {
|
|
106
|
+
const c = s[i];
|
|
107
|
+
if (quote) {
|
|
108
|
+
if (c === '\\' && quote === '"') i++;
|
|
109
|
+
else if (c === quote) quote = null;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (c === '\\') {
|
|
113
|
+
i++;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (c === "'" || c === '"') quote = c;
|
|
117
|
+
else if (/\s/.test(c)) return false;
|
|
118
|
+
}
|
|
119
|
+
return !quote;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Split a leading `cd <dir> && rest` / `cd <dir>; rest` into its parts. Agents
|
|
123
|
+
// prefix most commands this way, and a first-word match alone never sees the
|
|
124
|
+
// command that actually produces the output. Returns { dir, op, rest } or null
|
|
125
|
+
// when the command does not start with exactly that shape.
|
|
126
|
+
function splitCdPrefix(command) {
|
|
127
|
+
const s = String(command).trim();
|
|
128
|
+
const m = /^cd[ \t]+/.exec(s);
|
|
129
|
+
if (!m) return null;
|
|
130
|
+
const ops = topLevelOps(s);
|
|
131
|
+
if (!ops || !ops.length) return null;
|
|
132
|
+
const first = ops[0];
|
|
133
|
+
if (first.op !== '&&' && first.op !== ';') return null;
|
|
134
|
+
const dir = s.slice(m[0].length, first.i).trim();
|
|
135
|
+
if (!isSingleWord(dir)) return null;
|
|
136
|
+
const rest = s.slice(first.i + first.op.length).trim();
|
|
137
|
+
if (!rest) return null;
|
|
138
|
+
return { dir, op: first.op, rest };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = { topLevelOps, isSingleWord, splitCdPrefix };
|
package/src/tracking.js
CHANGED
|
@@ -17,6 +17,18 @@ function logPath() {
|
|
|
17
17
|
return path.join(dataDir(), 'log.jsonl');
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
// Which agent ran the command. Every agent spawns its shell with its own
|
|
21
|
+
// marker: Claude Code sets CLAUDECODE=1; Codex CLI sets CODEX_THREAD_ID /
|
|
22
|
+
// CODEX_TOOL_CALL_ID (CODEX_SANDBOX* under its sandbox); Gemini CLI sets
|
|
23
|
+
// GEMINI_CLI=1. LAKON_AGENT overrides, for agents with no marker.
|
|
24
|
+
function detectAgent(env = process.env) {
|
|
25
|
+
if (env.LAKON_AGENT) return String(env.LAKON_AGENT);
|
|
26
|
+
if (env.CLAUDECODE === '1') return 'claude';
|
|
27
|
+
if (env.CODEX_THREAD_ID || env.CODEX_TOOL_CALL_ID || env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED) return 'codex';
|
|
28
|
+
if (env.GEMINI_CLI === '1') return 'gemini';
|
|
29
|
+
return 'other';
|
|
30
|
+
}
|
|
31
|
+
|
|
20
32
|
function record({ cmd, args, rawTokens, filteredTokens }) {
|
|
21
33
|
if (process.env.LAKON_NO_TRACK === '1') return;
|
|
22
34
|
try {
|
|
@@ -28,6 +40,7 @@ function record({ cmd, args, rawTokens, filteredTokens }) {
|
|
|
28
40
|
raw: rawTokens,
|
|
29
41
|
out: filteredTokens,
|
|
30
42
|
saved: Math.max(0, rawTokens - filteredTokens),
|
|
43
|
+
agent: detectAgent(),
|
|
31
44
|
};
|
|
32
45
|
fs.appendFileSync(logPath(), JSON.stringify(entry) + '\n');
|
|
33
46
|
/* istanbul ignore next */
|
|
@@ -112,6 +125,22 @@ function responseStats(entries) {
|
|
|
112
125
|
};
|
|
113
126
|
}
|
|
114
127
|
|
|
128
|
+
// Savings per agent. Entries written before the agent field existed are
|
|
129
|
+
// grouped as 'unknown' rather than guessed.
|
|
130
|
+
function byAgent(entries) {
|
|
131
|
+
const map = new Map();
|
|
132
|
+
for (const e of entries) {
|
|
133
|
+
if (isSessionEntry(e)) continue;
|
|
134
|
+
const k = e.agent || 'unknown';
|
|
135
|
+
if (!map.has(k)) map.set(k, { agent: k, calls: 0, raw: 0, saved: 0 });
|
|
136
|
+
const acc = map.get(k);
|
|
137
|
+
acc.calls += 1;
|
|
138
|
+
acc.raw += e.raw || 0;
|
|
139
|
+
acc.saved += e.saved || 0;
|
|
140
|
+
}
|
|
141
|
+
return [...map.values()].sort((a, b) => b.saved - a.saved);
|
|
142
|
+
}
|
|
143
|
+
|
|
115
144
|
function pct(saved, raw) {
|
|
116
145
|
if (!raw) return 0;
|
|
117
146
|
return Math.round((saved / raw) * 100);
|
|
@@ -177,6 +206,12 @@ function report() {
|
|
|
177
206
|
);
|
|
178
207
|
}
|
|
179
208
|
|
|
209
|
+
const agents = byAgent(entries).filter((a) => a.agent !== 'unknown');
|
|
210
|
+
if (agents.length) {
|
|
211
|
+
lines.push('');
|
|
212
|
+
lines.push(' ' + dim('by agent: ') + agents.map((a) => `${a.agent} ${green(tok(a.saved))} ${dim(`(${pct(a.saved, a.raw)}%)`)}`).join(dim(' · ')));
|
|
213
|
+
}
|
|
214
|
+
|
|
180
215
|
const top = byCommand(entries).slice(0, 5);
|
|
181
216
|
if (top.length) {
|
|
182
217
|
lines.push('');
|
|
@@ -191,4 +226,4 @@ function reset() {
|
|
|
191
226
|
catch { return false; }
|
|
192
227
|
}
|
|
193
228
|
|
|
194
|
-
module.exports = { record, report, reset, readEntries, logPath, responseStats };
|
|
229
|
+
module.exports = { record, report, reset, readEntries, logPath, responseStats, detectAgent, byAgent };
|