lakonai 1.2.5 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,7 +20,7 @@
20
20
  <img src="https://img.shields.io/badge/node-%E2%89%A518-0F0F0F" alt="node ≥18" />
21
21
  <img src="https://img.shields.io/badge/deps-0-0F0F0F" alt="zero dependencies" />
22
22
  <img src="https://img.shields.io/badge/agents-6-0F0F0F" alt="6 AI agents" />
23
- <img src="https://img.shields.io/badge/tests-832-0F0F0F" alt="832 tests" />
23
+ <img src="https://img.shields.io/badge/tests-895-0F0F0F" alt="895 tests" />
24
24
  </p>
25
25
 
26
26
  <p align="center">
@@ -342,7 +342,7 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
342
342
 
343
343
  ## Test suite
344
344
 
345
- 832 tests across 54 suites — all passing, no mocks on I/O boundaries.
345
+ 895 tests across 58 suites — all passing, no mocks on I/O boundaries.
346
346
 
347
347
  | Type | Suites | Tests |
348
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
- process.stdout.write(' Claude talks to the API directly — no compression, nothing broken.\n');
492
- process.stdout.write(' Start it with `lakonai proxy start`.\n');
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.5",
3
+ "version": "1.2.7",
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 };
@@ -54,6 +54,16 @@ async function main() {
54
54
  const update = await checkForUpdate();
55
55
  if (update) parts.push(formatNotice(update));
56
56
 
57
+ // An upgrade leaves the old daemon running its old code; this is where a
58
+ // new session notices and replaces it.
59
+ if (!process.env.LAKON_NO_PROXY_REFRESH) {
60
+ try {
61
+ const { refreshStaleDaemon, formatRefreshNotice } = require('../proxy/refresh');
62
+ const notice = formatRefreshNotice(await refreshStaleDaemon());
63
+ if (notice) parts.push(notice);
64
+ } catch { /* best-effort */ }
65
+ }
66
+
57
67
  try {
58
68
  const learnReport = require('../learn-report');
59
69
  const summary = learnReport.maybeGetUnseen();
@@ -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({ type: 'command', command: hookCommand(dest) });
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: [{ type: 'command', command: hookCommand(dest) }],
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: [{ type: 'command', command: hookCommand(dest) }],
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 };
@@ -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 deferred - ${mcp.reason}; run \`lakonai mcp wrap\` after quitting Claude Code)`
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);
@@ -65,18 +65,126 @@ 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
- async function start({ allowRestart = true } = {}) {
169
+ async function start({ allowRestart = true, port: forcedPort = null } = {}) {
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
- await stop();
79
- return start({ allowRestart: false });
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
+ const held = current.port;
181
+ clearState();
182
+ // Carry the port across the clear. Sessions already running have that
183
+ // port baked into ANTHROPIC_BASE_URL for life, so the replacement has to
184
+ // land on it; re-reading preferredPort() here would find the state we
185
+ // just cleared and fall back to DEFAULT_PORT, stranding every one of them.
186
+ const next = await start({ allowRestart: false, port: held });
187
+ return { ...next, replaced: how };
80
188
  }
81
189
  // The env script is what the shell actually reads; an upgrade that adopts a
82
190
  // running daemon must still publish it, or the rc points at a missing file.
@@ -84,9 +192,13 @@ async function start({ allowRestart = true } = {}) {
84
192
  return { running: true, pid: current.pid, port: current.port, alreadyRunning: true };
85
193
  }
86
194
 
195
+ // Read the port BEFORE clearing: a session launched against the dead daemon
196
+ // has its ANTHROPIC_BASE_URL pinned to that port for its whole life, and it
197
+ // cannot be told to look elsewhere. Rebinding the same port is the only thing
198
+ // that brings those sessions back; clearing first would send us to the
199
+ // default and strand every one of them on ECONNREFUSED.
200
+ const port = forcedPort || preferredPort();
87
201
  clearState(); // drop stale pid/port so we don't read the dead daemon's values
88
-
89
- const port = preferredPort();
90
202
  const child = spawn(process.execPath, [serverScript], {
91
203
  detached: true,
92
204
  stdio: 'ignore',
@@ -224,10 +336,82 @@ async function unwire() {
224
336
  return { touched, stopped };
225
337
  }
226
338
 
339
+ // Read one environment variable out of another process. A process's env is
340
+ // fixed at exec time, so this reports what the process was actually launched
341
+ // with — not what the current shell would give it.
342
+ function processEnv(pid, key) {
343
+ // Linux: the kernel exposes it directly, NUL-separated. Exactly one of these
344
+ // two branches is dead on any given platform, so neither can be covered on
345
+ // both — the test suite exercises whichever one this machine actually uses.
346
+ /* istanbul ignore next -- platform branch */
347
+ try {
348
+ const raw = fs.readFileSync(`/proc/${pid}/environ`, 'utf8');
349
+ for (const kv of raw.split('\0')) {
350
+ if (kv.startsWith(`${key}=`)) return kv.slice(key.length + 1);
351
+ }
352
+ return null;
353
+ } catch { /* not Linux, or the process is gone */ }
354
+
355
+ // macOS: `ps e` appends the environment after the command line.
356
+ try {
357
+ const out = spawnSync('ps', ['eww', '-p', String(pid), '-o', 'command='], { encoding: 'utf8' });
358
+ if (out.error || typeof out.stdout !== 'string') return null;
359
+ const m = out.stdout.match(new RegExp(`(?:^|\\s)${key}=(\\S*)`));
360
+ return m ? m[1] : null;
361
+ } catch {
362
+ /* istanbul ignore next -- no ps: we simply cannot tell */
363
+ return null;
364
+ }
365
+ }
366
+
367
+ // Claude Code sessions pinned to a given local proxy port.
368
+ //
369
+ // A session reads ANTHROPIC_BASE_URL once, at launch, and keeps it for life.
370
+ // Nothing can re-point a process that is already running — not a hook, not a
371
+ // fresh env script, not a proxy that came back on a different port. So when the
372
+ // port they hold is dead, these sessions are not quietly falling back to direct
373
+ // API access: each retries a refused connection until the user quits it.
374
+ //
375
+ // The caller decides what the port's state means; this only answers "who is
376
+ // holding it". Best-effort by construction: an empty list means "none found",
377
+ // never a guarantee that none exist.
378
+ function sessionsOnPort(port) {
379
+ if (!port) return [];
380
+
381
+ let pids = [];
382
+ try {
383
+ const out = spawnSync('pgrep', ['-f', 'claude'], { encoding: 'utf8' });
384
+ if (typeof out.stdout !== 'string') return [];
385
+ pids = out.stdout.split('\n').map((l) => parseInt(l.trim(), 10)).filter(Boolean);
386
+ } catch {
387
+ /* istanbul ignore next -- no pgrep: we simply cannot tell */
388
+ return [];
389
+ }
390
+
391
+ const found = [];
392
+ for (const pid of pids) {
393
+ if (pid === process.pid) continue;
394
+ const url = processEnv(pid, 'ANTHROPIC_BASE_URL');
395
+ if (!url) continue;
396
+ // A remote gateway is the user's own routing decision, not ours to report.
397
+ const m = url.match(/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)\/?$/);
398
+ if (!m || Number(m[1]) !== Number(port)) continue;
399
+ found.push({ pid, port: Number(port), url });
400
+ }
401
+ return found;
402
+ }
403
+
227
404
  module.exports = {
228
405
  start,
406
+ sessionsOnPort,
407
+ processEnv,
229
408
  VERSION,
230
409
  ownsProxy,
410
+ retire,
411
+ reapRetired,
412
+ readRetired,
413
+ supportsRetire,
414
+ hasLiveConnections,
231
415
  stop,
232
416
  restart,
233
417
  status,
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ // Replacing a daemon left behind by an upgrade.
4
+ //
5
+ // `npm i -g lakonai` only swaps files on disk. The daemon already running keeps
6
+ // executing the `server.js` it was started with, so after an upgrade the CLI is
7
+ // new and the process serving every session is old code — the fix the user just
8
+ // installed is not the one answering their requests.
9
+ //
10
+ // `daemon.start()` already knows how to replace a version-mismatched daemon
11
+ // (retire the old one, rebind the same port). Nothing was calling it after an
12
+ // upgrade: npm runs no postinstall, and the only callers are `lakonai install`
13
+ // and `lakonai proxy start|restart`. This module is the missing trigger, run
14
+ // from the SessionStart hook — the moment a new session is about to depend on
15
+ // the proxy, and the cheapest place to notice the mismatch.
16
+
17
+ const daemon = require('./daemon');
18
+
19
+ const VERSION = require('../../package.json').version;
20
+
21
+ // Deps are injected so the unit tests can drive every branch without spawning
22
+ // a real daemon; production callers pass nothing.
23
+ async function refreshStaleDaemon({
24
+ status = daemon.status,
25
+ start = daemon.start,
26
+ version = VERSION,
27
+ } = {}) {
28
+ let current;
29
+ try {
30
+ current = await status();
31
+ } catch {
32
+ return null; // a status probe that throws is not a reason to fail a session
33
+ }
34
+
35
+ // Nothing running: starting one here is not this hook's job. A session that
36
+ // needs the proxy gets it from `lakonai install` / `lakonai proxy start`.
37
+ if (!current || !current.running) return null;
38
+
39
+ // Same comparison daemon.start() makes: an unstamped daemon (pre-1.2.3) is
40
+ // stale by definition, so `null !== version` correctly counts as a mismatch.
41
+ if (current.version === version) return null;
42
+
43
+ const from = current.version;
44
+ const fromPort = current.port;
45
+
46
+ let res;
47
+ try {
48
+ res = await start();
49
+ } catch (err) {
50
+ return { refreshed: false, from, to: version, error: err.message };
51
+ }
52
+
53
+ if (!res || !res.running) {
54
+ return { refreshed: false, from, to: version, error: (res && res.error) || 'the proxy did not come back up' };
55
+ }
56
+
57
+ return {
58
+ refreshed: true,
59
+ from,
60
+ to: version,
61
+ port: res.port,
62
+ // The old daemon held the port and was too old to hand it over, so the new
63
+ // one landed somewhere else. Sessions already pinned to `fromPort` keep
64
+ // talking to the old process until it goes idle and gets reaped.
65
+ movedPort: res.port !== fromPort ? fromPort : null,
66
+ replaced: res.replaced || null,
67
+ };
68
+ }
69
+
70
+ function formatRefreshNotice(result) {
71
+ if (!result) return null;
72
+
73
+ const from = result.from || 'an unstamped build';
74
+
75
+ if (!result.refreshed) {
76
+ return `lakonai proxy: the running daemon is still ${from} after the upgrade to ${result.to}, and restarting it failed (${result.error}).\nRun \`lakonai proxy restart\` to pick up the new code.`;
77
+ }
78
+
79
+ const lines = [`lakonai proxy: replaced the ${from} daemon left over by the upgrade — now serving ${result.to} on 127.0.0.1:${result.port}.`];
80
+ if (result.movedPort) {
81
+ lines.push(`The old daemon was too old to release port ${result.movedPort} and is still draining there; sessions pinned to it keep working and it is reaped once idle.`);
82
+ }
83
+ return lines.join('\n');
84
+ }
85
+
86
+ module.exports = { refreshStaleDaemon, formatRefreshNotice, VERSION };
@@ -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 */