lakonai 1.2.2 → 1.2.4

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-751-0F0F0F" alt="751 tests" />
23
+ <img src="https://img.shields.io/badge/tests-831-0F0F0F" alt="831 tests" />
24
24
  </p>
25
25
 
26
26
  <p align="center">
@@ -89,7 +89,7 @@ All numbers from live projects using `lakonai@1.1.1`.
89
89
  | **Proxy** | Every API request carries raw bloat | Local HTTP proxy compresses request bodies before they reach Anthropic |
90
90
  | **Graph** | File reads load entire source files | AST knowledge graph: serves a compact subgraph instead of the raw file (-87%) |
91
91
  | **Pixel** | Skill files are verbose markdown | Converts skill bodies to PNG — vision tokens cheaper than text tokens |
92
- | **Context** | MCP catalogs + memory re-paid every turn | Auto-compresses MCP catalogs; `compress-memory` via local AI CLI |
92
+ | **Context** | MCP catalogs + memory re-paid every turn | Auto-compresses MCP catalogs (`lakonai mcp`); `compress-memory` via local AI CLI |
93
93
 
94
94
  Auto-learning runs underneath all of this: lakonai detects new heavy commands and enables a safe filter automatically, no config. ([full reference →](docs/reference.md))
95
95
 
@@ -157,7 +157,7 @@ Benchmark on the lakonai codebase itself (30 queries, 15 literal + 15 semantic):
157
157
 
158
158
  ### Layer 3 — Proxy compression (Claude Code)
159
159
 
160
- A local HTTP proxy on port 7474 sits between Claude Code and `api.anthropic.com`. It compresses request bodies before they're sent — the model sees fewer tokens, you pay less.
160
+ A local HTTP proxy sits between Claude Code and `api.anthropic.com`. It compresses request bodies before they're sent — the model sees fewer tokens, you pay less.
161
161
 
162
162
  ```
163
163
  build logs → -99% (repetitive lines collapsed)
@@ -167,7 +167,52 @@ diffs → -4% (conservative; context preserved)
167
167
  source code → 0% (covered by graph instead)
168
168
  ```
169
169
 
170
- The proxy starts automatically on `lakonai install` and runs silently. No API key exposed. Stats accumulate in `~/.lakon/proxy-stats.json`.
170
+ The proxy starts automatically on `lakonai install` and runs silently on port
171
+ `41474` (it moves to a free port if that one is taken). No API key exposed. Stats
172
+ accumulate in `~/.lakon/proxy-stats.json`.
173
+
174
+ **It can never break your CLI.** The shell rc does not export
175
+ `ANTHROPIC_BASE_URL` directly — it sources `~/.lakon/proxy-env.sh`, which checks
176
+ that the proxy is actually listening before pointing anything at it. Proxy down
177
+ (reboot, crash, `lakonai proxy stop`) means no compression, and Claude talks to
178
+ the API directly as if lakonai were not installed. A base URL you set yourself is
179
+ never overridden.
180
+
181
+ Manage it with `lakonai proxy`:
182
+
183
+ ```bash
184
+ lakonai proxy # status (exit 1 when it is not serving)
185
+ lakonai proxy start # start it and refresh the shell wiring
186
+ lakonai proxy stop # stop it and unwire the shell
187
+ lakonai proxy restart
188
+ ```
189
+
190
+ ### MCP catalog compression and your Claude Code sessions
191
+
192
+ Wrapping MCP servers means editing `~/.claude.json` — the same file where Claude
193
+ Code keeps per-project session state (`lastSessionId`, trust dialogs,
194
+ `allowedTools`) and rewrites on every turn. lakonai therefore **never touches it
195
+ while a session is live**: `lakonai install` run from inside Claude Code defers
196
+ the wrap and says so. Apply it afterwards:
197
+
198
+ ```bash
199
+ lakonai mcp # status: how many servers are wrapped
200
+ lakonai mcp wrap # wrap them (after quitting Claude Code)
201
+ lakonai mcp unwrap # undo
202
+ ```
203
+
204
+ Every write to that file is atomic (temp file + rename, never a truncate in
205
+ place) and validated first: if the rewrite would drop a project or change a
206
+ session id, it is refused. `LAKON_NO_MCP=1` opts out of MCP wrapping entirely.
207
+
208
+ Upgrading migrates an old install by itself: `lakonai upgrade` replaces a daemon
209
+ running a previous version (a running process keeps executing the server code it
210
+ was started with), moves it off port 7474, and rewrites the old
211
+ `export ANTHROPIC_BASE_URL` line in your rc into the guarded one.
212
+
213
+ `lakonai uninstall` stops the proxy and removes the wiring. Set
214
+ `LAKON_PROXY_DISABLE=1` to keep `lakonai install` from touching your shell at
215
+ all.
171
216
 
172
217
  ### Layer 4 — Pixel (Claude Code + Codex)
173
218
 
@@ -239,6 +284,8 @@ After `lakonai install`, these are available in Claude Code:
239
284
  | `lakonai peek [id]` | Read output parked in sandbox (`--grep/--offset/--limit`) |
240
285
  | `lakonai gain` | Token savings across all measured fronts |
241
286
  | `lakonai inspect <cmd>` | Debug what filter applies to a command |
287
+ | `lakonai mcp [wrap\|unwrap]` | MCP catalog compression status/lifecycle |
288
+ | `lakonai proxy [start\|stop\|restart]` | Compression proxy status/lifecycle |
242
289
  | `lakonai doctor` | Health check: CLI on PATH, hooks, rule |
243
290
 
244
291
  Full flags, filters, env vars, internals: **[docs/reference.md](docs/reference.md)**.
@@ -294,7 +341,7 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
294
341
 
295
342
  ## Test suite
296
343
 
297
- 751 tests across 48 suites — all passing, no mocks on I/O boundaries.
344
+ 831 tests across 54 suites — all passing, no mocks on I/O boundaries.
298
345
 
299
346
  | Type | Suites | Tests |
300
347
  |------|--------|-------|
package/bin/lakonai.js CHANGED
@@ -49,6 +49,15 @@ Usage:
49
49
  lakonai gain Show token savings - INPUT (shell output, measured)
50
50
  AND OUTPUT (how much terser the model writes; measured
51
51
  weekly via your local AI CLI, no API key)
52
+ lakonai mcp [cmd] MCP catalog compression: status (default) | wrap |
53
+ unwrap. Wrapping edits ~/.claude.json, where Claude
54
+ Code keeps per-project session state, so it is
55
+ skipped while a session is live - run it after
56
+ quitting Claude Code (--force overrides).
57
+ lakonai proxy [cmd] Compression proxy: status (default) | start | stop
58
+ | restart. The proxy shrinks API request bodies;
59
+ while it is down lakonai simply stays out of the way
60
+ and Claude talks to the API directly.
52
61
  lakonai doctor Per-platform health: CLI on PATH, rule, hooks
53
62
  lakonai version Print the installed lakonai version
54
63
  lakonai --help This help
@@ -423,6 +432,92 @@ function runPixel(args) {
423
432
  process.stdout.write(pixel.formatConvert(results));
424
433
  }
425
434
 
435
+ function runMcp(args) {
436
+ const mcp = require('../src/install/mcp');
437
+ const { homedir } = require('../src/install/paths');
438
+ const home = homedir();
439
+ const sub = args[0] || 'status';
440
+ const force = args.includes('--force');
441
+
442
+ if (sub === 'status') {
443
+ const st = mcp.statusMcp(home);
444
+ if (!st.exists) {
445
+ process.stdout.write(`lakonai mcp: no Claude Code config at ${st.config}\n`);
446
+ return;
447
+ }
448
+ process.stdout.write(`lakonai mcp: ${st.wrapped} wrapped, ${st.unwrapped} not wrapped (${st.config})\n`);
449
+ if (st.blockedBy) {
450
+ process.stdout.write(` wrapping is on hold — ${st.blockedBy}\n`);
451
+ process.stdout.write(' ~/.claude.json holds your session state; run `lakonai mcp wrap` after quitting Claude Code.\n');
452
+ }
453
+ return;
454
+ }
455
+
456
+ if (sub === 'wrap' || sub === 'unwrap') {
457
+ const res = sub === 'wrap' ? mcp.wrapMcp(home, { force }) : mcp.unwrapMcp(home, { force });
458
+ if (res.skipped) {
459
+ process.stdout.write(`lakonai mcp: skipped — ${res.reason}\n`);
460
+ process.stdout.write(' ~/.claude.json carries your Claude Code sessions; rewriting it now could orphan them.\n');
461
+ process.stdout.write(` Quit Claude Code and run \`lakonai mcp ${sub}\` again (or pass --force).\n`);
462
+ process.exitCode = 1;
463
+ return;
464
+ }
465
+ const verb = sub === 'wrap' ? 'wrapped' : 'unwrapped';
466
+ process.stdout.write(
467
+ res.count ? `lakonai mcp: ${verb} ${res.count} server${res.count > 1 ? 's' : ''}\n` : `lakonai mcp: nothing to ${sub}\n`
468
+ );
469
+ return;
470
+ }
471
+
472
+ process.stdout.write(`lakonai mcp: unknown subcommand "${sub}" (use status|wrap|unwrap)\n`);
473
+ process.exitCode = 1;
474
+ }
475
+
476
+ async function runProxy(args) {
477
+ const daemon = require('../src/proxy/daemon');
478
+ const sub = args[0] || 'status';
479
+
480
+ if (sub === 'status') {
481
+ const s = await daemon.status();
482
+ if (s.running) {
483
+ process.stdout.write(`lakonai proxy: running (pid ${s.pid}) on http://127.0.0.1:${s.port}\n`);
484
+ return;
485
+ }
486
+ if (s.stale) {
487
+ process.stdout.write(`lakonai proxy: NOT serving on 127.0.0.1:${s.port} (stale state${s.pid ? `, pid ${s.pid} alive but not listening` : ''})\n`);
488
+ } else {
489
+ process.stdout.write('lakonai proxy: not running\n');
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');
493
+ process.exitCode = 1;
494
+ return;
495
+ }
496
+
497
+ if (sub === 'start' || sub === 'restart') {
498
+ const res = sub === 'restart' ? await daemon.restart() : await daemon.start();
499
+ if (!res.running) {
500
+ process.stdout.write(`lakonai proxy: failed to start — ${res.error}\n`);
501
+ process.exitCode = 1;
502
+ return;
503
+ }
504
+ const verb = res.alreadyRunning ? 'already running' : 'started';
505
+ process.stdout.write(`lakonai proxy: ${verb} (pid ${res.pid}) on http://127.0.0.1:${res.port}\n`);
506
+ const touched = daemon.rcFiles().filter((rc) => daemon.installEnv(rc));
507
+ if (touched.length) process.stdout.write(` shell wiring refreshed in ${touched.join(', ')}\n`);
508
+ return;
509
+ }
510
+
511
+ if (sub === 'stop') {
512
+ const stopped = await daemon.stop();
513
+ process.stdout.write(stopped ? 'lakonai proxy: stopped\n' : 'lakonai proxy: was not running\n');
514
+ return;
515
+ }
516
+
517
+ process.stdout.write(`lakonai proxy: unknown subcommand "${sub}" (use status|start|stop|restart)\n`);
518
+ process.exitCode = 1;
519
+ }
520
+
426
521
  async function main() {
427
522
  const argv = process.argv.slice(2);
428
523
  if (!argv.length || argv[0] === '--help' || argv[0] === '-h') {
@@ -485,6 +580,14 @@ async function main() {
485
580
  await maybeOfferUpdate();
486
581
  return;
487
582
  }
583
+ if (first === 'mcp') {
584
+ runMcp(rest);
585
+ return;
586
+ }
587
+ if (first === 'proxy') {
588
+ await runProxy(rest);
589
+ return;
590
+ }
488
591
  if (first === 'doctor') {
489
592
  const doctor = require('../src/doctor');
490
593
  process.stdout.write(doctor.format(doctor.report()));
@@ -519,4 +622,4 @@ if (require.main === module) {
519
622
  });
520
623
  }
521
624
 
522
- module.exports = { runAndFilter, printVersion, main, HELP };
625
+ module.exports = { runAndFilter, printVersion, main, runProxy, runMcp, HELP };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
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",
@@ -24,7 +24,6 @@
24
24
  ],
25
25
  "license": "MIT",
26
26
  "author": "bargadev",
27
- "homepage": "https://bargadev.github.io/lakonai-site",
28
27
  "repository": {
29
28
  "type": "git",
30
29
  "url": "git+https://github.com/bargadev/lakonai.git"
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ // Atomic file writes.
4
+ //
5
+ // `fs.writeFileSync` truncates the target and then fills it, so a reader that
6
+ // looks in that window — or a crash mid-write — sees a half file. That is fine
7
+ // for a shim script and catastrophic for `~/.claude.json`, which is where Claude
8
+ // Code keeps per-project session state (`lastSessionId`, trust dialogs,
9
+ // `allowedTools`): a truncated parse makes it fall back to an empty config and
10
+ // the user loses their sessions.
11
+ //
12
+ // Writing a sibling temp file and renaming it over the target makes the swap
13
+ // atomic: a concurrent reader sees either the whole old file or the whole new
14
+ // one, never a partial write.
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ function writeFileAtomic(filePath, data, { encoding = 'utf8' } = {}) {
20
+ const dir = path.dirname(filePath);
21
+ const tmp = path.join(dir, `.${path.basename(filePath)}.lakonai-${process.pid}-${Date.now()}.tmp`);
22
+
23
+ // Keep the target's permissions — rename replaces the inode, so the temp
24
+ // file's mode is what survives.
25
+ let mode;
26
+ try { mode = fs.statSync(filePath).mode; } catch { /* new file: default mode */ }
27
+
28
+ let fd;
29
+ try {
30
+ fd = fs.openSync(tmp, 'w', mode);
31
+ fs.writeFileSync(fd, data, { encoding });
32
+ // Flush before the rename, so a crash cannot leave the renamed file empty.
33
+ fs.fsyncSync(fd);
34
+ fs.closeSync(fd);
35
+ fd = undefined;
36
+ fs.renameSync(tmp, filePath);
37
+ } catch (err) {
38
+ /* istanbul ignore next -- best-effort cleanup of a temp file we may not have opened */
39
+ if (fd !== undefined) { try { fs.closeSync(fd); } catch { /* ignore */ } }
40
+ try { fs.unlinkSync(tmp); } catch { /* never created */ }
41
+ throw err;
42
+ }
43
+ return filePath;
44
+ }
45
+
46
+ module.exports = { writeFileAtomic };
@@ -4,6 +4,7 @@ const fs = require('fs');
4
4
  const path = require('path');
5
5
  const { backupFile } = require('./backup');
6
6
  const { claudeConfigDir } = require('./paths');
7
+ const { writeFileAtomic } = require('./atomic');
7
8
 
8
9
  const HOOKS = [
9
10
  {
@@ -74,7 +75,9 @@ function readSettings(home) {
74
75
  }
75
76
 
76
77
  function writeSettings(home, data) {
77
- fs.writeFileSync(settingsPath(home), JSON.stringify(data, null, 2) + '\n', 'utf8');
78
+ // settings.json is read by a running Claude Code; a truncated read would drop
79
+ // the user's permissions and hooks.
80
+ writeFileAtomic(settingsPath(home), JSON.stringify(data, null, 2) + '\n');
78
81
  }
79
82
 
80
83
  function entryHasHook(entry, basename) {
@@ -82,12 +82,14 @@ async function install({ only, here = false, upgraded = false } = {}) {
82
82
  }
83
83
  }
84
84
 
85
- // Start proxy daemon and wire ANTHROPIC_BASE_URL into shell rc — silently.
86
- /* istanbul ignore next -- daemon I/O; tested via proxy-daemon.test.js */
85
+ // Start the compression proxy, and only touch the shell rc if it really came
86
+ // up. Wiring ANTHROPIC_BASE_URL to a daemon that failed to bind is what broke
87
+ // fresh installs with ECONNREFUSED on every later `claude` run.
88
+ /* istanbul ignore next -- daemon I/O; logic lives in wireProxy, tested directly */
87
89
  try {
88
- const daemon = require('../proxy/daemon');
89
- daemon.start();
90
- for (const rc of daemon.rcFiles()) daemon.installEnv(rc);
90
+ // LAKON_PROXY_DISABLE keeps the test suite (and anyone who wants lakonai
91
+ // without the proxy) from spawning daemons and editing shell rc files.
92
+ if (process.env.LAKON_PROXY_DISABLE !== '1') await wireProxy(require('../proxy/daemon'));
91
93
  } catch { /* best-effort; never block install */ }
92
94
 
93
95
  process.stdout.write('\n');
@@ -207,6 +209,20 @@ async function maybeOfferCompress({ cwd, home }) {
207
209
  }
208
210
  }
209
211
 
212
+ // Bring the proxy up and, only on success, point the shell rc at it. Returns
213
+ // what happened so the installer can say so out loud instead of failing silent.
214
+ async function wireProxy(daemon, { write = (t) => process.stdout.write(t) } = {}) {
215
+ const res = await daemon.start();
216
+ if (!res.running) {
217
+ write(`${FAIL} ${padLabel('compression proxy')} ${ARROW} not started (${res.error})\n`);
218
+ write(` ${' '.repeat(25)} Shell left untouched — Claude talks to the API directly.\n`);
219
+ return { started: false, touched: [] };
220
+ }
221
+ const touched = daemon.rcFiles().filter((rc) => daemon.installEnv(rc));
222
+ write(`${OK} ${padLabel('compression proxy')} ${ARROW} listening on 127.0.0.1:${res.port}\n`);
223
+ return { started: true, port: res.port, touched };
224
+ }
225
+
210
226
  async function uninstall() {
211
227
  const home = homedir();
212
228
  process.stdout.write('\nlakonai uninstall\n');
@@ -223,6 +239,19 @@ async function uninstall() {
223
239
  process.stdout.write(`${FAIL} ${padLabel(p.label)} ${ARROW} ${err.message}\n`);
224
240
  }
225
241
  }
242
+ // The proxy wiring lives in the shell rc, not in a platform file — strip it
243
+ // here too, otherwise uninstalling lakonai leaves ANTHROPIC_BASE_URL behind.
244
+ /* istanbul ignore next -- daemon I/O; unwire itself is tested in proxy-daemon.test.js */
245
+ try {
246
+ if (process.env.LAKON_PROXY_DISABLE === '1') throw new Error('proxy disabled');
247
+ const { touched, stopped } = await require('../proxy/daemon').unwire();
248
+ if (touched.length || stopped) {
249
+ process.stdout.write(`${OK} ${padLabel('compression proxy')} ${ARROW} ${stopped ? 'stopped' : 'not running'}`);
250
+ if (touched.length) process.stdout.write(`, unwired from ${touched.map(shortenPath).join(', ')}`);
251
+ process.stdout.write('\n');
252
+ any = true;
253
+ }
254
+ } catch { /* best-effort */ }
226
255
  if (!any) process.stdout.write(' (nothing installed)\n');
227
256
  }
228
257
 
@@ -279,4 +308,4 @@ function listPlatforms() {
279
308
  });
280
309
  }
281
310
 
282
- module.exports = { install, uninstall, revert, listPlatforms, backupsReport, pickMemoryTarget };
311
+ module.exports = { install, uninstall, revert, listPlatforms, backupsReport, pickMemoryTarget, wireProxy };
@@ -6,15 +6,71 @@
6
6
  // context (via `lakonai __mcp <original-cmd>`). Backed up first, fully reversible
7
7
  // on uninstall. Only stdio servers (a string `command`) are touched; url/sse
8
8
  // servers and tool-call results are never altered. Opt out with LAKON_NO_MCP=1.
9
+ //
10
+ // ~/.claude.json is NOT just MCP config — Claude Code keeps per-project session
11
+ // state there (`lastSessionId`, `lastSessionFirstPrompt`, `hasTrustDialogAccepted`,
12
+ // `allowedTools`) and rewrites it on every turn. A read-modify-write from here
13
+ // while a session is live silently discards whatever Claude Code wrote in
14
+ // between, which orphans the session (`claude --resume` no longer finds it).
15
+ // So this module: refuses to write while a session is active, writes atomically,
16
+ // and validates that no project survived the round trip missing.
9
17
 
10
18
  const fs = require('fs');
11
19
  const path = require('path');
12
20
  const { backupFile } = require('./backup');
21
+ const { writeFileAtomic } = require('./atomic');
22
+
23
+ // A session that wrote the config this recently is treated as live.
24
+ const RECENT_WRITE_MS = 30_000;
25
+
26
+ // Where we record the mtime of our own last write, so we do not mistake it for
27
+ // a Claude Code session and refuse the very next command.
28
+ function lastWritePath() {
29
+ const home = process.env.LAKON_HOME || path.join(require('./paths').homedir(), '.lakon');
30
+ return path.join(home, 'mcp-last-write.json');
31
+ }
32
+
33
+ function recordOwnWrite(configPath) {
34
+ try {
35
+ const { mtimeMs } = fs.statSync(configPath);
36
+ fs.mkdirSync(path.dirname(lastWritePath()), { recursive: true });
37
+ fs.writeFileSync(lastWritePath(), JSON.stringify({ mtimeMs }));
38
+ } catch { /* best-effort: the worst case is one over-cautious refusal */ }
39
+ }
40
+
41
+ function isOwnWrite(mtimeMs) {
42
+ try {
43
+ return JSON.parse(fs.readFileSync(lastWritePath(), 'utf8')).mtimeMs === mtimeMs;
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
13
48
 
14
49
  function mcpConfigPath(home) {
15
50
  return path.join(home, '.claude.json');
16
51
  }
17
52
 
53
+ // Why it is unsafe to write ~/.claude.json right now, or null when it is safe.
54
+ // The env check catches the common case by far: `lakonai install` typed inside a
55
+ // Claude Code session. The mtime check catches a session running in another
56
+ // terminal.
57
+ function activeSessionReason(home, { now = Date.now() } = {}) {
58
+ if (process.env.CLAUDE_CODE_ENTRYPOINT || process.env.CLAUDE_PID) {
59
+ return 'this shell is inside a running Claude Code session';
60
+ }
61
+ try {
62
+ // A file timestamp can land a hair AHEAD of Date.now() (clock/fs
63
+ // granularity), so a negative age means "just written", not "stale" — and
64
+ // erring toward "a session is live" is the safe direction anyway.
65
+ const { mtimeMs } = fs.statSync(mcpConfigPath(home));
66
+ const age = now - mtimeMs;
67
+ if (age < RECENT_WRITE_MS && !isOwnWrite(mtimeMs)) {
68
+ return `a Claude Code session wrote ~/.claude.json ${Math.round(Math.max(age, 0) / 1000)}s ago`;
69
+ }
70
+ } catch { /* no config yet: nothing can be racing us */ }
71
+ return null;
72
+ }
73
+
18
74
  // Collect every `mcpServers` map anywhere in the config (top-level + per-project).
19
75
  function collectServerMaps(obj, out) {
20
76
  if (!obj || typeof obj !== 'object') return out;
@@ -60,28 +116,106 @@ function unwrapServers(config) {
60
116
  return n;
61
117
  }
62
118
 
63
- function applyToConfig(home, transform) {
64
- if (process.env.LAKON_NO_MCP === '1') return 0;
119
+ // Last line of defence before the rename: the bytes we are about to write must
120
+ // parse, and must still carry every project (with its session pointers) and
121
+ // every top-level key the file had. Anything less means a bug here would be
122
+ // destroying the user's Claude Code state.
123
+ function preservesState(before, serialized) {
124
+ let after;
125
+ try { after = JSON.parse(serialized); } catch { return false; }
126
+
127
+ for (const k of Object.keys(before)) {
128
+ if (!(k in after)) return false;
129
+ }
130
+ const oldProjects = before.projects && typeof before.projects === 'object' ? before.projects : null;
131
+ if (oldProjects) {
132
+ const newProjects = after.projects;
133
+ if (!newProjects || typeof newProjects !== 'object') return false;
134
+ for (const p of Object.keys(oldProjects)) {
135
+ if (!(p in newProjects)) return false;
136
+ if (oldProjects[p] && oldProjects[p].lastSessionId && newProjects[p].lastSessionId !== oldProjects[p].lastSessionId) {
137
+ return false;
138
+ }
139
+ }
140
+ }
141
+ return true;
142
+ }
143
+
144
+ // Returns { count, skipped, reason }. `count` is how many servers changed;
145
+ // `skipped` says the config was deliberately left alone.
146
+ function applyToConfig(home, transform, { force = false } = {}) {
147
+ if (process.env.LAKON_NO_MCP === '1') return { count: 0, skipped: true, reason: 'LAKON_NO_MCP=1' };
148
+
65
149
  const p = mcpConfigPath(home);
150
+ if (!force) {
151
+ const reason = activeSessionReason(home);
152
+ if (reason) return { count: 0, skipped: true, reason };
153
+ }
154
+
155
+ // Back up before reading, so the copy on disk is never newer than what we read.
156
+ backupFile('claude-code-mcp', p);
157
+
158
+ let raw;
66
159
  let config;
67
160
  try {
68
- config = JSON.parse(fs.readFileSync(p, 'utf8'));
161
+ raw = fs.readFileSync(p, 'utf8');
162
+ config = JSON.parse(raw);
69
163
  } catch {
70
- return 0; // no config / unreadable -> nothing to do
164
+ return { count: 0, skipped: false, reason: null }; // no config / unreadable -> nothing to do
71
165
  }
166
+
167
+ // Read → transform → write with nothing slow in between: every millisecond
168
+ // here is a millisecond of Claude Code writes we would clobber.
169
+ const before = JSON.parse(raw);
72
170
  const n = transform(config);
73
- if (n > 0) {
74
- backupFile('claude-code-mcp', p);
75
- fs.writeFileSync(p, JSON.stringify(config, null, 2) + '\n', 'utf8');
171
+ if (n === 0) return { count: 0, skipped: false, reason: null };
172
+
173
+ const serialized = JSON.stringify(config, null, 2) + '\n';
174
+ if (!preservesState(before, serialized)) {
175
+ return { count: 0, skipped: true, reason: 'refused: the rewrite would have dropped Claude Code state' };
76
176
  }
77
- return n;
177
+
178
+ writeFileAtomic(p, serialized);
179
+ recordOwnWrite(p);
180
+ return { count: n, skipped: false, reason: null };
78
181
  }
79
182
 
80
- function wrapMcp(home) {
81
- return applyToConfig(home, wrapServers);
183
+ function wrapMcp(home, opts) {
184
+ return applyToConfig(home, wrapServers, opts);
82
185
  }
83
- function unwrapMcp(home) {
84
- return applyToConfig(home, unwrapServers);
186
+ function unwrapMcp(home, opts) {
187
+ return applyToConfig(home, unwrapServers, opts);
188
+ }
189
+
190
+ // How many servers are currently wrapped / wrappable — for `lakonai mcp status`.
191
+ function statusMcp(home) {
192
+ const p = mcpConfigPath(home);
193
+ let config;
194
+ try { config = JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return { config: p, exists: false, wrapped: 0, unwrapped: 0 }; }
195
+ let wrapped = 0;
196
+ let unwrapped = 0;
197
+ for (const map of collectServerMaps(config, [])) {
198
+ for (const name of Object.keys(map)) {
199
+ const s = map[name];
200
+ if (!s || typeof s !== 'object') continue;
201
+ if (s._lakonai) wrapped++;
202
+ else if (typeof s.command === 'string') unwrapped++;
203
+ }
204
+ }
205
+ return { config: p, exists: true, wrapped, unwrapped, blockedBy: activeSessionReason(home) };
85
206
  }
86
207
 
87
- module.exports = { wrapMcp, unwrapMcp, wrapServers, unwrapServers, collectServerMaps, mcpConfigPath };
208
+ module.exports = {
209
+ applyToConfig,
210
+ wrapMcp,
211
+ unwrapMcp,
212
+ statusMcp,
213
+ wrapServers,
214
+ unwrapServers,
215
+ collectServerMaps,
216
+ mcpConfigPath,
217
+ activeSessionReason,
218
+ preservesState,
219
+ isOwnWrite,
220
+ recordOwnWrite,
221
+ };
@@ -6,6 +6,7 @@ const { backupFile, restoreAllBackups } = require('./backup');
6
6
  const { installHook, uninstallHook } = require('./claude-hook');
7
7
  const { installCommands, uninstallCommands } = require('./claude-commands');
8
8
  const { wrapMcp, unwrapMcp } = require('./mcp');
9
+ const { writeFileAtomic } = require('./atomic');
9
10
  const { claudeConfigDir } = require('./paths');
10
11
 
11
12
  const MARK_BEGIN = '<!-- lakonai:begin -->';
@@ -46,7 +47,7 @@ function upsertBlock(platformId, filePath, rule) {
46
47
  const block = wrap(rule);
47
48
  const re = new RegExp(`${ANY_BEGIN}[\\s\\S]*?${ANY_END}\\n?`);
48
49
  const next = re.test(existing) ? existing.replace(re, block) : (existing ? `${existing.trim()}\n\n${block}` : block);
49
- fs.writeFileSync(filePath, next, 'utf8');
50
+ writeFileAtomic(filePath, next);
50
51
  return filePath;
51
52
  }
52
53
 
@@ -56,7 +57,7 @@ function stripBlock(filePath) {
56
57
  const re = new RegExp(`\\n*${ANY_BEGIN}[\\s\\S]*?${ANY_END}\\n?`);
57
58
  if (!re.test(existing)) return null;
58
59
  const next = existing.replace(re, '').trim();
59
- if (next) fs.writeFileSync(filePath, next + '\n', 'utf8');
60
+ if (next) writeFileAtomic(filePath, next + '\n');
60
61
  else fs.unlinkSync(filePath);
61
62
  return filePath;
62
63
  }
@@ -77,12 +78,18 @@ const PLATFORMS = [
77
78
  const rulePath = upsertBlock(id, path.join(claudeConfigDir(home), 'CLAUDE.md'), rule);
78
79
  const hookResult = installHook(home);
79
80
  const cmds = installCommands(home);
80
- wrapMcp(home);
81
+ const mcp = wrapMcp(home);
81
82
  /* istanbul ignore next */
82
83
  const suffixHook = hookResult.settingsMerged ? '+ PreToolUse hook' : `(hook: ${hookResult.note})`;
83
84
  /* istanbul ignore next */
84
85
  const suffixCmds = cmds.length ? `+ ${cmds.length} slash command${cmds.length > 1 ? 's' : ''}` : '';
85
- return [rulePath, suffixHook, suffixCmds].filter(Boolean).join(' ');
86
+ // Never silent: writing ~/.claude.json under a live session can orphan it,
87
+ // so say that MCP compression was deferred and how to apply it later.
88
+ /* istanbul ignore next */
89
+ 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)`
91
+ : '';
92
+ return [rulePath, suffixHook, suffixCmds, suffixMcp].filter(Boolean).join(' ');
86
93
  },
87
94
  uninstall: ({ home }) => {
88
95
  uninstallHook(home);
@@ -1,81 +1,194 @@
1
1
  'use strict';
2
2
 
3
- const { spawnSync, spawn } = require('child_process');
3
+ // Supervisor for the local compression proxy.
4
+ //
5
+ // The contract every function here keeps: never report the proxy as up unless a
6
+ // TCP connect to its port succeeded. The original version returned
7
+ // `{running: true}` straight after `spawn()` and the installer trusted it, so a
8
+ // daemon that died on EADDRINUSE still got ANTHROPIC_BASE_URL written into three
9
+ // shell rc files — every later `claude` failed with ECONNREFUSED and nothing
10
+ // pointed at lakonai as the cause.
11
+
12
+ const { spawn, spawnSync } = require('child_process');
4
13
  const fs = require('fs');
5
14
  const path = require('path');
6
- const os = require('os');
7
15
 
8
- const PORT = Number(process.env.LAKON_PROXY_PORT) || 7474;
16
+ const state = require('./state');
17
+ const { homedir } = require('../install/paths');
9
18
 
10
- function lakonHome() {
11
- return process.env.LAKON_HOME || path.join(os.homedir(), '.lakon');
12
- }
19
+ const {
20
+ DEFAULT_PORT,
21
+ MARKER,
22
+ probePort,
23
+ waitForPort,
24
+ isRunning,
25
+ readState,
26
+ clearState,
27
+ envFile,
28
+ writeEnvScript,
29
+ removeEnvScript,
30
+ } = state;
31
+
32
+ const VERSION = require('../../package.json').version;
33
+
34
+ const START_TIMEOUT_MS = Number(process.env.LAKON_PROXY_START_TIMEOUT) || 6000;
35
+ const STOP_TIMEOUT_MS = 3000;
13
36
 
14
- const pidFile = () => path.join(lakonHome(), 'proxy.pid');
15
37
  const serverScript = path.join(__dirname, 'server.js');
16
38
 
17
- function readPid() {
18
- try { return Number(fs.readFileSync(pidFile(), 'utf8').trim()); } catch { return null; }
39
+ // Port to ask for: an explicit override, else whatever we bound last time, else
40
+ // the default. The server falls back to an OS-assigned port if it is taken.
41
+ function preferredPort() {
42
+ const forced = Number(process.env.LAKON_PROXY_PORT);
43
+ if (forced) return forced;
44
+ const s = readState();
45
+ return (s && s.port) || DEFAULT_PORT;
19
46
  }
20
47
 
21
- function isRunning(pid) {
22
- if (!pid) return false;
23
- try { process.kill(pid, 0); return true; } catch { return false; }
48
+ // Real health, not a PID guess: the process must be alive AND its port must
49
+ // answer. Either half missing means the state on disk is stale.
50
+ async function status() {
51
+ const s = readState();
52
+ if (!s) return { running: false, pid: null, port: preferredPort(), listening: false, stale: false, version: null };
53
+
54
+ const alive = isRunning(s.pid);
55
+ const listening = await probePort(s.port);
56
+ return {
57
+ running: alive && listening,
58
+ pid: alive ? s.pid : null,
59
+ port: s.port,
60
+ listening,
61
+ stale: !(alive && listening),
62
+ legacy: Boolean(s.legacy),
63
+ // null for a pre-1.2.3 daemon: it never stamped one.
64
+ version: s.version || null,
65
+ };
24
66
  }
25
67
 
26
- function status() {
27
- const pid = readPid();
28
- if (isRunning(pid)) return { running: true, pid, port: PORT };
29
- return { running: false, pid: null, port: PORT };
30
- }
68
+ // Start the daemon and wait until it actually serves. Returns
69
+ // `{running: false, error}` when it does not — callers must check before
70
+ // touching the user's shell rc.
71
+ async function start({ allowRestart = true } = {}) {
72
+ const current = await status();
73
+ if (current.running) {
74
+ // A live daemon keeps executing the server.js it was started with, so after
75
+ // an upgrade the running process is stale code — and a pre-1.2.3 daemon is
76
+ // still the one that made the CLI fail. Replace it instead of adopting it.
77
+ if (allowRestart && current.version !== VERSION) {
78
+ await stop();
79
+ return start({ allowRestart: false });
80
+ }
81
+ // The env script is what the shell actually reads; an upgrade that adopts a
82
+ // running daemon must still publish it, or the rc points at a missing file.
83
+ writeEnvScript(current.port);
84
+ return { running: true, pid: current.pid, port: current.port, alreadyRunning: true };
85
+ }
31
86
 
32
- function start() {
33
- const s = status();
34
- if (s.running) return s;
87
+ clearState(); // drop stale pid/port so we don't read the dead daemon's values
35
88
 
89
+ const port = preferredPort();
36
90
  const child = spawn(process.execPath, [serverScript], {
37
91
  detached: true,
38
92
  stdio: 'ignore',
39
- env: { ...process.env, LAKON_PROXY_PORT: String(PORT) },
93
+ env: { ...process.env, LAKON_PROXY_PORT: String(port) },
40
94
  });
95
+
96
+ let spawnError = null;
97
+ child.on('error', (err) => { spawnError = err; });
41
98
  child.unref();
42
99
 
43
- // Write PID
44
- try {
45
- fs.mkdirSync(lakonHome(), { recursive: true });
46
- fs.writeFileSync(pidFile(), String(child.pid));
47
- } catch { /* best-effort */ }
100
+ // The server publishes its state only once it is bound, so poll for that,
101
+ // then confirm with a connect.
102
+ const deadline = Date.now() + START_TIMEOUT_MS;
103
+ for (;;) {
104
+ if (spawnError) {
105
+ return { running: false, pid: null, port, error: `could not spawn the proxy: ${spawnError.message}` };
106
+ }
107
+ const s = readState();
108
+ if (s && (await probePort(s.port))) {
109
+ writeEnvScript(s.port);
110
+ return { running: true, pid: s.pid, port: s.port };
111
+ }
112
+ if (Date.now() >= deadline) break;
113
+ await state.sleep(100);
114
+ }
48
115
 
49
- return { running: true, pid: child.pid, port: PORT };
116
+ // Never leave a half-started child behind holding the port.
117
+ try { process.kill(child.pid, 'SIGTERM'); } catch { /* already gone */ }
118
+ clearState();
119
+ return {
120
+ running: false,
121
+ pid: null,
122
+ port,
123
+ error: `the proxy did not come up on 127.0.0.1:${port} within ${START_TIMEOUT_MS}ms`,
124
+ };
50
125
  }
51
126
 
52
- function stop() {
53
- const pid = readPid();
54
- if (!isRunning(pid)) {
55
- try { fs.unlinkSync(pidFile()); } catch { /* ok */ }
127
+ // Is this pid really our proxy? PIDs get recycled, and the state file is just a
128
+ // file — signalling whatever pid it happens to name could kill an unrelated
129
+ // process. A pid only counts as ours if it serves the port, or if its command
130
+ // line is the proxy server.
131
+ function ownsProxy(pid, port, { listening }) {
132
+ if (listening) return true;
133
+ try {
134
+ // status === 0 already implies ps ran and stdout is a string.
135
+ const out = spawnSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' });
136
+ return out.status === 0 && /proxy[/\\]server\.js/.test(out.stdout);
137
+ } catch {
138
+ /* istanbul ignore next -- ps missing: refuse to signal rather than guess */
139
+ return false;
140
+ }
141
+ }
142
+
143
+ // Stop the daemon and wait for the port to be released, so a restart cannot
144
+ // race the old socket.
145
+ async function stop() {
146
+ const s = readState();
147
+ const alive = s && isRunning(s.pid);
148
+ const listening = s ? await probePort(s.port) : false;
149
+ if (!alive || !ownsProxy(s.pid, s.port, { listening })) {
150
+ clearState();
151
+ removeEnvScript();
56
152
  return false;
57
153
  }
58
154
  try {
59
- process.kill(pid, 'SIGTERM');
60
- fs.unlinkSync(pidFile());
61
- return true;
155
+ process.kill(s.pid, 'SIGTERM');
62
156
  } catch {
157
+ /* istanbul ignore next -- lost the race with an exiting daemon */
63
158
  return false;
64
159
  }
160
+ await waitForPort(s.port, { timeoutMs: STOP_TIMEOUT_MS, want: false });
161
+ clearState();
162
+ removeEnvScript();
163
+ return true;
65
164
  }
66
165
 
67
- // Shell rc line to set ANTHROPIC_BASE_URL when proxy is active.
68
- function envLine() {
69
- return `export ANTHROPIC_BASE_URL=http://127.0.0.1:${PORT} # lakonai proxy`;
166
+ async function restart() {
167
+ await stop();
168
+ return start();
70
169
  }
71
170
 
72
- const LAKONAI_PROXY_MARKER = '# lakonai proxy';
171
+ // ── shell rc wiring ─────────────────────────────────────────────────────────
73
172
 
173
+ // The rc sources the generated script instead of exporting the URL directly —
174
+ // that script re-checks the port on every shell start, so a dead proxy degrades
175
+ // to plain direct API access instead of breaking the CLI.
176
+ function envLine() {
177
+ const f = envFile();
178
+ const home = homedir();
179
+ const display = f.startsWith(home) ? '$HOME' + f.slice(home.length) : f;
180
+ return `if [ -r "${display}" ]; then . "${display}"; fi ${MARKER}`;
181
+ }
182
+
183
+ // Idempotent, and self-healing: any older lakonai proxy line (including the
184
+ // unconditional `export ANTHROPIC_BASE_URL=…` of <= 1.2.2) is replaced.
74
185
  function installEnv(rcFile) {
75
186
  try {
76
187
  const content = fs.existsSync(rcFile) ? fs.readFileSync(rcFile, 'utf8') : '';
77
- if (content.includes(LAKONAI_PROXY_MARKER)) return false; // already installed
78
- fs.appendFileSync(rcFile, `\n${envLine()}\n`);
188
+ const kept = content.split('\n').filter((l) => !l.includes(MARKER)).join('\n').replace(/\n+$/, '');
189
+ const next = kept ? `${kept}\n\n${envLine()}\n` : `${envLine()}\n`;
190
+ if (next === content) return false;
191
+ fs.writeFileSync(rcFile, next);
79
192
  return true;
80
193
  } catch {
81
194
  return false;
@@ -86,7 +199,7 @@ function uninstallEnv(rcFile) {
86
199
  try {
87
200
  if (!fs.existsSync(rcFile)) return false;
88
201
  const content = fs.readFileSync(rcFile, 'utf8');
89
- const filtered = content.split('\n').filter((l) => !l.includes(LAKONAI_PROXY_MARKER)).join('\n');
202
+ const filtered = content.split('\n').filter((l) => !l.includes(MARKER)).join('\n');
90
203
  if (filtered === content) return false;
91
204
  fs.writeFileSync(rcFile, filtered);
92
205
  return true;
@@ -96,7 +209,7 @@ function uninstallEnv(rcFile) {
96
209
  }
97
210
 
98
211
  function rcFiles() {
99
- const home = os.homedir();
212
+ const home = homedir();
100
213
  return [
101
214
  path.join(home, '.zshrc'),
102
215
  path.join(home, '.bashrc'),
@@ -104,4 +217,27 @@ function rcFiles() {
104
217
  ].filter((f) => fs.existsSync(f));
105
218
  }
106
219
 
107
- module.exports = { start, stop, status, installEnv, uninstallEnv, rcFiles, envLine, pidFile, isRunning, readPid };
220
+ // Remove every trace from the shell: rc lines, generated script, running daemon.
221
+ async function unwire() {
222
+ const touched = rcFiles().filter((f) => uninstallEnv(f));
223
+ const stopped = await stop();
224
+ return { touched, stopped };
225
+ }
226
+
227
+ module.exports = {
228
+ start,
229
+ VERSION,
230
+ ownsProxy,
231
+ stop,
232
+ restart,
233
+ status,
234
+ unwire,
235
+ installEnv,
236
+ uninstallEnv,
237
+ rcFiles,
238
+ envLine,
239
+ preferredPort,
240
+ isRunning,
241
+ readState,
242
+ DEFAULT_PORT,
243
+ };
@@ -6,8 +6,9 @@ const fs = require('fs');
6
6
  const path = require('path');
7
7
  const os = require('os');
8
8
  const { compressRequest } = require('./compress');
9
+ const state = require('./state');
9
10
 
10
- const DEFAULT_PORT = 7474;
11
+ const DEFAULT_PORT = state.DEFAULT_PORT;
11
12
  const DEFAULT_UPSTREAM = { host: 'api.anthropic.com', port: 443, protocol: 'https' };
12
13
  const STATS_FILE = () => path.join(process.env.LAKON_HOME || path.join(os.homedir(), '.lakon'), 'proxy-stats.json');
13
14
 
@@ -91,19 +92,65 @@ function createServer(port = DEFAULT_PORT, upstream = DEFAULT_UPSTREAM) {
91
92
  return server;
92
93
  }
93
94
 
94
- /* istanbul ignore next */
95
- function main() {
96
- const port = Number(process.env.LAKON_PROXY_PORT) || DEFAULT_PORT;
97
- const server = createServer(port);
98
- server.listen(port, '127.0.0.1', () => {
99
- process.stdout.write(`lakonai proxy: listening on http://127.0.0.1:${port}\n`);
95
+ // Bind on `port`, falling back to an OS-assigned free port when it is taken.
96
+ // A busy port used to kill the daemon outright (exit 1) — silently, because the
97
+ // installer spawned it with stdio ignored — while the shell rc had already been
98
+ // pointed at that same dead port.
99
+ function bindServer(server, port, { allowFallback = true } = {}) {
100
+ return new Promise((resolve, reject) => {
101
+ const onError = (err) => {
102
+ /* istanbul ignore else -- non-EADDRINUSE bind errors (EACCES) can't be provoked portably */
103
+ if (err.code === 'EADDRINUSE' && allowFallback) {
104
+ server.listen(0, '127.0.0.1', () => resolve(server.address().port));
105
+ } else {
106
+ reject(err);
107
+ }
108
+ };
109
+ server.once('error', onError);
110
+ server.listen(port, '127.0.0.1', () => {
111
+ server.removeListener('error', onError);
112
+ resolve(server.address().port);
113
+ });
100
114
  });
101
- server.on('error', (err) => {
115
+ }
116
+
117
+ /* istanbul ignore next -- process entry point: bindServer and the state writes are unit-tested */
118
+ async function main() {
119
+ const preferred = Number(process.env.LAKON_PROXY_PORT) || DEFAULT_PORT;
120
+ const allowFallback = process.env.LAKON_PROXY_FALLBACK !== '0';
121
+ const server = createServer(preferred);
122
+
123
+ let port;
124
+ try {
125
+ port = await bindServer(server, preferred, { allowFallback });
126
+ } catch (err) {
102
127
  process.stderr.write(`lakonai proxy error: ${err.message}\n`);
103
128
  process.exit(1);
129
+ return;
130
+ }
131
+
132
+ // Publish the state only once a socket is really bound — the supervisor and
133
+ // the shell snippet both key off this.
134
+ state.writeState({
135
+ pid: process.pid,
136
+ port,
137
+ startedAt: new Date().toISOString(),
138
+ // Stamped so an upgrade can tell that the daemon in memory is stale code.
139
+ version: require('../../package.json').version,
104
140
  });
141
+ state.writeEnvScript(port);
142
+ process.stdout.write(`lakonai proxy: listening on http://127.0.0.1:${port}\n`);
143
+
144
+ const shutdown = () => {
145
+ state.clearState();
146
+ state.removeEnvScript();
147
+ process.exit(0);
148
+ };
149
+ process.on('SIGTERM', shutdown);
150
+ process.on('SIGINT', shutdown);
105
151
  }
106
152
 
153
+ /* istanbul ignore next -- process entry point */
107
154
  if (require.main === module) main();
108
155
 
109
- module.exports = { createServer, readStats, writeStats, mergeStats, DEFAULT_PORT, DEFAULT_UPSTREAM };
156
+ module.exports = { createServer, bindServer, readStats, writeStats, mergeStats, DEFAULT_PORT, DEFAULT_UPSTREAM };
@@ -0,0 +1,186 @@
1
+ 'use strict';
2
+
3
+ // Shared state for the compression proxy: where it lives on disk, which port it
4
+ // actually bound, and the shell snippet that points ANTHROPIC_BASE_URL at it.
5
+ //
6
+ // Both sides use this module — the daemon supervisor (start/stop/status) and the
7
+ // server process itself, which writes the state the moment it is really
8
+ // listening. That ordering is the point: nothing claims the proxy is up until a
9
+ // socket is bound.
10
+
11
+ const fs = require('fs');
12
+ const net = require('net');
13
+ const path = require('path');
14
+ const { homedir } = require('../install/paths');
15
+
16
+ // Default port. NOT 7474 — that is Neo4j's HTTP port, and the collision left
17
+ // fresh installs exporting ANTHROPIC_BASE_URL to a port nothing listened on,
18
+ // which broke every Claude session with ECONNREFUSED.
19
+ const DEFAULT_PORT = 41474;
20
+
21
+ // Port used by lakonai <= 1.2.2. Kept only so `proxy status` can still see (and
22
+ // `proxy stop` still kill) a daemon left over from an older install.
23
+ const LEGACY_PORT = 7474;
24
+
25
+ const MARKER = '# lakonai proxy';
26
+
27
+ function lakonHome() {
28
+ return process.env.LAKON_HOME || path.join(homedir(), '.lakon');
29
+ }
30
+
31
+ const stateFile = () => path.join(lakonHome(), 'proxy.json');
32
+ const legacyPidFile = () => path.join(lakonHome(), 'proxy.pid');
33
+ const envFile = () => path.join(lakonHome(), 'proxy-env.sh');
34
+
35
+ function readState() {
36
+ try {
37
+ const s = JSON.parse(fs.readFileSync(stateFile(), 'utf8'));
38
+ /* istanbul ignore else -- a state file that parses but lacks pid/port falls through to the legacy read */
39
+ if (s && Number(s.pid) && Number(s.port)) {
40
+ return { pid: Number(s.pid), port: Number(s.port), startedAt: s.startedAt || null, version: s.version || null };
41
+ }
42
+ } catch { /* fall through to the legacy file */ }
43
+ // Pre-1.2.3 installs only wrote a bare pid file and always used LEGACY_PORT.
44
+ try {
45
+ const pid = Number(fs.readFileSync(legacyPidFile(), 'utf8').trim());
46
+ if (pid) return { pid, port: LEGACY_PORT, startedAt: null, legacy: true };
47
+ } catch { /* no state at all */ }
48
+ return null;
49
+ }
50
+
51
+ function writeState(state) {
52
+ try {
53
+ fs.mkdirSync(lakonHome(), { recursive: true });
54
+ fs.writeFileSync(stateFile(), JSON.stringify(state));
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ function clearState() {
62
+ for (const f of [stateFile(), legacyPidFile()]) {
63
+ try { fs.unlinkSync(f); } catch { /* already gone */ }
64
+ }
65
+ }
66
+
67
+ // ── liveness ────────────────────────────────────────────────────────────────
68
+
69
+ // A real TCP connect. Checking the PID is not enough: a recycled PID reads as
70
+ // "running" while nothing is bound, which is exactly the failure this proxy
71
+ // shipped with.
72
+ function probePort(port, timeoutMs = 400) {
73
+ return new Promise((resolve) => {
74
+ const socket = new net.Socket();
75
+ let done = false;
76
+ const finish = (up) => {
77
+ /* istanbul ignore next -- the second of two racing events (timeout+error); not reproducible on a loopback socket */
78
+ if (done) return;
79
+ done = true;
80
+ socket.destroy();
81
+ resolve(up);
82
+ };
83
+ socket.setTimeout(timeoutMs);
84
+ socket.once('connect', () => finish(true));
85
+ /* istanbul ignore next -- a loopback connect always resolves or refuses before the timer; needs a black-holing host to reach */
86
+ socket.once('timeout', () => finish(false));
87
+ socket.once('error', () => finish(false));
88
+ socket.connect(port, '127.0.0.1');
89
+ });
90
+ }
91
+
92
+ // NOTE: no unref() here. An unref'd timer lets Node exit mid-poll, which made
93
+ // `lakonai proxy start` return silently with exit 0 and no daemon.
94
+ function sleep(ms) {
95
+ return new Promise((resolve) => { setTimeout(resolve, ms); });
96
+ }
97
+
98
+ // Poll until `want` matches whether the port answers, or the deadline passes.
99
+ async function waitForPort(port, { timeoutMs = 5000, want = true, intervalMs = 100 } = {}) {
100
+ const deadline = Date.now() + timeoutMs;
101
+ for (;;) {
102
+ if ((await probePort(port, Math.min(400, timeoutMs))) === want) return true;
103
+ if (Date.now() >= deadline) return false;
104
+ await sleep(intervalMs);
105
+ }
106
+ }
107
+
108
+ function isRunning(pid) {
109
+ if (!pid) return false;
110
+ try { process.kill(pid, 0); return true; } catch { return false; }
111
+ }
112
+
113
+ // ── shell env snippet ───────────────────────────────────────────────────────
114
+
115
+ // The rc file sources this script; this script exports ANTHROPIC_BASE_URL ONLY
116
+ // when something is actually listening. A dead proxy therefore costs the user
117
+ // compression, not their whole CLI — the previous unconditional export turned
118
+ // any daemon death into ECONNREFUSED on every request.
119
+ //
120
+ // The port check is shell-native where possible (zsh's ztcp, bash's /dev/tcp)
121
+ // and falls back to nc. If no mechanism is available nothing is exported, which
122
+ // is the safe direction.
123
+ function envScript(port) {
124
+ return `# lakonai proxy — generated by lakonai, safe to delete.
125
+ # Points ANTHROPIC_BASE_URL at the local compression proxy, but only while it is
126
+ # actually listening. Proxy down = plain direct API access, never a broken CLI.
127
+ __lakon_port=${port}
128
+ __lakon_up=0
129
+
130
+ # 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 our own local proxy.
132
+ case "$ANTHROPIC_BASE_URL" in
133
+ ""|http://127.0.0.1:*)
134
+ if [ -n "$ZSH_VERSION" ] && zmodload zsh/net/tcp 2>/dev/null; then
135
+ if ztcp 127.0.0.1 $__lakon_port 2>/dev/null; then
136
+ ztcp -c "$REPLY" 2>/dev/null
137
+ __lakon_up=1
138
+ fi
139
+ elif [ -n "$BASH_VERSION" ] && (exec 3<>/dev/tcp/127.0.0.1/$__lakon_port) 2>/dev/null; then
140
+ __lakon_up=1
141
+ elif command -v nc >/dev/null 2>&1 && nc -z -w 1 127.0.0.1 $__lakon_port >/dev/null 2>&1; then
142
+ __lakon_up=1
143
+ fi
144
+ ;;
145
+ esac
146
+
147
+ if [ "$__lakon_up" = 1 ]; then
148
+ export ANTHROPIC_BASE_URL=http://127.0.0.1:$__lakon_port
149
+ fi
150
+ unset __lakon_port __lakon_up
151
+ `;
152
+ }
153
+
154
+ function writeEnvScript(port) {
155
+ try {
156
+ fs.mkdirSync(lakonHome(), { recursive: true });
157
+ fs.writeFileSync(envFile(), envScript(port));
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ function removeEnvScript() {
165
+ try { fs.unlinkSync(envFile()); return true; } catch { return false; }
166
+ }
167
+
168
+ module.exports = {
169
+ DEFAULT_PORT,
170
+ LEGACY_PORT,
171
+ MARKER,
172
+ lakonHome,
173
+ stateFile,
174
+ legacyPidFile,
175
+ envFile,
176
+ readState,
177
+ writeState,
178
+ clearState,
179
+ probePort,
180
+ waitForPort,
181
+ isRunning,
182
+ envScript,
183
+ writeEnvScript,
184
+ removeEnvScript,
185
+ sleep,
186
+ };