@mebular/mcp 0.3.5 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/clients.mjs CHANGED
@@ -449,11 +449,19 @@ export function builtinAssistants(options = {}) {
449
449
  probe: {
450
450
  signals: [
451
451
  { kind: 'config-path', paths: [opencodePath] },
452
- { kind: 'cli', command: 'opencode --version', timeoutMs: 1500 },
452
+ { kind: 'cli', command: 'opencode --version', timeoutMs: 1500, version: true },
453
453
  { kind: 'app-bundle', paths: ['/Applications/OpenChamber.app'] },
454
454
  { kind: 'process', pattern: 'opencode serve --service' },
455
455
  ],
456
456
  },
457
+ // OpenChamber 复用 OpenCode 插件 → 同一 host 版本门。
458
+ compatibility: {
459
+ minVersion: MIN_OPENCODE_VERSION,
460
+ actionHint: 'upgrade_opencode',
461
+ reason: 'opencode_version_unsupported',
462
+ unknownActionHint: 'verify_host_version',
463
+ unknownReason: 'opencode_version_unknown',
464
+ },
457
465
  writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
458
466
  verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
459
467
  activation: { kind: 'user-reload', note: 'OpenChamber:由用户在 App 侧重载/重启生效;产品不得发 opencode reload 干扰运行服务' },
@@ -510,10 +518,18 @@ export function builtinAssistants(options = {}) {
510
518
  probe: {
511
519
  signals: [
512
520
  { kind: 'config-path', paths: [opencodePath] },
513
- { kind: 'cli', command: 'opencode --version', timeoutMs: 1500 },
521
+ { kind: 'cli', command: 'opencode --version', timeoutMs: 1500, version: true },
514
522
  { kind: 'dir', paths: [join(userHome, '.config', 'opencode')] },
515
523
  ],
516
524
  },
525
+ // `@mebular/opencode-plugin` 的启动门:宿主 < 2.2.0 时插件 disabled(自动记忆不可用)。
526
+ compatibility: {
527
+ minVersion: MIN_OPENCODE_VERSION,
528
+ actionHint: 'upgrade_opencode',
529
+ reason: 'opencode_version_unsupported',
530
+ unknownActionHint: 'verify_host_version',
531
+ unknownReason: 'opencode_version_unknown',
532
+ },
517
533
  writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
518
534
  verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
519
535
  activation: { kind: 'user-reload', note: 'OpenCode 侧重载/重启后生效' },
@@ -1167,6 +1183,62 @@ export function landingState(assistant, options = {}) {
1167
1183
 
1168
1184
  export const DEFAULT_CLI_TIMEOUT_MS = 1500;
1169
1185
 
1186
+ /**
1187
+ * OpenCode 插件启动门(与 `@mebular/opencode-plugin` 的 `MIN_OPENCODE_VERSION` 保持一致)。
1188
+ * 这是 host 兼容性下限:低版本宿主无法加载插件,自动记忆在运行时是关闭的。测试里用
1189
+ * `tests/mcp/clients.test.mjs` 的 drift guard 断言两处常量相等。
1190
+ */
1191
+ export const MIN_OPENCODE_VERSION = '2.2.0';
1192
+
1193
+ /** 从 `opencode --version` 之类的输出里取第一个 semver(容忍前缀/后缀)。 */
1194
+ export function parseHostVersion(value) {
1195
+ if (typeof value !== 'string') return null;
1196
+ const match = /(?:^|[^\d])(\d+)\.(\d+)\.(\d+)(?:[^\d]|$)/.exec(value);
1197
+ return match ? `${match[1]}.${match[2]}.${match[3]}` : null;
1198
+ }
1199
+
1200
+ /** 数值段比较(只用于本文件的 host 门;不含 prerelease 语义)。 */
1201
+ export function compareHostVersion(left, right) {
1202
+ const a = parseHostVersion(left);
1203
+ const b = parseHostVersion(right);
1204
+ if (!a || !b) return null;
1205
+ const av = a.split('.').map(Number);
1206
+ const bv = b.split('.').map(Number);
1207
+ for (let index = 0; index < 3; index += 1) {
1208
+ if (av[index] !== bv[index]) return av[index] < bv[index] ? -1 : 1;
1209
+ }
1210
+ return 0;
1211
+ }
1212
+
1213
+ /**
1214
+ * 由 descriptor 的 `compatibility` + 版本探针结果计算 host 兼容性。
1215
+ * 版本未知时 `supported=null`(fail-open:不凭猜测禁用,保持原有状态);
1216
+ * 版本已知且低于下限时 `supported=false`(fail-closed:绝不投影成「已接入」)。
1217
+ */
1218
+ export function evaluateHostCompatibility(assistant, signals) {
1219
+ const spec = assistant?.compatibility;
1220
+ if (!spec || typeof spec.minVersion !== 'string') return null;
1221
+ const hostVersion = (signals ?? [])
1222
+ .map((signal) => signal?.version)
1223
+ .find((version) => typeof version === 'string' && version.length > 0) ?? null;
1224
+ const compared = hostVersion === null ? null : compareHostVersion(hostVersion, spec.minVersion);
1225
+ const supported = compared === null ? null : compared >= 0;
1226
+ return {
1227
+ supported,
1228
+ hostVersion,
1229
+ requiredVersion: spec.minVersion,
1230
+ automaticMemory: supported === true ? true : supported === false ? false : null,
1231
+ ...(supported === false
1232
+ ? { actionHint: spec.actionHint ?? 'upgrade_host', reason: spec.reason ?? null }
1233
+ : supported === null
1234
+ ? {
1235
+ actionHint: spec.unknownActionHint ?? 'verify_host_version',
1236
+ reason: spec.unknownReason ?? 'host_version_unknown',
1237
+ }
1238
+ : {}),
1239
+ };
1240
+ }
1241
+
1170
1242
  function defaultRun(command, timeoutMs, options = {}) {
1171
1243
  const res = spawnSync(command, { shell: true, encoding: 'utf-8', timeout: timeoutMs, env: spawnEnv(options) });
1172
1244
  return { ok: res.status === 0, code: res.status ?? 1, stdout: res.stdout ?? '', stderr: res.stderr ?? '' };
@@ -1216,7 +1288,16 @@ export function probeSignal(signal, options = {}) {
1216
1288
  }
1217
1289
  if (signal.kind === 'cli') {
1218
1290
  const r = run(signal.command, signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS, options);
1219
- return { kind: signal.kind, source, hit: r.ok === true, detail: `rc=${r.code}` };
1291
+ const version = signal.version === true
1292
+ ? (parseHostVersion(String(r.stdout ?? '')) ?? parseHostVersion(String(r.stderr ?? '')))
1293
+ : null;
1294
+ return {
1295
+ kind: signal.kind,
1296
+ source,
1297
+ hit: r.ok === true,
1298
+ detail: version ? `版本:${version}` : `rc=${r.code}`,
1299
+ ...(signal.version === true ? { version } : {}),
1300
+ };
1220
1301
  }
1221
1302
  if (signal.kind === 'process') {
1222
1303
  const list = options.processList ?? (() => defaultProcessList(options));
@@ -1252,16 +1333,31 @@ export async function probeSignalAsync(signal, options = {}) {
1252
1333
  // (本机 hermes --version ≈763ms),`refresh` 只重算**列表/落面**,不必重复 spawn 版本探测。
1253
1334
  // 注:注入的 `run`/`runAsync`(测试)不缓存,保证替身语义确定。
1254
1335
  const injected = options.runAsync !== undefined || options.run !== undefined;
1255
- const cacheKey = `${signal.command}::${signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS}`;
1336
+ const cacheKey = `${signal.command}::${signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS}::${signal.version === true ? 'version' : 'plain'}`;
1256
1337
  if (!injected && options.refreshProbes !== true) {
1257
1338
  const cachedCli = cliProbeCache.get(cacheKey);
1258
1339
  if (cachedCli && Date.now() - cachedCli.at < PROBE_CACHE_TTL_MS) {
1259
- return { kind: signal.kind, source, hit: cachedCli.hit, detail: `rc=${cachedCli.code}` };
1340
+ return {
1341
+ kind: signal.kind,
1342
+ source,
1343
+ hit: cachedCli.hit,
1344
+ detail: cachedCli.version ? `版本:${cachedCli.version}` : `rc=${cachedCli.code}`,
1345
+ ...(signal.version === true ? { version: cachedCli.version ?? null } : {}),
1346
+ };
1260
1347
  }
1261
1348
  }
1262
1349
  const r = await runAsync(signal.command, signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS, options);
1263
- if (!injected) cliProbeCache.set(cacheKey, { at: Date.now(), hit: r.ok === true, code: r.code });
1264
- return { kind: signal.kind, source, hit: r.ok === true, detail: `rc=${r.code}` };
1350
+ const version = signal.version === true
1351
+ ? (parseHostVersion(String(r.stdout ?? '')) ?? parseHostVersion(String(r.stderr ?? '')))
1352
+ : null;
1353
+ if (!injected) cliProbeCache.set(cacheKey, { at: Date.now(), hit: r.ok === true, code: r.code, version });
1354
+ return {
1355
+ kind: signal.kind,
1356
+ source,
1357
+ hit: r.ok === true,
1358
+ detail: version ? `版本:${version}` : `rc=${r.code}`,
1359
+ ...(signal.version === true ? { version } : {}),
1360
+ };
1265
1361
  }
1266
1362
  if (signal.kind === 'process') {
1267
1363
  const out = String((await listAsync()) ?? '');
@@ -1310,7 +1406,16 @@ function buildStateItem(assistant, signals, landing, options = {}) {
1310
1406
  else if (staleStdio) state = 'stale'; // 已写入但过时(stdio)→ 升级直连
1311
1407
  else if (!anyHit) state = anyError ? 'detect-failed' : 'not-installed';
1312
1408
  else state = 'not-connected';
1313
- const STATE_LABEL = { 'not-installed': '未安装', 'not-connected': '未接入', connected: '已接入 ✓', manual: '需手动', 'detect-failed': '检测失败', stale: '已写入·需升级为直连', 'needs-confirmation': '需要修复/请确认' };
1409
+ // Host 兼容性门:只在原本会投影成绿色「已接入」时接管。
1410
+ // 版本已知且低于插件下限 → 自动记忆不可用;版本未知(超时/无输出/空版本)→ 无法确认。
1411
+ // stale / needs-confirmation 等更具体的可修复态保留原语义(它们本来也不是绿色)。
1412
+ const compatibility = evaluateHostCompatibility(assistant, signals);
1413
+ const compatibilityApplies = state === 'connected';
1414
+ const unsupported = compatibility?.supported === false && compatibilityApplies;
1415
+ const compatibilityUnknown = compatibility?.supported === null && compatibilityApplies;
1416
+ if (unsupported) state = 'unsupported';
1417
+ else if (compatibilityUnknown) state = 'compatibility-unknown';
1418
+ const STATE_LABEL = { 'not-installed': '未安装', 'not-connected': '未接入', connected: '已接入 ✓', manual: '需手动', 'detect-failed': '检测失败', stale: '已写入·需升级为直连', 'needs-confirmation': '需要修复/请确认', unsupported: '自动记忆不可用 · 需升级', 'compatibility-unknown': '无法确认兼容性 · 请重新检测' };
1314
1419
  const staleReason = needsConfirmation || staleUrl ? (landing.staleReason ?? 'MCP 地址与当前端点不一致,请确认或手动修复') : null;
1315
1420
  const nativeMemory = assistant.nativeMemoryProbe === 'openchamber'
1316
1421
  ? detectOpenChamberNativeMemory(options)
@@ -1336,7 +1441,23 @@ function buildStateItem(assistant, signals, landing, options = {}) {
1336
1441
  type: assistant.kind === 'snippet' ? 'snippet' : 'file', // file | snippet(descriptor 形态)
1337
1442
  registryKind: assistant.registryKind ?? 'builtin',
1338
1443
  state,
1339
- stateLabel: needsConfirmation ? '需要修复/请确认' : staleUrl ? '配置已过期 · 请自动修复' : (STATE_LABEL[state] ?? state),
1444
+ stateLabel: needsConfirmation
1445
+ ? '需要修复/请确认'
1446
+ : staleUrl
1447
+ ? '配置已过期 · 请自动修复'
1448
+ : unsupported && compatibility?.hostVersion
1449
+ ? `需升级(需要 >= ${compatibility.requiredVersion},当前 ${compatibility.hostVersion})`
1450
+ : compatibilityUnknown
1451
+ ? `无法确认当前版本(需要 >= ${compatibility.requiredVersion})`
1452
+ : (STATE_LABEL[state] ?? state),
1453
+ ...(compatibility
1454
+ ? {
1455
+ compatibility,
1456
+ automaticMemory: compatibility.automaticMemory,
1457
+ requiredVersion: compatibility.requiredVersion,
1458
+ ...(compatibility.actionHint ? { actionHint: compatibility.actionHint } : {}),
1459
+ }
1460
+ : {}),
1340
1461
  evidence: signals.map((s) => ({ ...s, detail: redactSecrets(s.detail) })),
1341
1462
  anySignalHit: anyHit,
1342
1463
  landing: {
@@ -1606,6 +1727,33 @@ async function attachSkills(result, id, options = {}) {
1606
1727
  return result;
1607
1728
  }
1608
1729
 
1730
+ /** 接入成功后顺带 ensure 该客户端的 Adapter;失败只记录,绝不阻断 MCP 接入。 */
1731
+ async function attachAdapter(result, id, options = {}) {
1732
+ if (!result?.ok || options.ensureAdapter === false) return result;
1733
+ try {
1734
+ const { ensureAdapter } = await import('./adapter-provision.mjs');
1735
+ result.adapter = await ensureAdapter(id, {
1736
+ ...(options.home ? { home: options.home } : {}),
1737
+ ...(options.userHome ? { userHome: options.userHome } : {}),
1738
+ ...(options.cwd ? { cwd: options.cwd } : {}),
1739
+ ...(options.env ? { env: options.env } : {}),
1740
+ ...(typeof options.adapterPackagePath === 'string' ? { adapterPackagePath: options.adapterPackagePath } : {}),
1741
+ ...(typeof options.packagePath === 'string' ? { packagePath: options.packagePath } : {}),
1742
+ ...(typeof options.resourcesPath === 'string' ? { resourcesPath: options.resourcesPath } : {}),
1743
+ ...(typeof options.expectedVersion === 'string' ? { expectedVersion: options.expectedVersion } : {}),
1744
+ ...(typeof options.run === 'function' ? { run: options.run } : {}),
1745
+ ...(typeof options.runAsync === 'function' ? { runAsync: options.runAsync } : {}),
1746
+ ...(options.canRestartHost !== undefined ? { canRestartHost: options.canRestartHost } : {}),
1747
+ ...(typeof options.reloadHost === 'function' ? { reloadHost: options.reloadHost } : {}),
1748
+ ...(typeof options.restartHost === 'function' ? { restartHost: options.restartHost } : {}),
1749
+ connected: true,
1750
+ });
1751
+ } catch {
1752
+ result.adapter = { ok: false, code: 'ADAPTER_FAILED' };
1753
+ }
1754
+ return result;
1755
+ }
1756
+
1609
1757
  /** 接入:merge-key(备份 → 原子写)/ cli-set(官方 CLI)/ manual(仅片段)。 */
1610
1758
  export async function connectClient(id, options = {}) {
1611
1759
  const assistant = descriptorFor(id, options);
@@ -1618,7 +1766,7 @@ export async function connectClient(id, options = {}) {
1618
1766
  if (isForbidden(assistant, primary)) {
1619
1767
  return { ok: false, reason: `禁写路径(landing.forbiddenPaths):${primary}` };
1620
1768
  }
1621
- if (strategy === 'cli-set') return attachSkills(await connectViaCli(assistant, options), id, options);
1769
+ if (strategy === 'cli-set') return attachAdapter(await attachSkills(await connectViaCli(assistant, options), id, options), id, options);
1622
1770
  const existing = safeReadText(primary);
1623
1771
  const merged = computeMerged(assistant, existing, options);
1624
1772
  if (merged.error) {
@@ -1626,7 +1774,7 @@ export async function connectClient(id, options = {}) {
1626
1774
  }
1627
1775
  const preview = lineDiff(existing ?? '', merged.text);
1628
1776
  if (!merged.changed) {
1629
- return attachSkills({ ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' }, id, options);
1777
+ return attachAdapter(await attachSkills({ ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' }, id, options), id, options);
1630
1778
  }
1631
1779
  const backupPath = existing !== null ? `${primary}.bak-${tsStamp()}` : null;
1632
1780
  if (backupPath) await copyFile(primary, backupPath);
@@ -1637,7 +1785,7 @@ export async function connectClient(id, options = {}) {
1637
1785
  if (backupPath) await copyFile(backupPath, primary); // 失败回滚
1638
1786
  return { ok: false, changed: false, rolledBack: Boolean(backupPath), backupPath, reason: `写入失败已回滚:${redactSecrets(error?.message ?? error)}` };
1639
1787
  }
1640
- return attachSkills({ ok: true, changed: true, configPath: primary, backupPath, preview }, id, options);
1788
+ return attachAdapter(await attachSkills({ ok: true, changed: true, configPath: primary, backupPath, preview }, id, options), id, options);
1641
1789
  }
1642
1790
 
1643
1791
  /**
@@ -1794,6 +1942,16 @@ export async function rollbackClient(id, options = {}) {
1794
1942
  // 验证闭环(A-9/A-10/A-11)
1795
1943
  // ---------------------------------------------------------------------------
1796
1944
 
1945
+ /** 该 plugin 条目是否属于 Mebular 自己的 adapter(读回比对时忽略它,保留用户插件)。 */
1946
+ function isMebularPluginEntry(entry) {
1947
+ const refs = typeof entry === 'string'
1948
+ ? [entry]
1949
+ : (entry !== null && typeof entry === 'object' && !Array.isArray(entry)
1950
+ ? ['package', 'path', 'module', 'plugin'].map((key) => entry[key]).filter((value) => typeof value === 'string')
1951
+ : []);
1952
+ return refs.some((ref) => ref === '@mebular/opencode-plugin' || /(^|[/\\])opencode-plugin([/\\]|$)/.test(ref));
1953
+ }
1954
+
1797
1955
  /** 回读校验:条目存在 ∧ 原配置其余键无损(有备份时逐键比对)。 */
1798
1956
  export function readbackCheck(assistant, options = {}) {
1799
1957
  const landing = landingState(assistant, options);
@@ -1830,6 +1988,13 @@ export function readbackCheck(assistant, options = {}) {
1830
1988
  let node = clone;
1831
1989
  for (const key of path.slice(0, -1)) { if (node?.[key] === undefined) return clone; node = node[key]; }
1832
1990
  if (node && typeof node === 'object') delete node[path[path.length - 1]];
1991
+ // Adapter provisioning may also add its own entry to `plugins`; ignore
1992
+ // only Mebular's entry so user plugins are still compared.
1993
+ if (Array.isArray(clone.plugins)) {
1994
+ const remaining = clone.plugins.filter((entry) => !isMebularPluginEntry(entry));
1995
+ if (remaining.length === 0) delete clone.plugins;
1996
+ else clone.plugins = remaining;
1997
+ }
1833
1998
  return pruneEmpty(clone);
1834
1999
  };
1835
2000
  intact = JSON.stringify(strip(before)) === JSON.stringify(strip(after));
@@ -2285,7 +2450,13 @@ export async function repairClients(options = {}) {
2285
2450
  continue;
2286
2451
  }
2287
2452
  try {
2288
- base.connect = await connectClient(assistant.id, { ...options, skipSkills: true });
2453
+ base.connect = await connectClient(assistant.id, {
2454
+ ...options,
2455
+ skipSkills: true,
2456
+ // Repair fans out to detected hosts; adapter provisioning is only
2457
+ // allowed for hosts that were already connected before this repair.
2458
+ ensureAdapter: assistant.connected === true,
2459
+ });
2289
2460
  } catch (error) {
2290
2461
  base.connect = { ok: false, reason: `接入失败:${redactSecrets(error?.message ?? error)}` };
2291
2462
  }
@@ -0,0 +1,343 @@
1
+ // 0.4.0 W1b:全新空 home 的一次性首启初始化(唯一允许的“新安装默认 immersive”路径)。
2
+ //
3
+ // 契约(docs/design/0.4.0-w0-contract.md §2.4):
4
+ // - 只在真正空 home / 首次安装时命中;已有 home 永不写 marker / 不补字段;
5
+ // - marker `<home>/first-run.json`(0600,原子写)只表达披露生命周期,不是第二个 mode;
6
+ // - 披露在现有首启页展示;ack 只由 Console 显式回传 `firstRunDisclosure` + 版本触发;
7
+ // - ack 后初始化(幂等):sidecar seed `{"schema":1,"model":{"source":"auto"}}`(仅当 sidecar
8
+ // config 不存在)+ 合并 `<home>/config.json` `memoryRuntime.enabled=true`(保留其他字段);
9
+ // - 不写 `intervention.mode`,不重写已有 `model.source`,不迁移、不删除任何旧字段;
10
+ // - 任一步失败 → 不写(或只保留未启用的部分)并保持 off;调用方只记录 `first_run_init_failed`,
11
+ // 不阻塞 serve,不回退到 heuristic。
12
+ //
13
+ // 本模块不 import 图谱/事件/sync,也不读写宿主私有存储。
14
+
15
+ import { existsSync } from 'node:fs';
16
+ import { chmod, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
17
+ import { randomBytes } from 'node:crypto';
18
+ import { dirname, join, resolve } from 'node:path';
19
+ import { acquireConfigFileLock } from './config-lock.mjs';
20
+ import { resolveMemoryRuntimePaths } from './memory-runtime-supervisor.mjs';
21
+
22
+ export const FIRST_RUN_FILE = 'first-run.json';
23
+ export const FIRST_RUN_SCHEMA = 1;
24
+ export const FIRST_RUN_DISCLOSURE_VERSION = 1;
25
+ /** 失败时的稳定 warning code;不含路径/配置正文。 */
26
+ export const FIRST_RUN_INIT_FAILED = 'first_run_init_failed';
27
+
28
+ const ALLOWED_EMPTY_ENTRIES = new Set(['.DS_Store', 'Thumbs.db', FIRST_RUN_FILE]);
29
+ const BLOCKING_ENTRIES = [
30
+ 'config.json',
31
+ 'user-master-key.json',
32
+ 'store.jsonl',
33
+ 'store.jsonl.identity.json',
34
+ 'runtime.json',
35
+ 'memory-runtime',
36
+ 'net',
37
+ ];
38
+ const VALID_STATES = new Set(['pending', 'acked', 'done']);
39
+
40
+ function isObject(value) {
41
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
42
+ }
43
+
44
+ function stringOrNull(value) {
45
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
46
+ }
47
+
48
+ function isoTimestamp(now) {
49
+ const value = typeof now === 'function' ? now() : now;
50
+ const date = value instanceof Date ? value : new Date(value ?? Date.now());
51
+ return date.toISOString();
52
+ }
53
+
54
+ function mcpConfigPath(home, env) {
55
+ return env?.MEBULAR_CONFIG ?? join(home, 'config.json');
56
+ }
57
+
58
+ function firstRunPath(home) {
59
+ return join(home, FIRST_RUN_FILE);
60
+ }
61
+
62
+ /** marker 文件存在且形状合法才返回;损坏/未知 state 视为不存在,避免把坏文件当 ack。 */
63
+ export async function readFirstRunMarker({ home } = {}) {
64
+ if (typeof home !== 'string' || home.length === 0) return null;
65
+ let parsed;
66
+ try {
67
+ parsed = JSON.parse(await readFile(firstRunPath(home), 'utf-8'));
68
+ } catch {
69
+ return null;
70
+ }
71
+ if (!isObject(parsed) || parsed.schema !== FIRST_RUN_SCHEMA) return null;
72
+ if (typeof parsed.state !== 'string' || !VALID_STATES.has(parsed.state)) return null;
73
+ if (!Number.isInteger(parsed.disclosureVersion) || parsed.disclosureVersion < 1) return null;
74
+ return {
75
+ schema: parsed.schema,
76
+ disclosureVersion: parsed.disclosureVersion,
77
+ state: parsed.state,
78
+ createdAt: stringOrNull(parsed.createdAt),
79
+ ...(stringOrNull(parsed.ackedAt) ? { ackedAt: stringOrNull(parsed.ackedAt) } : {}),
80
+ ...(stringOrNull(parsed.initializedAt) ? { initializedAt: stringOrNull(parsed.initializedAt) } : {}),
81
+ };
82
+ }
83
+
84
+ /** 给 Console/provision status 的最小只读视图;不含路径/用户数据。 */
85
+ export function firstRunPublicView(marker) {
86
+ if (!marker) return null;
87
+ return {
88
+ pending: marker.state === 'pending',
89
+ disclosureVersion: marker.disclosureVersion,
90
+ state: marker.state,
91
+ };
92
+ }
93
+
94
+ async function writeJsonAtomic(path, value) {
95
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
96
+ const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`;
97
+ try {
98
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
99
+ await chmod(tmp, 0o600).catch(() => undefined);
100
+ await rename(tmp, path);
101
+ await chmod(path, 0o600).catch(() => undefined);
102
+ } catch (error) {
103
+ await unlink(tmp).catch(() => undefined);
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 极窄空 home 判定(契约 §2.4):
110
+ * - 无 config / 主密钥 / store / identity / runtime.json / memory-runtime/ / net/;
111
+ * - 目录为空,或只含 `.DS_Store` / `Thumbs.db` / `first-run.json`;
112
+ * - 设置了 `MEBULAR_CONFIG` / `MEBULAR_MEMORY_RUNTIME_HOME` / `MEBULAR_STORAGE_PATH` 时
113
+ * 一律不命中(外部存储可能在 home 之外已有 store,不能证明“首次安装”)。
114
+ *
115
+ * 非 ENOENT 的 readdir 错误不当作空 home(失败闭合)。
116
+ */
117
+ export async function detectFreshHome({ home, env = process.env } = {}) {
118
+ if (typeof home !== 'string' || home.length === 0) return false;
119
+ if (stringOrNull(env?.MEBULAR_CONFIG)
120
+ || stringOrNull(env?.MEBULAR_MEMORY_RUNTIME_HOME)
121
+ || stringOrNull(env?.MEBULAR_STORAGE_PATH)) {
122
+ return false;
123
+ }
124
+ const root = resolve(home);
125
+ for (const name of BLOCKING_ENTRIES) {
126
+ if (existsSync(join(root, name))) return false;
127
+ }
128
+ let entries;
129
+ try {
130
+ entries = await readdir(root);
131
+ } catch (error) {
132
+ // 空 home 可能尚未创建目录;只有 ENOENT 视为空。
133
+ return error?.code === 'ENOENT';
134
+ }
135
+ return entries.every((entry) => ALLOWED_EMPTY_ENTRIES.has(entry));
136
+ }
137
+
138
+ /**
139
+ * 首启检测:只有真正空 home 才写 `pending` marker。
140
+ * 已有 home、非空目录、显式 env 覆盖一律 no-op(返回 null,不创建文件)。
141
+ */
142
+ export async function markFirstRunPending({ home, env = process.env, now = Date.now } = {}) {
143
+ if (!(await detectFreshHome({ home, env }))) return null;
144
+ const existing = await readFirstRunMarker({ home });
145
+ if (existing) return existing;
146
+ const marker = {
147
+ schema: FIRST_RUN_SCHEMA,
148
+ disclosureVersion: FIRST_RUN_DISCLOSURE_VERSION,
149
+ state: 'pending',
150
+ createdAt: isoTimestamp(now),
151
+ };
152
+ try {
153
+ await writeJsonAtomic(firstRunPath(home), marker);
154
+ } catch {
155
+ // 写 marker 失败 = 无法证明披露已发生:不落盘、不启用;调用方保持 off。
156
+ return null;
157
+ }
158
+ return readFirstRunMarker({ home });
159
+ }
160
+
161
+ /**
162
+ * 披露成功的显式 ack。只有 pending marker + 匹配的 disclosureVersion 才接受;
163
+ * 其他情况(已有用户 / 无 marker / 版本不符)返回 null,绝不凭空创建 marker。
164
+ */
165
+ export async function markFirstRunAcked({
166
+ home,
167
+ disclosureVersion = FIRST_RUN_DISCLOSURE_VERSION,
168
+ now = Date.now,
169
+ } = {}) {
170
+ const marker = await readFirstRunMarker({ home });
171
+ if (!marker || marker.state !== 'pending') return null;
172
+ if (!Number.isInteger(disclosureVersion) || disclosureVersion !== marker.disclosureVersion) return null;
173
+ const next = {
174
+ ...marker,
175
+ state: 'acked',
176
+ ackedAt: isoTimestamp(now),
177
+ };
178
+ try {
179
+ await writeJsonAtomic(firstRunPath(home), next);
180
+ } catch {
181
+ return null;
182
+ }
183
+ return readFirstRunMarker({ home });
184
+ }
185
+
186
+ async function markFirstRunDone({ home, marker, now = Date.now } = {}) {
187
+ if (!marker) return null;
188
+ const next = {
189
+ ...marker,
190
+ state: 'done',
191
+ initializedAt: marker.initializedAt ?? isoTimestamp(now),
192
+ };
193
+ try {
194
+ await writeJsonAtomic(firstRunPath(home), next);
195
+ } catch {
196
+ return null;
197
+ }
198
+ return readFirstRunMarker({ home });
199
+ }
200
+
201
+ async function readConfigObject(path) {
202
+ let text;
203
+ try {
204
+ text = await readFile(path, 'utf-8');
205
+ } catch (error) {
206
+ if (error?.code === 'ENOENT') return { exists: false, config: {} };
207
+ throw error;
208
+ }
209
+ let parsed;
210
+ try {
211
+ parsed = JSON.parse(text);
212
+ } catch {
213
+ const error = new Error('config_invalid');
214
+ error.code = 'config_invalid';
215
+ throw error;
216
+ }
217
+ if (!isObject(parsed)) {
218
+ const error = new Error('config_invalid');
219
+ error.code = 'config_invalid';
220
+ throw error;
221
+ }
222
+ return { exists: true, config: parsed };
223
+ }
224
+
225
+ function withMemoryRuntimeEnabled(config) {
226
+ const next = { ...config };
227
+ const memoryRuntime = isObject(next.memoryRuntime) ? { ...next.memoryRuntime } : {};
228
+ memoryRuntime.enabled = true;
229
+ next.memoryRuntime = memoryRuntime;
230
+ return next;
231
+ }
232
+
233
+ /**
234
+ * 把 acked marker 落成真正的 immersive 初始化。幂等、原子、失败闭合:
235
+ * - 无 marker / 非 acked → `{ ok:false, reason:'no_marker'|'not_acked' }`,不写任何配置;
236
+ * - 已 enabled → 只把 marker 收敛为 done;
237
+ * - sidecar config 不存在才写 seed(source=auto,sourcePresent 自然为 true);
238
+ * - MCP config 只合并 `memoryRuntime.enabled=true`,其他键逐字保留;
239
+ * - 任一步失败 → 返回 `{ ok:false, reason }`(调用方记录 warning),不抛异常、不阻塞启动。
240
+ */
241
+ export async function initializeFirstRunHome({ home, env = process.env, now = Date.now } = {}) {
242
+ if (typeof home !== 'string' || home.length === 0) {
243
+ return { ok: false, reason: 'home_required' };
244
+ }
245
+ const root = resolve(home);
246
+ let marker = await readFirstRunMarker({ home: root });
247
+ if (!marker) return { ok: false, reason: 'no_marker' };
248
+ if (marker.state === 'done') {
249
+ return { ok: true, skipped: 'done', initialized: false, enabled: false };
250
+ }
251
+ if (marker.state !== 'acked') return { ok: false, reason: 'not_acked' };
252
+
253
+ const configFile = mcpConfigPath(root, env);
254
+ const release = await acquireConfigFileLock(configFile, { timeoutMs: 2000 });
255
+ if (!release) return { ok: false, reason: 'config_locked' };
256
+ try {
257
+ // 锁内重查 marker + enabled:并发初始化/用户手动开启时只允许一个写者。
258
+ marker = await readFirstRunMarker({ home: root });
259
+ if (!marker || marker.state === 'done') {
260
+ return marker?.state === 'done'
261
+ ? { ok: true, skipped: 'done', initialized: false, enabled: false }
262
+ : { ok: false, reason: 'no_marker' };
263
+ }
264
+ if (marker.state !== 'acked') return { ok: false, reason: 'not_acked' };
265
+
266
+ const { config } = await readConfigObject(configFile);
267
+ // memoryRuntime 不是对象 = 用户配置损坏/未知形态:fail closed,绝不覆盖成 {enabled:true}。
268
+ if (config.memoryRuntime !== undefined && !isObject(config.memoryRuntime)) {
269
+ return { ok: false, reason: 'config_invalid', enabled: false };
270
+ }
271
+ const explicitEnabled = isObject(config.memoryRuntime)
272
+ && typeof config.memoryRuntime.enabled === 'boolean';
273
+ if (explicitEnabled) {
274
+ // 显式 enabled 已存在(用户/模板写过)→ 绝不覆盖;false 也视为用户选择,停止重试。
275
+ await markFirstRunDone({ home: root, marker, now });
276
+ const enabled = config.memoryRuntime.enabled === true;
277
+ return {
278
+ ok: true,
279
+ skipped: enabled ? 'already_enabled' : 'explicit_disabled',
280
+ initialized: false,
281
+ enabled,
282
+ };
283
+ }
284
+
285
+ // 先写 sidecar seed:失败则 MCP 仍保持 disabled(off),不会出现“enabled 但没有 source”。
286
+ const sidecarConfigPath = join(resolveMemoryRuntimePaths({ home: root, env }).dataDir, 'config.json');
287
+ let sidecarSeed = 'existing';
288
+ if (!existsSync(sidecarConfigPath)) {
289
+ try {
290
+ await mkdir(dirname(sidecarConfigPath), { recursive: true, mode: 0o700 });
291
+ await writeJsonAtomic(sidecarConfigPath, { schema: 1, model: { source: 'auto' } });
292
+ sidecarSeed = 'created';
293
+ } catch (error) {
294
+ return {
295
+ ok: false,
296
+ reason: 'sidecar_seed_failed',
297
+ error: String(error?.code ?? error?.message ?? error),
298
+ };
299
+ }
300
+ }
301
+
302
+ const next = withMemoryRuntimeEnabled(config);
303
+ try {
304
+ await writeJsonAtomic(configFile, next);
305
+ } catch (error) {
306
+ return {
307
+ ok: false,
308
+ reason: 'config_write_failed',
309
+ error: String(error?.code ?? error?.message ?? error),
310
+ sidecarSeed,
311
+ };
312
+ }
313
+
314
+ const done = await markFirstRunDone({ home: root, marker, now });
315
+ return {
316
+ ok: true,
317
+ initialized: true,
318
+ enabled: true,
319
+ source: sidecarSeed === 'created' ? 'auto' : 'existing',
320
+ sidecarSeed,
321
+ markerState: done?.state ?? marker.state,
322
+ };
323
+ } catch (error) {
324
+ return {
325
+ ok: false,
326
+ reason: error?.code === 'config_invalid' ? 'config_invalid' : 'first_run_init_failed',
327
+ error: String(error?.code ?? error?.message ?? error),
328
+ };
329
+ } finally {
330
+ await release().catch(() => undefined);
331
+ }
332
+ }
333
+
334
+ /** `first-run.json` 是否存在(诊断用;不创建目录)。 */
335
+ export async function firstRunMarkerExists({ home } = {}) {
336
+ if (typeof home !== 'string' || home.length === 0) return false;
337
+ try {
338
+ const info = await stat(firstRunPath(home));
339
+ return info.isFile();
340
+ } catch {
341
+ return false;
342
+ }
343
+ }