@llmnesia/local-agent-host 0.2.0-beta.1

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/install.mjs ADDED
@@ -0,0 +1,441 @@
1
+ #!/usr/bin/env node
2
+ // Installs the LLMnesia native messaging host so the browser extension can read
3
+ // local Claude Code sessions automatically (no folder picking) and sync its
4
+ // conversation corpus for the MCP companion (no File System Access picker).
5
+ //
6
+ // Usage: node install.mjs [<extension-id> ...] [--corpus <dir>] [--force]
7
+ //
8
+ // With no extension id it authorises the published Chrome Web Store build
9
+ // (STORE_EXTENSION_ID below). Pass ids only to ALSO allow dev/unpacked builds,
10
+ // whose ids are random per machine.
11
+ //
12
+ // It (1) copies the host script to ~/.llmnesia/, and (2) registers a
13
+ // com.llmnesia.claude_code native-messaging host — locked to the given extension
14
+ // id(s) — for every Chromium browser found, and (3) writes ~/.llmnesia/config.json
15
+ // naming the corpus root the host is allowed to write into. The host reads that
16
+ // root from its own config and never from anything the browser sends, so this
17
+ // file is what gives the write path a fixed, host-owned destination.
18
+ // • macOS / Linux: native messaging launches the script directly, so we pin its
19
+ // shebang to THIS node (nvm/volta node isn't on the bare PATH hosts get) and
20
+ // drop a JSON manifest into each browser's NativeMessagingHosts folder.
21
+ // • Windows: native messaging can't launch a .mjs directly and finds hosts via
22
+ // the registry, so we write a .bat launcher (invokes node with the script)
23
+ // and point an HKCU registry key at the manifest.
24
+ //
25
+ // The core logic below is exported as `installNativeHost()` so other packages
26
+ // (the @llmnesia/mcp installer) can call it in-process instead of shelling out
27
+ // to this script. Everything exported is a plain function with no dependency on
28
+ // process.argv — argv parsing lives only in this file's own CLI `main()`, which
29
+ // only runs when the file is executed directly (not when imported as a module).
30
+
31
+ import { execFile } from "node:child_process";
32
+ import { chmod, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
33
+ import { homedir, platform } from "node:os";
34
+ import { dirname, join, resolve } from "node:path";
35
+ import { fileURLToPath } from "node:url";
36
+ import { promisify } from "node:util";
37
+
38
+ const execFileAsync = promisify(execFile);
39
+ export const HOST_NAME = "com.llmnesia.claude_code";
40
+ // The published Chrome Web Store build's permanent id. It is derived from the
41
+ // item's public key and never changes across versions, so baking it in lets a
42
+ // normal install run with no arguments. (Source: the store reviews URL in
43
+ // extension/src/shared/review_prompt.ts.)
44
+ export const STORE_EXTENSION_ID = "leekfgbdojiaabifbjbbgiiclannjdkf";
45
+ const here = dirname(fileURLToPath(import.meta.url));
46
+ const home = homedir();
47
+ // Same root the host script itself reads from (llmnesia-claude-host.mjs's
48
+ // PROJECTS_DIR) — duplicated rather than imported so this file stays free of
49
+ // any dependency on the host script it installs. Exported so doctor.mjs can
50
+ // report against the same path without a third copy.
51
+ export const CLAUDE_PROJECTS_DIR = join(home, ".claude", "projects");
52
+ // Test seam: LLMNESIA_FAKE_PLATFORM lets the suite exercise the Windows install
53
+ // path (registry + .bat) from a non-Windows host. Unset in normal use.
54
+ const osPlatform = process.env.LLMNESIA_FAKE_PLATFORM || platform();
55
+
56
+ // Same resolution order as companion/src/config.ts: explicit --corpus > the
57
+ // LLMNESIA_CORPUS_DIR env > the documented default. Both the host's write path
58
+ // and the companion's read path must resolve to the same directory.
59
+ export function expandHome(p) {
60
+ if (p === "~") {
61
+ return home;
62
+ }
63
+ if (p.startsWith("~/") || p.startsWith("~\\")) {
64
+ return resolve(home, p.slice(2));
65
+ }
66
+ return resolve(p);
67
+ }
68
+ export function resolveCorpusDir(explicit) {
69
+ const raw = explicit ?? process.env.LLMNESIA_CORPUS_DIR ?? "~/.llmnesia/corpus";
70
+ return expandHome(raw);
71
+ }
72
+
73
+ // Where Codex keeps its rollouts. Same shape of resolution as the corpus dir:
74
+ // explicit --codex-home > the CODEX_HOME env Codex itself honours > its default.
75
+ // Resolved once at install time and persisted, so the host doesn't have to
76
+ // re-derive it from an environment native messaging doesn't give it.
77
+ //
78
+ // An empty or whitespace-only value counts as absent, not as "install here":
79
+ // `CODEX_HOME=` is a common way to blank a variable, and `expandHome("")`
80
+ // resolves to the process's cwd — which would silently point the helper at
81
+ // whatever directory the installer happened to run from.
82
+ export function resolveCodexHome(explicit) {
83
+ const candidates = [explicit, process.env.CODEX_HOME, "~/.codex"];
84
+ const raw = candidates.find((value) => typeof value === "string" && value.trim() !== "");
85
+ return expandHome(raw.trim());
86
+ }
87
+
88
+ export async function exists(path) {
89
+ try {
90
+ await stat(path);
91
+ return true;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ async function supportedBrowserCount(isWindows) {
98
+ const candidates = isWindows ? windowsBrowsers().map(([, path]) => path) : posixBrowsers().map(([, path]) => path);
99
+ let count = 0;
100
+ for (const path of candidates) {
101
+ if (await exists(path)) {
102
+ count += 1;
103
+ }
104
+ }
105
+ return count;
106
+ }
107
+
108
+ async function readExistingConfig(configPath) {
109
+ let raw;
110
+ try {
111
+ raw = await readFile(configPath, "utf8");
112
+ } catch (err) {
113
+ if (err && typeof err === "object" && err.code === "ENOENT") {
114
+ return null;
115
+ }
116
+ throw new Error(`LLMnesia couldn't read its settings at ${configPath}: ${err instanceof Error ? err.message : String(err)}. Nothing was changed.`);
117
+ }
118
+ let parsed;
119
+ try {
120
+ parsed = JSON.parse(raw);
121
+ } catch (err) {
122
+ throw new Error(
123
+ `LLMnesia found invalid JSON in its settings at ${configPath}: ${err instanceof Error ? err.message : String(err)}. Nothing was changed; repair or move that file aside, then retry.`
124
+ );
125
+ }
126
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
127
+ throw new Error(`LLMnesia settings at ${configPath} must contain a JSON object. Nothing was changed.`);
128
+ }
129
+ if ("corpusRoot" in parsed && typeof parsed.corpusRoot !== "string") {
130
+ throw new Error(`LLMnesia settings at ${configPath} contain an invalid conversation-data folder. Nothing was changed.`);
131
+ }
132
+ if ("codexHome" in parsed && typeof parsed.codexHome !== "string") {
133
+ throw new Error(`LLMnesia settings at ${configPath} contain an invalid Codex data folder. Nothing was changed.`);
134
+ }
135
+ return parsed;
136
+ }
137
+
138
+ // --- macOS / Linux: a JSON manifest in each browser's profile -------------
139
+
140
+ /**
141
+ * Browser profile roots to install into. `homeDir`/`forPlatform` default to
142
+ * this machine's real values; callers pass them explicitly to inspect a
143
+ * different home or OS (the doctor command does, so its --home is honest
144
+ * rather than silently reporting on the real one).
145
+ */
146
+ export function posixBrowsers(homeDir = home, forPlatform = osPlatform) {
147
+ if (forPlatform === "darwin") {
148
+ const base = join(homeDir, "Library", "Application Support");
149
+ return [
150
+ ["Brave", join(base, "BraveSoftware", "Brave-Browser")],
151
+ ["Chrome", join(base, "Google", "Chrome")],
152
+ ["Edge", join(base, "Microsoft Edge")],
153
+ ["Chromium", join(base, "Chromium")]
154
+ ];
155
+ }
156
+ // Linux
157
+ const base = join(homeDir, ".config");
158
+ return [
159
+ ["Brave", join(base, "BraveSoftware", "Brave-Browser")],
160
+ ["Chrome", join(base, "google-chrome")],
161
+ ["Edge", join(base, "microsoft-edge")],
162
+ ["Chromium", join(base, "chromium")]
163
+ ];
164
+ }
165
+
166
+ async function installPosix(manifestBase, hostPath, log) {
167
+ const manifest = { ...manifestBase, path: hostPath };
168
+ let installed = 0;
169
+ for (const [label, browserDir] of posixBrowsers()) {
170
+ if (!(await exists(browserDir))) {
171
+ continue;
172
+ }
173
+ const dir = join(browserDir, "NativeMessagingHosts");
174
+ await mkdir(dir, { recursive: true });
175
+ await writeFile(join(dir, `${HOST_NAME}.json`), `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
176
+ log(`✓ ${label} connected`);
177
+ installed += 1;
178
+ }
179
+ return installed;
180
+ }
181
+
182
+ // --- Windows: an HKCU registry key + a .bat launcher ----------------------
183
+
184
+ export function windowsBrowsers() {
185
+ const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local");
186
+ // [label, "User Data" dir (presence check), registry vendor path under HKCU]
187
+ return [
188
+ ["Brave", join(localAppData, "BraveSoftware", "Brave-Browser", "User Data"), "Software\\BraveSoftware\\Brave-Browser"],
189
+ ["Chrome", join(localAppData, "Google", "Chrome", "User Data"), "Software\\Google\\Chrome"],
190
+ ["Edge", join(localAppData, "Microsoft", "Edge", "User Data"), "Software\\Microsoft\\Edge"],
191
+ ["Chromium", join(localAppData, "Chromium", "User Data"), "Software\\Chromium"]
192
+ ];
193
+ }
194
+
195
+ async function installWindows(manifestBase, hostPath, installDir, log) {
196
+ // Chrome launches native hosts hidden (no console flash), but it can't run a
197
+ // .mjs, so point the manifest at a .bat that invokes THIS node with the script.
198
+ const batPath = join(installDir, "llmnesia-claude-host.bat");
199
+ await writeFile(batPath, `@echo off\r\n"${process.execPath}" "${hostPath}" %*\r\n`, "utf8");
200
+ log("✓ Windows launcher ready");
201
+
202
+ // The manifest lives in ~/.llmnesia; browsers find it via a registry key whose
203
+ // default value is this manifest's full path.
204
+ const manifest = { ...manifestBase, path: batPath };
205
+ const manifestPath = join(installDir, `${HOST_NAME}.json`);
206
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
207
+
208
+ let installed = 0;
209
+ for (const [label, userDataDir, vendorKey] of windowsBrowsers()) {
210
+ if (!(await exists(userDataDir))) {
211
+ continue;
212
+ }
213
+ const key = `HKCU\\${vendorKey}\\NativeMessagingHosts\\${HOST_NAME}`;
214
+ // /ve sets the key's (default) value; Chrome reads that as the manifest path.
215
+ // Use reg.exe's absolute path: without a shell, a bare "reg" isn't reliably
216
+ // resolved via PATHEXT, and System32 is redirected to SysWOW64 for a 32-bit
217
+ // node — reg.exe exists in both, and HKCU\Software isn't WOW64-split.
218
+ const regExe = join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
219
+ await execFileAsync(regExe, ["add", key, "/ve", "/t", "REG_SZ", "/d", manifestPath, "/f"]);
220
+ log(`✓ ${label} connected`);
221
+ installed += 1;
222
+ }
223
+ return installed;
224
+ }
225
+
226
+ /**
227
+ * Install (or update) the native-messaging host and its corpus config. Pure
228
+ * function of its arguments — no process.argv/process.exit — so it can be
229
+ * called both from this file's own CLI `main()` and imported by
230
+ * `@llmnesia/mcp`'s `install` subcommand.
231
+ *
232
+ * @param {{ ids?: string[], corpus?: string, codexHome?: string, force?: boolean, quiet?: boolean }} options
233
+ * `ids` are EXTRA dev/unpacked extension ids to allow, on top of the
234
+ * published Web Store build (always allowed). `corpus` overrides the
235
+ * resolved corpus directory. `codexHome` overrides where the host looks for
236
+ * Codex rollouts. `force` allows overwriting an existing, different
237
+ * corpusRoot in config.json.
238
+ * @returns {Promise<{ installedCount: number, allowedIds: string[], configPath: string, corpusRoot: string, corpusRootChanged: boolean, codexHome: string }>}
239
+ * @throws if no supported browser was found on this machine.
240
+ */
241
+ export async function installNativeHost({ ids = [], corpus, codexHome, force = false, quiet = false } = {}) {
242
+ const log = quiet ? () => {} : console.log;
243
+ const isWindows = osPlatform === "win32";
244
+ // The Web Store build is always allowed; any ids passed in are dev/unpacked
245
+ // builds allowed on top of it (deduped), so a call with no ids works for
246
+ // normal store users.
247
+ const invalidId = ids.find((id) => !/^[a-p]{32}$/.test(id));
248
+ if (invalidId) {
249
+ throw new Error(
250
+ `${JSON.stringify(invalidId)} is not a Chromium extension ID. ` +
251
+ "Only unpacked/development builds need an ID; it must be 32 letters from a through p. Run with --help for an example."
252
+ );
253
+ }
254
+ const allIds = [...new Set([STORE_EXTENSION_ID, ...ids])];
255
+ const allowedOrigins = allIds.map((id) => `chrome-extension://${id}/`);
256
+
257
+ // Validate every prerequisite before changing the machine. In particular,
258
+ // the old order left a stray host script behind when no browser existed and
259
+ // overwrote malformed config after silently treating it as absent.
260
+ if ((await supportedBrowserCount(isWindows)) === 0) {
261
+ throw new Error(
262
+ "LLMnesia couldn't find Chrome, Brave, Edge, or Chromium. Open your browser once so it creates a profile, then retry. " +
263
+ "Safari and Firefox are not supported yet. Nothing was installed."
264
+ );
265
+ }
266
+ const installDir = join(home, ".llmnesia");
267
+ const configPath = join(installDir, "config.json");
268
+ const existing = await readExistingConfig(configPath);
269
+
270
+ // 1. Install the host script into ~/.llmnesia.
271
+ await mkdir(installDir, { recursive: true });
272
+ const hostSource = await readFile(join(here, "llmnesia-claude-host.mjs"), "utf8");
273
+ // POSIX launches the script directly, so pin its shebang to THIS node. On
274
+ // Windows the .bat wrapper invokes node explicitly, so the shebang is unused.
275
+ const hosted = isWindows ? hostSource : hostSource.replace(/^#![^\n]*\n/, `#!${process.execPath}\n`);
276
+ const hostPath = join(installDir, "llmnesia-claude-host.mjs");
277
+ await writeFile(hostPath, hosted, "utf8");
278
+ if (!isWindows) {
279
+ await chmod(hostPath, 0o755);
280
+ }
281
+ log("✓ Helper installed");
282
+
283
+ const manifestBase = {
284
+ name: HOST_NAME,
285
+ description: "LLMnesia — reads local Claude Code and Codex sessions",
286
+ type: "stdio",
287
+ allowed_origins: allowedOrigins
288
+ };
289
+
290
+ // 2. Register the host for each installed browser.
291
+ const installedCount = isWindows
292
+ ? await installWindows(manifestBase, hostPath, installDir, log)
293
+ : await installPosix(manifestBase, hostPath, log);
294
+
295
+ // 3. Write the host-owned config: the corpus root it may write into, and
296
+ // where to look for Codex rollouts. Native messaging gives the host almost
297
+ // no environment, so CODEX_HOME has to be resolved here and persisted.
298
+ const corpusRoot = resolveCorpusDir(corpus);
299
+ const resolvedCodexHome = resolveCodexHome(codexHome);
300
+ const existingRoot = existing && typeof existing.corpusRoot === "string" ? existing.corpusRoot : null;
301
+ let corpusRootChanged = true;
302
+ if (existingRoot && existingRoot !== corpusRoot && !force) {
303
+ // Re-running the installer must not silently move a corpus that already has
304
+ // history in it. Keep the existing one; require --force to change it.
305
+ // The Codex home is not history-bearing (it's a read location), so it is
306
+ // still refreshed — that's what upgrades an older install in place.
307
+ corpusRootChanged = false;
308
+ await writeFile(
309
+ configPath,
310
+ `${JSON.stringify({ ...existing, corpusRoot: existingRoot, codexHome: resolvedCodexHome }, null, 2)}\n`,
311
+ { encoding: "utf8", mode: 0o600 }
312
+ );
313
+ await chmod(configPath, 0o600);
314
+ log("✓ Kept your existing conversation-data folder");
315
+ log(` Conversation data: ${existingRoot}`);
316
+ log(` To change it: re-run with --corpus <dir> --force`);
317
+ log(` Codex data: ${resolvedCodexHome}`);
318
+ } else {
319
+ await writeFile(
320
+ configPath,
321
+ `${JSON.stringify({ ...(existing ?? {}), corpusRoot, codexHome: resolvedCodexHome }, null, 2)}\n`,
322
+ { encoding: "utf8", mode: 0o600 }
323
+ );
324
+ await chmod(configPath, 0o600);
325
+ log("✓ Settings saved");
326
+ log(` Conversation data: ${corpusRoot}`);
327
+ log(` Codex data: ${resolvedCodexHome}`);
328
+ }
329
+
330
+ // Tell the user what the helper actually found, rather than a bare "Done" —
331
+ // a confident success message with a silently-empty Codex row (or vice versa)
332
+ // reads as broken to someone who doesn't know their absence is expected.
333
+ const [hasClaudeCode, hasCodex] = await Promise.all([
334
+ exists(CLAUDE_PROJECTS_DIR),
335
+ exists(join(resolvedCodexHome, "sessions"))
336
+ ]);
337
+ log("");
338
+ log(
339
+ hasClaudeCode
340
+ ? `✓ Found Claude Code sessions at ${CLAUDE_PROJECTS_DIR}`
341
+ : `– No Claude Code sessions found yet (fine if you don't use Claude Code).`
342
+ );
343
+ log(
344
+ hasCodex
345
+ ? `✓ Found Codex sessions at ${resolvedCodexHome}`
346
+ : `– No Codex sessions found yet (fine if you don't use Codex).`
347
+ );
348
+
349
+ const extraIdCount = allIds.length - 1;
350
+ if (extraIdCount > 0) {
351
+ log(`✓ Also authorized ${extraIdCount} unpacked extension ${extraIdCount === 1 ? "build" : "builds"}`);
352
+ }
353
+ log("\nAll set — LLMnesia can now read your local coding-agent sessions.");
354
+ log("Next: fully quit your browser (not just close its window), reopen it, then open LLMnesia Settings.");
355
+ log("If it doesn't connect, run: npx -y @llmnesia/local-agent-host@latest doctor");
356
+
357
+ return {
358
+ installedCount,
359
+ allowedIds: allIds,
360
+ configPath,
361
+ corpusRoot: existingRoot && !corpusRootChanged ? existingRoot : corpusRoot,
362
+ corpusRootChanged,
363
+ codexHome: resolvedCodexHome
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Remove the native-messaging manifests/registry keys and the host script
369
+ * this installer wrote. Deliberately does NOT touch ~/.llmnesia/config.json
370
+ * or the corpus directory it points at — uninstalling the plumbing must never
371
+ * delete the user's actual conversation data as a side effect. Returns what
372
+ * was removed; never throws for something already absent.
373
+ *
374
+ * @returns {Promise<{ removed: string[], corpusRoot: string | null }>}
375
+ */
376
+ export async function uninstallNativeHost() {
377
+ const isWindows = osPlatform === "win32";
378
+ const removed = [];
379
+ const installDir = join(home, ".llmnesia");
380
+ const configPath = join(installDir, "config.json");
381
+ let corpusRoot = null;
382
+ try {
383
+ const config = await readExistingConfig(configPath);
384
+ corpusRoot = config && typeof config.corpusRoot === "string" ? config.corpusRoot : null;
385
+ } catch {
386
+ // Uninstall plumbing even when the retained data config needs manual repair.
387
+ }
388
+
389
+ if (isWindows) {
390
+ const manifestPath = join(installDir, `${HOST_NAME}.json`);
391
+ const batPath = join(installDir, "llmnesia-claude-host.bat");
392
+ for (const [label, _userDataDir, vendorKey] of windowsBrowsers()) {
393
+ const key = `HKCU\\${vendorKey}\\NativeMessagingHosts\\${HOST_NAME}`;
394
+ const regExe = join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
395
+ try {
396
+ await execFileAsync(regExe, ["delete", key, "/f"]);
397
+ removed.push(`registry:${label}`);
398
+ } catch {
399
+ // Key may already be gone — not an error for uninstall.
400
+ }
401
+ }
402
+ if (await exists(manifestPath)) {
403
+ await rm(manifestPath, { force: true });
404
+ removed.push("manifest");
405
+ }
406
+ if (await exists(batPath)) {
407
+ await rm(batPath, { force: true });
408
+ removed.push("launcher");
409
+ }
410
+ } else {
411
+ for (const [label, browserDir] of posixBrowsers()) {
412
+ if (!(await exists(browserDir))) {
413
+ continue;
414
+ }
415
+ const manifestPath = join(browserDir, "NativeMessagingHosts", `${HOST_NAME}.json`);
416
+ if (await exists(manifestPath)) {
417
+ await rm(manifestPath, { force: true });
418
+ removed.push(`manifest:${label}`);
419
+ }
420
+ }
421
+ }
422
+
423
+ const hostScriptPath = join(installDir, "llmnesia-claude-host.mjs");
424
+ if (await exists(hostScriptPath)) {
425
+ await rm(hostScriptPath, { force: true });
426
+ removed.push("host-script");
427
+ }
428
+
429
+ return { removed, corpusRoot };
430
+ }
431
+
432
+ // This file is a pure module: importing it must have no side effects. The CLI
433
+ // lives in ./cli.mjs.
434
+ //
435
+ // It used to end with an `import.meta.url === file://${process.argv[1]}`
436
+ // self-execution guard. That guard is not bundler-safe: once this file is
437
+ // inlined into another bundle, import.meta.url becomes the *bundle's* URL, so
438
+ // the guard reads as true and the installer CLI runs on every invocation of
439
+ // the host program — parsing that program's own argv as extension ids and
440
+ // writing them into allowed_origins. Splitting the entry point out removes the
441
+ // failure mode rather than trying to detect it.