lakonai 1.2.4 → 1.2.6
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 +5 -4
- package/bin/lakonai.js +24 -2
- package/package.json +1 -1
- package/src/hooks/session-end.js +50 -0
- package/src/install/claude-hook.js +70 -5
- package/src/install/pending.js +102 -0
- package/src/install/platforms.js +12 -2
- package/src/proxy/daemon.js +183 -4
- package/src/proxy/server.js +9 -0
- package/src/proxy/state.js +32 -15
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-875-0F0F0F" alt="875 tests" />
|
|
24
24
|
</p>
|
|
25
25
|
|
|
26
26
|
<p align="center">
|
|
@@ -175,8 +175,9 @@ accumulate in `~/.lakon/proxy-stats.json`.
|
|
|
175
175
|
`ANTHROPIC_BASE_URL` directly — it sources `~/.lakon/proxy-env.sh`, which checks
|
|
176
176
|
that the proxy is actually listening before pointing anything at it. Proxy down
|
|
177
177
|
(reboot, crash, `lakonai proxy stop`) means no compression, and Claude talks to
|
|
178
|
-
the API directly as if lakonai were not installed.
|
|
179
|
-
|
|
178
|
+
the API directly as if lakonai were not installed. It also clears a dead lakonai
|
|
179
|
+
URL it finds already in the environment, so a shell that inherited one from an
|
|
180
|
+
older install heals itself. A base URL you set yourself is never touched.
|
|
180
181
|
|
|
181
182
|
Manage it with `lakonai proxy`:
|
|
182
183
|
|
|
@@ -341,7 +342,7 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
|
|
|
341
342
|
|
|
342
343
|
## Test suite
|
|
343
344
|
|
|
344
|
-
|
|
345
|
+
875 tests across 57 suites — all passing, no mocks on I/O boundaries.
|
|
345
346
|
|
|
346
347
|
| Type | Suites | Tests |
|
|
347
348
|
|------|--------|-------|
|
package/bin/lakonai.js
CHANGED
|
@@ -488,8 +488,19 @@ async function runProxy(args) {
|
|
|
488
488
|
} else {
|
|
489
489
|
process.stdout.write('lakonai proxy: not running\n');
|
|
490
490
|
}
|
|
491
|
-
|
|
492
|
-
|
|
491
|
+
// "Nothing broken" is only true for sessions that start from here on. A
|
|
492
|
+
// session already pointed at the dead port cannot be re-pointed — it is
|
|
493
|
+
// stuck on ECONNREFUSED — so say so instead of reporting a clean fallback.
|
|
494
|
+
const stranded = daemon.sessionsOnPort(s.port);
|
|
495
|
+
if (stranded.length) {
|
|
496
|
+
const plural = stranded.length > 1 ? 's' : '';
|
|
497
|
+
process.stdout.write(` ${stranded.length} Claude session${plural} still pointed at it (pid ${stranded.map((x) => x.pid).join(', ')}) — those are failing with ConnectionRefused.\n`);
|
|
498
|
+
process.stdout.write(' `lakonai proxy start` rebinds the same port and recovers them.\n');
|
|
499
|
+
process.stdout.write(' New sessions are unaffected: they talk to the API directly.\n');
|
|
500
|
+
} else {
|
|
501
|
+
process.stdout.write(' Claude talks to the API directly — no compression, nothing broken.\n');
|
|
502
|
+
process.stdout.write(' Start it with `lakonai proxy start`.\n');
|
|
503
|
+
}
|
|
493
504
|
process.exitCode = 1;
|
|
494
505
|
return;
|
|
495
506
|
}
|
|
@@ -518,8 +529,19 @@ async function runProxy(args) {
|
|
|
518
529
|
process.exitCode = 1;
|
|
519
530
|
}
|
|
520
531
|
|
|
532
|
+
// Work queued while a Claude Code session was live (chiefly the MCP wrap) is
|
|
533
|
+
// applied here too, not only by the SessionEnd hook — a machine whose sessions
|
|
534
|
+
// never end cleanly would otherwise keep the task forever. Silent and
|
|
535
|
+
// best-effort: it must never delay or break the command the user actually ran.
|
|
536
|
+
/* istanbul ignore next -- opportunistic I/O; drain() itself is tested */
|
|
537
|
+
function drainPendingWork() {
|
|
538
|
+
if (process.env.CLAUDE_CODE_ENTRYPOINT || process.env.CLAUDE_PID) return;
|
|
539
|
+
try { require('../src/install/pending').drain(); } catch { /* best-effort */ }
|
|
540
|
+
}
|
|
541
|
+
|
|
521
542
|
async function main() {
|
|
522
543
|
const argv = process.argv.slice(2);
|
|
544
|
+
drainPendingWork();
|
|
523
545
|
if (!argv.length || argv[0] === '--help' || argv[0] === '-h') {
|
|
524
546
|
process.stdout.write(HELP);
|
|
525
547
|
return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lakonai",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.6",
|
|
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",
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// SessionEnd hook: the first moment it is safe to touch ~/.claude.json.
|
|
4
|
+
//
|
|
5
|
+
// `lakonai install` run from inside Claude Code cannot wrap MCP servers — that
|
|
6
|
+
// would rewrite the file the live session is still using, which is how people
|
|
7
|
+
// lost their sessions. It queues the work instead, and this hook drains the
|
|
8
|
+
// queue once the session is over, so the user never has to run anything.
|
|
9
|
+
//
|
|
10
|
+
// Registered with `async: true`: SessionEnd hooks share a 1.5s budget, which is
|
|
11
|
+
// not enough to do file work safely, and async hooks are not timed out.
|
|
12
|
+
|
|
13
|
+
const { homedir } = require('../install/paths');
|
|
14
|
+
|
|
15
|
+
/* istanbul ignore next -- I/O shell; drainPending is the tested part */
|
|
16
|
+
function readStdin() {
|
|
17
|
+
return new Promise((resolve) => {
|
|
18
|
+
let raw = '';
|
|
19
|
+
process.stdin.setEncoding('utf8');
|
|
20
|
+
process.stdin.on('data', (c) => { raw += c; });
|
|
21
|
+
process.stdin.on('end', () => resolve(raw));
|
|
22
|
+
// A hook must never hang the shutdown path waiting for input.
|
|
23
|
+
setTimeout(() => resolve(raw), 500).unref();
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// The session that triggered this hook is ending, but its process may still be
|
|
28
|
+
// flushing state. The pending tasks carry their own safety guards (mcp-wrap
|
|
29
|
+
// re-checks how recently ~/.claude.json was written), so a task that is still
|
|
30
|
+
// unsafe simply stays queued for the next session end.
|
|
31
|
+
function drainPending({ home = homedir() } = {}) {
|
|
32
|
+
try {
|
|
33
|
+
return require('../install/pending').drain(home);
|
|
34
|
+
} catch {
|
|
35
|
+
/* istanbul ignore next -- never let a hook break session shutdown */
|
|
36
|
+
return { done: [], kept: [] };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/* istanbul ignore next -- process entry point */
|
|
41
|
+
async function main() {
|
|
42
|
+
await readStdin();
|
|
43
|
+
drainPending();
|
|
44
|
+
process.exit(0);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/* istanbul ignore next */
|
|
48
|
+
if (require.main === module) main();
|
|
49
|
+
|
|
50
|
+
module.exports = { drainPending };
|
|
@@ -47,6 +47,17 @@ const HOOKS = [
|
|
|
47
47
|
event: 'SessionStart',
|
|
48
48
|
matcher: null,
|
|
49
49
|
},
|
|
50
|
+
{
|
|
51
|
+
// Drains work that could not be done while the session was live — chiefly
|
|
52
|
+
// the MCP wrap, which must not rewrite ~/.claude.json under a running
|
|
53
|
+
// session. Async because SessionEnd hooks share a 1.5s budget and async
|
|
54
|
+
// ones are not timed out.
|
|
55
|
+
basename: 'lakon-session-end.js',
|
|
56
|
+
src: path.join(__dirname, '..', 'hooks', 'session-end.js'),
|
|
57
|
+
event: 'SessionEnd',
|
|
58
|
+
matcher: null,
|
|
59
|
+
async: true,
|
|
60
|
+
},
|
|
50
61
|
];
|
|
51
62
|
|
|
52
63
|
const SUPPORT_FILES = [
|
|
@@ -99,6 +110,12 @@ function hookCommand(dest) {
|
|
|
99
110
|
return dest;
|
|
100
111
|
}
|
|
101
112
|
|
|
113
|
+
function hookEntry(hookDef, dest) {
|
|
114
|
+
const entry = { type: 'command', command: hookCommand(dest) };
|
|
115
|
+
if (hookDef.async) entry.async = true;
|
|
116
|
+
return entry;
|
|
117
|
+
}
|
|
118
|
+
|
|
102
119
|
function mergeHook(data, hookDef, dest) {
|
|
103
120
|
/* istanbul ignore next */
|
|
104
121
|
const eventKey = hookDef.event || 'PreToolUse';
|
|
@@ -111,12 +128,12 @@ function mergeHook(data, hookDef, dest) {
|
|
|
111
128
|
if (!entryHasHook(existing, hookDef.basename)) {
|
|
112
129
|
/* istanbul ignore next */
|
|
113
130
|
existing.hooks = existing.hooks || [];
|
|
114
|
-
existing.hooks.push(
|
|
131
|
+
existing.hooks.push(hookEntry(hookDef, dest));
|
|
115
132
|
}
|
|
116
133
|
} else {
|
|
117
134
|
data.hooks[eventKey].push({
|
|
118
135
|
matcher: hookDef.matcher,
|
|
119
|
-
hooks: [
|
|
136
|
+
hooks: [hookEntry(hookDef, dest)],
|
|
120
137
|
});
|
|
121
138
|
}
|
|
122
139
|
} else {
|
|
@@ -125,12 +142,58 @@ function mergeHook(data, hookDef, dest) {
|
|
|
125
142
|
);
|
|
126
143
|
if (!existing) {
|
|
127
144
|
data.hooks[eventKey].push({
|
|
128
|
-
hooks: [
|
|
145
|
+
hooks: [hookEntry(hookDef, dest)],
|
|
129
146
|
});
|
|
130
147
|
}
|
|
131
148
|
}
|
|
132
149
|
}
|
|
133
150
|
|
|
151
|
+
// Launchers this version does not ship are leftovers from an older lakonai: the
|
|
152
|
+
// file was removed from the package, but the generated launcher and its
|
|
153
|
+
// settings.json entry stayed behind and now crash on every event they are wired
|
|
154
|
+
// to. `install` owns the `lakon-` namespace, so it prunes them — nothing else
|
|
155
|
+
// will, and the user has no way to know which stale entry is failing.
|
|
156
|
+
function pruneOrphanHooks(home, data) {
|
|
157
|
+
const dir = path.join(claudeConfigDir(home), 'hooks');
|
|
158
|
+
const removed = [];
|
|
159
|
+
|
|
160
|
+
let entries = [];
|
|
161
|
+
try { entries = fs.readdirSync(dir); } catch { /* no hooks dir yet */ }
|
|
162
|
+
for (const f of entries) {
|
|
163
|
+
if (!f.startsWith('lakon-') || !f.endsWith('.js')) continue;
|
|
164
|
+
if (ALL_BASENAMES.includes(f)) continue;
|
|
165
|
+
try { fs.unlinkSync(path.join(dir, f)); removed.push(f); } catch { /* leave it */ }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Drop settings entries pointing at any lakon- launcher we no longer provide,
|
|
169
|
+
// whether or not its file was still on disk.
|
|
170
|
+
const isOrphan = (cmd) => {
|
|
171
|
+
if (typeof cmd !== 'string') return false;
|
|
172
|
+
const m = cmd.match(/lakon-[\w.-]+\.js/);
|
|
173
|
+
return Boolean(m) && !ALL_BASENAMES.includes(m[0]);
|
|
174
|
+
};
|
|
175
|
+
if (data && data.hooks && typeof data.hooks === 'object') {
|
|
176
|
+
for (const eventKey of Object.keys(data.hooks)) {
|
|
177
|
+
if (!Array.isArray(data.hooks[eventKey])) continue;
|
|
178
|
+
data.hooks[eventKey] = data.hooks[eventKey]
|
|
179
|
+
.map((entry) => {
|
|
180
|
+
if (!entry || !Array.isArray(entry.hooks)) return entry;
|
|
181
|
+
const keep = entry.hooks.filter((h) => {
|
|
182
|
+
if (!h || !isOrphan(h.command)) return true;
|
|
183
|
+
const m = h.command.match(/lakon-[\w.-]+\.js/);
|
|
184
|
+
if (m && !removed.includes(m[0])) removed.push(m[0]);
|
|
185
|
+
return false;
|
|
186
|
+
});
|
|
187
|
+
if (keep.length === 0) return null;
|
|
188
|
+
return { ...entry, hooks: keep };
|
|
189
|
+
})
|
|
190
|
+
.filter(Boolean);
|
|
191
|
+
if (data.hooks[eventKey].length === 0) delete data.hooks[eventKey];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return removed;
|
|
195
|
+
}
|
|
196
|
+
|
|
134
197
|
function installHook(home) {
|
|
135
198
|
const sp = settingsPath(home);
|
|
136
199
|
if (fs.existsSync(sp)) backupFile('claude-code', sp);
|
|
@@ -162,6 +225,8 @@ function installHook(home) {
|
|
|
162
225
|
installed.push(dest);
|
|
163
226
|
}
|
|
164
227
|
|
|
228
|
+
const pruned = pruneOrphanHooks(home, data);
|
|
229
|
+
|
|
165
230
|
writeSettings(home, data);
|
|
166
231
|
|
|
167
232
|
try {
|
|
@@ -172,7 +237,7 @@ function installHook(home) {
|
|
|
172
237
|
// never let marker write break install
|
|
173
238
|
}
|
|
174
239
|
|
|
175
|
-
return { hookFile: installed.join(', '), settingsMerged: true };
|
|
240
|
+
return { hookFile: installed.join(', '), settingsMerged: true, pruned };
|
|
176
241
|
}
|
|
177
242
|
|
|
178
243
|
function uninstallHook(home) {
|
|
@@ -207,4 +272,4 @@ function uninstallHook(home) {
|
|
|
207
272
|
}
|
|
208
273
|
}
|
|
209
274
|
|
|
210
|
-
module.exports = { installHook, uninstallHook, hookDest, HOOK_BASENAMES: ALL_BASENAMES };
|
|
275
|
+
module.exports = { installHook, uninstallHook, hookDest, pruneOrphanHooks, HOOK_BASENAMES: ALL_BASENAMES };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Work that could not be done safely when it was asked for, kept until a safe
|
|
4
|
+
// moment arrives.
|
|
5
|
+
//
|
|
6
|
+
// The case this exists for: wrapping MCP servers means writing ~/.claude.json,
|
|
7
|
+
// which is unsafe while a Claude Code session is live (it holds the session
|
|
8
|
+
// state that session is still writing). Refusing is correct — but leaving the
|
|
9
|
+
// user to remember a command is not. So `install` queues the task and lakonai
|
|
10
|
+
// drains it itself: on SessionEnd, and opportunistically at the start of any
|
|
11
|
+
// lakonai command that runs outside a session.
|
|
12
|
+
//
|
|
13
|
+
// Draining never forces and never blocks: a task that still cannot run stays
|
|
14
|
+
// queued.
|
|
15
|
+
|
|
16
|
+
const fs = require('fs');
|
|
17
|
+
const path = require('path');
|
|
18
|
+
const { homedir } = require('./paths');
|
|
19
|
+
|
|
20
|
+
const TASKS = {
|
|
21
|
+
// id -> { label, run(home) -> { done, reason } }
|
|
22
|
+
'mcp-wrap': {
|
|
23
|
+
label: 'wrap MCP servers for catalog compression',
|
|
24
|
+
run(home) {
|
|
25
|
+
const { wrapMcp } = require('./mcp');
|
|
26
|
+
const res = wrapMcp(home);
|
|
27
|
+
// `skipped` means the guard said not yet — keep it queued. A count of 0
|
|
28
|
+
// with no skip means there was nothing to do, which is also done.
|
|
29
|
+
return { done: !res.skipped, reason: res.reason };
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function lakonHome() {
|
|
35
|
+
return process.env.LAKON_HOME || path.join(homedir(), '.lakon');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function queuePath() {
|
|
39
|
+
return path.join(lakonHome(), 'pending.json');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function read() {
|
|
43
|
+
try {
|
|
44
|
+
const q = JSON.parse(fs.readFileSync(queuePath(), 'utf8'));
|
|
45
|
+
return Array.isArray(q.tasks) ? q.tasks.filter((t) => TASKS[t]) : [];
|
|
46
|
+
} catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function write(tasks) {
|
|
52
|
+
try {
|
|
53
|
+
fs.mkdirSync(lakonHome(), { recursive: true });
|
|
54
|
+
if (!tasks.length) {
|
|
55
|
+
try { fs.unlinkSync(queuePath()); } catch { /* already gone */ }
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
fs.writeFileSync(queuePath(), JSON.stringify({ tasks }));
|
|
59
|
+
return true;
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function enqueue(id) {
|
|
66
|
+
if (!TASKS[id]) return false;
|
|
67
|
+
const tasks = read();
|
|
68
|
+
if (tasks.includes(id)) return false;
|
|
69
|
+
tasks.push(id);
|
|
70
|
+
write(tasks);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function list() {
|
|
75
|
+
return read().map((id) => ({ id, label: TASKS[id].label }));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Try every queued task. Returns what ran and what stayed. Errors in a task are
|
|
79
|
+
// swallowed on purpose — a drain runs in the background and must never be the
|
|
80
|
+
// reason a command fails.
|
|
81
|
+
function drain(home = homedir()) {
|
|
82
|
+
const tasks = read();
|
|
83
|
+
if (!tasks.length) return { done: [], kept: [] };
|
|
84
|
+
|
|
85
|
+
const done = [];
|
|
86
|
+
const kept = [];
|
|
87
|
+
for (const id of tasks) {
|
|
88
|
+
let result;
|
|
89
|
+
try {
|
|
90
|
+
result = TASKS[id].run(home);
|
|
91
|
+
} catch {
|
|
92
|
+
/* istanbul ignore next -- a task that throws is kept for the next attempt */
|
|
93
|
+
result = { done: false, reason: 'task threw' };
|
|
94
|
+
}
|
|
95
|
+
if (result && result.done) done.push(id);
|
|
96
|
+
else kept.push(id);
|
|
97
|
+
}
|
|
98
|
+
write(kept);
|
|
99
|
+
return { done, kept };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = { enqueue, drain, list, queuePath, TASKS };
|
package/src/install/platforms.js
CHANGED
|
@@ -79,17 +79,27 @@ const PLATFORMS = [
|
|
|
79
79
|
const hookResult = installHook(home);
|
|
80
80
|
const cmds = installCommands(home);
|
|
81
81
|
const mcp = wrapMcp(home);
|
|
82
|
+
// Deferred, not dropped: the SessionEnd hook (or the next lakonai command
|
|
83
|
+
// run outside a session) applies it, so the user has nothing to remember.
|
|
84
|
+
/* istanbul ignore next */
|
|
85
|
+
if (mcp.skipped && mcp.reason && !mcp.reason.startsWith('LAKON_NO_MCP')) {
|
|
86
|
+
try { require('./pending').enqueue('mcp-wrap'); } catch { /* best-effort */ }
|
|
87
|
+
}
|
|
82
88
|
/* istanbul ignore next */
|
|
83
89
|
const suffixHook = hookResult.settingsMerged ? '+ PreToolUse hook' : `(hook: ${hookResult.note})`;
|
|
84
90
|
/* istanbul ignore next */
|
|
91
|
+
const suffixPruned = hookResult.pruned && hookResult.pruned.length
|
|
92
|
+
? `+ pruned ${hookResult.pruned.length} stale hook${hookResult.pruned.length > 1 ? 's' : ''}`
|
|
93
|
+
: '';
|
|
94
|
+
/* istanbul ignore next */
|
|
85
95
|
const suffixCmds = cmds.length ? `+ ${cmds.length} slash command${cmds.length > 1 ? 's' : ''}` : '';
|
|
86
96
|
// Never silent: writing ~/.claude.json under a live session can orphan it,
|
|
87
97
|
// so say that MCP compression was deferred and how to apply it later.
|
|
88
98
|
/* istanbul ignore next */
|
|
89
99
|
const suffixMcp = mcp.skipped && mcp.reason && !mcp.reason.startsWith('LAKON_NO_MCP')
|
|
90
|
-
? `(MCP compression
|
|
100
|
+
? `(MCP compression queued - ${mcp.reason}; applied automatically when the session ends)`
|
|
91
101
|
: '';
|
|
92
|
-
return [rulePath, suffixHook, suffixCmds, suffixMcp].filter(Boolean).join(' ');
|
|
102
|
+
return [rulePath, suffixHook, suffixPruned, suffixCmds, suffixMcp].filter(Boolean).join(' ');
|
|
93
103
|
},
|
|
94
104
|
uninstall: ({ home }) => {
|
|
95
105
|
uninstallHook(home);
|
package/src/proxy/daemon.js
CHANGED
|
@@ -65,18 +65,121 @@ async function status() {
|
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
// The release that taught the server to retire gracefully (SIGUSR2). Sending it
|
|
69
|
+
// to anything older would just kill the process — Node's default disposition for
|
|
70
|
+
// SIGUSR2 is to terminate — which is exactly what retirement exists to avoid.
|
|
71
|
+
const RETIRE_SINCE = [1, 2, 6];
|
|
72
|
+
|
|
73
|
+
function supportsRetire(version) {
|
|
74
|
+
if (!version) return false; // pre-1.2.3 daemons stamped nothing
|
|
75
|
+
const parts = String(version).split('.').map((n) => parseInt(n, 10));
|
|
76
|
+
if (parts.length < 3 || parts.some(Number.isNaN)) return false;
|
|
77
|
+
for (let i = 0; i < 3; i++) {
|
|
78
|
+
if (parts[i] > RETIRE_SINCE[i]) return true;
|
|
79
|
+
if (parts[i] < RETIRE_SINCE[i]) return false;
|
|
80
|
+
}
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Does anything still hold a connection to this port? Used before killing a
|
|
85
|
+
// daemon too old to retire on its own: a live connection means a session is
|
|
86
|
+
// mid-request, and killing it produces the ECONNREFUSED this whole subsystem
|
|
87
|
+
// exists to prevent. Unknown (no lsof) counts as "yes" — the cautious answer.
|
|
88
|
+
function hasLiveConnections(port) {
|
|
89
|
+
try {
|
|
90
|
+
const out = spawnSync('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:ESTABLISHED'], { encoding: 'utf8' });
|
|
91
|
+
if (out.error || typeof out.stdout !== 'string') return true;
|
|
92
|
+
return out.stdout.trim().split('\n').filter((l) => l && !l.startsWith('COMMAND')).length > 0;
|
|
93
|
+
} catch {
|
|
94
|
+
/* istanbul ignore next -- lsof missing: assume a connection rather than kill */
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Replace a daemon without dropping anyone's in-flight requests.
|
|
100
|
+
// 'exited' — retired gracefully and is already gone
|
|
101
|
+
// 'draining' — stopped listening, still serving open connections
|
|
102
|
+
// 'left-running' — too old to retire and still in use; reaped later
|
|
103
|
+
// 'stopped' — too old to retire, nothing connected, terminated
|
|
104
|
+
// 'gone' — was not running
|
|
105
|
+
async function retire(s) {
|
|
106
|
+
if (!s || !isRunning(s.pid)) return 'gone';
|
|
107
|
+
|
|
108
|
+
if (supportsRetire(s.version)) {
|
|
109
|
+
try { process.kill(s.pid, 'SIGUSR2'); } catch { return 'gone'; }
|
|
110
|
+
// It stops listening immediately, so the port frees up for the new daemon
|
|
111
|
+
// while the old connections finish on the old process.
|
|
112
|
+
await waitForPort(s.port, { timeoutMs: STOP_TIMEOUT_MS, want: false });
|
|
113
|
+
return isRunning(s.pid) ? 'draining' : 'exited';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (hasLiveConnections(s.port)) {
|
|
117
|
+
rememberRetired(s);
|
|
118
|
+
return 'left-running';
|
|
119
|
+
}
|
|
120
|
+
try { process.kill(s.pid, 'SIGTERM'); } catch { /* already gone */ }
|
|
121
|
+
await waitForPort(s.port, { timeoutMs: STOP_TIMEOUT_MS, want: false });
|
|
122
|
+
return 'stopped';
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Old daemons we could not stop safely, remembered so a later run can finish the
|
|
126
|
+
// job once they are idle.
|
|
127
|
+
function retiredFile() {
|
|
128
|
+
return path.join(state.lakonHome(), 'proxy-retired.json');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function rememberRetired(s) {
|
|
132
|
+
try {
|
|
133
|
+
const list = readRetired().filter((r) => r.pid !== s.pid);
|
|
134
|
+
list.push({ pid: s.pid, port: s.port });
|
|
135
|
+
fs.mkdirSync(state.lakonHome(), { recursive: true });
|
|
136
|
+
fs.writeFileSync(retiredFile(), JSON.stringify(list));
|
|
137
|
+
} catch { /* best-effort */ }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function readRetired() {
|
|
141
|
+
try {
|
|
142
|
+
const list = JSON.parse(fs.readFileSync(retiredFile(), 'utf8'));
|
|
143
|
+
return Array.isArray(list) ? list.filter((r) => r && r.pid && r.port) : [];
|
|
144
|
+
} catch {
|
|
145
|
+
return [];
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Kill off retired daemons that have finally gone idle. Cheap, silent, and run
|
|
150
|
+
// on every start so the leftovers do not accumulate.
|
|
151
|
+
function reapRetired() {
|
|
152
|
+
const reaped = [];
|
|
153
|
+
const kept = [];
|
|
154
|
+
for (const r of readRetired()) {
|
|
155
|
+
if (!isRunning(r.pid)) { reaped.push(r.pid); continue; }
|
|
156
|
+
if (hasLiveConnections(r.port)) { kept.push(r); continue; }
|
|
157
|
+
try { process.kill(r.pid, 'SIGTERM'); reaped.push(r.pid); } catch { /* gone */ }
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
if (kept.length) fs.writeFileSync(retiredFile(), JSON.stringify(kept));
|
|
161
|
+
else fs.unlinkSync(retiredFile());
|
|
162
|
+
} catch { /* best-effort */ }
|
|
163
|
+
return { reaped, kept: kept.map((r) => r.pid) };
|
|
164
|
+
}
|
|
165
|
+
|
|
68
166
|
// Start the daemon and wait until it actually serves. Returns
|
|
69
167
|
// `{running: false, error}` when it does not — callers must check before
|
|
70
168
|
// touching the user's shell rc.
|
|
71
169
|
async function start({ allowRestart = true } = {}) {
|
|
170
|
+
reapRetired();
|
|
72
171
|
const current = await status();
|
|
73
172
|
if (current.running) {
|
|
74
173
|
// A live daemon keeps executing the server.js it was started with, so after
|
|
75
174
|
// an upgrade the running process is stale code — and a pre-1.2.3 daemon is
|
|
76
175
|
// still the one that made the CLI fail. Replace it instead of adopting it.
|
|
77
176
|
if (allowRestart && current.version !== VERSION) {
|
|
78
|
-
|
|
79
|
-
|
|
177
|
+
// Retire, do not kill: an upgrade run from inside a Claude Code session
|
|
178
|
+
// would otherwise drop that session's own connection to the proxy.
|
|
179
|
+
const how = await retire({ pid: current.pid, port: current.port, version: current.version });
|
|
180
|
+
clearState();
|
|
181
|
+
const next = await start({ allowRestart: false });
|
|
182
|
+
return { ...next, replaced: how };
|
|
80
183
|
}
|
|
81
184
|
// The env script is what the shell actually reads; an upgrade that adopts a
|
|
82
185
|
// running daemon must still publish it, or the rc points at a missing file.
|
|
@@ -84,9 +187,13 @@ async function start({ allowRestart = true } = {}) {
|
|
|
84
187
|
return { running: true, pid: current.pid, port: current.port, alreadyRunning: true };
|
|
85
188
|
}
|
|
86
189
|
|
|
87
|
-
|
|
88
|
-
|
|
190
|
+
// Read the port BEFORE clearing: a session launched against the dead daemon
|
|
191
|
+
// has its ANTHROPIC_BASE_URL pinned to that port for its whole life, and it
|
|
192
|
+
// cannot be told to look elsewhere. Rebinding the same port is the only thing
|
|
193
|
+
// that brings those sessions back; clearing first would send us to the
|
|
194
|
+
// default and strand every one of them on ECONNREFUSED.
|
|
89
195
|
const port = preferredPort();
|
|
196
|
+
clearState(); // drop stale pid/port so we don't read the dead daemon's values
|
|
90
197
|
const child = spawn(process.execPath, [serverScript], {
|
|
91
198
|
detached: true,
|
|
92
199
|
stdio: 'ignore',
|
|
@@ -224,10 +331,82 @@ async function unwire() {
|
|
|
224
331
|
return { touched, stopped };
|
|
225
332
|
}
|
|
226
333
|
|
|
334
|
+
// Read one environment variable out of another process. A process's env is
|
|
335
|
+
// fixed at exec time, so this reports what the process was actually launched
|
|
336
|
+
// with — not what the current shell would give it.
|
|
337
|
+
function processEnv(pid, key) {
|
|
338
|
+
// Linux: the kernel exposes it directly, NUL-separated. Exactly one of these
|
|
339
|
+
// two branches is dead on any given platform, so neither can be covered on
|
|
340
|
+
// both — the test suite exercises whichever one this machine actually uses.
|
|
341
|
+
/* istanbul ignore next -- platform branch */
|
|
342
|
+
try {
|
|
343
|
+
const raw = fs.readFileSync(`/proc/${pid}/environ`, 'utf8');
|
|
344
|
+
for (const kv of raw.split('\0')) {
|
|
345
|
+
if (kv.startsWith(`${key}=`)) return kv.slice(key.length + 1);
|
|
346
|
+
}
|
|
347
|
+
return null;
|
|
348
|
+
} catch { /* not Linux, or the process is gone */ }
|
|
349
|
+
|
|
350
|
+
// macOS: `ps e` appends the environment after the command line.
|
|
351
|
+
try {
|
|
352
|
+
const out = spawnSync('ps', ['eww', '-p', String(pid), '-o', 'command='], { encoding: 'utf8' });
|
|
353
|
+
if (out.error || typeof out.stdout !== 'string') return null;
|
|
354
|
+
const m = out.stdout.match(new RegExp(`(?:^|\\s)${key}=(\\S*)`));
|
|
355
|
+
return m ? m[1] : null;
|
|
356
|
+
} catch {
|
|
357
|
+
/* istanbul ignore next -- no ps: we simply cannot tell */
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Claude Code sessions pinned to a given local proxy port.
|
|
363
|
+
//
|
|
364
|
+
// A session reads ANTHROPIC_BASE_URL once, at launch, and keeps it for life.
|
|
365
|
+
// Nothing can re-point a process that is already running — not a hook, not a
|
|
366
|
+
// fresh env script, not a proxy that came back on a different port. So when the
|
|
367
|
+
// port they hold is dead, these sessions are not quietly falling back to direct
|
|
368
|
+
// API access: each retries a refused connection until the user quits it.
|
|
369
|
+
//
|
|
370
|
+
// The caller decides what the port's state means; this only answers "who is
|
|
371
|
+
// holding it". Best-effort by construction: an empty list means "none found",
|
|
372
|
+
// never a guarantee that none exist.
|
|
373
|
+
function sessionsOnPort(port) {
|
|
374
|
+
if (!port) return [];
|
|
375
|
+
|
|
376
|
+
let pids = [];
|
|
377
|
+
try {
|
|
378
|
+
const out = spawnSync('pgrep', ['-f', 'claude'], { encoding: 'utf8' });
|
|
379
|
+
if (typeof out.stdout !== 'string') return [];
|
|
380
|
+
pids = out.stdout.split('\n').map((l) => parseInt(l.trim(), 10)).filter(Boolean);
|
|
381
|
+
} catch {
|
|
382
|
+
/* istanbul ignore next -- no pgrep: we simply cannot tell */
|
|
383
|
+
return [];
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const found = [];
|
|
387
|
+
for (const pid of pids) {
|
|
388
|
+
if (pid === process.pid) continue;
|
|
389
|
+
const url = processEnv(pid, 'ANTHROPIC_BASE_URL');
|
|
390
|
+
if (!url) continue;
|
|
391
|
+
// A remote gateway is the user's own routing decision, not ours to report.
|
|
392
|
+
const m = url.match(/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)\/?$/);
|
|
393
|
+
if (!m || Number(m[1]) !== Number(port)) continue;
|
|
394
|
+
found.push({ pid, port: Number(port), url });
|
|
395
|
+
}
|
|
396
|
+
return found;
|
|
397
|
+
}
|
|
398
|
+
|
|
227
399
|
module.exports = {
|
|
228
400
|
start,
|
|
401
|
+
sessionsOnPort,
|
|
402
|
+
processEnv,
|
|
229
403
|
VERSION,
|
|
230
404
|
ownsProxy,
|
|
405
|
+
retire,
|
|
406
|
+
reapRetired,
|
|
407
|
+
readRetired,
|
|
408
|
+
supportsRetire,
|
|
409
|
+
hasLiveConnections,
|
|
231
410
|
stop,
|
|
232
411
|
restart,
|
|
233
412
|
status,
|
package/src/proxy/server.js
CHANGED
|
@@ -148,6 +148,15 @@ async function main() {
|
|
|
148
148
|
};
|
|
149
149
|
process.on('SIGTERM', shutdown);
|
|
150
150
|
process.on('SIGINT', shutdown);
|
|
151
|
+
|
|
152
|
+
// Retirement: an upgrade replaces this process, but killing it would drop the
|
|
153
|
+
// API connections of whatever session is talking to it right now. On SIGUSR2
|
|
154
|
+
// we stop accepting (freeing the port for the new daemon immediately) and
|
|
155
|
+
// exit once the last existing connection closes.
|
|
156
|
+
process.on('SIGUSR2', () => {
|
|
157
|
+
process.stdout.write('lakonai proxy: retiring — draining open connections\n');
|
|
158
|
+
server.close(() => process.exit(0));
|
|
159
|
+
});
|
|
151
160
|
}
|
|
152
161
|
|
|
153
162
|
/* istanbul ignore next -- process entry point */
|
package/src/proxy/state.js
CHANGED
|
@@ -124,30 +124,47 @@ function envScript(port) {
|
|
|
124
124
|
return `# lakonai proxy — generated by lakonai, safe to delete.
|
|
125
125
|
# Points ANTHROPIC_BASE_URL at the local compression proxy, but only while it is
|
|
126
126
|
# actually listening. Proxy down = plain direct API access, never a broken CLI.
|
|
127
|
+
|
|
128
|
+
# Is something listening on 127.0.0.1:$1? Shell-native where possible.
|
|
129
|
+
__lakon_probe() {
|
|
130
|
+
if [ -n "$ZSH_VERSION" ] && zmodload zsh/net/tcp 2>/dev/null; then
|
|
131
|
+
if ztcp 127.0.0.1 "$1" 2>/dev/null; then ztcp -c "$REPLY" 2>/dev/null; return 0; fi
|
|
132
|
+
return 1
|
|
133
|
+
elif [ -n "$BASH_VERSION" ]; then
|
|
134
|
+
(exec 3<>/dev/tcp/127.0.0.1/"$1") 2>/dev/null && return 0
|
|
135
|
+
return 1
|
|
136
|
+
elif command -v nc >/dev/null 2>&1; then
|
|
137
|
+
nc -z -w 1 127.0.0.1 "$1" >/dev/null 2>&1 && return 0
|
|
138
|
+
return 1
|
|
139
|
+
fi
|
|
140
|
+
return 1
|
|
141
|
+
}
|
|
142
|
+
|
|
127
143
|
__lakon_port=${port}
|
|
128
|
-
__lakon_up=0
|
|
129
144
|
|
|
130
145
|
# Never clobber a base URL the user set for another endpoint — only take over
|
|
131
|
-
# when nothing is set, or when what is set is
|
|
146
|
+
# when nothing is set, or when what is set is a local proxy.
|
|
132
147
|
case "$ANTHROPIC_BASE_URL" in
|
|
133
148
|
""|http://127.0.0.1:*)
|
|
134
|
-
if
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
149
|
+
if __lakon_probe "$__lakon_port"; then
|
|
150
|
+
export ANTHROPIC_BASE_URL=http://127.0.0.1:$__lakon_port
|
|
151
|
+
else
|
|
152
|
+
# A dead lakonai URL inherited from the environment (ours, or the
|
|
153
|
+
# pre-1.2.3 port 7474) is what broke the CLI in the first place. If
|
|
154
|
+
# nothing answers there, drop it and let Claude talk to the API directly.
|
|
155
|
+
case "$ANTHROPIC_BASE_URL" in
|
|
156
|
+
http://127.0.0.1:$__lakon_port|http://127.0.0.1:7474)
|
|
157
|
+
__lakon_stale=\${ANTHROPIC_BASE_URL##*:}
|
|
158
|
+
__lakon_probe "$__lakon_stale" || unset ANTHROPIC_BASE_URL
|
|
159
|
+
unset __lakon_stale
|
|
160
|
+
;;
|
|
161
|
+
esac
|
|
143
162
|
fi
|
|
144
163
|
;;
|
|
145
164
|
esac
|
|
146
165
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
fi
|
|
150
|
-
unset __lakon_port __lakon_up
|
|
166
|
+
unset __lakon_port
|
|
167
|
+
unset -f __lakon_probe 2>/dev/null
|
|
151
168
|
`;
|
|
152
169
|
}
|
|
153
170
|
|