@mebular/mcp 0.3.4 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,966 @@
1
+ // Adapter descriptor: Hermes Agent (`mebular` MemoryProvider).
2
+ //
3
+ // Boundaries (see docs/integrations/HERMES.md):
4
+ // * installs *only* `$HERMES_HOME/plugins/mebular` (directory name == the
5
+ // value of `memory.provider`, never `mebular-memory`);
6
+ // * selects the provider through the official CLI
7
+ // (`hermes config set memory.provider mebular`), then reads it back;
8
+ // * never writes Hermes' internal DB / session storage / provider spool;
9
+ // * never downloads from npm: the bundle comes from the App bundle, a managed
10
+ // directory, or (dev/tests) this repository / an injected path;
11
+ // * never kills a host process: activation is an injected reload/restart
12
+ // callback, otherwise `next-start`;
13
+ // * byte-level config backup, staged directory install, rollback.
14
+ //
15
+ // `sync_turn` ingest health is deliberately *not* checked here (verify only
16
+ // proves configuration); the existing repair/health flow owns ingest evidence.
17
+
18
+ import { execFile } from 'node:child_process';
19
+ import { createHash } from 'node:crypto';
20
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
21
+ import { chmod, copyFile, cp, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
22
+ import { homedir } from 'node:os';
23
+ import { basename, delimiter, dirname, join, resolve, sep } from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { APP_VERSION } from '../version.mjs';
26
+
27
+ export const PACKAGE_NAME = 'mebular';
28
+ export const PLUGIN_DIR_NAME = 'mebular';
29
+ export const CONFIG_KEY = 'memory.provider';
30
+
31
+ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
32
+ const MANAGED_DIR = 'adapters';
33
+ const MANAGED_NAME = 'hermes';
34
+
35
+ const FORBIDDEN_HOST_DIRS = [
36
+ 'sessions',
37
+ 'session',
38
+ 'db',
39
+ 'databases',
40
+ 'state',
41
+ 'data',
42
+ 'cache',
43
+ 'logs',
44
+ 'history',
45
+ 'memories',
46
+ 'mebular-memory',
47
+ ];
48
+
49
+ /** assistant 落面以用户主目录为基(与 clients.mjs 的 `assistantUserHome` 同语义)。 */
50
+ export function resolveUserHome(options = {}) {
51
+ if (typeof options.userHome === 'string' && options.userHome.length > 0) return options.userHome;
52
+ const env = options.env ?? process.env;
53
+ const fromEnv = env?.MEBULAR_USER_HOME;
54
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv;
55
+ return homedir();
56
+ }
57
+
58
+ function expandPath(value, userHome) {
59
+ if (typeof value !== 'string' || value.trim().length === 0) return null;
60
+ const text = value.trim();
61
+ if (text === '~') return userHome;
62
+ if (/^~[\\/]/.test(text)) return join(userHome, text.slice(2));
63
+ return resolve(text);
64
+ }
65
+
66
+ /**
67
+ * `$HERMES_HOME`: explicit option > injected env > process env > `~/.hermes`.
68
+ * It is *not* Mebular's home (`MEBULAR_HOME`); mixing the two is a host bug.
69
+ */
70
+ export function hermesHomeFor(options = {}) {
71
+ const explicit = options.hermesHome;
72
+ const userHome = resolveUserHome(options);
73
+ if (typeof explicit === 'string' && explicit.length > 0) return expandPath(explicit, userHome);
74
+ const env = options.env ?? process.env;
75
+ const fromEnv = env?.HERMES_HOME;
76
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return expandPath(fromEnv, userHome);
77
+ return join(userHome, '.hermes');
78
+ }
79
+
80
+ export function configPathFor(options = {}) {
81
+ const explicit = options.configPath ?? options.primaryPath;
82
+ const userHome = resolveUserHome(options);
83
+ if (typeof explicit === 'string' && explicit.length > 0) return expandPath(explicit, userHome);
84
+ return join(hermesHomeFor(options), 'config.yaml');
85
+ }
86
+
87
+ export function providerPathFor(options = {}) {
88
+ const explicit = options.providerPath;
89
+ const userHome = resolveUserHome(options);
90
+ if (typeof explicit === 'string' && explicit.length > 0) return expandPath(explicit, userHome);
91
+ return join(hermesHomeFor(options), 'plugins', PLUGIN_DIR_NAME);
92
+ }
93
+
94
+ /** 禁写路径:Hermes 内部 DB / 会话存储 / provider spool,只允许 plugins/mebular 与配置。 */
95
+ export function isForbiddenPath(file, options = {}) {
96
+ if (typeof file !== 'string' || file.length === 0) return true;
97
+ if ((Array.isArray(options.forbiddenPaths) ? options.forbiddenPaths : []).includes(file)) return true;
98
+ const hermesHome = hermesHomeFor(options);
99
+ const roots = [
100
+ ...FORBIDDEN_HOST_DIRS.map((name) => join(hermesHome, name)),
101
+ ...(Array.isArray(options.forbiddenRoots) ? options.forbiddenRoots : []),
102
+ ];
103
+ if (roots.some((root) => typeof root === 'string' && (file === root || file.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)))) {
104
+ return true;
105
+ }
106
+ const basenameHit = basename(file);
107
+ if (basenameHit === 'auth.json' || basenameHit === '.env') return true;
108
+ return false;
109
+ }
110
+
111
+ function tsStamp() {
112
+ return new Date().toISOString().replace(/[:.]/g, '-');
113
+ }
114
+
115
+ function readTextFile(path) {
116
+ try {
117
+ return readFileSync(path, 'utf-8');
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+
123
+ function parsePluginYaml(text) {
124
+ const name = /^name:\s*["']?([^"'\s#]+)["']?\s*(?:#.*)?$/m.exec(text ?? '');
125
+ const version = /^version:\s*["']?([^"'\s#]+)["']?\s*(?:#.*)?$/m.exec(text ?? '');
126
+ return { name: name ? name[1] : null, version: version ? version[1] : null };
127
+ }
128
+
129
+ function skipArtifacts(source) {
130
+ const name = basename(source);
131
+ return name !== '__pycache__' && !name.endsWith('.pyc') && !name.endsWith('.pyo');
132
+ }
133
+
134
+ /**
135
+ * Read a provider bundle (a directory with `plugin.yaml` + `__init__.py`).
136
+ * The fingerprint makes idempotency content-aware, not just version-aware.
137
+ */
138
+ export function readBundle(dir) {
139
+ if (typeof dir !== 'string' || dir.length === 0) return null;
140
+ const yaml = readTextFile(join(dir, 'plugin.yaml'));
141
+ if (yaml === null) return null;
142
+ const init = readTextFile(join(dir, '__init__.py'));
143
+ const manifest = parsePluginYaml(yaml);
144
+ return {
145
+ path: dir,
146
+ name: manifest.name,
147
+ version: manifest.version,
148
+ hasInit: init !== null,
149
+ fingerprint: init === null ? null : createHash('sha256').update(yaml).update('\0').update(init).digest('hex'),
150
+ };
151
+ }
152
+
153
+ function bundleMatches(bundle, expectedVersion) {
154
+ return bundle !== null
155
+ && bundle.name === PACKAGE_NAME
156
+ && bundle.version === expectedVersion
157
+ && bundle.hasInit === true;
158
+ }
159
+
160
+ function sameBundle(a, b, expectedVersion) {
161
+ return bundleMatches(a, expectedVersion)
162
+ && bundleMatches(b, expectedVersion)
163
+ && typeof a.fingerprint === 'string'
164
+ && a.fingerprint === b.fingerprint;
165
+ }
166
+
167
+ function hermesCommand(options = {}) {
168
+ return typeof options.hermesCommand === 'string' && options.hermesCommand.length > 0
169
+ ? options.hermesCommand
170
+ : 'hermes';
171
+ }
172
+
173
+ function cliEnv(options = {}, hermesHome = hermesHomeFor(options)) {
174
+ const userHome = resolveUserHome(options);
175
+ const provided = options.env ?? {};
176
+ const basePath = typeof provided.PATH === 'string' && provided.PATH.length > 0
177
+ ? provided.PATH
178
+ : process.env.PATH;
179
+ const extra = [join(userHome, '.local', 'bin'), dirname(process.execPath)];
180
+ if (process.platform !== 'win32') extra.push('/usr/local/bin', '/opt/homebrew/bin');
181
+ const parts = [...(typeof basePath === 'string' && basePath.length > 0 ? basePath.split(delimiter) : []), ...extra]
182
+ .filter((entry) => typeof entry === 'string' && entry.length > 0);
183
+ const env = { ...process.env, ...provided };
184
+ if (parts.length > 0) env.PATH = [...new Set(parts)].join(delimiter);
185
+ env.HERMES_HOME = hermesHome;
186
+ return env;
187
+ }
188
+
189
+ function normalizeCliResult(result) {
190
+ if (result === null || typeof result !== 'object') return { ok: false, code: 'CLI_FAILED', stdout: '', stderr: '' };
191
+ return {
192
+ ok: result.ok === true,
193
+ code: result.code ?? (result.ok === true ? 0 : 1),
194
+ stdout: typeof result.stdout === 'string' ? result.stdout : '',
195
+ stderr: typeof result.stderr === 'string' ? result.stderr : '',
196
+ };
197
+ }
198
+
199
+ /** Run the Hermes CLI. Never logs stdout/stderr (they may contain host state). */
200
+ function shellQuote(value) {
201
+ const text = String(value);
202
+ if (/^[A-Za-z0-9_./:@%+-]+$/.test(text)) return text;
203
+ return `'${text.replace(/'/g, `'\\''`)}'`;
204
+ }
205
+
206
+ async function runHermesCli(args, options = {}, { timeoutMs = 10_000 } = {}) {
207
+ const command = hermesCommand(options);
208
+ const env = cliEnv(options);
209
+ const commandLine = [shellQuote(command), ...args.map(shellQuote)].join(' ');
210
+
211
+ // Injected runners (tests / App-owned host control) are honored before
212
+ // spawning a real process; they receive the same shell-style command line as
213
+ // clients.mjs (`run` is the synchronous legacy alias).
214
+ const injected = typeof options.runCli === 'function'
215
+ ? async () => options.runCli({ command, args, env, timeoutMs })
216
+ : typeof options.runAsync === 'function'
217
+ ? async () => options.runAsync(commandLine, timeoutMs)
218
+ : typeof options.run === 'function'
219
+ ? async () => options.run(commandLine, timeoutMs)
220
+ : null;
221
+ if (injected) {
222
+ try {
223
+ return normalizeCliResult(await injected());
224
+ } catch (error) {
225
+ return { ok: false, code: error?.code ?? 'CLI_FAILED', stdout: '', stderr: '' };
226
+ }
227
+ }
228
+ return await new Promise((resolvePromise) => {
229
+ execFile(command, args, {
230
+ timeout: timeoutMs,
231
+ encoding: 'utf-8',
232
+ maxBuffer: 1 << 20,
233
+ windowsHide: true,
234
+ // Hermes' Windows installer ships `hermes.exe`; pipx/legacy installs may
235
+ // expose a `.cmd` shim. `execFile` cannot launch `.cmd` without a shell,
236
+ // so route the trusted, fixed CLI arguments through cmd.exe on Windows.
237
+ shell: process.platform === 'win32',
238
+ env,
239
+ }, (error, stdout, stderr) => {
240
+ if (error) {
241
+ resolvePromise({ ok: false, code: error.code ?? 1, stdout: stdout ?? '', stderr: stderr ?? '' });
242
+ return;
243
+ }
244
+ resolvePromise({ ok: true, code: 0, stdout: stdout ?? '', stderr: stderr ?? '' });
245
+ });
246
+ });
247
+ }
248
+
249
+ function unquote(value) {
250
+ const text = String(value ?? '').trim();
251
+ if (text === 'None' || text === 'null' || text === '~') return '';
252
+ if ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'"))) {
253
+ return text.slice(1, -1);
254
+ }
255
+ return text;
256
+ }
257
+
258
+ /** Minimal read-only `memory.provider` parser for Hermes' config.yaml. */
259
+ export function parseProviderFromConfigText(text) {
260
+ const lines = String(text ?? '').split(/\r?\n/);
261
+ let memoryIndent = null;
262
+ for (const line of lines) {
263
+ const top = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(line);
264
+ if (top) {
265
+ if (top[1] !== 'memory') {
266
+ memoryIndent = null;
267
+ continue;
268
+ }
269
+ memoryIndent = 0;
270
+ const inline = top[2].trim();
271
+ if (inline.startsWith('{') && inline.endsWith('}')) {
272
+ const match = /(?:^|[,{\s])provider\s*:\s*([^,}\s]+)/.exec(inline);
273
+ if (match) return unquote(match[1]);
274
+ }
275
+ continue;
276
+ }
277
+ if (memoryIndent === null) continue;
278
+ const child = /^(\s+)provider:\s*(.*)$/.exec(line);
279
+ if (child) return unquote(child[2].replace(/\s+#.*$/, '').trim());
280
+ }
281
+ return null;
282
+ }
283
+
284
+ function parseProviderOutput(stdout) {
285
+ const lines = String(stdout ?? '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
286
+ if (lines.length === 0) return null;
287
+ const last = lines[lines.length - 1];
288
+ const keyed = /^[^:]+:\s*(.*)$/.exec(last);
289
+ return unquote(keyed ? keyed[1] : last);
290
+ }
291
+
292
+ /**
293
+ * Read `memory.provider` through the CLI first, then the config file.
294
+ * An empty CLI result falls back to the file so a stale CLI cannot mask a
295
+ * correctly selected provider.
296
+ */
297
+ export async function readProvider(options = {}) {
298
+ const configPath = configPathFor(options);
299
+ const cli = await runHermesCli(['config', 'get', CONFIG_KEY], options);
300
+ if (cli.ok) {
301
+ const value = parseProviderOutput(cli.stdout);
302
+ if (value !== null && value !== '') return { value, source: 'cli' };
303
+ }
304
+ const text = readTextFile(configPath);
305
+ if (text !== null) {
306
+ const value = parseProviderFromConfigText(text);
307
+ if (value !== null) return { value, source: 'file' };
308
+ }
309
+ if (cli.ok) return { value: '', source: 'cli' };
310
+ return { value: null, source: null };
311
+ }
312
+
313
+ /** Host detection: config/dir signals plus `hermes --version` (read-only). */
314
+ export async function detect(options = {}) {
315
+ const hermesHome = hermesHomeFor(options);
316
+ const configPath = configPathFor(options);
317
+ const configHit = existsSync(configPath);
318
+ const dirHit = existsSync(hermesHome);
319
+ const cli = await runHermesCli(['--version'], options, { timeoutMs: 2500 });
320
+ const cliVersion = cli.ok ? String(cli.stdout ?? '').split(/\r?\n/)[0].trim() || null : null;
321
+ return {
322
+ detected: configHit || dirHit || cli.ok,
323
+ hermesHome,
324
+ configPath,
325
+ cliVersion,
326
+ signals: [
327
+ { kind: 'config-file', source: configPath, hit: configHit },
328
+ { kind: 'hermes-home', source: hermesHome, hit: dirHit },
329
+ { kind: 'cli', source: `${hermesCommand(options)} --version`, hit: cli.ok === true, detail: `rc=${cli.code}` },
330
+ ],
331
+ };
332
+ }
333
+
334
+ function packageCandidates(options = {}, expectedVersion) {
335
+ const userHome = resolveUserHome(options);
336
+ const explicit = options.adapterPackagePath ?? options.packagePath;
337
+ if (typeof explicit === 'string' && explicit.length > 0) {
338
+ return [{ path: expandPath(explicit, userHome), source: 'manual', exclusive: true }];
339
+ }
340
+ const candidates = [];
341
+ const home = options.home ?? options.mebularHome;
342
+ if (typeof home === 'string' && home.length > 0) {
343
+ candidates.push({
344
+ path: join(home, MANAGED_DIR, MANAGED_NAME, expectedVersion),
345
+ source: 'managed-dir',
346
+ });
347
+ }
348
+ const resourcesPath = options.resourcesPath
349
+ ?? process.env.MEBULAR_RESOURCES_PATH
350
+ ?? process.resourcesPath;
351
+ if (typeof resourcesPath === 'string' && resourcesPath.length > 0) {
352
+ candidates.push({ path: join(resourcesPath, MANAGED_DIR, MANAGED_NAME), source: 'bundled' });
353
+ }
354
+ candidates.push({ path: join(REPO_ROOT, 'integrations', 'hermes', 'mebular-memory'), source: 'manual' });
355
+ return candidates;
356
+ }
357
+
358
+ async function stageBundledPackage(source, options, expectedVersion) {
359
+ const home = options.home ?? options.mebularHome;
360
+ if (typeof home !== 'string' || home.length === 0) return null;
361
+ const target = join(home, MANAGED_DIR, MANAGED_NAME, expectedVersion);
362
+ const existing = readBundle(target);
363
+ if (sameBundle(source, existing, expectedVersion)) {
364
+ return { path: target, changed: false, created: false };
365
+ }
366
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
367
+ try {
368
+ await mkdir(dirname(target), { recursive: true });
369
+ await rm(tmp, { recursive: true, force: true });
370
+ await cp(source.path, tmp, { recursive: true, filter: skipArtifacts });
371
+ const staged = readBundle(tmp);
372
+ if (!sameBundle(source, staged, expectedVersion)) {
373
+ await rm(tmp, { recursive: true, force: true });
374
+ return null;
375
+ }
376
+ await rm(target, { recursive: true, force: true });
377
+ await rename(tmp, target);
378
+ return { path: target, changed: true, created: existing === null };
379
+ } catch {
380
+ try { await rm(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
381
+ return null;
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Resolve the provider bundle. Order: explicit path, managed dir
387
+ * (`<home>/adapters/hermes/<version>`), App bundle (`<resources>/adapters/hermes`),
388
+ * repository checkout. Never npm; version must equal the App lockstep version.
389
+ * `dryRun` and `stagePackage:false` are strictly read-only.
390
+ */
391
+ export async function ensurePackage(options = {}) {
392
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
393
+ const candidates = packageCandidates(options, expectedVersion);
394
+ let mismatch = null;
395
+ for (const candidate of candidates) {
396
+ if (!candidate?.path) continue;
397
+ const bundle = readBundle(candidate.path);
398
+ if (!bundle) {
399
+ if (candidate.exclusive) return { ok: false, code: 'ADAPTER_PACKAGE_NOT_FOUND' };
400
+ continue;
401
+ }
402
+ if (!bundleMatches(bundle, expectedVersion)) {
403
+ mismatch = { version: bundle.version ?? null, name: bundle.name ?? null };
404
+ if (candidate.exclusive) break;
405
+ continue;
406
+ }
407
+ if (candidate.source === 'bundled') {
408
+ const home = options.home ?? options.mebularHome;
409
+ if (options.dryRun === true || options.stagePackage === false) {
410
+ if (options.dryRun === true) {
411
+ const plannedPath = typeof home === 'string' && home.length > 0
412
+ ? join(home, MANAGED_DIR, MANAGED_NAME, expectedVersion)
413
+ : resolve(candidate.path);
414
+ const existing = readBundle(plannedPath);
415
+ const alreadyManaged = sameBundle(bundle, existing, expectedVersion);
416
+ return {
417
+ ok: true,
418
+ path: plannedPath,
419
+ sourcePath: resolve(candidate.path),
420
+ version: expectedVersion,
421
+ source: 'managed-dir',
422
+ changed: !alreadyManaged,
423
+ created: false,
424
+ planned: !alreadyManaged,
425
+ managedPath: plannedPath,
426
+ };
427
+ }
428
+ return {
429
+ ok: true,
430
+ path: resolve(candidate.path),
431
+ version: expectedVersion,
432
+ source: 'bundled',
433
+ changed: false,
434
+ created: false,
435
+ planned: false,
436
+ managedPath: null,
437
+ };
438
+ }
439
+ const staged = await stageBundledPackage(bundle, options, expectedVersion);
440
+ if (staged) {
441
+ return {
442
+ ok: true,
443
+ path: staged.path,
444
+ version: expectedVersion,
445
+ source: 'managed-dir',
446
+ changed: staged.changed,
447
+ created: staged.created,
448
+ planned: false,
449
+ managedPath: staged.created ? staged.path : null,
450
+ };
451
+ }
452
+ }
453
+ return {
454
+ ok: true,
455
+ path: resolve(candidate.path),
456
+ version: expectedVersion,
457
+ source: candidate.source,
458
+ changed: false,
459
+ created: false,
460
+ planned: false,
461
+ managedPath: null,
462
+ };
463
+ }
464
+ if (mismatch) return { ok: false, code: 'ADAPTER_VERSION_MISMATCH', version: mismatch.version };
465
+ return { ok: false, code: 'ADAPTER_PACKAGE_NOT_FOUND' };
466
+ }
467
+
468
+ async function uniqueBackupPath(base) {
469
+ const stamp = tsStamp();
470
+ let candidate = `${base}.bak-${stamp}`;
471
+ for (let index = 1; existsSync(candidate); index += 1) {
472
+ candidate = `${base}.bak-${stamp}-${index}`;
473
+ }
474
+ return candidate;
475
+ }
476
+
477
+ function latestProviderBackup(target) {
478
+ try {
479
+ const dir = dirname(target);
480
+ const prefix = `${basename(target)}.bak-`;
481
+ const names = readdirSync(dir).filter((name) => name.startsWith(prefix)).sort();
482
+ return names.length > 0 ? join(dir, names[names.length - 1]) : null;
483
+ } catch {
484
+ return null;
485
+ }
486
+ }
487
+
488
+ function configBackupDir(options = {}) {
489
+ const home = options.home ?? options.mebularHome;
490
+ if (typeof home === 'string' && home.length > 0) return join(home, MANAGED_DIR, 'backups');
491
+ return dirname(configPathFor(options));
492
+ }
493
+
494
+ function latestConfigBackup(options = {}) {
495
+ try {
496
+ const dir = configBackupDir(options);
497
+ const prefix = `${basename(configPathFor(options))}.bak-`;
498
+ const names = readdirSync(dir).filter((name) => name.startsWith(prefix)).sort();
499
+ return names.length > 0 ? join(dir, names[names.length - 1]) : null;
500
+ } catch {
501
+ return null;
502
+ }
503
+ }
504
+
505
+ function latestConfigAbsentMarker(options = {}) {
506
+ try {
507
+ const dir = configBackupDir(options);
508
+ const names = readdirSync(dir).filter((name) => name.startsWith('config.absent-')).sort();
509
+ return names.length > 0 ? join(dir, names[names.length - 1]) : null;
510
+ } catch {
511
+ return null;
512
+ }
513
+ }
514
+
515
+ async function markConfigAbsent(options) {
516
+ const dir = configBackupDir(options);
517
+ await mkdir(dir, { recursive: true, mode: 0o700 });
518
+ const stamp = tsStamp();
519
+ let marker = join(dir, `config.absent-${stamp}`);
520
+ for (let index = 1; existsSync(marker); index += 1) marker = join(dir, `config.absent-${stamp}-${index}`);
521
+ await writeFile(marker, '', { encoding: 'utf-8', mode: 0o600 });
522
+ return marker;
523
+ }
524
+
525
+ function latestProviderAbsentMarker(options = {}) {
526
+ try {
527
+ const dir = configBackupDir(options);
528
+ const names = readdirSync(dir).filter((name) => name.startsWith('provider.absent-')).sort();
529
+ return names.length > 0 ? join(dir, names[names.length - 1]) : null;
530
+ } catch {
531
+ return null;
532
+ }
533
+ }
534
+
535
+ async function markProviderAbsent(options) {
536
+ const dir = configBackupDir(options);
537
+ await mkdir(dir, { recursive: true, mode: 0o700 });
538
+ const stamp = tsStamp();
539
+ let marker = join(dir, `provider.absent-${stamp}`);
540
+ for (let index = 1; existsSync(marker); index += 1) marker = join(dir, `provider.absent-${stamp}-${index}`);
541
+ await writeFile(marker, '', { encoding: 'utf-8', mode: 0o600 });
542
+ return marker;
543
+ }
544
+
545
+ async function clearProviderAbsentMarkers(options) {
546
+ try {
547
+ const dir = configBackupDir(options);
548
+ const names = readdirSync(dir).filter((name) => name.startsWith('provider.absent-'));
549
+ await Promise.all(names.map((name) => rm(join(dir, name), { force: true })));
550
+ } catch {
551
+ // Diagnostic markers only.
552
+ }
553
+ }
554
+
555
+ async function backupConfig(configPath, options) {
556
+ const dir = configBackupDir(options);
557
+ await mkdir(dir, { recursive: true, mode: 0o700 });
558
+ const target = await uniqueBackupPath(join(dir, basename(configPath)));
559
+ await copyFile(configPath, target);
560
+ return target;
561
+ }
562
+
563
+ async function atomicWrite(file, text, mode = 0o600) {
564
+ await mkdir(dirname(file), { recursive: true });
565
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
566
+ try {
567
+ await writeFile(tmp, text, { encoding: 'utf-8', mode });
568
+ try { await chmod(tmp, mode); } catch { /* Windows 无 POSIX mode */ }
569
+ await rename(tmp, file);
570
+ } catch (error) {
571
+ try { await rm(tmp, { force: true }); } catch { /* ignore */ }
572
+ throw error;
573
+ }
574
+ }
575
+
576
+ async function installProvider(sourcePath, options, expectedVersion) {
577
+ const target = providerPathFor(options);
578
+ if (isForbiddenPath(target, options)) return { ok: false, code: 'FORBIDDEN_PATH' };
579
+ const source = readBundle(sourcePath);
580
+ if (!bundleMatches(source, expectedVersion)) return { ok: false, code: 'ADAPTER_PACKAGE_INVALID' };
581
+ const existing = readBundle(target);
582
+ if (sameBundle(source, existing, expectedVersion) && options.force !== true) {
583
+ return { ok: true, changed: false, backupPath: null, target };
584
+ }
585
+ if (options.dryRun === true) {
586
+ return { ok: true, changed: true, planned: true, backupPath: null, target };
587
+ }
588
+
589
+ const pluginsDir = dirname(target);
590
+ const stage = join(pluginsDir, `.mebular-stage-${process.pid}-${Date.now()}`);
591
+ try {
592
+ await mkdir(pluginsDir, { recursive: true });
593
+ await rm(stage, { recursive: true, force: true });
594
+ await cp(sourcePath, stage, { recursive: true, filter: skipArtifacts });
595
+ if (!bundleMatches(readBundle(stage), expectedVersion)) {
596
+ await rm(stage, { recursive: true, force: true });
597
+ return { ok: false, code: 'PROVIDER_STAGE_FAILED' };
598
+ }
599
+
600
+ let backupPath = null;
601
+ if (existsSync(target)) {
602
+ backupPath = await uniqueBackupPath(target);
603
+ await rename(target, backupPath);
604
+ }
605
+ try {
606
+ await rename(stage, target);
607
+ } catch {
608
+ await rm(stage, { recursive: true, force: true });
609
+ if (backupPath) {
610
+ try { await rename(backupPath, target); } catch { /* ignore */ }
611
+ }
612
+ return { ok: false, code: 'PROVIDER_INSTALL_FAILED' };
613
+ }
614
+ return { ok: true, changed: true, backupPath, target };
615
+ } catch {
616
+ try { await rm(stage, { recursive: true, force: true }); } catch { /* ignore */ }
617
+ return { ok: false, code: 'PROVIDER_INSTALL_FAILED' };
618
+ }
619
+ }
620
+
621
+ async function undoProvider(install, options) {
622
+ if (!install?.changed) return;
623
+ const target = install.target ?? providerPathFor(options);
624
+ if (install.backupPath && existsSync(install.backupPath)) {
625
+ try {
626
+ if (existsSync(target)) await rm(target, { recursive: true, force: true });
627
+ await rename(install.backupPath, target);
628
+ } catch {
629
+ // Leave the backup in place for an explicit rollback.
630
+ }
631
+ return;
632
+ }
633
+ try { await rm(target, { recursive: true, force: true }); } catch { /* ignore */ }
634
+ }
635
+
636
+ async function undoConfig(configPath, configExisted, backupPath, absentMarker) {
637
+ try {
638
+ if (backupPath && existsSync(backupPath)) {
639
+ const text = await readFile(backupPath, 'utf-8');
640
+ let mode = 0o600;
641
+ try { mode = (await stat(configPath)).mode & 0o777; } catch { /* newly created */ }
642
+ await atomicWrite(configPath, text, mode);
643
+ } else if (!configExisted && existsSync(configPath)) {
644
+ await rm(configPath, { force: true });
645
+ }
646
+ if (absentMarker && existsSync(absentMarker)) await rm(absentMarker, { force: true });
647
+ } catch {
648
+ // Best effort; the config backup remains available for explicit rollback.
649
+ }
650
+ }
651
+
652
+ function previewText(sourcePath, target, currentValue) {
653
+ return [
654
+ `install provider: ${sourcePath} -> ${target}`,
655
+ `config ${CONFIG_KEY}: ${currentValue === null ? '(unset)' : JSON.stringify(currentValue)} -> ${JSON.stringify(PACKAGE_NAME)}`,
656
+ ].join('\n');
657
+ }
658
+
659
+ /**
660
+ * Configure: install the provider directory (staged + backup), then select it
661
+ * through `hermes config set memory.provider mebular` and read it back.
662
+ * `dryRun` performs read-only checks and returns the planned changes.
663
+ */
664
+ export async function configure(options = {}) {
665
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
666
+ const hermesHome = hermesHomeFor(options);
667
+ const configPath = configPathFor(options);
668
+ const providerTarget = providerPathFor(options);
669
+ if (isForbiddenPath(providerTarget, options) || isForbiddenPath(configPath, options)) {
670
+ return { ok: false, code: 'FORBIDDEN_PATH' };
671
+ }
672
+
673
+ const packageInfo = options.packageInfo?.ok === true
674
+ ? options.packageInfo
675
+ : await ensurePackage({
676
+ ...options,
677
+ hermesHome,
678
+ ...(options.dryRun === true ? { dryRun: true, stagePackage: false } : {}),
679
+ });
680
+ if (!packageInfo?.ok) return packageInfo;
681
+
682
+ const sourcePath = options.dryRun === true && typeof packageInfo.sourcePath === 'string'
683
+ ? packageInfo.sourcePath
684
+ : packageInfo.path;
685
+ const source = readBundle(sourcePath);
686
+ if (!bundleMatches(source, expectedVersion)) return { ok: false, code: 'ADAPTER_PACKAGE_INVALID' };
687
+
688
+ const current = await readProvider({ ...options, hermesHome, configPath });
689
+ const needsInstall = !sameBundle(source, readBundle(providerTarget), expectedVersion);
690
+ const needsConfig = current.value !== PACKAGE_NAME;
691
+ const changed = needsInstall || needsConfig;
692
+
693
+ if (options.dryRun === true) {
694
+ return {
695
+ ok: true,
696
+ changed,
697
+ dryRun: true,
698
+ configPath,
699
+ providerPath: providerTarget,
700
+ backupPath: null,
701
+ entry: { provider: PACKAGE_NAME },
702
+ preview: previewText(sourcePath, providerTarget, current.value),
703
+ };
704
+ }
705
+
706
+ let providerAbsentMarker = null;
707
+ if (needsInstall && !existsSync(providerTarget)) {
708
+ try {
709
+ providerAbsentMarker = await markProviderAbsent(options);
710
+ } catch {
711
+ return { ok: false, code: 'PROVIDER_BACKUP_FAILED' };
712
+ }
713
+ }
714
+
715
+ const install = await installProvider(packageInfo.path, { ...options, hermesHome }, expectedVersion);
716
+ if (!install.ok) {
717
+ if (providerAbsentMarker) {
718
+ try { await rm(providerAbsentMarker, { force: true }); } catch { /* ignore */ }
719
+ }
720
+ return install;
721
+ }
722
+ if (install.backupPath) await clearProviderAbsentMarkers(options);
723
+ if (!install.changed && providerAbsentMarker) {
724
+ try { await rm(providerAbsentMarker, { force: true }); } catch { /* ignore */ }
725
+ providerAbsentMarker = null;
726
+ }
727
+
728
+ let configBackup = null;
729
+ let configAbsentMarker = null;
730
+ if (needsConfig) {
731
+ const configExisted = existsSync(configPath);
732
+ if (configExisted) {
733
+ try {
734
+ configBackup = await backupConfig(configPath, options);
735
+ } catch {
736
+ await undoProvider(install, options);
737
+ if (providerAbsentMarker) {
738
+ try { await rm(providerAbsentMarker, { force: true }); } catch { /* ignore */ }
739
+ }
740
+ return { ok: false, code: 'CONFIG_BACKUP_FAILED', rolledBack: install.changed === true };
741
+ }
742
+ } else {
743
+ try {
744
+ configAbsentMarker = await markConfigAbsent(options);
745
+ } catch {
746
+ await undoProvider(install, options);
747
+ if (providerAbsentMarker) {
748
+ try { await rm(providerAbsentMarker, { force: true }); } catch { /* ignore */ }
749
+ }
750
+ return { ok: false, code: 'CONFIG_BACKUP_FAILED', rolledBack: install.changed === true };
751
+ }
752
+ }
753
+ const set = await runHermesCli(['config', 'set', CONFIG_KEY, PACKAGE_NAME], options);
754
+ if (!set.ok) {
755
+ await undoProvider(install, options);
756
+ await undoConfig(configPath, configExisted, configBackup, configAbsentMarker);
757
+ if (providerAbsentMarker) {
758
+ try { await rm(providerAbsentMarker, { force: true }); } catch { /* ignore */ }
759
+ }
760
+ return {
761
+ ok: false,
762
+ code: set.code === 'ENOENT' ? 'HERMES_CLI_UNAVAILABLE' : 'CONFIG_SET_FAILED',
763
+ rolledBack: true,
764
+ };
765
+ }
766
+ const readback = await readProvider({ ...options, hermesHome, configPath });
767
+ if (readback.value !== PACKAGE_NAME) {
768
+ await undoProvider(install, options);
769
+ await undoConfig(configPath, configExisted, configBackup, configAbsentMarker);
770
+ if (providerAbsentMarker) {
771
+ try { await rm(providerAbsentMarker, { force: true }); } catch { /* ignore */ }
772
+ }
773
+ return { ok: false, code: 'CONFIG_VERIFY_FAILED', rolledBack: true };
774
+ }
775
+ }
776
+
777
+ return {
778
+ ok: true,
779
+ changed,
780
+ configPath,
781
+ providerPath: providerTarget,
782
+ backupPath: configBackup,
783
+ configAbsentMarker,
784
+ providerBackupPath: install.backupPath ?? null,
785
+ entry: { provider: PACKAGE_NAME },
786
+ preview: changed ? previewText(sourcePath, providerTarget, current.value) : '',
787
+ };
788
+ }
789
+
790
+ /** Activation: injected reload/restart only; otherwise the next Hermes session. */
791
+ export async function activate(options = {}) {
792
+ if (options.canRestartHost === true && typeof options.reloadHost === 'function') {
793
+ try {
794
+ await options.reloadHost();
795
+ return { ok: true, activation: 'reload' };
796
+ } catch {
797
+ return { ok: false, code: 'ACTIVATION_FAILED', activation: 'next-start' };
798
+ }
799
+ }
800
+ if (options.canRestartHost === true && typeof options.restartHost === 'function') {
801
+ try {
802
+ await options.restartHost();
803
+ return { ok: true, activation: 'restart' };
804
+ } catch {
805
+ return { ok: false, code: 'ACTIVATION_FAILED', activation: 'next-start' };
806
+ }
807
+ }
808
+ return { ok: true, activation: 'next-start' };
809
+ }
810
+
811
+ /**
812
+ * Verify configuration only: provider dir + manifest, `memory.provider=mebular`,
813
+ * version lockstep. `sync_turn` ingest health belongs to repair.
814
+ */
815
+ export async function verify(options = {}) {
816
+ const expectedVersion = options.expectedVersion ?? APP_VERSION;
817
+ const target = providerPathFor(options);
818
+ const checks = [];
819
+ const bundle = readBundle(target);
820
+ checks.push({ name: 'provider-dir', ok: bundle !== null });
821
+ if (!bundle) {
822
+ return { ok: false, code: 'VERIFY_PROVIDER_MISSING', checks, ingested: null, health: 'deferred' };
823
+ }
824
+ const nameOk = bundle.name === PACKAGE_NAME;
825
+ checks.push({ name: 'provider-name', ok: nameOk });
826
+ checks.push({ name: 'provider-entry', ok: bundle.hasInit === true });
827
+ const versionOk = bundle.version === expectedVersion;
828
+ checks.push({ name: 'version-lockstep', ok: versionOk });
829
+
830
+ const provider = await readProvider(options);
831
+ const selected = provider.value === PACKAGE_NAME;
832
+ checks.push({ name: 'config-provider', ok: selected });
833
+
834
+ let code = null;
835
+ if (!nameOk || bundle.hasInit !== true) code = 'VERIFY_PROVIDER_INVALID';
836
+ else if (!versionOk) code = 'VERIFY_VERSION_MISMATCH';
837
+ else if (!selected) code = 'VERIFY_PROVIDER_NOT_SELECTED';
838
+ const ok = code === null;
839
+ return {
840
+ ok,
841
+ code,
842
+ checks,
843
+ version: bundle.version ?? null,
844
+ provider: provider.value,
845
+ ingested: null,
846
+ health: 'deferred',
847
+ };
848
+ }
849
+
850
+ async function restoreProvider(target, backup) {
851
+ const current = existsSync(target) ? `${target}.rollback-${tsStamp()}` : null;
852
+ try {
853
+ if (current) await rename(target, current);
854
+ try {
855
+ await rename(backup, target);
856
+ } catch {
857
+ if (current) {
858
+ try { await rename(current, target); } catch { /* ignore */ }
859
+ }
860
+ return false;
861
+ }
862
+ if (current) {
863
+ try { await rm(current, { recursive: true, force: true }); } catch { /* ignore */ }
864
+ }
865
+ return true;
866
+ } catch {
867
+ return false;
868
+ }
869
+ }
870
+
871
+ /**
872
+ * Roll back the provider directory and config. Hermes DB / session storage and
873
+ * the provider's own `mebular-memory` spool are never touched.
874
+ */
875
+ export async function rollback(options = {}) {
876
+ const target = providerPathFor(options);
877
+ const providerBackup = options.providerBackupPath ?? latestProviderBackup(target);
878
+ const providerAbsentMarker = latestProviderAbsentMarker(options);
879
+ let providerRestored = false;
880
+ let removed = false;
881
+ let ok = true;
882
+
883
+ if (providerBackup && existsSync(providerBackup)) {
884
+ providerRestored = await restoreProvider(target, providerBackup);
885
+ if (!providerRestored) ok = false;
886
+ } else if (providerAbsentMarker) {
887
+ try {
888
+ if (existsSync(target)) {
889
+ await rm(target, { recursive: true, force: true });
890
+ removed = true;
891
+ }
892
+ await rm(providerAbsentMarker, { force: true });
893
+ } catch {
894
+ ok = false;
895
+ }
896
+ }
897
+ if (providerRestored) {
898
+ try { await clearProviderAbsentMarkers(options); } catch { /* ignore */ }
899
+ }
900
+
901
+ const configPath = configPathFor(options);
902
+ const configBackup = options.backupPath ?? latestConfigBackup(options);
903
+ const absentMarker = latestConfigAbsentMarker(options);
904
+ let configRestored = false;
905
+ let configRemoved = false;
906
+ if (configBackup && existsSync(configBackup)) {
907
+ try {
908
+ const text = await readFile(configBackup, 'utf-8');
909
+ let mode = 0o600;
910
+ try { mode = (await stat(configPath)).mode & 0o777; } catch { /* newly created */ }
911
+ await atomicWrite(configPath, text, mode);
912
+ configRestored = true;
913
+ } catch {
914
+ ok = false;
915
+ }
916
+ } else if (absentMarker && existsSync(absentMarker)) {
917
+ try {
918
+ if (existsSync(configPath)) {
919
+ await rm(configPath, { force: true });
920
+ configRemoved = true;
921
+ }
922
+ await rm(absentMarker, { force: true });
923
+ } catch {
924
+ ok = false;
925
+ }
926
+ }
927
+
928
+ if (options.removePackage === true && options.packageInfo?.created === true
929
+ && typeof options.packageInfo.managedPath === 'string') {
930
+ const home = options.home ?? options.mebularHome;
931
+ if (typeof home === 'string' && home.length > 0) {
932
+ const managedRoot = join(home, MANAGED_DIR);
933
+ if (options.packageInfo.managedPath === managedRoot
934
+ || options.packageInfo.managedPath.startsWith(`${managedRoot}${sep}`)) {
935
+ try { await rm(options.packageInfo.managedPath, { recursive: true, force: true }); } catch { /* ignore */ }
936
+ }
937
+ }
938
+ }
939
+
940
+ return {
941
+ ok,
942
+ code: ok ? null : 'ROLLBACK_FAILED',
943
+ removed,
944
+ restoredFrom: providerRestored || configRestored ? 'backup' : null,
945
+ providerRestored,
946
+ configRestored,
947
+ configRemoved,
948
+ };
949
+ }
950
+
951
+ export function createHermesAdapter() {
952
+ return {
953
+ hostId: 'hermes',
954
+ displayName: 'Hermes',
955
+ status: 'supported',
956
+ package: { name: PACKAGE_NAME, version: APP_VERSION, source: 'bundled' },
957
+ detect,
958
+ ensurePackage,
959
+ configure,
960
+ activate,
961
+ verify,
962
+ rollback,
963
+ };
964
+ }
965
+
966
+ export const hermesAdapter = createHermesAdapter();