@llmnesia/mcp 0.1.1 → 0.1.2

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.
@@ -0,0 +1,3877 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __llmnesiaCreateRequire } from "node:module";
3
+ const require = __llmnesiaCreateRequire(import.meta.url);
4
+ import {
5
+ Corpus,
6
+ SearchIndex,
7
+ deleteIndexDb,
8
+ drainInbox,
9
+ ingestFile,
10
+ openSearchIndex,
11
+ resolveCorpusDir
12
+ } from "./chunk-7BW63ZTP.js";
13
+ import {
14
+ VERSION,
15
+ __commonJS,
16
+ __require,
17
+ __toESM
18
+ } from "./chunk-BQM5Q4XX.js";
19
+
20
+ // ../node_modules/isexe/windows.js
21
+ var require_windows = __commonJS({
22
+ "../node_modules/isexe/windows.js"(exports, module) {
23
+ "use strict";
24
+ module.exports = isexe;
25
+ isexe.sync = sync;
26
+ var fs = __require("fs");
27
+ function checkPathExt(path, options) {
28
+ var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
29
+ if (!pathext) {
30
+ return true;
31
+ }
32
+ pathext = pathext.split(";");
33
+ if (pathext.indexOf("") !== -1) {
34
+ return true;
35
+ }
36
+ for (var i = 0; i < pathext.length; i++) {
37
+ var p = pathext[i].toLowerCase();
38
+ if (p && path.substr(-p.length).toLowerCase() === p) {
39
+ return true;
40
+ }
41
+ }
42
+ return false;
43
+ }
44
+ function checkStat(stat6, path, options) {
45
+ if (!stat6.isSymbolicLink() && !stat6.isFile()) {
46
+ return false;
47
+ }
48
+ return checkPathExt(path, options);
49
+ }
50
+ function isexe(path, options, cb) {
51
+ fs.stat(path, function(er, stat6) {
52
+ cb(er, er ? false : checkStat(stat6, path, options));
53
+ });
54
+ }
55
+ function sync(path, options) {
56
+ return checkStat(fs.statSync(path), path, options);
57
+ }
58
+ }
59
+ });
60
+
61
+ // ../node_modules/isexe/mode.js
62
+ var require_mode = __commonJS({
63
+ "../node_modules/isexe/mode.js"(exports, module) {
64
+ "use strict";
65
+ module.exports = isexe;
66
+ isexe.sync = sync;
67
+ var fs = __require("fs");
68
+ function isexe(path, options, cb) {
69
+ fs.stat(path, function(er, stat6) {
70
+ cb(er, er ? false : checkStat(stat6, options));
71
+ });
72
+ }
73
+ function sync(path, options) {
74
+ return checkStat(fs.statSync(path), options);
75
+ }
76
+ function checkStat(stat6, options) {
77
+ return stat6.isFile() && checkMode(stat6, options);
78
+ }
79
+ function checkMode(stat6, options) {
80
+ var mod = stat6.mode;
81
+ var uid = stat6.uid;
82
+ var gid = stat6.gid;
83
+ var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
84
+ var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
85
+ var u = parseInt("100", 8);
86
+ var g = parseInt("010", 8);
87
+ var o = parseInt("001", 8);
88
+ var ug = u | g;
89
+ var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
90
+ return ret;
91
+ }
92
+ }
93
+ });
94
+
95
+ // ../node_modules/isexe/index.js
96
+ var require_isexe = __commonJS({
97
+ "../node_modules/isexe/index.js"(exports, module) {
98
+ "use strict";
99
+ var fs = __require("fs");
100
+ var core;
101
+ if (process.platform === "win32" || global.TESTING_WINDOWS) {
102
+ core = require_windows();
103
+ } else {
104
+ core = require_mode();
105
+ }
106
+ module.exports = isexe;
107
+ isexe.sync = sync;
108
+ function isexe(path, options, cb) {
109
+ if (typeof options === "function") {
110
+ cb = options;
111
+ options = {};
112
+ }
113
+ if (!cb) {
114
+ if (typeof Promise !== "function") {
115
+ throw new TypeError("callback not provided");
116
+ }
117
+ return new Promise(function(resolve4, reject) {
118
+ isexe(path, options || {}, function(er, is) {
119
+ if (er) {
120
+ reject(er);
121
+ } else {
122
+ resolve4(is);
123
+ }
124
+ });
125
+ });
126
+ }
127
+ core(path, options || {}, function(er, is) {
128
+ if (er) {
129
+ if (er.code === "EACCES" || options && options.ignoreErrors) {
130
+ er = null;
131
+ is = false;
132
+ }
133
+ }
134
+ cb(er, is);
135
+ });
136
+ }
137
+ function sync(path, options) {
138
+ try {
139
+ return core.sync(path, options || {});
140
+ } catch (er) {
141
+ if (options && options.ignoreErrors || er.code === "EACCES") {
142
+ return false;
143
+ } else {
144
+ throw er;
145
+ }
146
+ }
147
+ }
148
+ }
149
+ });
150
+
151
+ // ../node_modules/which/which.js
152
+ var require_which = __commonJS({
153
+ "../node_modules/which/which.js"(exports, module) {
154
+ "use strict";
155
+ var isWindows2 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
156
+ var path = __require("path");
157
+ var COLON = isWindows2 ? ";" : ":";
158
+ var isexe = require_isexe();
159
+ var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
160
+ var getPathInfo = (cmd, opt) => {
161
+ const colon = opt.colon || COLON;
162
+ const pathEnv = cmd.match(/\//) || isWindows2 && cmd.match(/\\/) ? [""] : [
163
+ // windows always checks the cwd first
164
+ ...isWindows2 ? [process.cwd()] : [],
165
+ ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
166
+ "").split(colon)
167
+ ];
168
+ const pathExtExe = isWindows2 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
169
+ const pathExt = isWindows2 ? pathExtExe.split(colon) : [""];
170
+ if (isWindows2) {
171
+ if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
172
+ pathExt.unshift("");
173
+ }
174
+ return {
175
+ pathEnv,
176
+ pathExt,
177
+ pathExtExe
178
+ };
179
+ };
180
+ var which = (cmd, opt, cb) => {
181
+ if (typeof opt === "function") {
182
+ cb = opt;
183
+ opt = {};
184
+ }
185
+ if (!opt)
186
+ opt = {};
187
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
188
+ const found = [];
189
+ const step = (i) => new Promise((resolve4, reject) => {
190
+ if (i === pathEnv.length)
191
+ return opt.all && found.length ? resolve4(found) : reject(getNotFoundError(cmd));
192
+ const ppRaw = pathEnv[i];
193
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
194
+ const pCmd = path.join(pathPart, cmd);
195
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
196
+ resolve4(subStep(p, i, 0));
197
+ });
198
+ const subStep = (p, i, ii) => new Promise((resolve4, reject) => {
199
+ if (ii === pathExt.length)
200
+ return resolve4(step(i + 1));
201
+ const ext = pathExt[ii];
202
+ isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
203
+ if (!er && is) {
204
+ if (opt.all)
205
+ found.push(p + ext);
206
+ else
207
+ return resolve4(p + ext);
208
+ }
209
+ return resolve4(subStep(p, i, ii + 1));
210
+ });
211
+ });
212
+ return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
213
+ };
214
+ var whichSync = (cmd, opt) => {
215
+ opt = opt || {};
216
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
217
+ const found = [];
218
+ for (let i = 0; i < pathEnv.length; i++) {
219
+ const ppRaw = pathEnv[i];
220
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
221
+ const pCmd = path.join(pathPart, cmd);
222
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
223
+ for (let j = 0; j < pathExt.length; j++) {
224
+ const cur = p + pathExt[j];
225
+ try {
226
+ const is = isexe.sync(cur, { pathExt: pathExtExe });
227
+ if (is) {
228
+ if (opt.all)
229
+ found.push(cur);
230
+ else
231
+ return cur;
232
+ }
233
+ } catch (ex) {
234
+ }
235
+ }
236
+ }
237
+ if (opt.all && found.length)
238
+ return found;
239
+ if (opt.nothrow)
240
+ return null;
241
+ throw getNotFoundError(cmd);
242
+ };
243
+ module.exports = which;
244
+ which.sync = whichSync;
245
+ }
246
+ });
247
+
248
+ // ../node_modules/path-key/index.js
249
+ var require_path_key = __commonJS({
250
+ "../node_modules/path-key/index.js"(exports, module) {
251
+ "use strict";
252
+ var pathKey = (options = {}) => {
253
+ const environment = options.env || process.env;
254
+ const platform4 = options.platform || process.platform;
255
+ if (platform4 !== "win32") {
256
+ return "PATH";
257
+ }
258
+ return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
259
+ };
260
+ module.exports = pathKey;
261
+ module.exports.default = pathKey;
262
+ }
263
+ });
264
+
265
+ // ../node_modules/cross-spawn/lib/util/resolveCommand.js
266
+ var require_resolveCommand = __commonJS({
267
+ "../node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
268
+ "use strict";
269
+ var path = __require("path");
270
+ var which = require_which();
271
+ var getPathKey = require_path_key();
272
+ function resolveCommandAttempt(parsed, withoutPathExt) {
273
+ const env = parsed.options.env || process.env;
274
+ const cwd = process.cwd();
275
+ const hasCustomCwd = parsed.options.cwd != null;
276
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
277
+ if (shouldSwitchCwd) {
278
+ try {
279
+ process.chdir(parsed.options.cwd);
280
+ } catch (err) {
281
+ }
282
+ }
283
+ let resolved;
284
+ try {
285
+ resolved = which.sync(parsed.command, {
286
+ path: env[getPathKey({ env })],
287
+ pathExt: withoutPathExt ? path.delimiter : void 0
288
+ });
289
+ } catch (e) {
290
+ } finally {
291
+ if (shouldSwitchCwd) {
292
+ process.chdir(cwd);
293
+ }
294
+ }
295
+ if (resolved) {
296
+ resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
297
+ }
298
+ return resolved;
299
+ }
300
+ function resolveCommand(parsed) {
301
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
302
+ }
303
+ module.exports = resolveCommand;
304
+ }
305
+ });
306
+
307
+ // ../node_modules/cross-spawn/lib/util/escape.js
308
+ var require_escape = __commonJS({
309
+ "../node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
310
+ "use strict";
311
+ var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
312
+ function escapeCommand(arg) {
313
+ arg = arg.replace(metaCharsRegExp, "^$1");
314
+ return arg;
315
+ }
316
+ function escapeArgument(arg, doubleEscapeMetaChars) {
317
+ arg = `${arg}`;
318
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
319
+ arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
320
+ arg = `"${arg}"`;
321
+ arg = arg.replace(metaCharsRegExp, "^$1");
322
+ if (doubleEscapeMetaChars) {
323
+ arg = arg.replace(metaCharsRegExp, "^$1");
324
+ }
325
+ return arg;
326
+ }
327
+ module.exports.command = escapeCommand;
328
+ module.exports.argument = escapeArgument;
329
+ }
330
+ });
331
+
332
+ // ../node_modules/shebang-regex/index.js
333
+ var require_shebang_regex = __commonJS({
334
+ "../node_modules/shebang-regex/index.js"(exports, module) {
335
+ "use strict";
336
+ module.exports = /^#!(.*)/;
337
+ }
338
+ });
339
+
340
+ // ../node_modules/shebang-command/index.js
341
+ var require_shebang_command = __commonJS({
342
+ "../node_modules/shebang-command/index.js"(exports, module) {
343
+ "use strict";
344
+ var shebangRegex = require_shebang_regex();
345
+ module.exports = (string = "") => {
346
+ const match = string.match(shebangRegex);
347
+ if (!match) {
348
+ return null;
349
+ }
350
+ const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
351
+ const binary = path.split("/").pop();
352
+ if (binary === "env") {
353
+ return argument;
354
+ }
355
+ return argument ? `${binary} ${argument}` : binary;
356
+ };
357
+ }
358
+ });
359
+
360
+ // ../node_modules/cross-spawn/lib/util/readShebang.js
361
+ var require_readShebang = __commonJS({
362
+ "../node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
363
+ "use strict";
364
+ var fs = __require("fs");
365
+ var shebangCommand = require_shebang_command();
366
+ function readShebang(command) {
367
+ const size = 150;
368
+ const buffer = Buffer.alloc(size);
369
+ let fd;
370
+ try {
371
+ fd = fs.openSync(command, "r");
372
+ fs.readSync(fd, buffer, 0, size, 0);
373
+ fs.closeSync(fd);
374
+ } catch (e) {
375
+ }
376
+ return shebangCommand(buffer.toString());
377
+ }
378
+ module.exports = readShebang;
379
+ }
380
+ });
381
+
382
+ // ../node_modules/cross-spawn/lib/parse.js
383
+ var require_parse = __commonJS({
384
+ "../node_modules/cross-spawn/lib/parse.js"(exports, module) {
385
+ "use strict";
386
+ var path = __require("path");
387
+ var resolveCommand = require_resolveCommand();
388
+ var escape = require_escape();
389
+ var readShebang = require_readShebang();
390
+ var isWin = process.platform === "win32";
391
+ var isExecutableRegExp = /\.(?:com|exe)$/i;
392
+ var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
393
+ function detectShebang(parsed) {
394
+ parsed.file = resolveCommand(parsed);
395
+ const shebang = parsed.file && readShebang(parsed.file);
396
+ if (shebang) {
397
+ parsed.args.unshift(parsed.file);
398
+ parsed.command = shebang;
399
+ return resolveCommand(parsed);
400
+ }
401
+ return parsed.file;
402
+ }
403
+ function parseNonShell(parsed) {
404
+ if (!isWin) {
405
+ return parsed;
406
+ }
407
+ const commandFile = detectShebang(parsed);
408
+ const needsShell = !isExecutableRegExp.test(commandFile);
409
+ if (parsed.options.forceShell || needsShell) {
410
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
411
+ parsed.command = path.normalize(parsed.command);
412
+ parsed.command = escape.command(parsed.command);
413
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
414
+ const shellCommand = [parsed.command].concat(parsed.args).join(" ");
415
+ parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
416
+ parsed.command = process.env.comspec || "cmd.exe";
417
+ parsed.options.windowsVerbatimArguments = true;
418
+ }
419
+ return parsed;
420
+ }
421
+ function parse(command, args, options) {
422
+ if (args && !Array.isArray(args)) {
423
+ options = args;
424
+ args = null;
425
+ }
426
+ args = args ? args.slice(0) : [];
427
+ options = Object.assign({}, options);
428
+ const parsed = {
429
+ command,
430
+ args,
431
+ options,
432
+ file: void 0,
433
+ original: {
434
+ command,
435
+ args
436
+ }
437
+ };
438
+ return options.shell ? parsed : parseNonShell(parsed);
439
+ }
440
+ module.exports = parse;
441
+ }
442
+ });
443
+
444
+ // ../node_modules/cross-spawn/lib/enoent.js
445
+ var require_enoent = __commonJS({
446
+ "../node_modules/cross-spawn/lib/enoent.js"(exports, module) {
447
+ "use strict";
448
+ var isWin = process.platform === "win32";
449
+ function notFoundError(original, syscall) {
450
+ return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
451
+ code: "ENOENT",
452
+ errno: "ENOENT",
453
+ syscall: `${syscall} ${original.command}`,
454
+ path: original.command,
455
+ spawnargs: original.args
456
+ });
457
+ }
458
+ function hookChildProcess(cp2, parsed) {
459
+ if (!isWin) {
460
+ return;
461
+ }
462
+ const originalEmit = cp2.emit;
463
+ cp2.emit = function(name, arg1) {
464
+ if (name === "exit") {
465
+ const err = verifyENOENT(arg1, parsed);
466
+ if (err) {
467
+ return originalEmit.call(cp2, "error", err);
468
+ }
469
+ }
470
+ return originalEmit.apply(cp2, arguments);
471
+ };
472
+ }
473
+ function verifyENOENT(status, parsed) {
474
+ if (isWin && status === 1 && !parsed.file) {
475
+ return notFoundError(parsed.original, "spawn");
476
+ }
477
+ return null;
478
+ }
479
+ function verifyENOENTSync(status, parsed) {
480
+ if (isWin && status === 1 && !parsed.file) {
481
+ return notFoundError(parsed.original, "spawnSync");
482
+ }
483
+ return null;
484
+ }
485
+ module.exports = {
486
+ hookChildProcess,
487
+ verifyENOENT,
488
+ verifyENOENTSync,
489
+ notFoundError
490
+ };
491
+ }
492
+ });
493
+
494
+ // ../node_modules/cross-spawn/index.js
495
+ var require_cross_spawn = __commonJS({
496
+ "../node_modules/cross-spawn/index.js"(exports, module) {
497
+ "use strict";
498
+ var cp2 = __require("child_process");
499
+ var parse = require_parse();
500
+ var enoent = require_enoent();
501
+ function spawn(command, args, options) {
502
+ const parsed = parse(command, args, options);
503
+ const spawned = cp2.spawn(parsed.command, parsed.args, parsed.options);
504
+ enoent.hookChildProcess(spawned, parsed);
505
+ return spawned;
506
+ }
507
+ function spawnSync(command, args, options) {
508
+ const parsed = parse(command, args, options);
509
+ const result = cp2.spawnSync(parsed.command, parsed.args, parsed.options);
510
+ result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
511
+ return result;
512
+ }
513
+ module.exports = spawn;
514
+ module.exports.spawn = spawn;
515
+ module.exports.sync = spawnSync;
516
+ module.exports._parse = parse;
517
+ module.exports._enoent = enoent;
518
+ }
519
+ });
520
+
521
+ // src/cli.ts
522
+ import { createInterface } from "readline/promises";
523
+
524
+ // ../packages/native-host/install.mjs
525
+ import { execFile } from "child_process";
526
+ import { chmod, mkdir, readFile, rm, stat, writeFile } from "fs/promises";
527
+ import { homedir, platform } from "os";
528
+ import { dirname, join, resolve } from "path";
529
+ import { fileURLToPath } from "url";
530
+ import { promisify } from "util";
531
+ var execFileAsync = promisify(execFile);
532
+ var HOST_NAME = "com.llmnesia.claude_code";
533
+ var STORE_EXTENSION_ID = "leekfgbdojiaabifbjbbgiiclannjdkf";
534
+ var here = dirname(fileURLToPath(import.meta.url));
535
+ var home = homedir();
536
+ var osPlatform = process.env.LLMNESIA_FAKE_PLATFORM || platform();
537
+ function expandHome(p) {
538
+ if (p === "~") {
539
+ return home;
540
+ }
541
+ if (p.startsWith("~/") || p.startsWith("~\\")) {
542
+ return resolve(home, p.slice(2));
543
+ }
544
+ return resolve(p);
545
+ }
546
+ function resolveCorpusDir2(explicit) {
547
+ const raw = explicit ?? process.env.LLMNESIA_CORPUS_DIR ?? "~/.llmnesia/corpus";
548
+ return expandHome(raw);
549
+ }
550
+ async function exists(path) {
551
+ try {
552
+ await stat(path);
553
+ return true;
554
+ } catch {
555
+ return false;
556
+ }
557
+ }
558
+ async function supportedBrowserCount(isWindows2) {
559
+ const candidates = isWindows2 ? windowsBrowsers().map(([, path]) => path) : posixBrowsers().map(([, path]) => path);
560
+ let count = 0;
561
+ for (const path of candidates) {
562
+ if (await exists(path)) {
563
+ count += 1;
564
+ }
565
+ }
566
+ return count;
567
+ }
568
+ async function readExistingConfig(configPath) {
569
+ let raw;
570
+ try {
571
+ raw = await readFile(configPath, "utf8");
572
+ } catch (err) {
573
+ if (err && typeof err === "object" && err.code === "ENOENT") {
574
+ return null;
575
+ }
576
+ throw new Error(`Could not read existing native-host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
577
+ }
578
+ let parsed;
579
+ try {
580
+ parsed = JSON.parse(raw);
581
+ } catch (err) {
582
+ throw new Error(
583
+ `Could not parse existing native-host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}. The file was left unchanged.`
584
+ );
585
+ }
586
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
587
+ throw new Error(`Existing native-host config at ${configPath} must be a JSON object. The file was left unchanged.`);
588
+ }
589
+ if ("corpusRoot" in parsed && typeof parsed.corpusRoot !== "string") {
590
+ throw new Error(`Existing native-host config at ${configPath} has an invalid corpusRoot. The file was left unchanged.`);
591
+ }
592
+ return parsed;
593
+ }
594
+ function posixBrowsers(homeDir = home, forPlatform = osPlatform) {
595
+ if (forPlatform === "darwin") {
596
+ const base2 = join(homeDir, "Library", "Application Support");
597
+ return [
598
+ ["Brave", join(base2, "BraveSoftware", "Brave-Browser")],
599
+ ["Chrome", join(base2, "Google", "Chrome")],
600
+ ["Edge", join(base2, "Microsoft Edge")],
601
+ ["Chromium", join(base2, "Chromium")]
602
+ ];
603
+ }
604
+ const base = join(homeDir, ".config");
605
+ return [
606
+ ["Brave", join(base, "BraveSoftware", "Brave-Browser")],
607
+ ["Chrome", join(base, "google-chrome")],
608
+ ["Edge", join(base, "microsoft-edge")],
609
+ ["Chromium", join(base, "chromium")]
610
+ ];
611
+ }
612
+ async function installPosix(manifestBase, hostPath) {
613
+ const manifest = { ...manifestBase, path: hostPath };
614
+ let installed = 0;
615
+ for (const [label, browserDir] of posixBrowsers()) {
616
+ if (!await exists(browserDir)) {
617
+ continue;
618
+ }
619
+ const dir = join(browserDir, "NativeMessagingHosts");
620
+ await mkdir(dir, { recursive: true });
621
+ await writeFile(join(dir, `${HOST_NAME}.json`), `${JSON.stringify(manifest, null, 2)}
622
+ `, "utf8");
623
+ console.log(`Manifest \u2192 ${label}: ${join(dir, `${HOST_NAME}.json`)}`);
624
+ installed += 1;
625
+ }
626
+ return installed;
627
+ }
628
+ function windowsBrowsers() {
629
+ const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local");
630
+ return [
631
+ ["Brave", join(localAppData, "BraveSoftware", "Brave-Browser", "User Data"), "Software\\BraveSoftware\\Brave-Browser"],
632
+ ["Chrome", join(localAppData, "Google", "Chrome", "User Data"), "Software\\Google\\Chrome"],
633
+ ["Edge", join(localAppData, "Microsoft", "Edge", "User Data"), "Software\\Microsoft\\Edge"],
634
+ ["Chromium", join(localAppData, "Chromium", "User Data"), "Software\\Chromium"]
635
+ ];
636
+ }
637
+ async function installWindows(manifestBase, hostPath, installDir) {
638
+ const batPath = join(installDir, "llmnesia-claude-host.bat");
639
+ await writeFile(batPath, `@echo off\r
640
+ "${process.execPath}" "${hostPath}" %*\r
641
+ `, "utf8");
642
+ console.log(`Launcher \u2192 ${batPath}`);
643
+ const manifest = { ...manifestBase, path: batPath };
644
+ const manifestPath = join(installDir, `${HOST_NAME}.json`);
645
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}
646
+ `, "utf8");
647
+ console.log(`Manifest \u2192 ${manifestPath}`);
648
+ let installed = 0;
649
+ for (const [label, userDataDir, vendorKey] of windowsBrowsers()) {
650
+ if (!await exists(userDataDir)) {
651
+ continue;
652
+ }
653
+ const key = `HKCU\\${vendorKey}\\NativeMessagingHosts\\${HOST_NAME}`;
654
+ const regExe = join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
655
+ await execFileAsync(regExe, ["add", key, "/ve", "/t", "REG_SZ", "/d", manifestPath, "/f"]);
656
+ console.log(`Registry \u2192 ${label}: ${key}`);
657
+ installed += 1;
658
+ }
659
+ return installed;
660
+ }
661
+ async function installNativeHost({ ids = [], corpus, force = false } = {}) {
662
+ const isWindows2 = osPlatform === "win32";
663
+ const invalidId = ids.find((id) => !/^[a-p]{32}$/.test(id));
664
+ if (invalidId) {
665
+ throw new Error(`Invalid Chromium extension id: ${JSON.stringify(invalidId)}. Expected 32 letters from a through p.`);
666
+ }
667
+ const allIds = [.../* @__PURE__ */ new Set([STORE_EXTENSION_ID, ...ids])];
668
+ const allowedOrigins = allIds.map((id) => `chrome-extension://${id}/`);
669
+ if (await supportedBrowserCount(isWindows2) === 0) {
670
+ throw new Error("No supported Chromium browser found (Chrome, Brave, Edge, or Chromium) \u2014 the browser helper was not installed.");
671
+ }
672
+ const installDir = join(home, ".llmnesia");
673
+ const configPath = join(installDir, "config.json");
674
+ const existing = await readExistingConfig(configPath);
675
+ await mkdir(installDir, { recursive: true });
676
+ const hostSource = await readFile(join(here, "llmnesia-claude-host.mjs"), "utf8");
677
+ const hosted = isWindows2 ? hostSource : hostSource.replace(/^#![^\n]*\n/, `#!${process.execPath}
678
+ `);
679
+ const hostPath = join(installDir, "llmnesia-claude-host.mjs");
680
+ await writeFile(hostPath, hosted, "utf8");
681
+ if (!isWindows2) {
682
+ await chmod(hostPath, 493);
683
+ }
684
+ console.log(`Host script \u2192 ${hostPath}`);
685
+ const manifestBase = {
686
+ name: HOST_NAME,
687
+ description: "LLMnesia \u2014 reads local Claude Code sessions",
688
+ type: "stdio",
689
+ allowed_origins: allowedOrigins
690
+ };
691
+ const installedCount = isWindows2 ? await installWindows(manifestBase, hostPath, installDir) : await installPosix(manifestBase, hostPath);
692
+ const corpusRoot = resolveCorpusDir2(corpus);
693
+ const existingRoot = existing && typeof existing.corpusRoot === "string" ? existing.corpusRoot : null;
694
+ let corpusRootChanged = true;
695
+ if (existingRoot && existingRoot !== corpusRoot && !force) {
696
+ corpusRootChanged = false;
697
+ console.log(`Corpus config kept \u2192 ${configPath}`);
698
+ console.log(` already points at: ${existingRoot}`);
699
+ console.log(` to change it: re-run with --corpus <dir> --force`);
700
+ } else {
701
+ await writeFile(configPath, `${JSON.stringify({ corpusRoot }, null, 2)}
702
+ `, { encoding: "utf8", mode: 384 });
703
+ await chmod(configPath, 384);
704
+ console.log(`Corpus config \u2192 ${configPath}`);
705
+ console.log(` corpus root: ${corpusRoot}`);
706
+ }
707
+ console.log(`
708
+ Done. Allowed extension id(s): ${allIds.join(", ")}`);
709
+ console.log("Fully quit and reopen the browser, then open LLMnesia Settings.");
710
+ return {
711
+ installedCount,
712
+ allowedIds: allIds,
713
+ configPath,
714
+ corpusRoot: existingRoot && !corpusRootChanged ? existingRoot : corpusRoot,
715
+ corpusRootChanged
716
+ };
717
+ }
718
+ async function uninstallNativeHost() {
719
+ const isWindows2 = osPlatform === "win32";
720
+ const removed = [];
721
+ const installDir = join(home, ".llmnesia");
722
+ const configPath = join(installDir, "config.json");
723
+ let corpusRoot = null;
724
+ try {
725
+ const config = await readExistingConfig(configPath);
726
+ corpusRoot = config && typeof config.corpusRoot === "string" ? config.corpusRoot : null;
727
+ } catch {
728
+ }
729
+ if (isWindows2) {
730
+ const manifestPath = join(installDir, `${HOST_NAME}.json`);
731
+ const batPath = join(installDir, "llmnesia-claude-host.bat");
732
+ for (const [label, _userDataDir, vendorKey] of windowsBrowsers()) {
733
+ const key = `HKCU\\${vendorKey}\\NativeMessagingHosts\\${HOST_NAME}`;
734
+ const regExe = join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
735
+ try {
736
+ await execFileAsync(regExe, ["delete", key, "/f"]);
737
+ removed.push(`registry:${label}`);
738
+ } catch {
739
+ }
740
+ }
741
+ if (await exists(manifestPath)) {
742
+ await rm(manifestPath, { force: true });
743
+ removed.push("manifest");
744
+ }
745
+ if (await exists(batPath)) {
746
+ await rm(batPath, { force: true });
747
+ removed.push("launcher");
748
+ }
749
+ } else {
750
+ for (const [label, browserDir] of posixBrowsers()) {
751
+ if (!await exists(browserDir)) {
752
+ continue;
753
+ }
754
+ const manifestPath = join(browserDir, "NativeMessagingHosts", `${HOST_NAME}.json`);
755
+ if (await exists(manifestPath)) {
756
+ await rm(manifestPath, { force: true });
757
+ removed.push(`manifest:${label}`);
758
+ }
759
+ }
760
+ }
761
+ const hostScriptPath = join(installDir, "llmnesia-claude-host.mjs");
762
+ if (await exists(hostScriptPath)) {
763
+ await rm(hostScriptPath, { force: true });
764
+ removed.push("host-script");
765
+ }
766
+ return { removed, corpusRoot };
767
+ }
768
+
769
+ // src/args.ts
770
+ var OPTION_ALIASES = {
771
+ c: "corpus",
772
+ n: "limit",
773
+ v: "version",
774
+ h: "help",
775
+ y: "yes"
776
+ };
777
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["force", "yes", "version", "help"]);
778
+ var VALUE_OPTIONS = /* @__PURE__ */ new Set(["corpus", "limit", "platform", "title", "from", "to"]);
779
+ function parseArgs(argv) {
780
+ const positionals = [];
781
+ const options = {};
782
+ const flags = /* @__PURE__ */ new Set();
783
+ let optionsEnded = false;
784
+ for (let i = 0; i < argv.length; i += 1) {
785
+ const arg = argv[i];
786
+ if (!optionsEnded && arg === "--") {
787
+ optionsEnded = true;
788
+ } else if (!optionsEnded && arg.startsWith("--") && arg.includes("=")) {
789
+ const eq = arg.indexOf("=");
790
+ const key = arg.slice(2, eq);
791
+ const value = arg.slice(eq + 1);
792
+ if (!VALUE_OPTIONS.has(key)) {
793
+ throw new Error(`Unknown or valueless option: --${key}`);
794
+ }
795
+ if (!value) {
796
+ throw new Error(`Option --${key} requires a value`);
797
+ }
798
+ options[key] = value;
799
+ } else if (!optionsEnded && arg.startsWith("--")) {
800
+ const key = arg.slice(2);
801
+ if (BOOLEAN_FLAGS.has(key)) {
802
+ flags.add(key);
803
+ } else if (!VALUE_OPTIONS.has(key)) {
804
+ throw new Error(`Unknown option: --${key}`);
805
+ } else {
806
+ const value = argv[++i];
807
+ if (!value || value.startsWith("-")) {
808
+ throw new Error(`Option --${key} requires a value`);
809
+ }
810
+ options[key] = value;
811
+ }
812
+ } else if (!optionsEnded && arg.startsWith("-") && arg.length === 2) {
813
+ const key = OPTION_ALIASES[arg.slice(1)] ?? arg.slice(1);
814
+ if (BOOLEAN_FLAGS.has(key)) {
815
+ flags.add(key);
816
+ } else if (!VALUE_OPTIONS.has(key)) {
817
+ throw new Error(`Unknown option: ${arg}`);
818
+ } else {
819
+ const value = argv[++i];
820
+ if (!value || value.startsWith("-")) {
821
+ throw new Error(`Option ${arg} requires a value`);
822
+ }
823
+ options[key] = value;
824
+ }
825
+ } else {
826
+ positionals.push(arg);
827
+ }
828
+ }
829
+ return { command: positionals[0], positionals: positionals.slice(1), options, flags };
830
+ }
831
+
832
+ // ../node_modules/chokidar/esm/index.js
833
+ import { stat as statcb } from "fs";
834
+ import { stat as stat4, readdir as readdir2 } from "fs/promises";
835
+ import { EventEmitter } from "events";
836
+ import * as sysPath2 from "path";
837
+
838
+ // ../node_modules/readdirp/esm/index.js
839
+ import { stat as stat2, lstat, readdir, realpath } from "fs/promises";
840
+ import { Readable } from "stream";
841
+ import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "path";
842
+ var EntryTypes = {
843
+ FILE_TYPE: "files",
844
+ DIR_TYPE: "directories",
845
+ FILE_DIR_TYPE: "files_directories",
846
+ EVERYTHING_TYPE: "all"
847
+ };
848
+ var defaultOptions = {
849
+ root: ".",
850
+ fileFilter: (_entryInfo) => true,
851
+ directoryFilter: (_entryInfo) => true,
852
+ type: EntryTypes.FILE_TYPE,
853
+ lstat: false,
854
+ depth: 2147483648,
855
+ alwaysStat: false,
856
+ highWaterMark: 4096
857
+ };
858
+ Object.freeze(defaultOptions);
859
+ var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
860
+ var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
861
+ var ALL_TYPES = [
862
+ EntryTypes.DIR_TYPE,
863
+ EntryTypes.EVERYTHING_TYPE,
864
+ EntryTypes.FILE_DIR_TYPE,
865
+ EntryTypes.FILE_TYPE
866
+ ];
867
+ var DIR_TYPES = /* @__PURE__ */ new Set([
868
+ EntryTypes.DIR_TYPE,
869
+ EntryTypes.EVERYTHING_TYPE,
870
+ EntryTypes.FILE_DIR_TYPE
871
+ ]);
872
+ var FILE_TYPES = /* @__PURE__ */ new Set([
873
+ EntryTypes.EVERYTHING_TYPE,
874
+ EntryTypes.FILE_DIR_TYPE,
875
+ EntryTypes.FILE_TYPE
876
+ ]);
877
+ var isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
878
+ var wantBigintFsStats = process.platform === "win32";
879
+ var emptyFn = (_entryInfo) => true;
880
+ var normalizeFilter = (filter) => {
881
+ if (filter === void 0)
882
+ return emptyFn;
883
+ if (typeof filter === "function")
884
+ return filter;
885
+ if (typeof filter === "string") {
886
+ const fl = filter.trim();
887
+ return (entry) => entry.basename === fl;
888
+ }
889
+ if (Array.isArray(filter)) {
890
+ const trItems = filter.map((item) => item.trim());
891
+ return (entry) => trItems.some((f) => entry.basename === f);
892
+ }
893
+ return emptyFn;
894
+ };
895
+ var ReaddirpStream = class extends Readable {
896
+ constructor(options = {}) {
897
+ super({
898
+ objectMode: true,
899
+ autoDestroy: true,
900
+ highWaterMark: options.highWaterMark
901
+ });
902
+ const opts = { ...defaultOptions, ...options };
903
+ const { root, type } = opts;
904
+ this._fileFilter = normalizeFilter(opts.fileFilter);
905
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
906
+ const statMethod = opts.lstat ? lstat : stat2;
907
+ if (wantBigintFsStats) {
908
+ this._stat = (path) => statMethod(path, { bigint: true });
909
+ } else {
910
+ this._stat = statMethod;
911
+ }
912
+ this._maxDepth = opts.depth ?? defaultOptions.depth;
913
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
914
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
915
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
916
+ this._root = presolve(root);
917
+ this._isDirent = !opts.alwaysStat;
918
+ this._statsProp = this._isDirent ? "dirent" : "stats";
919
+ this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
920
+ this.parents = [this._exploreDir(root, 1)];
921
+ this.reading = false;
922
+ this.parent = void 0;
923
+ }
924
+ async _read(batch) {
925
+ if (this.reading)
926
+ return;
927
+ this.reading = true;
928
+ try {
929
+ while (!this.destroyed && batch > 0) {
930
+ const par = this.parent;
931
+ const fil = par && par.files;
932
+ if (fil && fil.length > 0) {
933
+ const { path, depth } = par;
934
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
935
+ const awaited = await Promise.all(slice);
936
+ for (const entry of awaited) {
937
+ if (!entry)
938
+ continue;
939
+ if (this.destroyed)
940
+ return;
941
+ const entryType = await this._getEntryType(entry);
942
+ if (entryType === "directory" && this._directoryFilter(entry)) {
943
+ if (depth <= this._maxDepth) {
944
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
945
+ }
946
+ if (this._wantsDir) {
947
+ this.push(entry);
948
+ batch--;
949
+ }
950
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
951
+ if (this._wantsFile) {
952
+ this.push(entry);
953
+ batch--;
954
+ }
955
+ }
956
+ }
957
+ } else {
958
+ const parent = this.parents.pop();
959
+ if (!parent) {
960
+ this.push(null);
961
+ break;
962
+ }
963
+ this.parent = await parent;
964
+ if (this.destroyed)
965
+ return;
966
+ }
967
+ }
968
+ } catch (error) {
969
+ this.destroy(error);
970
+ } finally {
971
+ this.reading = false;
972
+ }
973
+ }
974
+ async _exploreDir(path, depth) {
975
+ let files;
976
+ try {
977
+ files = await readdir(path, this._rdOptions);
978
+ } catch (error) {
979
+ this._onError(error);
980
+ }
981
+ return { files, depth, path };
982
+ }
983
+ async _formatEntry(dirent, path) {
984
+ let entry;
985
+ const basename3 = this._isDirent ? dirent.name : dirent;
986
+ try {
987
+ const fullPath = presolve(pjoin(path, basename3));
988
+ entry = { path: prelative(this._root, fullPath), fullPath, basename: basename3 };
989
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
990
+ } catch (err) {
991
+ this._onError(err);
992
+ return;
993
+ }
994
+ return entry;
995
+ }
996
+ _onError(err) {
997
+ if (isNormalFlowError(err) && !this.destroyed) {
998
+ this.emit("warn", err);
999
+ } else {
1000
+ this.destroy(err);
1001
+ }
1002
+ }
1003
+ async _getEntryType(entry) {
1004
+ if (!entry && this._statsProp in entry) {
1005
+ return "";
1006
+ }
1007
+ const stats = entry[this._statsProp];
1008
+ if (stats.isFile())
1009
+ return "file";
1010
+ if (stats.isDirectory())
1011
+ return "directory";
1012
+ if (stats && stats.isSymbolicLink()) {
1013
+ const full = entry.fullPath;
1014
+ try {
1015
+ const entryRealPath = await realpath(full);
1016
+ const entryRealPathStats = await lstat(entryRealPath);
1017
+ if (entryRealPathStats.isFile()) {
1018
+ return "file";
1019
+ }
1020
+ if (entryRealPathStats.isDirectory()) {
1021
+ const len = entryRealPath.length;
1022
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
1023
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
1024
+ recursiveError.code = RECURSIVE_ERROR_CODE;
1025
+ return this._onError(recursiveError);
1026
+ }
1027
+ return "directory";
1028
+ }
1029
+ } catch (error) {
1030
+ this._onError(error);
1031
+ return "";
1032
+ }
1033
+ }
1034
+ }
1035
+ _includeAsFile(entry) {
1036
+ const stats = entry && entry[this._statsProp];
1037
+ return stats && this._wantsEverything && !stats.isDirectory();
1038
+ }
1039
+ };
1040
+ function readdirp(root, options = {}) {
1041
+ let type = options.entryType || options.type;
1042
+ if (type === "both")
1043
+ type = EntryTypes.FILE_DIR_TYPE;
1044
+ if (type)
1045
+ options.type = type;
1046
+ if (!root) {
1047
+ throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
1048
+ } else if (typeof root !== "string") {
1049
+ throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
1050
+ } else if (type && !ALL_TYPES.includes(type)) {
1051
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
1052
+ }
1053
+ options.root = root;
1054
+ return new ReaddirpStream(options);
1055
+ }
1056
+
1057
+ // ../node_modules/chokidar/esm/handler.js
1058
+ import { watchFile, unwatchFile, watch as fs_watch } from "fs";
1059
+ import { open, stat as stat3, lstat as lstat2, realpath as fsrealpath } from "fs/promises";
1060
+ import * as sysPath from "path";
1061
+ import { type as osType } from "os";
1062
+ var STR_DATA = "data";
1063
+ var STR_END = "end";
1064
+ var STR_CLOSE = "close";
1065
+ var EMPTY_FN = () => {
1066
+ };
1067
+ var pl = process.platform;
1068
+ var isWindows = pl === "win32";
1069
+ var isMacos = pl === "darwin";
1070
+ var isLinux = pl === "linux";
1071
+ var isFreeBSD = pl === "freebsd";
1072
+ var isIBMi = osType() === "OS400";
1073
+ var EVENTS = {
1074
+ ALL: "all",
1075
+ READY: "ready",
1076
+ ADD: "add",
1077
+ CHANGE: "change",
1078
+ ADD_DIR: "addDir",
1079
+ UNLINK: "unlink",
1080
+ UNLINK_DIR: "unlinkDir",
1081
+ RAW: "raw",
1082
+ ERROR: "error"
1083
+ };
1084
+ var EV = EVENTS;
1085
+ var THROTTLE_MODE_WATCH = "watch";
1086
+ var statMethods = { lstat: lstat2, stat: stat3 };
1087
+ var KEY_LISTENERS = "listeners";
1088
+ var KEY_ERR = "errHandlers";
1089
+ var KEY_RAW = "rawEmitters";
1090
+ var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
1091
+ var binaryExtensions = /* @__PURE__ */ new Set([
1092
+ "3dm",
1093
+ "3ds",
1094
+ "3g2",
1095
+ "3gp",
1096
+ "7z",
1097
+ "a",
1098
+ "aac",
1099
+ "adp",
1100
+ "afdesign",
1101
+ "afphoto",
1102
+ "afpub",
1103
+ "ai",
1104
+ "aif",
1105
+ "aiff",
1106
+ "alz",
1107
+ "ape",
1108
+ "apk",
1109
+ "appimage",
1110
+ "ar",
1111
+ "arj",
1112
+ "asf",
1113
+ "au",
1114
+ "avi",
1115
+ "bak",
1116
+ "baml",
1117
+ "bh",
1118
+ "bin",
1119
+ "bk",
1120
+ "bmp",
1121
+ "btif",
1122
+ "bz2",
1123
+ "bzip2",
1124
+ "cab",
1125
+ "caf",
1126
+ "cgm",
1127
+ "class",
1128
+ "cmx",
1129
+ "cpio",
1130
+ "cr2",
1131
+ "cur",
1132
+ "dat",
1133
+ "dcm",
1134
+ "deb",
1135
+ "dex",
1136
+ "djvu",
1137
+ "dll",
1138
+ "dmg",
1139
+ "dng",
1140
+ "doc",
1141
+ "docm",
1142
+ "docx",
1143
+ "dot",
1144
+ "dotm",
1145
+ "dra",
1146
+ "DS_Store",
1147
+ "dsk",
1148
+ "dts",
1149
+ "dtshd",
1150
+ "dvb",
1151
+ "dwg",
1152
+ "dxf",
1153
+ "ecelp4800",
1154
+ "ecelp7470",
1155
+ "ecelp9600",
1156
+ "egg",
1157
+ "eol",
1158
+ "eot",
1159
+ "epub",
1160
+ "exe",
1161
+ "f4v",
1162
+ "fbs",
1163
+ "fh",
1164
+ "fla",
1165
+ "flac",
1166
+ "flatpak",
1167
+ "fli",
1168
+ "flv",
1169
+ "fpx",
1170
+ "fst",
1171
+ "fvt",
1172
+ "g3",
1173
+ "gh",
1174
+ "gif",
1175
+ "graffle",
1176
+ "gz",
1177
+ "gzip",
1178
+ "h261",
1179
+ "h263",
1180
+ "h264",
1181
+ "icns",
1182
+ "ico",
1183
+ "ief",
1184
+ "img",
1185
+ "ipa",
1186
+ "iso",
1187
+ "jar",
1188
+ "jpeg",
1189
+ "jpg",
1190
+ "jpgv",
1191
+ "jpm",
1192
+ "jxr",
1193
+ "key",
1194
+ "ktx",
1195
+ "lha",
1196
+ "lib",
1197
+ "lvp",
1198
+ "lz",
1199
+ "lzh",
1200
+ "lzma",
1201
+ "lzo",
1202
+ "m3u",
1203
+ "m4a",
1204
+ "m4v",
1205
+ "mar",
1206
+ "mdi",
1207
+ "mht",
1208
+ "mid",
1209
+ "midi",
1210
+ "mj2",
1211
+ "mka",
1212
+ "mkv",
1213
+ "mmr",
1214
+ "mng",
1215
+ "mobi",
1216
+ "mov",
1217
+ "movie",
1218
+ "mp3",
1219
+ "mp4",
1220
+ "mp4a",
1221
+ "mpeg",
1222
+ "mpg",
1223
+ "mpga",
1224
+ "mxu",
1225
+ "nef",
1226
+ "npx",
1227
+ "numbers",
1228
+ "nupkg",
1229
+ "o",
1230
+ "odp",
1231
+ "ods",
1232
+ "odt",
1233
+ "oga",
1234
+ "ogg",
1235
+ "ogv",
1236
+ "otf",
1237
+ "ott",
1238
+ "pages",
1239
+ "pbm",
1240
+ "pcx",
1241
+ "pdb",
1242
+ "pdf",
1243
+ "pea",
1244
+ "pgm",
1245
+ "pic",
1246
+ "png",
1247
+ "pnm",
1248
+ "pot",
1249
+ "potm",
1250
+ "potx",
1251
+ "ppa",
1252
+ "ppam",
1253
+ "ppm",
1254
+ "pps",
1255
+ "ppsm",
1256
+ "ppsx",
1257
+ "ppt",
1258
+ "pptm",
1259
+ "pptx",
1260
+ "psd",
1261
+ "pya",
1262
+ "pyc",
1263
+ "pyo",
1264
+ "pyv",
1265
+ "qt",
1266
+ "rar",
1267
+ "ras",
1268
+ "raw",
1269
+ "resources",
1270
+ "rgb",
1271
+ "rip",
1272
+ "rlc",
1273
+ "rmf",
1274
+ "rmvb",
1275
+ "rpm",
1276
+ "rtf",
1277
+ "rz",
1278
+ "s3m",
1279
+ "s7z",
1280
+ "scpt",
1281
+ "sgi",
1282
+ "shar",
1283
+ "snap",
1284
+ "sil",
1285
+ "sketch",
1286
+ "slk",
1287
+ "smv",
1288
+ "snk",
1289
+ "so",
1290
+ "stl",
1291
+ "suo",
1292
+ "sub",
1293
+ "swf",
1294
+ "tar",
1295
+ "tbz",
1296
+ "tbz2",
1297
+ "tga",
1298
+ "tgz",
1299
+ "thmx",
1300
+ "tif",
1301
+ "tiff",
1302
+ "tlz",
1303
+ "ttc",
1304
+ "ttf",
1305
+ "txz",
1306
+ "udf",
1307
+ "uvh",
1308
+ "uvi",
1309
+ "uvm",
1310
+ "uvp",
1311
+ "uvs",
1312
+ "uvu",
1313
+ "viv",
1314
+ "vob",
1315
+ "war",
1316
+ "wav",
1317
+ "wax",
1318
+ "wbmp",
1319
+ "wdp",
1320
+ "weba",
1321
+ "webm",
1322
+ "webp",
1323
+ "whl",
1324
+ "wim",
1325
+ "wm",
1326
+ "wma",
1327
+ "wmv",
1328
+ "wmx",
1329
+ "woff",
1330
+ "woff2",
1331
+ "wrm",
1332
+ "wvx",
1333
+ "xbm",
1334
+ "xif",
1335
+ "xla",
1336
+ "xlam",
1337
+ "xls",
1338
+ "xlsb",
1339
+ "xlsm",
1340
+ "xlsx",
1341
+ "xlt",
1342
+ "xltm",
1343
+ "xltx",
1344
+ "xm",
1345
+ "xmind",
1346
+ "xpi",
1347
+ "xpm",
1348
+ "xwd",
1349
+ "xz",
1350
+ "z",
1351
+ "zip",
1352
+ "zipx"
1353
+ ]);
1354
+ var isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
1355
+ var foreach = (val, fn) => {
1356
+ if (val instanceof Set) {
1357
+ val.forEach(fn);
1358
+ } else {
1359
+ fn(val);
1360
+ }
1361
+ };
1362
+ var addAndConvert = (main2, prop, item) => {
1363
+ let container = main2[prop];
1364
+ if (!(container instanceof Set)) {
1365
+ main2[prop] = container = /* @__PURE__ */ new Set([container]);
1366
+ }
1367
+ container.add(item);
1368
+ };
1369
+ var clearItem = (cont) => (key) => {
1370
+ const set = cont[key];
1371
+ if (set instanceof Set) {
1372
+ set.clear();
1373
+ } else {
1374
+ delete cont[key];
1375
+ }
1376
+ };
1377
+ var delFromSet = (main2, prop, item) => {
1378
+ const container = main2[prop];
1379
+ if (container instanceof Set) {
1380
+ container.delete(item);
1381
+ } else if (container === item) {
1382
+ delete main2[prop];
1383
+ }
1384
+ };
1385
+ var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
1386
+ var FsWatchInstances = /* @__PURE__ */ new Map();
1387
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
1388
+ const handleEvent = (rawEvent, evPath) => {
1389
+ listener(path);
1390
+ emitRaw(rawEvent, evPath, { watchedPath: path });
1391
+ if (evPath && path !== evPath) {
1392
+ fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
1393
+ }
1394
+ };
1395
+ try {
1396
+ return fs_watch(path, {
1397
+ persistent: options.persistent
1398
+ }, handleEvent);
1399
+ } catch (error) {
1400
+ errHandler(error);
1401
+ return void 0;
1402
+ }
1403
+ }
1404
+ var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
1405
+ const cont = FsWatchInstances.get(fullPath);
1406
+ if (!cont)
1407
+ return;
1408
+ foreach(cont[listenerType], (listener) => {
1409
+ listener(val1, val2, val3);
1410
+ });
1411
+ };
1412
+ var setFsWatchListener = (path, fullPath, options, handlers) => {
1413
+ const { listener, errHandler, rawEmitter } = handlers;
1414
+ let cont = FsWatchInstances.get(fullPath);
1415
+ let watcher;
1416
+ if (!options.persistent) {
1417
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
1418
+ if (!watcher)
1419
+ return;
1420
+ return watcher.close.bind(watcher);
1421
+ }
1422
+ if (cont) {
1423
+ addAndConvert(cont, KEY_LISTENERS, listener);
1424
+ addAndConvert(cont, KEY_ERR, errHandler);
1425
+ addAndConvert(cont, KEY_RAW, rawEmitter);
1426
+ } else {
1427
+ watcher = createFsWatchInstance(
1428
+ path,
1429
+ options,
1430
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
1431
+ errHandler,
1432
+ // no need to use broadcast here
1433
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
1434
+ );
1435
+ if (!watcher)
1436
+ return;
1437
+ watcher.on(EV.ERROR, async (error) => {
1438
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
1439
+ if (cont)
1440
+ cont.watcherUnusable = true;
1441
+ if (isWindows && error.code === "EPERM") {
1442
+ try {
1443
+ const fd = await open(path, "r");
1444
+ await fd.close();
1445
+ broadcastErr(error);
1446
+ } catch (err) {
1447
+ }
1448
+ } else {
1449
+ broadcastErr(error);
1450
+ }
1451
+ });
1452
+ cont = {
1453
+ listeners: listener,
1454
+ errHandlers: errHandler,
1455
+ rawEmitters: rawEmitter,
1456
+ watcher
1457
+ };
1458
+ FsWatchInstances.set(fullPath, cont);
1459
+ }
1460
+ return () => {
1461
+ delFromSet(cont, KEY_LISTENERS, listener);
1462
+ delFromSet(cont, KEY_ERR, errHandler);
1463
+ delFromSet(cont, KEY_RAW, rawEmitter);
1464
+ if (isEmptySet(cont.listeners)) {
1465
+ cont.watcher.close();
1466
+ FsWatchInstances.delete(fullPath);
1467
+ HANDLER_KEYS.forEach(clearItem(cont));
1468
+ cont.watcher = void 0;
1469
+ Object.freeze(cont);
1470
+ }
1471
+ };
1472
+ };
1473
+ var FsWatchFileInstances = /* @__PURE__ */ new Map();
1474
+ var setFsWatchFileListener = (path, fullPath, options, handlers) => {
1475
+ const { listener, rawEmitter } = handlers;
1476
+ let cont = FsWatchFileInstances.get(fullPath);
1477
+ const copts = cont && cont.options;
1478
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
1479
+ unwatchFile(fullPath);
1480
+ cont = void 0;
1481
+ }
1482
+ if (cont) {
1483
+ addAndConvert(cont, KEY_LISTENERS, listener);
1484
+ addAndConvert(cont, KEY_RAW, rawEmitter);
1485
+ } else {
1486
+ cont = {
1487
+ listeners: listener,
1488
+ rawEmitters: rawEmitter,
1489
+ options,
1490
+ watcher: watchFile(fullPath, options, (curr, prev) => {
1491
+ foreach(cont.rawEmitters, (rawEmitter2) => {
1492
+ rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
1493
+ });
1494
+ const currmtime = curr.mtimeMs;
1495
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
1496
+ foreach(cont.listeners, (listener2) => listener2(path, curr));
1497
+ }
1498
+ })
1499
+ };
1500
+ FsWatchFileInstances.set(fullPath, cont);
1501
+ }
1502
+ return () => {
1503
+ delFromSet(cont, KEY_LISTENERS, listener);
1504
+ delFromSet(cont, KEY_RAW, rawEmitter);
1505
+ if (isEmptySet(cont.listeners)) {
1506
+ FsWatchFileInstances.delete(fullPath);
1507
+ unwatchFile(fullPath);
1508
+ cont.options = cont.watcher = void 0;
1509
+ Object.freeze(cont);
1510
+ }
1511
+ };
1512
+ };
1513
+ var NodeFsHandler = class {
1514
+ constructor(fsW) {
1515
+ this.fsw = fsW;
1516
+ this._boundHandleError = (error) => fsW._handleError(error);
1517
+ }
1518
+ /**
1519
+ * Watch file for changes with fs_watchFile or fs_watch.
1520
+ * @param path to file or dir
1521
+ * @param listener on fs change
1522
+ * @returns closer for the watcher instance
1523
+ */
1524
+ _watchWithNodeFs(path, listener) {
1525
+ const opts = this.fsw.options;
1526
+ const directory = sysPath.dirname(path);
1527
+ const basename3 = sysPath.basename(path);
1528
+ const parent = this.fsw._getWatchedDir(directory);
1529
+ parent.add(basename3);
1530
+ const absolutePath = sysPath.resolve(path);
1531
+ const options = {
1532
+ persistent: opts.persistent
1533
+ };
1534
+ if (!listener)
1535
+ listener = EMPTY_FN;
1536
+ let closer;
1537
+ if (opts.usePolling) {
1538
+ const enableBin = opts.interval !== opts.binaryInterval;
1539
+ options.interval = enableBin && isBinaryPath(basename3) ? opts.binaryInterval : opts.interval;
1540
+ closer = setFsWatchFileListener(path, absolutePath, options, {
1541
+ listener,
1542
+ rawEmitter: this.fsw._emitRaw
1543
+ });
1544
+ } else {
1545
+ closer = setFsWatchListener(path, absolutePath, options, {
1546
+ listener,
1547
+ errHandler: this._boundHandleError,
1548
+ rawEmitter: this.fsw._emitRaw
1549
+ });
1550
+ }
1551
+ return closer;
1552
+ }
1553
+ /**
1554
+ * Watch a file and emit add event if warranted.
1555
+ * @returns closer for the watcher instance
1556
+ */
1557
+ _handleFile(file, stats, initialAdd) {
1558
+ if (this.fsw.closed) {
1559
+ return;
1560
+ }
1561
+ const dirname7 = sysPath.dirname(file);
1562
+ const basename3 = sysPath.basename(file);
1563
+ const parent = this.fsw._getWatchedDir(dirname7);
1564
+ let prevStats = stats;
1565
+ if (parent.has(basename3))
1566
+ return;
1567
+ const listener = async (path, newStats) => {
1568
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
1569
+ return;
1570
+ if (!newStats || newStats.mtimeMs === 0) {
1571
+ try {
1572
+ const newStats2 = await stat3(file);
1573
+ if (this.fsw.closed)
1574
+ return;
1575
+ const at = newStats2.atimeMs;
1576
+ const mt = newStats2.mtimeMs;
1577
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
1578
+ this.fsw._emit(EV.CHANGE, file, newStats2);
1579
+ }
1580
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
1581
+ this.fsw._closeFile(path);
1582
+ prevStats = newStats2;
1583
+ const closer2 = this._watchWithNodeFs(file, listener);
1584
+ if (closer2)
1585
+ this.fsw._addPathCloser(path, closer2);
1586
+ } else {
1587
+ prevStats = newStats2;
1588
+ }
1589
+ } catch (error) {
1590
+ this.fsw._remove(dirname7, basename3);
1591
+ }
1592
+ } else if (parent.has(basename3)) {
1593
+ const at = newStats.atimeMs;
1594
+ const mt = newStats.mtimeMs;
1595
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
1596
+ this.fsw._emit(EV.CHANGE, file, newStats);
1597
+ }
1598
+ prevStats = newStats;
1599
+ }
1600
+ };
1601
+ const closer = this._watchWithNodeFs(file, listener);
1602
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
1603
+ if (!this.fsw._throttle(EV.ADD, file, 0))
1604
+ return;
1605
+ this.fsw._emit(EV.ADD, file, stats);
1606
+ }
1607
+ return closer;
1608
+ }
1609
+ /**
1610
+ * Handle symlinks encountered while reading a dir.
1611
+ * @param entry returned by readdirp
1612
+ * @param directory path of dir being read
1613
+ * @param path of this item
1614
+ * @param item basename of this item
1615
+ * @returns true if no more processing is needed for this entry.
1616
+ */
1617
+ async _handleSymlink(entry, directory, path, item) {
1618
+ if (this.fsw.closed) {
1619
+ return;
1620
+ }
1621
+ const full = entry.fullPath;
1622
+ const dir = this.fsw._getWatchedDir(directory);
1623
+ if (!this.fsw.options.followSymlinks) {
1624
+ this.fsw._incrReadyCount();
1625
+ let linkPath;
1626
+ try {
1627
+ linkPath = await fsrealpath(path);
1628
+ } catch (e) {
1629
+ this.fsw._emitReady();
1630
+ return true;
1631
+ }
1632
+ if (this.fsw.closed)
1633
+ return;
1634
+ if (dir.has(item)) {
1635
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
1636
+ this.fsw._symlinkPaths.set(full, linkPath);
1637
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
1638
+ }
1639
+ } else {
1640
+ dir.add(item);
1641
+ this.fsw._symlinkPaths.set(full, linkPath);
1642
+ this.fsw._emit(EV.ADD, path, entry.stats);
1643
+ }
1644
+ this.fsw._emitReady();
1645
+ return true;
1646
+ }
1647
+ if (this.fsw._symlinkPaths.has(full)) {
1648
+ return true;
1649
+ }
1650
+ this.fsw._symlinkPaths.set(full, true);
1651
+ }
1652
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
1653
+ directory = sysPath.join(directory, "");
1654
+ throttler = this.fsw._throttle("readdir", directory, 1e3);
1655
+ if (!throttler)
1656
+ return;
1657
+ const previous = this.fsw._getWatchedDir(wh.path);
1658
+ const current = /* @__PURE__ */ new Set();
1659
+ let stream = this.fsw._readdirp(directory, {
1660
+ fileFilter: (entry) => wh.filterPath(entry),
1661
+ directoryFilter: (entry) => wh.filterDir(entry)
1662
+ });
1663
+ if (!stream)
1664
+ return;
1665
+ stream.on(STR_DATA, async (entry) => {
1666
+ if (this.fsw.closed) {
1667
+ stream = void 0;
1668
+ return;
1669
+ }
1670
+ const item = entry.path;
1671
+ let path = sysPath.join(directory, item);
1672
+ current.add(item);
1673
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
1674
+ return;
1675
+ }
1676
+ if (this.fsw.closed) {
1677
+ stream = void 0;
1678
+ return;
1679
+ }
1680
+ if (item === target || !target && !previous.has(item)) {
1681
+ this.fsw._incrReadyCount();
1682
+ path = sysPath.join(dir, sysPath.relative(dir, path));
1683
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
1684
+ }
1685
+ }).on(EV.ERROR, this._boundHandleError);
1686
+ return new Promise((resolve4, reject) => {
1687
+ if (!stream)
1688
+ return reject();
1689
+ stream.once(STR_END, () => {
1690
+ if (this.fsw.closed) {
1691
+ stream = void 0;
1692
+ return;
1693
+ }
1694
+ const wasThrottled = throttler ? throttler.clear() : false;
1695
+ resolve4(void 0);
1696
+ previous.getChildren().filter((item) => {
1697
+ return item !== directory && !current.has(item);
1698
+ }).forEach((item) => {
1699
+ this.fsw._remove(directory, item);
1700
+ });
1701
+ stream = void 0;
1702
+ if (wasThrottled)
1703
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
1704
+ });
1705
+ });
1706
+ }
1707
+ /**
1708
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
1709
+ * @param dir fs path
1710
+ * @param stats
1711
+ * @param initialAdd
1712
+ * @param depth relative to user-supplied path
1713
+ * @param target child path targeted for watch
1714
+ * @param wh Common watch helpers for this path
1715
+ * @param realpath
1716
+ * @returns closer for the watcher instance.
1717
+ */
1718
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
1719
+ const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
1720
+ const tracked = parentDir.has(sysPath.basename(dir));
1721
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
1722
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
1723
+ }
1724
+ parentDir.add(sysPath.basename(dir));
1725
+ this.fsw._getWatchedDir(dir);
1726
+ let throttler;
1727
+ let closer;
1728
+ const oDepth = this.fsw.options.depth;
1729
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
1730
+ if (!target) {
1731
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
1732
+ if (this.fsw.closed)
1733
+ return;
1734
+ }
1735
+ closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
1736
+ if (stats2 && stats2.mtimeMs === 0)
1737
+ return;
1738
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
1739
+ });
1740
+ }
1741
+ return closer;
1742
+ }
1743
+ /**
1744
+ * Handle added file, directory, or glob pattern.
1745
+ * Delegates call to _handleFile / _handleDir after checks.
1746
+ * @param path to file or ir
1747
+ * @param initialAdd was the file added at watch instantiation?
1748
+ * @param priorWh depth relative to user-supplied path
1749
+ * @param depth Child path actually targeted for watch
1750
+ * @param target Child path actually targeted for watch
1751
+ */
1752
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
1753
+ const ready = this.fsw._emitReady;
1754
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
1755
+ ready();
1756
+ return false;
1757
+ }
1758
+ const wh = this.fsw._getWatchHelpers(path);
1759
+ if (priorWh) {
1760
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
1761
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
1762
+ }
1763
+ try {
1764
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
1765
+ if (this.fsw.closed)
1766
+ return;
1767
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
1768
+ ready();
1769
+ return false;
1770
+ }
1771
+ const follow = this.fsw.options.followSymlinks;
1772
+ let closer;
1773
+ if (stats.isDirectory()) {
1774
+ const absPath = sysPath.resolve(path);
1775
+ const targetPath = follow ? await fsrealpath(path) : path;
1776
+ if (this.fsw.closed)
1777
+ return;
1778
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
1779
+ if (this.fsw.closed)
1780
+ return;
1781
+ if (absPath !== targetPath && targetPath !== void 0) {
1782
+ this.fsw._symlinkPaths.set(absPath, targetPath);
1783
+ }
1784
+ } else if (stats.isSymbolicLink()) {
1785
+ const targetPath = follow ? await fsrealpath(path) : path;
1786
+ if (this.fsw.closed)
1787
+ return;
1788
+ const parent = sysPath.dirname(wh.watchPath);
1789
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
1790
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
1791
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
1792
+ if (this.fsw.closed)
1793
+ return;
1794
+ if (targetPath !== void 0) {
1795
+ this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
1796
+ }
1797
+ } else {
1798
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
1799
+ }
1800
+ ready();
1801
+ if (closer)
1802
+ this.fsw._addPathCloser(path, closer);
1803
+ return false;
1804
+ } catch (error) {
1805
+ if (this.fsw._handleError(error)) {
1806
+ ready();
1807
+ return path;
1808
+ }
1809
+ }
1810
+ }
1811
+ };
1812
+
1813
+ // ../node_modules/chokidar/esm/index.js
1814
+ var SLASH = "/";
1815
+ var SLASH_SLASH = "//";
1816
+ var ONE_DOT = ".";
1817
+ var TWO_DOTS = "..";
1818
+ var STRING_TYPE = "string";
1819
+ var BACK_SLASH_RE = /\\/g;
1820
+ var DOUBLE_SLASH_RE = /\/\//;
1821
+ var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
1822
+ var REPLACER_RE = /^\.[/\\]/;
1823
+ function arrify(item) {
1824
+ return Array.isArray(item) ? item : [item];
1825
+ }
1826
+ var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
1827
+ function createPattern(matcher) {
1828
+ if (typeof matcher === "function")
1829
+ return matcher;
1830
+ if (typeof matcher === "string")
1831
+ return (string) => matcher === string;
1832
+ if (matcher instanceof RegExp)
1833
+ return (string) => matcher.test(string);
1834
+ if (typeof matcher === "object" && matcher !== null) {
1835
+ return (string) => {
1836
+ if (matcher.path === string)
1837
+ return true;
1838
+ if (matcher.recursive) {
1839
+ const relative3 = sysPath2.relative(matcher.path, string);
1840
+ if (!relative3) {
1841
+ return false;
1842
+ }
1843
+ return !relative3.startsWith("..") && !sysPath2.isAbsolute(relative3);
1844
+ }
1845
+ return false;
1846
+ };
1847
+ }
1848
+ return () => false;
1849
+ }
1850
+ function normalizePath(path) {
1851
+ if (typeof path !== "string")
1852
+ throw new Error("string expected");
1853
+ path = sysPath2.normalize(path);
1854
+ path = path.replace(/\\/g, "/");
1855
+ let prepend = false;
1856
+ if (path.startsWith("//"))
1857
+ prepend = true;
1858
+ const DOUBLE_SLASH_RE2 = /\/\//;
1859
+ while (path.match(DOUBLE_SLASH_RE2))
1860
+ path = path.replace(DOUBLE_SLASH_RE2, "/");
1861
+ if (prepend)
1862
+ path = "/" + path;
1863
+ return path;
1864
+ }
1865
+ function matchPatterns(patterns, testString, stats) {
1866
+ const path = normalizePath(testString);
1867
+ for (let index = 0; index < patterns.length; index++) {
1868
+ const pattern = patterns[index];
1869
+ if (pattern(path, stats)) {
1870
+ return true;
1871
+ }
1872
+ }
1873
+ return false;
1874
+ }
1875
+ function anymatch(matchers, testString) {
1876
+ if (matchers == null) {
1877
+ throw new TypeError("anymatch: specify first argument");
1878
+ }
1879
+ const matchersArray = arrify(matchers);
1880
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
1881
+ if (testString == null) {
1882
+ return (testString2, stats) => {
1883
+ return matchPatterns(patterns, testString2, stats);
1884
+ };
1885
+ }
1886
+ return matchPatterns(patterns, testString);
1887
+ }
1888
+ var unifyPaths = (paths_) => {
1889
+ const paths2 = arrify(paths_).flat();
1890
+ if (!paths2.every((p) => typeof p === STRING_TYPE)) {
1891
+ throw new TypeError(`Non-string provided as watch path: ${paths2}`);
1892
+ }
1893
+ return paths2.map(normalizePathToUnix);
1894
+ };
1895
+ var toUnix = (string) => {
1896
+ let str = string.replace(BACK_SLASH_RE, SLASH);
1897
+ let prepend = false;
1898
+ if (str.startsWith(SLASH_SLASH)) {
1899
+ prepend = true;
1900
+ }
1901
+ while (str.match(DOUBLE_SLASH_RE)) {
1902
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
1903
+ }
1904
+ if (prepend) {
1905
+ str = SLASH + str;
1906
+ }
1907
+ return str;
1908
+ };
1909
+ var normalizePathToUnix = (path) => toUnix(sysPath2.normalize(toUnix(path)));
1910
+ var normalizeIgnored = (cwd = "") => (path) => {
1911
+ if (typeof path === "string") {
1912
+ return normalizePathToUnix(sysPath2.isAbsolute(path) ? path : sysPath2.join(cwd, path));
1913
+ } else {
1914
+ return path;
1915
+ }
1916
+ };
1917
+ var getAbsolutePath = (path, cwd) => {
1918
+ if (sysPath2.isAbsolute(path)) {
1919
+ return path;
1920
+ }
1921
+ return sysPath2.join(cwd, path);
1922
+ };
1923
+ var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
1924
+ var DirEntry = class {
1925
+ constructor(dir, removeWatcher) {
1926
+ this.path = dir;
1927
+ this._removeWatcher = removeWatcher;
1928
+ this.items = /* @__PURE__ */ new Set();
1929
+ }
1930
+ add(item) {
1931
+ const { items } = this;
1932
+ if (!items)
1933
+ return;
1934
+ if (item !== ONE_DOT && item !== TWO_DOTS)
1935
+ items.add(item);
1936
+ }
1937
+ async remove(item) {
1938
+ const { items } = this;
1939
+ if (!items)
1940
+ return;
1941
+ items.delete(item);
1942
+ if (items.size > 0)
1943
+ return;
1944
+ const dir = this.path;
1945
+ try {
1946
+ await readdir2(dir);
1947
+ } catch (err) {
1948
+ if (this._removeWatcher) {
1949
+ this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
1950
+ }
1951
+ }
1952
+ }
1953
+ has(item) {
1954
+ const { items } = this;
1955
+ if (!items)
1956
+ return;
1957
+ return items.has(item);
1958
+ }
1959
+ getChildren() {
1960
+ const { items } = this;
1961
+ if (!items)
1962
+ return [];
1963
+ return [...items.values()];
1964
+ }
1965
+ dispose() {
1966
+ this.items.clear();
1967
+ this.path = "";
1968
+ this._removeWatcher = EMPTY_FN;
1969
+ this.items = EMPTY_SET;
1970
+ Object.freeze(this);
1971
+ }
1972
+ };
1973
+ var STAT_METHOD_F = "stat";
1974
+ var STAT_METHOD_L = "lstat";
1975
+ var WatchHelper = class {
1976
+ constructor(path, follow, fsw) {
1977
+ this.fsw = fsw;
1978
+ const watchPath = path;
1979
+ this.path = path = path.replace(REPLACER_RE, "");
1980
+ this.watchPath = watchPath;
1981
+ this.fullWatchPath = sysPath2.resolve(watchPath);
1982
+ this.dirParts = [];
1983
+ this.dirParts.forEach((parts) => {
1984
+ if (parts.length > 1)
1985
+ parts.pop();
1986
+ });
1987
+ this.followSymlinks = follow;
1988
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1989
+ }
1990
+ entryPath(entry) {
1991
+ return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
1992
+ }
1993
+ filterPath(entry) {
1994
+ const { stats } = entry;
1995
+ if (stats && stats.isSymbolicLink())
1996
+ return this.filterDir(entry);
1997
+ const resolvedPath = this.entryPath(entry);
1998
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1999
+ }
2000
+ filterDir(entry) {
2001
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
2002
+ }
2003
+ };
2004
+ var FSWatcher = class extends EventEmitter {
2005
+ // Not indenting methods for history sake; for now.
2006
+ constructor(_opts = {}) {
2007
+ super();
2008
+ this.closed = false;
2009
+ this._closers = /* @__PURE__ */ new Map();
2010
+ this._ignoredPaths = /* @__PURE__ */ new Set();
2011
+ this._throttled = /* @__PURE__ */ new Map();
2012
+ this._streams = /* @__PURE__ */ new Set();
2013
+ this._symlinkPaths = /* @__PURE__ */ new Map();
2014
+ this._watched = /* @__PURE__ */ new Map();
2015
+ this._pendingWrites = /* @__PURE__ */ new Map();
2016
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
2017
+ this._readyCount = 0;
2018
+ this._readyEmitted = false;
2019
+ const awf = _opts.awaitWriteFinish;
2020
+ const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
2021
+ const opts = {
2022
+ // Defaults
2023
+ persistent: true,
2024
+ ignoreInitial: false,
2025
+ ignorePermissionErrors: false,
2026
+ interval: 100,
2027
+ binaryInterval: 300,
2028
+ followSymlinks: true,
2029
+ usePolling: false,
2030
+ // useAsync: false,
2031
+ atomic: true,
2032
+ // NOTE: overwritten later (depends on usePolling)
2033
+ ..._opts,
2034
+ // Change format
2035
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
2036
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
2037
+ };
2038
+ if (isIBMi)
2039
+ opts.usePolling = true;
2040
+ if (opts.atomic === void 0)
2041
+ opts.atomic = !opts.usePolling;
2042
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
2043
+ if (envPoll !== void 0) {
2044
+ const envLower = envPoll.toLowerCase();
2045
+ if (envLower === "false" || envLower === "0")
2046
+ opts.usePolling = false;
2047
+ else if (envLower === "true" || envLower === "1")
2048
+ opts.usePolling = true;
2049
+ else
2050
+ opts.usePolling = !!envLower;
2051
+ }
2052
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
2053
+ if (envInterval)
2054
+ opts.interval = Number.parseInt(envInterval, 10);
2055
+ let readyCalls = 0;
2056
+ this._emitReady = () => {
2057
+ readyCalls++;
2058
+ if (readyCalls >= this._readyCount) {
2059
+ this._emitReady = EMPTY_FN;
2060
+ this._readyEmitted = true;
2061
+ process.nextTick(() => this.emit(EVENTS.READY));
2062
+ }
2063
+ };
2064
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
2065
+ this._boundRemove = this._remove.bind(this);
2066
+ this.options = opts;
2067
+ this._nodeFsHandler = new NodeFsHandler(this);
2068
+ Object.freeze(opts);
2069
+ }
2070
+ _addIgnoredPath(matcher) {
2071
+ if (isMatcherObject(matcher)) {
2072
+ for (const ignored of this._ignoredPaths) {
2073
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
2074
+ return;
2075
+ }
2076
+ }
2077
+ }
2078
+ this._ignoredPaths.add(matcher);
2079
+ }
2080
+ _removeIgnoredPath(matcher) {
2081
+ this._ignoredPaths.delete(matcher);
2082
+ if (typeof matcher === "string") {
2083
+ for (const ignored of this._ignoredPaths) {
2084
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
2085
+ this._ignoredPaths.delete(ignored);
2086
+ }
2087
+ }
2088
+ }
2089
+ }
2090
+ // Public methods
2091
+ /**
2092
+ * Adds paths to be watched on an existing FSWatcher instance.
2093
+ * @param paths_ file or file list. Other arguments are unused
2094
+ */
2095
+ add(paths_, _origAdd, _internal) {
2096
+ const { cwd } = this.options;
2097
+ this.closed = false;
2098
+ this._closePromise = void 0;
2099
+ let paths2 = unifyPaths(paths_);
2100
+ if (cwd) {
2101
+ paths2 = paths2.map((path) => {
2102
+ const absPath = getAbsolutePath(path, cwd);
2103
+ return absPath;
2104
+ });
2105
+ }
2106
+ paths2.forEach((path) => {
2107
+ this._removeIgnoredPath(path);
2108
+ });
2109
+ this._userIgnored = void 0;
2110
+ if (!this._readyCount)
2111
+ this._readyCount = 0;
2112
+ this._readyCount += paths2.length;
2113
+ Promise.all(paths2.map(async (path) => {
2114
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
2115
+ if (res)
2116
+ this._emitReady();
2117
+ return res;
2118
+ })).then((results) => {
2119
+ if (this.closed)
2120
+ return;
2121
+ results.forEach((item) => {
2122
+ if (item)
2123
+ this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
2124
+ });
2125
+ });
2126
+ return this;
2127
+ }
2128
+ /**
2129
+ * Close watchers or start ignoring events from specified paths.
2130
+ */
2131
+ unwatch(paths_) {
2132
+ if (this.closed)
2133
+ return this;
2134
+ const paths2 = unifyPaths(paths_);
2135
+ const { cwd } = this.options;
2136
+ paths2.forEach((path) => {
2137
+ if (!sysPath2.isAbsolute(path) && !this._closers.has(path)) {
2138
+ if (cwd)
2139
+ path = sysPath2.join(cwd, path);
2140
+ path = sysPath2.resolve(path);
2141
+ }
2142
+ this._closePath(path);
2143
+ this._addIgnoredPath(path);
2144
+ if (this._watched.has(path)) {
2145
+ this._addIgnoredPath({
2146
+ path,
2147
+ recursive: true
2148
+ });
2149
+ }
2150
+ this._userIgnored = void 0;
2151
+ });
2152
+ return this;
2153
+ }
2154
+ /**
2155
+ * Close watchers and remove all listeners from watched paths.
2156
+ */
2157
+ close() {
2158
+ if (this._closePromise) {
2159
+ return this._closePromise;
2160
+ }
2161
+ this.closed = true;
2162
+ this.removeAllListeners();
2163
+ const closers = [];
2164
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
2165
+ const promise = closer();
2166
+ if (promise instanceof Promise)
2167
+ closers.push(promise);
2168
+ }));
2169
+ this._streams.forEach((stream) => stream.destroy());
2170
+ this._userIgnored = void 0;
2171
+ this._readyCount = 0;
2172
+ this._readyEmitted = false;
2173
+ this._watched.forEach((dirent) => dirent.dispose());
2174
+ this._closers.clear();
2175
+ this._watched.clear();
2176
+ this._streams.clear();
2177
+ this._symlinkPaths.clear();
2178
+ this._throttled.clear();
2179
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
2180
+ return this._closePromise;
2181
+ }
2182
+ /**
2183
+ * Expose list of watched paths
2184
+ * @returns for chaining
2185
+ */
2186
+ getWatched() {
2187
+ const watchList = {};
2188
+ this._watched.forEach((entry, dir) => {
2189
+ const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
2190
+ const index = key || ONE_DOT;
2191
+ watchList[index] = entry.getChildren().sort();
2192
+ });
2193
+ return watchList;
2194
+ }
2195
+ emitWithAll(event, args) {
2196
+ this.emit(event, ...args);
2197
+ if (event !== EVENTS.ERROR)
2198
+ this.emit(EVENTS.ALL, event, ...args);
2199
+ }
2200
+ // Common helpers
2201
+ // --------------
2202
+ /**
2203
+ * Normalize and emit events.
2204
+ * Calling _emit DOES NOT MEAN emit() would be called!
2205
+ * @param event Type of event
2206
+ * @param path File or directory path
2207
+ * @param stats arguments to be passed with event
2208
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
2209
+ */
2210
+ async _emit(event, path, stats) {
2211
+ if (this.closed)
2212
+ return;
2213
+ const opts = this.options;
2214
+ if (isWindows)
2215
+ path = sysPath2.normalize(path);
2216
+ if (opts.cwd)
2217
+ path = sysPath2.relative(opts.cwd, path);
2218
+ const args = [path];
2219
+ if (stats != null)
2220
+ args.push(stats);
2221
+ const awf = opts.awaitWriteFinish;
2222
+ let pw;
2223
+ if (awf && (pw = this._pendingWrites.get(path))) {
2224
+ pw.lastChange = /* @__PURE__ */ new Date();
2225
+ return this;
2226
+ }
2227
+ if (opts.atomic) {
2228
+ if (event === EVENTS.UNLINK) {
2229
+ this._pendingUnlinks.set(path, [event, ...args]);
2230
+ setTimeout(() => {
2231
+ this._pendingUnlinks.forEach((entry, path2) => {
2232
+ this.emit(...entry);
2233
+ this.emit(EVENTS.ALL, ...entry);
2234
+ this._pendingUnlinks.delete(path2);
2235
+ });
2236
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
2237
+ return this;
2238
+ }
2239
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
2240
+ event = EVENTS.CHANGE;
2241
+ this._pendingUnlinks.delete(path);
2242
+ }
2243
+ }
2244
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
2245
+ const awfEmit = (err, stats2) => {
2246
+ if (err) {
2247
+ event = EVENTS.ERROR;
2248
+ args[0] = err;
2249
+ this.emitWithAll(event, args);
2250
+ } else if (stats2) {
2251
+ if (args.length > 1) {
2252
+ args[1] = stats2;
2253
+ } else {
2254
+ args.push(stats2);
2255
+ }
2256
+ this.emitWithAll(event, args);
2257
+ }
2258
+ };
2259
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
2260
+ return this;
2261
+ }
2262
+ if (event === EVENTS.CHANGE) {
2263
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path, 50);
2264
+ if (isThrottled)
2265
+ return this;
2266
+ }
2267
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
2268
+ const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path) : path;
2269
+ let stats2;
2270
+ try {
2271
+ stats2 = await stat4(fullPath);
2272
+ } catch (err) {
2273
+ }
2274
+ if (!stats2 || this.closed)
2275
+ return;
2276
+ args.push(stats2);
2277
+ }
2278
+ this.emitWithAll(event, args);
2279
+ return this;
2280
+ }
2281
+ /**
2282
+ * Common handler for errors
2283
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
2284
+ */
2285
+ _handleError(error) {
2286
+ const code = error && error.code;
2287
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
2288
+ this.emit(EVENTS.ERROR, error);
2289
+ }
2290
+ return error || this.closed;
2291
+ }
2292
+ /**
2293
+ * Helper utility for throttling
2294
+ * @param actionType type being throttled
2295
+ * @param path being acted upon
2296
+ * @param timeout duration of time to suppress duplicate actions
2297
+ * @returns tracking object or false if action should be suppressed
2298
+ */
2299
+ _throttle(actionType, path, timeout) {
2300
+ if (!this._throttled.has(actionType)) {
2301
+ this._throttled.set(actionType, /* @__PURE__ */ new Map());
2302
+ }
2303
+ const action = this._throttled.get(actionType);
2304
+ if (!action)
2305
+ throw new Error("invalid throttle");
2306
+ const actionPath = action.get(path);
2307
+ if (actionPath) {
2308
+ actionPath.count++;
2309
+ return false;
2310
+ }
2311
+ let timeoutObject;
2312
+ const clear = () => {
2313
+ const item = action.get(path);
2314
+ const count = item ? item.count : 0;
2315
+ action.delete(path);
2316
+ clearTimeout(timeoutObject);
2317
+ if (item)
2318
+ clearTimeout(item.timeoutObject);
2319
+ return count;
2320
+ };
2321
+ timeoutObject = setTimeout(clear, timeout);
2322
+ const thr = { timeoutObject, clear, count: 0 };
2323
+ action.set(path, thr);
2324
+ return thr;
2325
+ }
2326
+ _incrReadyCount() {
2327
+ return this._readyCount++;
2328
+ }
2329
+ /**
2330
+ * Awaits write operation to finish.
2331
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
2332
+ * @param path being acted upon
2333
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
2334
+ * @param event
2335
+ * @param awfEmit Callback to be called when ready for event to be emitted.
2336
+ */
2337
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
2338
+ const awf = this.options.awaitWriteFinish;
2339
+ if (typeof awf !== "object")
2340
+ return;
2341
+ const pollInterval = awf.pollInterval;
2342
+ let timeoutHandler;
2343
+ let fullPath = path;
2344
+ if (this.options.cwd && !sysPath2.isAbsolute(path)) {
2345
+ fullPath = sysPath2.join(this.options.cwd, path);
2346
+ }
2347
+ const now = /* @__PURE__ */ new Date();
2348
+ const writes = this._pendingWrites;
2349
+ function awaitWriteFinishFn(prevStat) {
2350
+ statcb(fullPath, (err, curStat) => {
2351
+ if (err || !writes.has(path)) {
2352
+ if (err && err.code !== "ENOENT")
2353
+ awfEmit(err);
2354
+ return;
2355
+ }
2356
+ const now2 = Number(/* @__PURE__ */ new Date());
2357
+ if (prevStat && curStat.size !== prevStat.size) {
2358
+ writes.get(path).lastChange = now2;
2359
+ }
2360
+ const pw = writes.get(path);
2361
+ const df = now2 - pw.lastChange;
2362
+ if (df >= threshold) {
2363
+ writes.delete(path);
2364
+ awfEmit(void 0, curStat);
2365
+ } else {
2366
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
2367
+ }
2368
+ });
2369
+ }
2370
+ if (!writes.has(path)) {
2371
+ writes.set(path, {
2372
+ lastChange: now,
2373
+ cancelWait: () => {
2374
+ writes.delete(path);
2375
+ clearTimeout(timeoutHandler);
2376
+ return event;
2377
+ }
2378
+ });
2379
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
2380
+ }
2381
+ }
2382
+ /**
2383
+ * Determines whether user has asked to ignore this path.
2384
+ */
2385
+ _isIgnored(path, stats) {
2386
+ if (this.options.atomic && DOT_RE.test(path))
2387
+ return true;
2388
+ if (!this._userIgnored) {
2389
+ const { cwd } = this.options;
2390
+ const ign = this.options.ignored;
2391
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
2392
+ const ignoredPaths = [...this._ignoredPaths];
2393
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
2394
+ this._userIgnored = anymatch(list, void 0);
2395
+ }
2396
+ return this._userIgnored(path, stats);
2397
+ }
2398
+ _isntIgnored(path, stat6) {
2399
+ return !this._isIgnored(path, stat6);
2400
+ }
2401
+ /**
2402
+ * Provides a set of common helpers and properties relating to symlink handling.
2403
+ * @param path file or directory pattern being watched
2404
+ */
2405
+ _getWatchHelpers(path) {
2406
+ return new WatchHelper(path, this.options.followSymlinks, this);
2407
+ }
2408
+ // Directory helpers
2409
+ // -----------------
2410
+ /**
2411
+ * Provides directory tracking objects
2412
+ * @param directory path of the directory
2413
+ */
2414
+ _getWatchedDir(directory) {
2415
+ const dir = sysPath2.resolve(directory);
2416
+ if (!this._watched.has(dir))
2417
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
2418
+ return this._watched.get(dir);
2419
+ }
2420
+ // File helpers
2421
+ // ------------
2422
+ /**
2423
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
2424
+ */
2425
+ _hasReadPermissions(stats) {
2426
+ if (this.options.ignorePermissionErrors)
2427
+ return true;
2428
+ return Boolean(Number(stats.mode) & 256);
2429
+ }
2430
+ /**
2431
+ * Handles emitting unlink events for
2432
+ * files and directories, and via recursion, for
2433
+ * files and directories within directories that are unlinked
2434
+ * @param directory within which the following item is located
2435
+ * @param item base path of item/directory
2436
+ */
2437
+ _remove(directory, item, isDirectory) {
2438
+ const path = sysPath2.join(directory, item);
2439
+ const fullPath = sysPath2.resolve(path);
2440
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
2441
+ if (!this._throttle("remove", path, 100))
2442
+ return;
2443
+ if (!isDirectory && this._watched.size === 1) {
2444
+ this.add(directory, item, true);
2445
+ }
2446
+ const wp = this._getWatchedDir(path);
2447
+ const nestedDirectoryChildren = wp.getChildren();
2448
+ nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
2449
+ const parent = this._getWatchedDir(directory);
2450
+ const wasTracked = parent.has(item);
2451
+ parent.remove(item);
2452
+ if (this._symlinkPaths.has(fullPath)) {
2453
+ this._symlinkPaths.delete(fullPath);
2454
+ }
2455
+ let relPath = path;
2456
+ if (this.options.cwd)
2457
+ relPath = sysPath2.relative(this.options.cwd, path);
2458
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
2459
+ const event = this._pendingWrites.get(relPath).cancelWait();
2460
+ if (event === EVENTS.ADD)
2461
+ return;
2462
+ }
2463
+ this._watched.delete(path);
2464
+ this._watched.delete(fullPath);
2465
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
2466
+ if (wasTracked && !this._isIgnored(path))
2467
+ this._emit(eventName, path);
2468
+ this._closePath(path);
2469
+ }
2470
+ /**
2471
+ * Closes all watchers for a path
2472
+ */
2473
+ _closePath(path) {
2474
+ this._closeFile(path);
2475
+ const dir = sysPath2.dirname(path);
2476
+ this._getWatchedDir(dir).remove(sysPath2.basename(path));
2477
+ }
2478
+ /**
2479
+ * Closes only file-specific watchers
2480
+ */
2481
+ _closeFile(path) {
2482
+ const closers = this._closers.get(path);
2483
+ if (!closers)
2484
+ return;
2485
+ closers.forEach((closer) => closer());
2486
+ this._closers.delete(path);
2487
+ }
2488
+ _addPathCloser(path, closer) {
2489
+ if (!closer)
2490
+ return;
2491
+ let list = this._closers.get(path);
2492
+ if (!list) {
2493
+ list = [];
2494
+ this._closers.set(path, list);
2495
+ }
2496
+ list.push(closer);
2497
+ }
2498
+ _readdirp(root, opts) {
2499
+ if (this.closed)
2500
+ return;
2501
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
2502
+ let stream = readdirp(root, options);
2503
+ this._streams.add(stream);
2504
+ stream.once(STR_CLOSE, () => {
2505
+ stream = void 0;
2506
+ });
2507
+ stream.once(STR_END, () => {
2508
+ if (stream) {
2509
+ this._streams.delete(stream);
2510
+ stream = void 0;
2511
+ }
2512
+ });
2513
+ return stream;
2514
+ }
2515
+ };
2516
+ function watch(paths2, options = {}) {
2517
+ const watcher = new FSWatcher(options);
2518
+ watcher.add(paths2);
2519
+ return watcher;
2520
+ }
2521
+ var esm_default = { watch, FSWatcher };
2522
+
2523
+ // src/watch.ts
2524
+ async function watchInbox(corpus, onDrain) {
2525
+ await corpus.init();
2526
+ const index = await openSearchIndex(corpus);
2527
+ let draining = false;
2528
+ let pending = false;
2529
+ const runDrain = async () => {
2530
+ if (draining) {
2531
+ pending = true;
2532
+ return;
2533
+ }
2534
+ draining = true;
2535
+ try {
2536
+ do {
2537
+ pending = false;
2538
+ const report = await drainInbox(corpus, index);
2539
+ if (report.files > 0) {
2540
+ onDrain?.(report);
2541
+ }
2542
+ } while (pending);
2543
+ } finally {
2544
+ draining = false;
2545
+ }
2546
+ };
2547
+ const watcher = esm_default.watch(corpus.paths.inboxDir, {
2548
+ ignoreInitial: true,
2549
+ depth: 0,
2550
+ awaitWriteFinish: { stabilityThreshold: 300, pollInterval: 100 }
2551
+ });
2552
+ watcher.on("add", () => void runDrain());
2553
+ await runDrain();
2554
+ return {
2555
+ close: async () => {
2556
+ await watcher.close();
2557
+ index.close();
2558
+ }
2559
+ };
2560
+ }
2561
+
2562
+ // src/clientRegistration.ts
2563
+ var import_cross_spawn = __toESM(require_cross_spawn(), 1);
2564
+ import { execFile as execFile2 } from "child_process";
2565
+ import { access, readFile as readFile2, stat as stat5, writeFile as writeFile2 } from "fs/promises";
2566
+ import { homedir as homedir2, platform as platform2 } from "os";
2567
+ import { dirname as dirname4, join as join4 } from "path";
2568
+ import { promisify as promisify2 } from "util";
2569
+ var execFileAsync2 = promisify2(execFile2);
2570
+ var SERVER_NAME = "llmnesia";
2571
+ async function commandOnPath(name) {
2572
+ try {
2573
+ const { stdout } = await execFileAsync2(process.platform === "win32" ? "where" : "which", [name]);
2574
+ return stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? null;
2575
+ } catch {
2576
+ return null;
2577
+ }
2578
+ }
2579
+ async function runExecutable(executable, args) {
2580
+ return new Promise((resolve4, reject) => {
2581
+ const child = (0, import_cross_spawn.default)(executable, args, { stdio: ["ignore", "pipe", "pipe"] });
2582
+ let stdout = "";
2583
+ let stderr = "";
2584
+ child.stdout?.setEncoding("utf8");
2585
+ child.stderr?.setEncoding("utf8");
2586
+ child.stdout?.on("data", (chunk) => {
2587
+ stdout += chunk;
2588
+ });
2589
+ child.stderr?.on("data", (chunk) => {
2590
+ stderr += chunk;
2591
+ });
2592
+ child.once("error", reject);
2593
+ child.once("close", (code, signal) => {
2594
+ if (code === 0) {
2595
+ resolve4({ stdout, stderr });
2596
+ return;
2597
+ }
2598
+ reject(
2599
+ Object.assign(new Error(`Command failed with ${signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`}`), {
2600
+ code,
2601
+ signal,
2602
+ stdout,
2603
+ stderr
2604
+ })
2605
+ );
2606
+ });
2607
+ });
2608
+ }
2609
+ async function runPathCli(name, args) {
2610
+ const executable = await commandOnPath(name);
2611
+ if (!executable) {
2612
+ throw new Error(`\`${name}\` was not found on PATH`);
2613
+ }
2614
+ return runExecutable(executable, args);
2615
+ }
2616
+ async function resolveCodexExecutable() {
2617
+ const onPath = await commandOnPath("codex");
2618
+ if (onPath) {
2619
+ return onPath;
2620
+ }
2621
+ if (process.platform === "darwin") {
2622
+ const candidates = [
2623
+ "/Applications/ChatGPT.app/Contents/Resources/codex",
2624
+ "/Applications/Codex.app/Contents/Resources/codex",
2625
+ join4(homedir2(), "Applications", "ChatGPT.app", "Contents", "Resources", "codex"),
2626
+ join4(homedir2(), "Applications", "Codex.app", "Contents", "Resources", "codex")
2627
+ ];
2628
+ for (const candidate of candidates) {
2629
+ try {
2630
+ await access(candidate);
2631
+ return candidate;
2632
+ } catch {
2633
+ }
2634
+ }
2635
+ }
2636
+ return null;
2637
+ }
2638
+ var realClaudeCli = {
2639
+ detect: async () => {
2640
+ return await commandOnPath("claude") !== null;
2641
+ },
2642
+ get: async (name) => {
2643
+ const configRoot = process.env.CLAUDE_CONFIG_DIR || homedir2();
2644
+ const configPath = join4(configRoot, ".claude.json");
2645
+ let raw;
2646
+ try {
2647
+ raw = await readFile2(configPath, "utf8");
2648
+ } catch (err) {
2649
+ if (isErrnoException(err) && err.code === "ENOENT") {
2650
+ return null;
2651
+ }
2652
+ throw new Error(`Could not read Claude Code settings at ${configPath}: ${errorMessage(err)}`, { cause: err });
2653
+ }
2654
+ const value = JSON.parse(raw);
2655
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2656
+ throw new Error(`Claude Code settings at ${configPath} are not a JSON object`);
2657
+ }
2658
+ const servers = value.mcpServers;
2659
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) {
2660
+ return null;
2661
+ }
2662
+ const entry = servers[name];
2663
+ if (!entry) {
2664
+ return null;
2665
+ }
2666
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
2667
+ return { serve: null };
2668
+ }
2669
+ const record = entry;
2670
+ if (typeof record.command !== "string" || !Array.isArray(record.args) || !record.args.every((arg) => typeof arg === "string")) {
2671
+ return { serve: null };
2672
+ }
2673
+ return { serve: { command: record.command, args: record.args } };
2674
+ },
2675
+ status: async (name) => {
2676
+ const { stdout } = await runPathCli("claude", ["mcp", "list"]);
2677
+ return stdout.split(/\r?\n/).find((line) => line.trimStart().startsWith(`${name}:`))?.trim() ?? null;
2678
+ },
2679
+ removeLegacyLocal: async (name) => {
2680
+ const configRoot = process.env.CLAUDE_CONFIG_DIR || homedir2();
2681
+ const configPath = join4(configRoot, ".claude.json");
2682
+ let raw;
2683
+ try {
2684
+ raw = await readFile2(configPath, "utf8");
2685
+ } catch (err) {
2686
+ if (isErrnoException(err) && err.code === "ENOENT") {
2687
+ return 0;
2688
+ }
2689
+ throw err;
2690
+ }
2691
+ const value = JSON.parse(raw);
2692
+ const projects = value.projects;
2693
+ if (!projects || typeof projects !== "object" || Array.isArray(projects)) {
2694
+ return 0;
2695
+ }
2696
+ let removed = 0;
2697
+ for (const project of Object.values(projects)) {
2698
+ if (!project || typeof project !== "object" || Array.isArray(project)) {
2699
+ continue;
2700
+ }
2701
+ const projectRecord = project;
2702
+ const servers = projectRecord.mcpServers;
2703
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) {
2704
+ continue;
2705
+ }
2706
+ const serverMap = servers;
2707
+ const entry = serverMap[name];
2708
+ if (!isManagedRuntimeEntry(entry)) {
2709
+ continue;
2710
+ }
2711
+ delete serverMap[name];
2712
+ removed += 1;
2713
+ }
2714
+ if (removed > 0) {
2715
+ await writeFile2(`${configPath}.bak-llmnesia-${Date.now()}`, raw, "utf8");
2716
+ await writeFile2(configPath, `${JSON.stringify(value, null, 2)}
2717
+ `, "utf8");
2718
+ }
2719
+ return removed;
2720
+ },
2721
+ add: async (name, serve) => {
2722
+ await runPathCli("claude", ["mcp", "add", "--scope", "user", name, "--", serve.command, ...serve.args]);
2723
+ },
2724
+ remove: async (name) => {
2725
+ await runPathCli("claude", ["mcp", "remove", name, "--scope", "user"]);
2726
+ }
2727
+ };
2728
+ function isManagedRuntimeEntry(entry) {
2729
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
2730
+ return false;
2731
+ }
2732
+ const args = entry.args;
2733
+ if (!Array.isArray(args) || args.length < 2 || !args.every((arg) => typeof arg === "string")) {
2734
+ return false;
2735
+ }
2736
+ const script = args[0].replace(/\\/g, "/");
2737
+ return script.endsWith("/.llmnesia/bin/cli.js") && args[1] === "serve";
2738
+ }
2739
+ async function runCodex(args) {
2740
+ const executable = await resolveCodexExecutable();
2741
+ if (!executable) {
2742
+ throw new Error("`codex` was not found on PATH or in a supported desktop app location");
2743
+ }
2744
+ return runExecutable(executable, args);
2745
+ }
2746
+ function parseCodexRegistration(raw) {
2747
+ const value = JSON.parse(raw);
2748
+ const transport = value.transport && typeof value.transport === "object" ? value.transport : value;
2749
+ const command = transport.command;
2750
+ const rawArgs = transport.args;
2751
+ if (typeof command !== "string" || !Array.isArray(rawArgs) || !rawArgs.every((arg) => typeof arg === "string")) {
2752
+ return { serve: null };
2753
+ }
2754
+ return { serve: { command, args: rawArgs } };
2755
+ }
2756
+ var realCodexCli = {
2757
+ detect: async () => await resolveCodexExecutable() !== null,
2758
+ get: async (name) => {
2759
+ try {
2760
+ const { stdout } = await runCodex(["mcp", "get", name, "--json"]);
2761
+ return parseCodexRegistration(stdout);
2762
+ } catch (err) {
2763
+ const output = err && typeof err === "object" ? `${"stdout" in err ? String(err.stdout) : ""}
2764
+ ${"stderr" in err ? String(err.stderr) : ""}` : errorMessage(err);
2765
+ if (/No MCP server named/i.test(output)) {
2766
+ return null;
2767
+ }
2768
+ throw err;
2769
+ }
2770
+ },
2771
+ add: async (name, serve) => {
2772
+ await runCodex(["mcp", "add", name, "--", serve.command, ...serve.args]);
2773
+ },
2774
+ remove: async (name) => {
2775
+ await runCodex(["mcp", "remove", name]);
2776
+ }
2777
+ };
2778
+ function paths(home2, osPlatform2) {
2779
+ const claudeDesktop = osPlatform2 === "darwin" ? join4(home2, "Library", "Application Support", "Claude", "claude_desktop_config.json") : osPlatform2 === "win32" ? join4(process.env.APPDATA || join4(home2, "AppData", "Roaming"), "Claude", "claude_desktop_config.json") : null;
2780
+ return {
2781
+ claudeDesktop,
2782
+ cursor: join4(home2, ".cursor", "mcp.json"),
2783
+ codex: join4(home2, ".codex", "config.toml")
2784
+ };
2785
+ }
2786
+ async function readJsonFile(path) {
2787
+ let raw;
2788
+ try {
2789
+ raw = await readFile2(path, "utf8");
2790
+ } catch (err) {
2791
+ if (isErrnoException(err) && err.code === "ENOENT") {
2792
+ return { data: {}, existed: false, raw: null };
2793
+ }
2794
+ throw new Error(`Could not read ${path}: ${errorMessage(err)}`, { cause: err });
2795
+ }
2796
+ try {
2797
+ const parsed = JSON.parse(raw);
2798
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2799
+ throw new Error("the top-level value must be a JSON object");
2800
+ }
2801
+ return { data: parsed, existed: true, raw };
2802
+ } catch (err) {
2803
+ throw new Error(`Could not parse ${path}: ${errorMessage(err)}. The file was left unchanged.`, { cause: err });
2804
+ }
2805
+ }
2806
+ function mcpServersOf(data, configPath) {
2807
+ if (!("mcpServers" in data) || data.mcpServers === void 0) {
2808
+ return {};
2809
+ }
2810
+ if (!data.mcpServers || typeof data.mcpServers !== "object" || Array.isArray(data.mcpServers)) {
2811
+ throw new Error(`Could not update ${configPath}: "mcpServers" must be a JSON object. The file was left unchanged.`);
2812
+ }
2813
+ return data.mcpServers;
2814
+ }
2815
+ function isErrnoException(value) {
2816
+ return value instanceof Error && "code" in value;
2817
+ }
2818
+ function errorMessage(value) {
2819
+ return value instanceof Error ? value.message : String(value);
2820
+ }
2821
+ async function clientDirExists(configPath) {
2822
+ try {
2823
+ return (await stat5(dirname4(configPath))).isDirectory();
2824
+ } catch {
2825
+ return false;
2826
+ }
2827
+ }
2828
+ async function registerClaudeCode(serve, cli, confirm) {
2829
+ const present = await cli.detect();
2830
+ if (!present) {
2831
+ return { client: "Claude Code", action: "skipped", detail: "`claude` not found on PATH." };
2832
+ }
2833
+ let existing;
2834
+ try {
2835
+ existing = await cli.get(SERVER_NAME);
2836
+ } catch (err) {
2837
+ return { client: "Claude Code", action: "error", detail: `Could not inspect Claude Code MCP settings: ${errorMessage(err)}` };
2838
+ }
2839
+ if (existing?.serve && sameServeCommand(existing.serve, serve)) {
2840
+ let migrated;
2841
+ try {
2842
+ migrated = await cli.removeLegacyLocal(SERVER_NAME);
2843
+ } catch (err) {
2844
+ return {
2845
+ client: "Claude Code",
2846
+ action: "error",
2847
+ detail: `Already registered globally, but legacy project-local cleanup failed: ${errorMessage(err)}`
2848
+ };
2849
+ }
2850
+ return {
2851
+ client: "Claude Code",
2852
+ action: "skipped",
2853
+ detail: `Already registered globally (user scope).${migrated ? ` Removed ${migrated} legacy project-local entry/entries.` : ""}`
2854
+ };
2855
+ }
2856
+ if (existing && !existing.serve) {
2857
+ return {
2858
+ client: "Claude Code",
2859
+ action: "error",
2860
+ detail: `An unrecognised user-scope "${SERVER_NAME}" entry already exists. It was left unchanged.`
2861
+ };
2862
+ }
2863
+ const verb = existing ? "replace its existing global LLMnesia registration" : "register LLMnesia for all projects";
2864
+ if (!await confirm(`Claude Code: ${verb}?
2865
+ claude mcp add --scope user ${SERVER_NAME} -- ${serve.command} ${serve.args.join(" ")}`)) {
2866
+ return { client: "Claude Code", action: "declined", detail: "Skipped by user." };
2867
+ }
2868
+ if (existing) {
2869
+ try {
2870
+ await cli.remove(SERVER_NAME);
2871
+ } catch (err) {
2872
+ return { client: "Claude Code", action: "error", detail: `Could not remove the old registration: ${errorMessage(err)}` };
2873
+ }
2874
+ }
2875
+ try {
2876
+ await cli.add(SERVER_NAME, serve);
2877
+ } catch (err) {
2878
+ if (existing?.serve) {
2879
+ try {
2880
+ await cli.add(SERVER_NAME, existing.serve);
2881
+ } catch (restoreErr) {
2882
+ return {
2883
+ client: "Claude Code",
2884
+ action: "error",
2885
+ detail: `Registration failed (${errorMessage(err)}) and restoring the previous entry also failed (${errorMessage(restoreErr)}).`
2886
+ };
2887
+ }
2888
+ }
2889
+ return {
2890
+ client: "Claude Code",
2891
+ action: "error",
2892
+ detail: `claude mcp add failed: ${errorMessage(err)}`
2893
+ };
2894
+ }
2895
+ try {
2896
+ const migrated = await cli.removeLegacyLocal(SERVER_NAME);
2897
+ return {
2898
+ client: "Claude Code",
2899
+ action: "registered",
2900
+ detail: `Ran: claude mcp add --scope user ${SERVER_NAME} -- ${serve.command} ${serve.args.join(" ")}` + (migrated ? `; removed ${migrated} legacy project-local entry/entries.` : "")
2901
+ };
2902
+ } catch (err) {
2903
+ return {
2904
+ client: "Claude Code",
2905
+ action: "error",
2906
+ detail: `Registered globally, but legacy project-local cleanup failed: ${errorMessage(err)}`
2907
+ };
2908
+ }
2909
+ }
2910
+ function sameServeCommand(left, right) {
2911
+ return left.command === right.command && JSON.stringify(left.args) === JSON.stringify(right.args);
2912
+ }
2913
+ async function registerCodex(serve, cli, configPath, confirm) {
2914
+ if (!await cli.detect()) {
2915
+ if (!await clientDirExists(configPath)) {
2916
+ return {
2917
+ client: "Codex",
2918
+ action: "skipped",
2919
+ detail: `Not installed (no Codex CLI and no ${dirname4(configPath)}).`
2920
+ };
2921
+ }
2922
+ return {
2923
+ client: "Codex",
2924
+ action: "printed",
2925
+ detail: `Codex's CLI was not found. Add this to ${configPath}:
2926
+ ${codexBlock(serve)}Then fully quit and reopen Codex.`
2927
+ };
2928
+ }
2929
+ let existing;
2930
+ try {
2931
+ existing = await cli.get(SERVER_NAME);
2932
+ } catch (err) {
2933
+ return { client: "Codex", action: "error", detail: `Could not inspect Codex MCP settings: ${errorMessage(err)}` };
2934
+ }
2935
+ if (existing?.serve && sameServeCommand(existing.serve, serve)) {
2936
+ return { client: "Codex", action: "skipped", detail: "Already registered." };
2937
+ }
2938
+ if (existing && !existing.serve) {
2939
+ return {
2940
+ client: "Codex",
2941
+ action: "error",
2942
+ detail: `A non-stdio or unrecognised "${SERVER_NAME}" entry already exists. It was left unchanged.`
2943
+ };
2944
+ }
2945
+ const verb = existing ? "replace its existing LLMnesia MCP registration" : "register the LLMnesia MCP server";
2946
+ const ok = await confirm(
2947
+ `Codex: ${verb}?
2948
+ codex mcp add ${SERVER_NAME} -- ${serve.command} ${serve.args.join(" ")}`
2949
+ );
2950
+ if (!ok) {
2951
+ return { client: "Codex", action: "declined", detail: "Skipped by user." };
2952
+ }
2953
+ if (existing) {
2954
+ try {
2955
+ await cli.remove(SERVER_NAME);
2956
+ } catch (err) {
2957
+ return { client: "Codex", action: "error", detail: `Could not remove the old registration: ${errorMessage(err)}` };
2958
+ }
2959
+ }
2960
+ try {
2961
+ await cli.add(SERVER_NAME, serve);
2962
+ } catch (err) {
2963
+ if (existing?.serve) {
2964
+ try {
2965
+ await cli.add(SERVER_NAME, existing.serve);
2966
+ } catch (restoreErr) {
2967
+ return {
2968
+ client: "Codex",
2969
+ action: "error",
2970
+ detail: `Registration failed (${errorMessage(err)}) and restoring the previous entry also failed (${errorMessage(restoreErr)}).`
2971
+ };
2972
+ }
2973
+ }
2974
+ return { client: "Codex", action: "error", detail: `codex mcp add failed: ${errorMessage(err)}` };
2975
+ }
2976
+ return {
2977
+ client: "Codex",
2978
+ action: "registered",
2979
+ detail: `Ran: codex mcp add ${SERVER_NAME} -- ${serve.command} ${serve.args.join(" ")}`
2980
+ };
2981
+ }
2982
+ async function registerJsonClient(clientLabel, configPath, serve, confirm, now) {
2983
+ if (!await clientDirExists(configPath)) {
2984
+ return {
2985
+ client: clientLabel,
2986
+ action: "skipped",
2987
+ detail: `Not installed (no ${dirname4(configPath)}). Re-run install after setting it up.`
2988
+ };
2989
+ }
2990
+ let data;
2991
+ let existed;
2992
+ let raw;
2993
+ try {
2994
+ ({ data, existed, raw } = await readJsonFile(configPath));
2995
+ } catch (err) {
2996
+ return { client: clientLabel, action: "error", detail: errorMessage(err) };
2997
+ }
2998
+ let servers;
2999
+ try {
3000
+ servers = mcpServersOf(data, configPath);
3001
+ } catch (err) {
3002
+ return { client: clientLabel, action: "error", detail: errorMessage(err) };
3003
+ }
3004
+ const already = servers[SERVER_NAME];
3005
+ const nextEntry = { command: serve.command, args: serve.args };
3006
+ if (already && JSON.stringify(already) === JSON.stringify(nextEntry)) {
3007
+ return { client: clientLabel, action: "skipped", detail: `Already registered at ${configPath}.` };
3008
+ }
3009
+ const preview = JSON.stringify({ mcpServers: { ...servers, [SERVER_NAME]: nextEntry } }, null, 2);
3010
+ const message = existed ? `${clientLabel}: update ${configPath} to add the "${SERVER_NAME}" MCP server?
3011
+ ${preview}` : `${clientLabel}: create ${configPath} with the "${SERVER_NAME}" MCP server?
3012
+ ${preview}`;
3013
+ const ok = await confirm(message);
3014
+ if (!ok) {
3015
+ return { client: clientLabel, action: "declined", detail: `Skipped by user. Config: ${configPath}` };
3016
+ }
3017
+ try {
3018
+ if (existed) {
3019
+ const backupPath = `${configPath}.bak-${now()}`;
3020
+ await writeFile2(backupPath, raw ?? JSON.stringify(data, null, 2), "utf8");
3021
+ }
3022
+ const nextData = { ...data, mcpServers: { ...servers, [SERVER_NAME]: nextEntry } };
3023
+ await writeFile2(configPath, `${JSON.stringify(nextData, null, 2)}
3024
+ `, "utf8");
3025
+ return { client: clientLabel, action: "registered", detail: `Wrote ${configPath}.` };
3026
+ } catch (err) {
3027
+ return { client: clientLabel, action: "error", detail: `Could not write ${configPath}: ${errorMessage(err)}` };
3028
+ }
3029
+ }
3030
+ function codexBlock(serve) {
3031
+ const argsToml = serve.args.map((a) => JSON.stringify(a)).join(", ");
3032
+ return `[mcp_servers.${SERVER_NAME}]
3033
+ command = ${JSON.stringify(serve.command)}
3034
+ args = [${argsToml}]
3035
+ `;
3036
+ }
3037
+ function genericBlock(serve) {
3038
+ return JSON.stringify({ mcpServers: { [SERVER_NAME]: { command: serve.command, args: serve.args } } }, null, 2);
3039
+ }
3040
+ async function registerClients(options) {
3041
+ const home2 = options.home ?? homedir2();
3042
+ const osPlatform2 = options.osPlatform ?? platform2();
3043
+ const now = options.now ?? (() => Date.now());
3044
+ const { claudeDesktop, cursor, codex } = paths(home2, osPlatform2);
3045
+ const results = [];
3046
+ const safe = async (client, fn) => {
3047
+ try {
3048
+ return await fn();
3049
+ } catch (err) {
3050
+ return { client, action: "error", detail: `Unexpected setup failure: ${errorMessage(err)}` };
3051
+ }
3052
+ };
3053
+ results.push(
3054
+ await safe(
3055
+ "Claude Code",
3056
+ () => registerClaudeCode(options.serve, options.claudeCli ?? realClaudeCli, options.confirm)
3057
+ )
3058
+ );
3059
+ if (claudeDesktop) {
3060
+ results.push(
3061
+ await safe(
3062
+ "Claude Desktop",
3063
+ () => registerJsonClient("Claude Desktop", claudeDesktop, options.serve, options.confirm, now)
3064
+ )
3065
+ );
3066
+ }
3067
+ results.push(await safe("Cursor", () => registerJsonClient("Cursor", cursor, options.serve, options.confirm, now)));
3068
+ results.push(
3069
+ await safe("Codex", () => registerCodex(options.serve, options.codexCli ?? realCodexCli, codex, options.confirm))
3070
+ );
3071
+ results.push({
3072
+ client: "Other MCP clients (Windsurf, Zed, LM Studio, ...)",
3073
+ action: "printed",
3074
+ detail: `Any client that accepts a stdio command+args block can use:
3075
+ ${genericBlock(options.serve)}`
3076
+ });
3077
+ return results;
3078
+ }
3079
+ async function unregisterClaudeCode(cli) {
3080
+ const present = await cli.detect();
3081
+ if (!present) {
3082
+ try {
3083
+ const existing = await cli.get(SERVER_NAME);
3084
+ if (!existing) {
3085
+ return { client: "Claude Code", action: "skipped", detail: "`claude` not found on PATH and no global registration exists." };
3086
+ }
3087
+ return {
3088
+ client: "Claude Code",
3089
+ action: "error",
3090
+ detail: "A global registration still exists, but `claude` is not on PATH to remove it. Reinstall/restore the Claude CLI, then retry uninstall. The runtime was retained so the entry does not break."
3091
+ };
3092
+ } catch (err) {
3093
+ return { client: "Claude Code", action: "error", detail: `Could not verify Claude Code settings: ${errorMessage(err)}` };
3094
+ }
3095
+ }
3096
+ try {
3097
+ const existing = await cli.get(SERVER_NAME);
3098
+ if (!existing) {
3099
+ return { client: "Claude Code", action: "skipped", detail: "Not registered globally (user scope)." };
3100
+ }
3101
+ await cli.remove(SERVER_NAME);
3102
+ return { client: "Claude Code", action: "registered", detail: `Ran: claude mcp remove ${SERVER_NAME} --scope user` };
3103
+ } catch (err) {
3104
+ return {
3105
+ client: "Claude Code",
3106
+ action: "error",
3107
+ detail: `claude mcp remove failed (may already be unregistered): ${err instanceof Error ? err.message : String(err)}`
3108
+ };
3109
+ }
3110
+ }
3111
+ async function unregisterCodex(cli, configPath) {
3112
+ if (!await cli.detect()) {
3113
+ try {
3114
+ const text = await readFile2(configPath, "utf8");
3115
+ if (new RegExp(`^\\s*\\[mcp_servers\\.${SERVER_NAME}\\]\\s*$`, "m").test(text)) {
3116
+ return {
3117
+ client: "Codex",
3118
+ action: "error",
3119
+ detail: `A registration remains in ${configPath}, but the Codex CLI is unavailable to remove it safely. Restore the CLI and retry. The runtime was retained.`
3120
+ };
3121
+ }
3122
+ } catch (err) {
3123
+ if (!(isErrnoException(err) && err.code === "ENOENT")) {
3124
+ return { client: "Codex", action: "error", detail: `Could not inspect ${configPath}: ${errorMessage(err)}` };
3125
+ }
3126
+ }
3127
+ return { client: "Codex", action: "skipped", detail: "`codex` not found and no registration was detected." };
3128
+ }
3129
+ try {
3130
+ const existing = await cli.get(SERVER_NAME);
3131
+ if (!existing) {
3132
+ return { client: "Codex", action: "skipped", detail: "Not registered." };
3133
+ }
3134
+ await cli.remove(SERVER_NAME);
3135
+ return { client: "Codex", action: "registered", detail: `Ran: codex mcp remove ${SERVER_NAME}` };
3136
+ } catch (err) {
3137
+ return { client: "Codex", action: "error", detail: `codex mcp remove failed: ${errorMessage(err)}` };
3138
+ }
3139
+ }
3140
+ async function unregisterJsonClient(clientLabel, configPath, now) {
3141
+ let data;
3142
+ let existed;
3143
+ let raw;
3144
+ try {
3145
+ ({ data, existed, raw } = await readJsonFile(configPath));
3146
+ } catch (err) {
3147
+ return { client: clientLabel, action: "error", detail: errorMessage(err) };
3148
+ }
3149
+ if (!existed) {
3150
+ return { client: clientLabel, action: "skipped", detail: `No ${configPath}.` };
3151
+ }
3152
+ let servers;
3153
+ try {
3154
+ servers = mcpServersOf(data, configPath);
3155
+ } catch (err) {
3156
+ return { client: clientLabel, action: "error", detail: errorMessage(err) };
3157
+ }
3158
+ if (!(SERVER_NAME in servers)) {
3159
+ return { client: clientLabel, action: "skipped", detail: `Not registered in ${configPath}.` };
3160
+ }
3161
+ const backupPath = `${configPath}.bak-${now()}`;
3162
+ try {
3163
+ await writeFile2(backupPath, raw ?? JSON.stringify(data, null, 2), "utf8");
3164
+ const { [SERVER_NAME]: _removed, ...rest } = servers;
3165
+ const nextData = { ...data, mcpServers: rest };
3166
+ await writeFile2(configPath, `${JSON.stringify(nextData, null, 2)}
3167
+ `, "utf8");
3168
+ return { client: clientLabel, action: "registered", detail: `Removed from ${configPath} (backup: ${backupPath}).` };
3169
+ } catch (err) {
3170
+ return { client: clientLabel, action: "error", detail: `Could not update ${configPath}: ${errorMessage(err)}` };
3171
+ }
3172
+ }
3173
+ async function unregisterClients(options = {}) {
3174
+ const home2 = options.home ?? homedir2();
3175
+ const osPlatform2 = options.osPlatform ?? platform2();
3176
+ const now = options.now ?? (() => Date.now());
3177
+ const { claudeDesktop, cursor, codex } = paths(home2, osPlatform2);
3178
+ const safe = async (client, fn) => {
3179
+ try {
3180
+ return await fn();
3181
+ } catch (err) {
3182
+ return { client, action: "error", detail: `Unexpected uninstall failure: ${errorMessage(err)}` };
3183
+ }
3184
+ };
3185
+ const results = [
3186
+ await safe("Claude Code", () => unregisterClaudeCode(options.claudeCli ?? realClaudeCli))
3187
+ ];
3188
+ if (claudeDesktop) {
3189
+ results.push(await safe("Claude Desktop", () => unregisterJsonClient("Claude Desktop", claudeDesktop, now)));
3190
+ }
3191
+ results.push(await safe("Cursor", () => unregisterJsonClient("Cursor", cursor, now)));
3192
+ results.push(await safe("Codex", () => unregisterCodex(options.codexCli ?? realCodexCli, codex)));
3193
+ results.push({
3194
+ client: "Other MCP clients",
3195
+ action: "skipped",
3196
+ detail: "These were only shown as copy-paste blocks, never auto-edited \u2014 remove the block yourself if you added it."
3197
+ });
3198
+ return results;
3199
+ }
3200
+
3201
+ // src/doctor.ts
3202
+ import { existsSync as existsSync2, readFileSync } from "fs";
3203
+ import { delimiter, dirname as dirname6, isAbsolute as isAbsolute2, join as join6, sep } from "path";
3204
+ import { homedir as homedir4, platform as platform3 } from "os";
3205
+
3206
+ // src/runtimeInstall.ts
3207
+ import { cp, mkdir as mkdir2, readdir as readdir3, rename, rm as rm2, writeFile as writeFile3 } from "fs/promises";
3208
+ import { existsSync } from "fs";
3209
+ import { homedir as homedir3 } from "os";
3210
+ import { dirname as dirname5, join as join5 } from "path";
3211
+ import { fileURLToPath as fileURLToPath2 } from "url";
3212
+ function defaultSourceDir() {
3213
+ return dirname5(fileURLToPath2(import.meta.url));
3214
+ }
3215
+ function runtimeBinDir(home2 = homedir3()) {
3216
+ return join5(home2, ".llmnesia", "bin");
3217
+ }
3218
+ async function installRuntime(options = {}) {
3219
+ const home2 = options.home ?? homedir3();
3220
+ const sourceDir = options.sourceDir ?? defaultSourceDir();
3221
+ const nodePath = options.nodePath ?? process.execPath;
3222
+ const binDir = runtimeBinDir(home2);
3223
+ const sourceEntry = join5(sourceDir, "cli.js");
3224
+ if (!existsSync(sourceEntry)) {
3225
+ throw new Error(
3226
+ `Cannot locate the built runtime: no cli.js in ${sourceDir}. Run this from an installed package (npx -y @llmnesia/mcp@latest install) or build first (npm run build).`
3227
+ );
3228
+ }
3229
+ const parentDir = dirname5(binDir);
3230
+ const nonce = `${process.pid}-${Date.now()}`;
3231
+ const stagingDir = join5(parentDir, `.bin-install-${nonce}`);
3232
+ const backupDir = join5(parentDir, `.bin-backup-${nonce}`);
3233
+ await mkdir2(parentDir, { recursive: true });
3234
+ await rm2(stagingDir, { recursive: true, force: true });
3235
+ await rm2(backupDir, { recursive: true, force: true });
3236
+ await mkdir2(stagingDir, { recursive: true });
3237
+ try {
3238
+ for (const name of await readdir3(sourceDir)) {
3239
+ await cp(join5(sourceDir, name), join5(stagingDir, name), { recursive: true });
3240
+ }
3241
+ await writeFile3(
3242
+ join5(stagingDir, "package.json"),
3243
+ `${JSON.stringify(
3244
+ {
3245
+ name: "llmnesia-mcp-runtime",
3246
+ private: true,
3247
+ type: "module",
3248
+ comment: "Installed copy of @llmnesia/mcp's dist. Managed by the LLMnesia installer; edits are lost on reinstall."
3249
+ },
3250
+ null,
3251
+ 2
3252
+ )}
3253
+ `,
3254
+ "utf8"
3255
+ );
3256
+ const hadPreviousRuntime = existsSync(binDir);
3257
+ if (hadPreviousRuntime) {
3258
+ await rename(binDir, backupDir);
3259
+ }
3260
+ try {
3261
+ await rename(stagingDir, binDir);
3262
+ } catch (err) {
3263
+ if (hadPreviousRuntime && !existsSync(binDir) && existsSync(backupDir)) {
3264
+ await rename(backupDir, binDir);
3265
+ }
3266
+ throw err;
3267
+ }
3268
+ await rm2(backupDir, { recursive: true, force: true });
3269
+ } finally {
3270
+ await rm2(stagingDir, { recursive: true, force: true });
3271
+ }
3272
+ const entry = join5(binDir, "cli.js");
3273
+ return {
3274
+ binDir,
3275
+ entry,
3276
+ serve: { command: nodePath, args: [entry, "serve"] },
3277
+ sourceDir,
3278
+ nodePath
3279
+ };
3280
+ }
3281
+ async function uninstallRuntime(home2 = homedir3()) {
3282
+ const binDir = runtimeBinDir(home2);
3283
+ if (!existsSync(binDir)) {
3284
+ return null;
3285
+ }
3286
+ await rm2(binDir, { recursive: true, force: true });
3287
+ return binDir;
3288
+ }
3289
+
3290
+ // src/doctor.ts
3291
+ var INSTALL_COMMAND = "npx -y @llmnesia/mcp@latest install";
3292
+ function checkNativeHostManifest(home2, osPlatform2) {
3293
+ if (osPlatform2 === "win32") {
3294
+ const manifestPath = join6(home2, ".llmnesia", `${HOST_NAME}.json`);
3295
+ if (existsSync2(manifestPath)) {
3296
+ return {
3297
+ name: "Native messaging host",
3298
+ status: "ok",
3299
+ detail: `Manifest present at ${manifestPath}. (This confirms the file the installer writes, not the registry key independently \u2014 re-run "install" if a browser still can't find it.)`
3300
+ };
3301
+ }
3302
+ return {
3303
+ name: "Native messaging host",
3304
+ status: "missing",
3305
+ detail: `No manifest at ${manifestPath}. Run: ${INSTALL_COMMAND}`
3306
+ };
3307
+ }
3308
+ const found = [];
3309
+ for (const [label, browserDir] of posixBrowsers(home2, osPlatform2)) {
3310
+ if (!existsSync2(browserDir)) {
3311
+ continue;
3312
+ }
3313
+ const manifestPath = join6(browserDir, "NativeMessagingHosts", `${HOST_NAME}.json`);
3314
+ if (existsSync2(manifestPath)) {
3315
+ found.push(label);
3316
+ }
3317
+ }
3318
+ if (found.length > 0) {
3319
+ return { name: "Native messaging host", status: "ok", detail: `Registered for: ${found.join(", ")}.` };
3320
+ }
3321
+ return {
3322
+ name: "Native messaging host",
3323
+ status: "missing",
3324
+ detail: `No browser has the native-messaging manifest installed. Run: ${INSTALL_COMMAND}`
3325
+ };
3326
+ }
3327
+ async function checkCorpus(home2, corpusRoot) {
3328
+ const configPath = join6(home2, ".llmnesia", "config.json");
3329
+ if (!corpusRoot && !existsSync2(configPath)) {
3330
+ return {
3331
+ name: "Corpus config",
3332
+ status: "missing",
3333
+ detail: `No ${configPath}. Run: ${INSTALL_COMMAND}`
3334
+ };
3335
+ }
3336
+ const root = corpusRoot ?? resolveCorpusDir();
3337
+ if (!existsSync2(root)) {
3338
+ return {
3339
+ name: "Corpus",
3340
+ status: "warn",
3341
+ detail: `Config points at ${root}, but that directory doesn't exist yet. It is created when a supported extension build syncs, when the MCP save_conversation tool is used, or when data is ingested. Normal right after installing.`
3342
+ };
3343
+ }
3344
+ try {
3345
+ const corpus = new Corpus(root);
3346
+ const stats = await corpus.stats();
3347
+ if (stats.conversationCount === 0) {
3348
+ return {
3349
+ name: "Corpus",
3350
+ status: "warn",
3351
+ detail: `Corpus at ${root} exists but is empty. It fills in as you chat, or on the browser extension's first backfill sync.`
3352
+ };
3353
+ }
3354
+ return {
3355
+ name: "Corpus",
3356
+ status: "ok",
3357
+ detail: `${stats.conversationCount} conversation(s), ${stats.messageCount} message(s) at ${root}.`
3358
+ };
3359
+ } catch (err) {
3360
+ return {
3361
+ name: "Corpus",
3362
+ status: "warn",
3363
+ detail: `Couldn't read corpus at ${root}: ${err instanceof Error ? err.message : String(err)}`
3364
+ };
3365
+ }
3366
+ }
3367
+ function commandProblem(command, args = []) {
3368
+ const looksLikePath = isAbsolute2(command) || command.includes(sep) || command.includes("/");
3369
+ if (looksLikePath) {
3370
+ if (!existsSync2(command)) {
3371
+ return `its command does not exist: ${command}`;
3372
+ }
3373
+ } else if (!resolveOnPath(command)) {
3374
+ return `its command "${command}" is not on PATH. GUI clients get a minimal PATH (no nvm, no homebrew), so a bare command name is unreliable even when your shell can find it. Re-run: ${INSTALL_COMMAND}`;
3375
+ }
3376
+ const script = args.find((a) => a.endsWith(".js") || a.endsWith(".mjs"));
3377
+ if (script && (isAbsolute2(script) || script.includes(sep)) && !existsSync2(script)) {
3378
+ return `its script does not exist: ${script}. Re-run: ${INSTALL_COMMAND}`;
3379
+ }
3380
+ return null;
3381
+ }
3382
+ function resolveOnPath(command) {
3383
+ const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
3384
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
3385
+ if (!dir) {
3386
+ continue;
3387
+ }
3388
+ for (const ext of exts) {
3389
+ if (existsSync2(join6(dir, command + ext))) {
3390
+ return true;
3391
+ }
3392
+ }
3393
+ }
3394
+ return false;
3395
+ }
3396
+ function checkRuntime(home2) {
3397
+ const entry = join6(runtimeBinDir(home2), "cli.js");
3398
+ if (existsSync2(entry)) {
3399
+ return { name: "MCP server runtime", status: "ok", detail: `Installed at ${entry}.` };
3400
+ }
3401
+ return {
3402
+ name: "MCP server runtime",
3403
+ status: "missing",
3404
+ detail: `No runtime at ${entry}. Clients spawn this copy, so registration alone is not enough. Run: ${INSTALL_COMMAND}`
3405
+ };
3406
+ }
3407
+ async function checkJsonClient(label, configPath) {
3408
+ if (!existsSync2(dirname6(configPath))) {
3409
+ return { name: label, status: "warn", detail: `Not installed (no ${dirname6(configPath)}).` };
3410
+ }
3411
+ if (!existsSync2(configPath)) {
3412
+ return {
3413
+ name: label,
3414
+ status: "missing",
3415
+ detail: `${label} is installed but has no MCP config yet. Run: ${INSTALL_COMMAND}`
3416
+ };
3417
+ }
3418
+ try {
3419
+ const data = JSON.parse(readFileSync(configPath, "utf8"));
3420
+ const entry = data.mcpServers?.[SERVER_NAME];
3421
+ if (!entry) {
3422
+ return {
3423
+ name: label,
3424
+ status: "missing",
3425
+ detail: `${label} is installed but not registered. Run: ${INSTALL_COMMAND}`
3426
+ };
3427
+ }
3428
+ if (typeof entry.command !== "string") {
3429
+ return { name: label, status: "missing", detail: `Registered in ${configPath} but the entry has no command. Run: ${INSTALL_COMMAND}` };
3430
+ }
3431
+ const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
3432
+ const problem = commandProblem(entry.command, args);
3433
+ if (problem) {
3434
+ return { name: label, status: "missing", detail: `Registered in ${configPath}, but ${problem}` };
3435
+ }
3436
+ return { name: label, status: "ok", detail: `Registered in ${configPath} and its command resolves.` };
3437
+ } catch (err) {
3438
+ return {
3439
+ name: label,
3440
+ status: "warn",
3441
+ detail: `Found ${configPath} but couldn't parse it: ${err instanceof Error ? err.message : String(err)}`
3442
+ };
3443
+ }
3444
+ }
3445
+ async function checkClaudeCode(cli) {
3446
+ if (!await cli.detect()) {
3447
+ return {
3448
+ name: "Claude Code",
3449
+ status: "warn",
3450
+ detail: "`claude` not found on PATH \u2014 not installed, or not registered here yet."
3451
+ };
3452
+ }
3453
+ try {
3454
+ const registration = await cli.get(SERVER_NAME);
3455
+ if (!registration) {
3456
+ return { name: "Claude Code", status: "missing", detail: `\`claude\` found but not registered globally. Run: ${INSTALL_COMMAND}` };
3457
+ }
3458
+ if (!registration.serve) {
3459
+ return { name: "Claude Code", status: "missing", detail: `The global LLMnesia entry is not a valid stdio registration. Run: ${INSTALL_COMMAND}` };
3460
+ }
3461
+ const problem = commandProblem(registration.serve.command, registration.serve.args);
3462
+ if (problem) {
3463
+ return { name: "Claude Code", status: "missing", detail: `Registered globally, but ${problem}` };
3464
+ }
3465
+ const line = await cli.status(SERVER_NAME);
3466
+ if (!line) {
3467
+ return { name: "Claude Code", status: "missing", detail: "The global entry exists but `claude mcp list` did not report it." };
3468
+ }
3469
+ if (/✗|failed|error/i.test(line)) {
3470
+ return { name: "Claude Code", status: "missing", detail: `Registered but not connecting \u2014 ${line.trim()}` };
3471
+ }
3472
+ return { name: "Claude Code", status: "ok", detail: `Registered: ${line.trim()}` };
3473
+ } catch (err) {
3474
+ return {
3475
+ name: "Claude Code",
3476
+ status: "warn",
3477
+ detail: `\`claude mcp list\` failed: ${err instanceof Error ? err.message : String(err)}`
3478
+ };
3479
+ }
3480
+ }
3481
+ async function checkCodex(home2, cli) {
3482
+ if (await cli.detect()) {
3483
+ try {
3484
+ const registration = await cli.get(SERVER_NAME);
3485
+ if (!registration) {
3486
+ return { name: "Codex", status: "missing", detail: `Codex is installed but not configured. Run: ${INSTALL_COMMAND}` };
3487
+ }
3488
+ if (!registration.serve) {
3489
+ return { name: "Codex", status: "missing", detail: `Codex has an unrecognised LLMnesia MCP entry. Run: ${INSTALL_COMMAND}` };
3490
+ }
3491
+ const problem = commandProblem(registration.serve.command, registration.serve.args);
3492
+ if (problem) {
3493
+ return { name: "Codex", status: "missing", detail: `Registered through Codex, but ${problem}` };
3494
+ }
3495
+ return { name: "Codex", status: "ok", detail: "Registered through the Codex CLI and its command resolves." };
3496
+ } catch (err) {
3497
+ return { name: "Codex", status: "warn", detail: `Could not inspect Codex MCP settings: ${err instanceof Error ? err.message : String(err)}` };
3498
+ }
3499
+ }
3500
+ const configPath = join6(home2, ".codex", "config.toml");
3501
+ if (!existsSync2(configPath)) {
3502
+ return { name: "Codex", status: "warn", detail: `Not installed (no ${configPath}), or never configured.` };
3503
+ }
3504
+ let text;
3505
+ try {
3506
+ text = readFileSync(configPath, "utf8");
3507
+ } catch (err) {
3508
+ return {
3509
+ name: "Codex",
3510
+ status: "warn",
3511
+ detail: `Found ${configPath} but couldn't read it: ${err instanceof Error ? err.message : String(err)}`
3512
+ };
3513
+ }
3514
+ const header = new RegExp(`^\\s*\\[mcp_servers\\.${SERVER_NAME}\\]\\s*$`, "m");
3515
+ if (header.test(text)) {
3516
+ return {
3517
+ name: "Codex",
3518
+ status: "warn",
3519
+ detail: `Found a manual entry in ${configPath}, but the Codex CLI is unavailable so its command could not be verified.`
3520
+ };
3521
+ }
3522
+ return {
3523
+ name: "Codex",
3524
+ status: "missing",
3525
+ detail: `Codex is installed but not configured. Run: ${INSTALL_COMMAND} (it uses Codex's CLI when available).`
3526
+ };
3527
+ }
3528
+ async function runDoctor(options = {}) {
3529
+ const home2 = options.home ?? homedir4();
3530
+ const osPlatform2 = options.osPlatform ?? platform3();
3531
+ const claudeCli = options.claudeCli ?? realClaudeCli;
3532
+ const codexCli = options.codexCli ?? realCodexCli;
3533
+ const claudeDesktopPath = osPlatform2 === "darwin" ? join6(home2, "Library", "Application Support", "Claude", "claude_desktop_config.json") : osPlatform2 === "win32" ? join6(process.env.APPDATA || join6(home2, "AppData", "Roaming"), "Claude", "claude_desktop_config.json") : null;
3534
+ const checks = [];
3535
+ const run = async (name, fn) => {
3536
+ try {
3537
+ checks.push(await fn());
3538
+ } catch (err) {
3539
+ checks.push({
3540
+ name,
3541
+ status: "warn",
3542
+ detail: `Check failed unexpectedly: ${err instanceof Error ? err.message : String(err)}`
3543
+ });
3544
+ }
3545
+ };
3546
+ await run("Native messaging host", () => checkNativeHostManifest(home2, osPlatform2));
3547
+ await run("MCP server runtime", () => checkRuntime(home2));
3548
+ await run("Corpus", () => checkCorpus(home2, options.corpusRoot));
3549
+ if (claudeDesktopPath) {
3550
+ await run("Claude Desktop", () => checkJsonClient("Claude Desktop", claudeDesktopPath));
3551
+ }
3552
+ await run("Cursor", () => checkJsonClient("Cursor", join6(home2, ".cursor", "mcp.json")));
3553
+ await run("Claude Code", () => checkClaudeCode(claudeCli));
3554
+ await run("Codex", () => checkCodex(home2, codexCli));
3555
+ checks.push({
3556
+ name: "Reminder",
3557
+ status: "warn",
3558
+ detail: "This can't detect whether you've restarted your browser or MCP client since installing \u2014 a fully quit-and-reopen is required for any of the above to take effect."
3559
+ });
3560
+ return { checks, allOk: checks.every((c) => c.status !== "missing") };
3561
+ }
3562
+ function formatDoctorReport(report) {
3563
+ const icon = { ok: "\u2713", warn: "\u2022", missing: "\u2717" };
3564
+ return report.checks.map((c) => `${icon[c.status]} ${c.name}: ${c.detail}`).join("\n");
3565
+ }
3566
+
3567
+ // src/cli.ts
3568
+ var USAGE = `llmnesia-mcp ${VERSION}
3569
+
3570
+ Usage: llmnesia-mcp <command> [options]
3571
+
3572
+ Setup:
3573
+ install [ext-id...] Install the native host + register this MCP server with
3574
+ detected clients (Claude Code/Desktop, Cursor, Codex, ...)
3575
+ doctor Diagnose: host installed? corpus present? clients wired?
3576
+ uninstall Remove native host + client registrations (never deletes
3577
+ your corpus \u2014 see the printed path if you want that too)
3578
+ serve Run the MCP stdio server (what install registers with clients)
3579
+
3580
+ Power-user / debugging:
3581
+ init Create the corpus directory skeleton
3582
+ ingest <file...> Ingest one or more NDJSON backup files into the corpus
3583
+ drain Ingest every file in <corpus>/inbox, then archive them
3584
+ watch Watch <corpus>/inbox and ingest new deltas live
3585
+ stats Print corpus counts (conversations, messages, platforms)
3586
+ reindex Drop and rebuild the search index from the corpus
3587
+ search <query> Full-text search the corpus (BM25)
3588
+
3589
+ Options:
3590
+ -c, --corpus <dir> Corpus root (default: $LLMNESIA_CORPUS_DIR or ~/.llmnesia/corpus)
3591
+ -n, --limit <n> search: max results (default 10)
3592
+ --platform <name> search: restrict to one platform
3593
+ --title <substr> search: title must contain this substring
3594
+ --from <iso|ms> search: only conversations created on/after this date
3595
+ --to <iso|ms> search: only conversations created on/before this date
3596
+ --force install: overwrite a differing corpus root in config.json
3597
+ --yes, -y install/uninstall: skip confirmation prompts
3598
+ --version, -v print the version and exit
3599
+ `;
3600
+ function parseDate(value) {
3601
+ if (!value) {
3602
+ return void 0;
3603
+ }
3604
+ if (/^\d+$/.test(value)) {
3605
+ return Number(value);
3606
+ }
3607
+ const ms = Date.parse(value);
3608
+ return Number.isNaN(ms) ? void 0 : ms;
3609
+ }
3610
+ async function promptConfirm(message) {
3611
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3612
+ try {
3613
+ process.stdout.write(`
3614
+ ${message}
3615
+ `);
3616
+ const answer = await rl.question("Proceed? [y/N] ");
3617
+ return /^y(es)?$/i.test(answer.trim());
3618
+ } finally {
3619
+ rl.close();
3620
+ }
3621
+ }
3622
+ function printRegistrationResults(results) {
3623
+ for (const r of results) {
3624
+ const icon = r.action === "registered" ? "\u2713" : r.action === "error" ? "\u2717" : "\u2022";
3625
+ process.stdout.write(`${icon} ${r.client}: ${r.detail}
3626
+
3627
+ `);
3628
+ }
3629
+ }
3630
+ async function runInstall(positionals, options, flags) {
3631
+ const skipConfirm = flags.has("yes");
3632
+ let hadProblems = false;
3633
+ process.stdout.write("Installing native messaging host\u2026\n");
3634
+ try {
3635
+ await installNativeHost({ ids: positionals, corpus: options.corpus, force: flags.has("force") });
3636
+ } catch (err) {
3637
+ hadProblems = true;
3638
+ process.stderr.write(`
3639
+ Native host install failed: ${err instanceof Error ? err.message : String(err)}
3640
+ `);
3641
+ process.stderr.write("Continuing to register MCP clients anyway \u2014 the server itself doesn't need a browser.\n");
3642
+ }
3643
+ process.stdout.write("\nInstalling the MCP server runtime\u2026\n");
3644
+ const runtime = await installRuntime();
3645
+ process.stdout.write(`Installed to ${runtime.binDir} (running on ${runtime.nodePath})
3646
+ `);
3647
+ process.stdout.write("\nRegistering MCP clients\u2026\n\n");
3648
+ const confirm = skipConfirm ? async () => true : promptConfirm;
3649
+ const results = await registerClients({ serve: runtime.serve, confirm });
3650
+ printRegistrationResults(results);
3651
+ hadProblems ||= results.some((result) => result.action === "error");
3652
+ process.stdout.write(
3653
+ "Next step: fully quit and reopen your MCP client (and your browser, if you\nuse the extension). Reloading a window is not enough \u2014 the config is read\nonce at startup.\n\nFor automatic browser-history sync, open LLMnesia Settings and click\n\u2018Enable automatic sync\u2019 once. Chrome requires that one permission click;\nthe existing-history backfill and future updates are automatic after it.\n\n"
3654
+ );
3655
+ process.stdout.write("Then run `npx -y @llmnesia/mcp@latest doctor` to check what's wired up.\n");
3656
+ if (hadProblems) {
3657
+ process.stderr.write(
3658
+ "\nInstall completed with problems. Review the error messages above; no failure was silently treated as success.\n"
3659
+ );
3660
+ return 1;
3661
+ }
3662
+ return 0;
3663
+ }
3664
+ async function runUninstall(flags) {
3665
+ const skipConfirm = flags.has("yes");
3666
+ if (!skipConfirm) {
3667
+ const ok = await promptConfirm(
3668
+ "This removes the native-messaging host and MCP client registrations. Your corpus (conversation data) is never deleted by this command."
3669
+ );
3670
+ if (!ok) {
3671
+ process.stdout.write("Cancelled.\n");
3672
+ return 0;
3673
+ }
3674
+ }
3675
+ const results = await unregisterClients();
3676
+ printRegistrationResults(results);
3677
+ if (results.some((result) => result.action === "error")) {
3678
+ process.stderr.write(
3679
+ "Uninstall stopped before removing the runtime or browser host because one or more client registrations could not be removed. Fix the \u2717 messages above and retry.\n"
3680
+ );
3681
+ return 1;
3682
+ }
3683
+ const hostResult = await uninstallNativeHost();
3684
+ process.stdout.write(`Removed: ${hostResult.removed.length > 0 ? hostResult.removed.join(", ") : "(nothing to remove)"}
3685
+ `);
3686
+ const removedRuntime = await uninstallRuntime();
3687
+ process.stdout.write(`Removed runtime: ${removedRuntime ?? "(none installed)"}
3688
+
3689
+ `);
3690
+ if (hostResult.corpusRoot) {
3691
+ process.stdout.write(
3692
+ `Your corpus was NOT deleted \u2014 it's still at ${hostResult.corpusRoot}
3693
+ Delete it yourself if you want your data gone: rm -rf "${hostResult.corpusRoot}"
3694
+ `
3695
+ );
3696
+ }
3697
+ return 0;
3698
+ }
3699
+ async function main() {
3700
+ const { command, positionals, options, flags } = parseArgs(process.argv.slice(2));
3701
+ if (flags.has("version")) {
3702
+ process.stdout.write(`${VERSION}
3703
+ `);
3704
+ return 0;
3705
+ }
3706
+ if (flags.has("help")) {
3707
+ process.stdout.write(USAGE);
3708
+ return 0;
3709
+ }
3710
+ const root = resolveCorpusDir(options.corpus);
3711
+ const corpus = new Corpus(root);
3712
+ switch (command) {
3713
+ case void 0:
3714
+ case "help":
3715
+ process.stdout.write(USAGE);
3716
+ return 0;
3717
+ case "install":
3718
+ return runInstall(positionals, options, flags);
3719
+ case "uninstall":
3720
+ return runUninstall(flags);
3721
+ case "doctor": {
3722
+ const report = await runDoctor();
3723
+ process.stdout.write(`${formatDoctorReport(report)}
3724
+ `);
3725
+ return report.allOk ? 0 : 1;
3726
+ }
3727
+ case "serve": {
3728
+ const { runServe } = await import("./mcp.js");
3729
+ await runServe();
3730
+ return 0;
3731
+ }
3732
+ case "init": {
3733
+ await corpus.init();
3734
+ process.stdout.write(`Initialized corpus at ${root}
3735
+ `);
3736
+ return 0;
3737
+ }
3738
+ case "ingest": {
3739
+ if (positionals.length === 0) {
3740
+ process.stderr.write("ingest: expected at least one file path\n");
3741
+ return 2;
3742
+ }
3743
+ await corpus.init();
3744
+ let created = 0;
3745
+ let updated = 0;
3746
+ let skipped = 0;
3747
+ let conversations = 0;
3748
+ let malformed = 0;
3749
+ for (const file of positionals) {
3750
+ const report = await ingestFile(corpus, file);
3751
+ created += report.created;
3752
+ updated += report.updated;
3753
+ skipped += report.skipped;
3754
+ conversations += report.conversations;
3755
+ malformed += report.malformedLines;
3756
+ }
3757
+ await corpus.touchIngestMeta();
3758
+ process.stdout.write(
3759
+ `Ingested ${conversations} conversation(s): ${created} created, ${updated} updated, ${skipped} unchanged` + (malformed > 0 ? `, ${malformed} malformed line(s) skipped` : "") + `
3760
+ `
3761
+ );
3762
+ return 0;
3763
+ }
3764
+ case "drain": {
3765
+ const index = await openSearchIndex(corpus);
3766
+ try {
3767
+ const report = await drainInbox(corpus, index, {
3768
+ onFileError: (name, error) => process.stderr.write(` ! ${name}: ${error instanceof Error ? error.message : String(error)}
3769
+ `)
3770
+ });
3771
+ process.stdout.write(
3772
+ `Drained ${report.files} inbox file(s): ${report.conversations} conversation(s) \u2014 ${report.created} created, ${report.updated} updated, ${report.skipped} unchanged` + (report.failed > 0 ? `, ${report.failed} file(s) failed` : "") + `
3773
+ `
3774
+ );
3775
+ } finally {
3776
+ index.close();
3777
+ }
3778
+ return 0;
3779
+ }
3780
+ case "watch": {
3781
+ process.stdout.write(`Watching ${corpus.paths.inboxDir} for new deltas (Ctrl+C to stop)\u2026
3782
+ `);
3783
+ const handle = await watchInbox(corpus, (s) => {
3784
+ process.stdout.write(
3785
+ `Ingested ${s.files} file(s): ${s.created} created, ${s.updated} updated, ${s.skipped} unchanged
3786
+ `
3787
+ );
3788
+ });
3789
+ await new Promise((resolve4) => {
3790
+ const stop = () => {
3791
+ void handle.close().then(resolve4);
3792
+ };
3793
+ process.once("SIGINT", stop);
3794
+ process.once("SIGTERM", stop);
3795
+ });
3796
+ return 0;
3797
+ }
3798
+ case "stats": {
3799
+ const stats = await corpus.stats();
3800
+ const platforms = Object.entries(stats.byPlatform).sort((a, b) => b[1] - a[1]).map(([p, n]) => ` ${p}: ${n}`).join("\n");
3801
+ process.stdout.write(
3802
+ `Corpus: ${root}
3803
+ conversations: ${stats.conversationCount}
3804
+ messages: ${stats.messageCount}
3805
+ ` + (platforms ? ` by platform:
3806
+ ${platforms}
3807
+ ` : "")
3808
+ );
3809
+ return 0;
3810
+ }
3811
+ case "reindex": {
3812
+ await corpus.init();
3813
+ await deleteIndexDb(corpus.paths.indexDbFile);
3814
+ const index = new SearchIndex(corpus.paths.indexDbFile);
3815
+ try {
3816
+ const { conversations } = await index.rebuildFrom(corpus);
3817
+ process.stdout.write(`Rebuilt index: ${conversations} conversation(s)
3818
+ `);
3819
+ } finally {
3820
+ index.close();
3821
+ }
3822
+ return 0;
3823
+ }
3824
+ case "search": {
3825
+ const query = positionals.join(" ").trim();
3826
+ if (!query) {
3827
+ process.stderr.write("search: expected a query\n");
3828
+ return 2;
3829
+ }
3830
+ const filters = {
3831
+ platform: options.platform || void 0,
3832
+ title: options.title || void 0,
3833
+ dateFrom: parseDate(options.from),
3834
+ dateTo: parseDate(options.to),
3835
+ limit: options.limit ? Number(options.limit) : void 0
3836
+ };
3837
+ const index = await openSearchIndex(corpus);
3838
+ try {
3839
+ const hits = index.search(query, filters);
3840
+ if (hits.length === 0) {
3841
+ process.stdout.write("No matches.\n");
3842
+ return 0;
3843
+ }
3844
+ for (const hit of hits) {
3845
+ const when = new Date(hit.createdAt).toISOString().slice(0, 10);
3846
+ const where = hit.matchRole === "title" ? "title" : `${hit.matchRole} #${hit.matchMsgIndex}`;
3847
+ process.stdout.write(
3848
+ `${hit.pinned ? "\u2605 " : ""}${hit.title} [${hit.platform} \xB7 ${when} \xB7 score ${hit.score.toFixed(2)}]
3849
+ ${hit.docId}
3850
+ ${collapse(hit.snippet)} (${where})
3851
+
3852
+ `
3853
+ );
3854
+ }
3855
+ } finally {
3856
+ index.close();
3857
+ }
3858
+ return 0;
3859
+ }
3860
+ default:
3861
+ process.stderr.write(`Unknown command: ${command}
3862
+
3863
+ ${USAGE}`);
3864
+ return 2;
3865
+ }
3866
+ }
3867
+ function collapse(text) {
3868
+ return text.replace(/\s+/g, " ").trim();
3869
+ }
3870
+ export {
3871
+ main
3872
+ };
3873
+ /*! Bundled license information:
3874
+
3875
+ chokidar/esm/index.js:
3876
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
3877
+ */