lakonai 1.2.1 → 1.2.3

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
@@ -7,18 +7,26 @@
7
7
  <h3 align="center">Speak less. Ship more.</h3>
8
8
 
9
9
  <p align="center">
10
- <strong>Cut LLM tokens by up to 94% — without losing a single identifier.</strong>
10
+ <strong>Cut LLM tokens by up to 99.8% — without losing a single identifier.</strong><br/>
11
+ <sub>A 182k-line <code>git diff</code> went <strong>1,513,910 → 2,331 tokens</strong>. Measured, not rounded.</sub>
11
12
  </p>
12
13
 
13
14
  <p align="center"><em>Spartan replies for AI agents.</em></p>
14
15
 
15
16
  <p align="center">
16
17
  <a href="https://www.npmjs.com/package/lakonai"><img src="https://img.shields.io/npm/v/lakonai?color=0F0F0F&label=npm" alt="npm" /></a>
18
+ <a href="https://github.com/bargadev/lakonai"><img src="https://img.shields.io/badge/GitHub-bargadev%2Flakonai-0F0F0F?logo=github" alt="GitHub repo" /></a>
17
19
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-0F0F0F" alt="MIT" /></a>
18
20
  <img src="https://img.shields.io/badge/node-%E2%89%A518-0F0F0F" alt="node ≥18" />
19
21
  <img src="https://img.shields.io/badge/deps-0-0F0F0F" alt="zero dependencies" />
20
22
  <img src="https://img.shields.io/badge/agents-6-0F0F0F" alt="6 AI agents" />
21
- <img src="https://img.shields.io/badge/tests-725-0F0F0F" alt="725 tests" />
23
+ <img src="https://img.shields.io/badge/tests-796-0F0F0F" alt="796 tests" />
24
+ </p>
25
+
26
+ <p align="center">
27
+ <a href="https://github.com/bargadev/lakonai">
28
+ <img src="./docs/assets/before-after.svg" width="820" alt="lakonai: a 182k-line git diff main…HEAD went 1,513,910 → 2,331 tokens (−99.8%), structure and identifiers intact" />
29
+ </a>
22
30
  </p>
23
31
 
24
32
  <p align="center">
@@ -149,7 +157,7 @@ Benchmark on the lakonai codebase itself (30 queries, 15 literal + 15 semantic):
149
157
 
150
158
  ### Layer 3 — Proxy compression (Claude Code)
151
159
 
152
- 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.
153
161
 
154
162
  ```
155
163
  build logs → -99% (repetitive lines collapsed)
@@ -159,7 +167,34 @@ diffs → -4% (conservative; context preserved)
159
167
  source code → 0% (covered by graph instead)
160
168
  ```
161
169
 
162
- 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
+ Upgrading migrates an old install by itself: `lakonai upgrade` replaces a daemon
191
+ running a previous version (a running process keeps executing the server code it
192
+ was started with), moves it off port 7474, and rewrites the old
193
+ `export ANTHROPIC_BASE_URL` line in your rc into the guarded one.
194
+
195
+ `lakonai uninstall` stops the proxy and removes the wiring. Set
196
+ `LAKON_PROXY_DISABLE=1` to keep `lakonai install` from touching your shell at
197
+ all.
163
198
 
164
199
  ### Layer 4 — Pixel (Claude Code + Codex)
165
200
 
@@ -231,6 +266,7 @@ After `lakonai install`, these are available in Claude Code:
231
266
  | `lakonai peek [id]` | Read output parked in sandbox (`--grep/--offset/--limit`) |
232
267
  | `lakonai gain` | Token savings across all measured fronts |
233
268
  | `lakonai inspect <cmd>` | Debug what filter applies to a command |
269
+ | `lakonai proxy [start\|stop\|restart]` | Compression proxy status/lifecycle |
234
270
  | `lakonai doctor` | Health check: CLI on PATH, hooks, rule |
235
271
 
236
272
  Full flags, filters, env vars, internals: **[docs/reference.md](docs/reference.md)**.
@@ -286,14 +322,14 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
286
322
 
287
323
  ## Test suite
288
324
 
289
- 725 tests across 47 suites — all passing, no mocks on I/O boundaries.
325
+ 796 tests across 51 suites — all passing, no mocks on I/O boundaries.
290
326
 
291
327
  | Type | Suites | Tests |
292
328
  |------|--------|-------|
293
- | Unit | 13 | 183 |
294
- | Integration (module + real FS) | 31 | 489 |
295
- | E2E / CLI (spawn + real process) | 3 | 53 |
296
- | **Total** | **47** | **725** |
329
+ | Unit | 13 | 170 |
330
+ | Integration (module + real FS) | 33 | 530 |
331
+ | E2E / CLI (spawn + real process) | 2 | 51 |
332
+ | **Total** | **48** | **751** |
297
333
 
298
334
  Coverage: **95% statements · 89% branches · 97% functions**
299
335
 
@@ -311,12 +347,17 @@ Your AI agent isn't laconic. It opens with _"Sure! I'd be happy to help…"_, re
311
347
 
312
348
  ## Credits
313
349
 
314
- Built on ideas from three projects:
350
+ lakonai is an original, zero-dependency tool written from scratch. Several of its
351
+ layers were **inspired by** prior art — none of it is vendored or forked, and the
352
+ compression engine, auto-learning, read-guard, overflow sandbox, and BM25 graph
353
+ query are lakonai's own:
315
354
 
316
- - [**caveman**](https://github.com/juliusbrussee/caveman) (MIT) — terse rule, auto-clarity, proxy compression, pixel mode
317
- - [**graphify**](https://github.com/Bklieger/graphify) — AST knowledge graph, Leiden community detection, force-directed viz, NL query (reimplemented in Node.js; BM25 replaces LLM query)
318
- - [**rtk**](https://github.com/rtk-ai/rtk) — CLI output filtering approach, extended with auto-learning and 30+ built-in filters
355
+ - [**caveman**](https://github.com/juliusbrussee/caveman) (MIT) — inspired the terse-response rule, auto-clarity, and pixel skill mode
356
+ - [**graphify**](https://github.com/Bklieger/graphify) — inspired the AST knowledge graph and community detection; lakonai reimplements it in Node.js and drops the LLM at query time for zero-cost BM25
357
+ - [**rtk**](https://github.com/rtk-ai/rtk) — inspired the CLI-filtering approach; lakonai goes further with auto-learning and 30+ built-in filters
319
358
 
320
- Condensed into one zero-dependency npm package with automatic install, savings tracking, and four layers of compression.
359
+ Where an idea carries a license (caveman is MIT), credit stays. Everything else —
360
+ the declarative filter engine, the hook dispatch, savings tracking, and the four
361
+ layers of compression — is built here.
321
362
 
322
363
  MIT — see [LICENSE](LICENSE).
package/bin/lakonai.js CHANGED
@@ -49,6 +49,10 @@ 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 proxy [cmd] Compression proxy: status (default) | start | stop
53
+ | restart. The proxy shrinks API request bodies;
54
+ while it is down lakonai simply stays out of the way
55
+ and Claude talks to the API directly.
52
56
  lakonai doctor Per-platform health: CLI on PATH, rule, hooks
53
57
  lakonai version Print the installed lakonai version
54
58
  lakonai --help This help
@@ -423,6 +427,51 @@ function runPixel(args) {
423
427
  process.stdout.write(pixel.formatConvert(results));
424
428
  }
425
429
 
430
+ async function runProxy(args) {
431
+ const daemon = require('../src/proxy/daemon');
432
+ const sub = args[0] || 'status';
433
+
434
+ if (sub === 'status') {
435
+ const s = await daemon.status();
436
+ if (s.running) {
437
+ process.stdout.write(`lakonai proxy: running (pid ${s.pid}) on http://127.0.0.1:${s.port}\n`);
438
+ return;
439
+ }
440
+ if (s.stale) {
441
+ 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`);
442
+ } else {
443
+ process.stdout.write('lakonai proxy: not running\n');
444
+ }
445
+ process.stdout.write(' Claude talks to the API directly — no compression, nothing broken.\n');
446
+ process.stdout.write(' Start it with `lakonai proxy start`.\n');
447
+ process.exitCode = 1;
448
+ return;
449
+ }
450
+
451
+ if (sub === 'start' || sub === 'restart') {
452
+ const res = sub === 'restart' ? await daemon.restart() : await daemon.start();
453
+ if (!res.running) {
454
+ process.stdout.write(`lakonai proxy: failed to start — ${res.error}\n`);
455
+ process.exitCode = 1;
456
+ return;
457
+ }
458
+ const verb = res.alreadyRunning ? 'already running' : 'started';
459
+ process.stdout.write(`lakonai proxy: ${verb} (pid ${res.pid}) on http://127.0.0.1:${res.port}\n`);
460
+ const touched = daemon.rcFiles().filter((rc) => daemon.installEnv(rc));
461
+ if (touched.length) process.stdout.write(` shell wiring refreshed in ${touched.join(', ')}\n`);
462
+ return;
463
+ }
464
+
465
+ if (sub === 'stop') {
466
+ const stopped = await daemon.stop();
467
+ process.stdout.write(stopped ? 'lakonai proxy: stopped\n' : 'lakonai proxy: was not running\n');
468
+ return;
469
+ }
470
+
471
+ process.stdout.write(`lakonai proxy: unknown subcommand "${sub}" (use status|start|stop|restart)\n`);
472
+ process.exitCode = 1;
473
+ }
474
+
426
475
  async function main() {
427
476
  const argv = process.argv.slice(2);
428
477
  if (!argv.length || argv[0] === '--help' || argv[0] === '-h') {
@@ -485,6 +534,10 @@ async function main() {
485
534
  await maybeOfferUpdate();
486
535
  return;
487
536
  }
537
+ if (first === 'proxy') {
538
+ await runProxy(rest);
539
+ return;
540
+ }
488
541
  if (first === 'doctor') {
489
542
  const doctor = require('../src/doctor');
490
543
  process.stdout.write(doctor.format(doctor.report()));
@@ -519,4 +572,4 @@ if (require.main === module) {
519
572
  });
520
573
  }
521
574
 
522
- module.exports = { runAndFilter, printVersion, main, HELP };
575
+ module.exports = { runAndFilter, printVersion, main, runProxy, HELP };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
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"
@@ -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 };
@@ -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
+ };