@mebular/mcp 0.2.3 → 0.3.0

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
@@ -19,13 +19,15 @@
19
19
  //
20
20
  // 纯函数式:home/cwd/platform/env/run 可注入,便于单元测试(不触碰真实用户目录)。
21
21
 
22
+ import { createHash } from 'node:crypto';
22
23
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
23
- import { chmod, copyFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
24
+ import { chmod, copyFile, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
24
25
  import { exec, spawnSync } from 'node:child_process';
25
26
  import { promisify } from 'node:util';
26
- import { homedir } from 'node:os';
27
- import { delimiter, dirname, join, sep } from 'node:path';
27
+ import { homedir, tmpdir } from 'node:os';
28
+ import { basename, delimiter, dirname, join, resolve, sep } from 'node:path';
28
29
  import { fileURLToPath } from 'node:url';
30
+ import { APP_VERSION } from './version.mjs';
29
31
 
30
32
  // ---------------------------------------------------------------------------
31
33
  // 格式适配器(落面形状的唯一真源;A-17 以 `opencode mcp add` 产出为准)
@@ -100,6 +102,123 @@ export function daemonMcpUrl({ host, encrypted } = {}) {
100
102
  return `${encrypted ? 'https' : 'http'}://${target}:${port}/mcp`;
101
103
  }
102
104
 
105
+ // ---------------------------------------------------------------------------
106
+ // MCP URL 同端点判定(陈旧配置检测;只用于 HTTP/remote 条目,stdio 不适用)
107
+ // ---------------------------------------------------------------------------
108
+
109
+ /**
110
+ * HTTP(S) MCP URL 归一化:
111
+ * - 忽略**末尾 `/`**(`…/mcp/` ≡ `…/mcp`);
112
+ * - host / scheme 大小写归一,`localhost` ≡ `127.0.0.1`(同机回环别名);
113
+ * - **端口不同 = 不同端点**(旧 56007 vs 当前 7331 必须判为不匹配);
114
+ * - 路径/查询不同 = 不同端点;非 http(s)/不可解析 → null(不参与比较)。
115
+ */
116
+ export function normalizeMcpUrl(raw) {
117
+ if (typeof raw !== 'string') return null;
118
+ const text = raw.trim();
119
+ if (text.length === 0) return null;
120
+ let parsed;
121
+ try {
122
+ parsed = new URL(text);
123
+ } catch {
124
+ return null;
125
+ }
126
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
127
+ let host = parsed.hostname.toLowerCase();
128
+ if (host === 'localhost') host = '127.0.0.1';
129
+ const port = parsed.port.length > 0 ? `:${parsed.port}` : '';
130
+ const path = parsed.pathname.replace(/\/+$/, '');
131
+ return `${parsed.protocol}//${host}${port}${path}${parsed.search}`;
132
+ }
133
+
134
+ /** 两个 MCP URL 是否指向同一端点(末尾 `/` 等价;端口不同不等价)。 */
135
+ export function sameMcpUrl(a, b) {
136
+ const left = normalizeMcpUrl(a);
137
+ const right = normalizeMcpUrl(b);
138
+ if (left === null || right === null) {
139
+ return typeof a === 'string' && typeof b === 'string' && a.trim() === b.trim();
140
+ }
141
+ return left === right;
142
+ }
143
+
144
+ /** 是否为**回环** HTTP MCP 地址(只对这类条目做“旧端口/旧路径”判定)。 */
145
+ export function isLoopbackMcpUrl(raw) {
146
+ const normalized = normalizeMcpUrl(raw);
147
+ if (normalized === null) return false;
148
+ let host;
149
+ try {
150
+ host = new URL(normalized).hostname.toLowerCase();
151
+ } catch {
152
+ return false;
153
+ }
154
+ return host === '127.0.0.1' || host === 'localhost' || host === '[::1]' || host === '::1' || host === '0.0.0.0';
155
+ }
156
+
157
+ /** URL 诊断展示:去掉 userinfo(如 `user:pass@`)并脱敏已知凭据参数。 */
158
+ function displayMcpUrl(raw) {
159
+ try {
160
+ const parsed = new URL(raw);
161
+ if (parsed.username.length > 0 || parsed.password.length > 0) {
162
+ parsed.username = '';
163
+ parsed.password = '';
164
+ return redactSecrets(parsed.toString());
165
+ }
166
+ } catch {
167
+ // 无法解析时按原文脱敏展示(不阻断诊断)。
168
+ }
169
+ return redactSecrets(raw);
170
+ }
171
+
172
+ /** 回环配置是否与当前 runtime 端点“过期”:同端口/路径仅主机不同(如经 LAN 访问控制台)不算。 */
173
+ function staleLoopbackUrl(configuredUrl, expectedUrl) {
174
+ if (!isLoopbackMcpUrl(configuredUrl)) return false;
175
+ if (sameMcpUrl(configuredUrl, expectedUrl)) return false;
176
+ try {
177
+ const configured = new URL(normalizeMcpUrl(configuredUrl));
178
+ const expected = new URL(normalizeMcpUrl(expectedUrl));
179
+ // 控制台可能经 LAN/反向代理访问:同一 scheme+端口+路径时,loopback 对同机客户端仍有效。
180
+ if (configured.protocol === expected.protocol
181
+ && configured.port === expected.port
182
+ && configured.pathname === expected.pathname) return false;
183
+ } catch {
184
+ return true;
185
+ }
186
+ return true;
187
+ }
188
+
189
+ /**
190
+ * 诊断字段 + 可自愈判定:
191
+ * - **回环 URL** 且端口/路径(或 scheme)与当前 runtime 不一致 → `staleUrl`(可自动 reconcile);
192
+ * - **非回环/自定义远端 URL** 且与当前端点不一致 → `needsConfirmation`(不自动覆盖,人工确认/显式修复);
193
+ * - 两端一致(仅末尾 `/`、回环别名差异)→ 正常。
194
+ */
195
+ function urlDiagnostics(configuredUrl, expectedUrl) {
196
+ const out = {};
197
+ if (typeof configuredUrl === 'string' && configuredUrl.length > 0) out.configuredUrl = displayMcpUrl(configuredUrl);
198
+ if (typeof expectedUrl === 'string' && expectedUrl.length > 0) out.expectedUrl = displayMcpUrl(expectedUrl);
199
+ if (!out.configuredUrl || !out.expectedUrl) return { ...out, staleUrl: false, needsConfirmation: false };
200
+ const configuredLoopback = isLoopbackMcpUrl(configuredUrl);
201
+ const matches = sameMcpUrl(configuredUrl, expectedUrl);
202
+ if (!matches && !configuredLoopback) {
203
+ return {
204
+ ...out,
205
+ staleUrl: false,
206
+ needsConfirmation: true,
207
+ remoteUrl: true,
208
+ staleReason: `自定义远端 MCP 地址与当前端点不一致:${out.configuredUrl}(当前为 ${out.expectedUrl}),不会自动覆盖,请确认或手动修复`,
209
+ };
210
+ }
211
+ const staleUrl = staleLoopbackUrl(configuredUrl, expectedUrl);
212
+ if (!staleUrl) return { ...out, staleUrl: false, needsConfirmation: false, remoteUrl: !configuredLoopback };
213
+ return {
214
+ ...out,
215
+ staleUrl: true,
216
+ needsConfirmation: false,
217
+ remoteUrl: false,
218
+ staleReason: `MCP 地址已过期:${out.configuredUrl}(当前为 ${out.expectedUrl}),请自动修复`,
219
+ };
220
+ }
221
+
103
222
  /** 形状选择:给 url → HTTP 形态;否则 stdio(descriptor 可用 `landing.httpShape` 覆盖)。 */
104
223
  function shapeFor(format, options = {}) {
105
224
  const adapter = adapterFor(format);
@@ -116,7 +235,13 @@ function shapeFor(format, options = {}) {
116
235
  export function mebularEntry(format, options = {}) {
117
236
  const adapter = adapterFor(format);
118
237
  if (!adapter) return { command: 'mebular', args: ['mcp'] };
119
- return entryForShape(shapeFor(format, options), options.url) ?? { command: 'mebular', args: ['mcp'] };
238
+ const entry = entryForShape(shapeFor(format, options), options.url) ?? { command: 'mebular', args: ['mcp'] };
239
+ // descriptor 的固定字段(如 OpenChamber remote 条目的 oauth:false / codemode:false)。
240
+ // 只在 HTTP 形态应用;stdio 回落保持最小形状。
241
+ if (options.url && options.entryDefaults && entry !== null && typeof entry === 'object' && !Array.isArray(entry)) {
242
+ return { ...entry, ...options.entryDefaults };
243
+ }
244
+ return entry;
120
245
  }
121
246
 
122
247
  /** 各客户端 MCP 片段(与 `mebular print-config --client …` 同源);有 `url` → HTTP 形态。 */
@@ -179,6 +304,93 @@ export function assistantUserHome(options = {}) {
179
304
  return homedir();
180
305
  }
181
306
 
307
+ // ---------------------------------------------------------------------------
308
+ // OpenChamber 原生 memory 共存探测(只读;不读 entries / 不写 / 不注册工具)
309
+ // ---------------------------------------------------------------------------
310
+
311
+ const NATIVE_MEMORY_TRUTHY = new Set(['1', 'true', 'yes', 'on']);
312
+
313
+ /** OpenChamber 数据根:`OPENCHAMBER_DATA_DIR` 优先,否则 `~/.config/openchamber`。 */
314
+ export function openChamberDataDir(options = {}) {
315
+ const env = options.env ?? process.env;
316
+ const raw = typeof env.OPENCHAMBER_DATA_DIR === 'string' ? env.OPENCHAMBER_DATA_DIR.trim() : '';
317
+ if (raw.length > 0) return resolve(raw);
318
+ return join(assistantUserHome(options), '.config', 'openchamber');
319
+ }
320
+
321
+ /**
322
+ * 原生 memory 共存守卫(**只读**):
323
+ * - 读 env `OPENCHAMBER_MEMORY_ENABLE`(与 OpenChamber 同 truthy 集合);
324
+ * - 读 `settings.json` 的 `agentMemoryToolEnabled` 布尔值;
325
+ * - 只 `exists`/列目录判断 `memory.json` 是否存在(global + projects/*),**绝不读取条目**。
326
+ *
327
+ * 不导入、不替换、不双写,也不注册任何 OpenChamber 原生 memory 工具。原生 memory 开启时
328
+ * Mebular 沉浸式默认 `tool-only`,必须由用户显式 opt-in;状态里如实给出 summary/证据。
329
+ */
330
+ export function detectOpenChamberNativeMemory(options = {}) {
331
+ const env = options.env ?? process.env;
332
+ const dataDir = openChamberDataDir(options);
333
+ const settingsPath = join(dataDir, 'settings.json');
334
+ const rawFlag = typeof env.OPENCHAMBER_MEMORY_ENABLE === 'string' ? env.OPENCHAMBER_MEMORY_ENABLE : '';
335
+ const featureEnabled = NATIVE_MEMORY_TRUTHY.has(rawFlag.trim().toLowerCase());
336
+
337
+ let settingsRead = false;
338
+ let toolEnabled = false;
339
+ try {
340
+ const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
341
+ settingsRead = true;
342
+ toolEnabled = settings?.agentMemoryToolEnabled === true;
343
+ } catch {
344
+ // 文件不存在/不可读/损坏都按「未开启」处理;不修改、不创建。
345
+ }
346
+
347
+ const globalMemoryFileExists = existsSync(join(dataDir, 'memory.json'));
348
+ let projectMemoryFiles = 0;
349
+ try {
350
+ const projectsDir = join(dataDir, 'projects');
351
+ for (const entry of readdirSync(projectsDir, { withFileTypes: true })) {
352
+ if (entry.isDirectory() && existsSync(join(projectsDir, entry.name, 'memory.json'))) {
353
+ projectMemoryFiles += 1;
354
+ }
355
+ }
356
+ } catch {
357
+ // 无 projects/ 目录:正常(尚未使用原生 memory)。
358
+ }
359
+ const memoryFileExists = globalMemoryFileExists || projectMemoryFiles > 0;
360
+ const enabled = featureEnabled && toolEnabled;
361
+ const summary = enabled
362
+ ? (memoryFileExists
363
+ ? 'OpenChamber 原生 memory 已开启且检测到 memory.json;Mebular 沉浸式默认 tool-only,需显式 opt-in(不导入/不替换/不双写)'
364
+ : 'OpenChamber 原生 memory 已开启(尚无 memory.json);Mebular 沉浸式默认 tool-only,需显式 opt-in(不导入/不替换/不双写)')
365
+ : (featureEnabled || toolEnabled || memoryFileExists
366
+ ? 'OpenChamber 原生 memory 未完全开启;Mebular 沉浸式默认 tool-only,需显式 opt-in(不写入原生 memory)'
367
+ : '未检测到 OpenChamber 原生 memory;Mebular 沉浸式仍需显式 opt-in');
368
+
369
+ return {
370
+ kind: 'openchamber-native-memory',
371
+ readOnly: true,
372
+ featureFlag: 'OPENCHAMBER_MEMORY_ENABLE',
373
+ featureEnabled,
374
+ setting: 'agentMemoryToolEnabled',
375
+ toolEnabled,
376
+ settingsRead,
377
+ settingsPath,
378
+ dataDir,
379
+ memoryFileExists,
380
+ memoryFiles: { global: globalMemoryFileExists, projects: projectMemoryFiles },
381
+ enabled,
382
+ active: enabled,
383
+ immersiveDefault: 'tool-only',
384
+ requiresExplicitOptIn: true,
385
+ summary,
386
+ signals: {
387
+ env: 'OPENCHAMBER_MEMORY_ENABLE',
388
+ setting: 'agentMemoryToolEnabled',
389
+ memoryFile: 'memory.json',
390
+ },
391
+ };
392
+ }
393
+
182
394
  /** 桌面壳/守护常驻的 opencode 捆绑目录(存在才注入 PATH)。 */
183
395
  export const OPENCODE_BUNDLE_BIN = '/Applications/OpenChamber.app/Contents/Resources/opencode-cli';
184
396
 
@@ -218,15 +430,21 @@ export function builtinAssistants(options = {}) {
218
430
  : (env.XDG_CONFIG_HOME ?? join(userHome, '.config'));
219
431
  const opencodePath = expandHome(HOME_OPENCODE, userHome);
220
432
  const hermesPath = expandHome(HOME_HERMES, userHome);
433
+ const openChamberDir = join(userHome, '.config', 'openchamber');
221
434
 
222
435
  return [
223
436
  {
224
437
  id: 'openchamber', name: 'OpenChamber', kind: 'file', format: 'opencode-json',
438
+ description: '复用 OpenCode global 配置:只写 mcp.servers.mebular(remote /mcp);不接管原生 memory',
225
439
  landing: {
226
440
  primaryPath: opencodePath,
227
441
  keyPath: 'mcp.servers.mebular',
228
- forbiddenPaths: [join(userHome, '.config', 'openchamber', 'opencode.managed.json')],
442
+ // App 私有 managed config(含每次启动 run/instances/* 下的副本)只读、禁写。
443
+ forbiddenPaths: [join(openChamberDir, 'opencode.managed.json')],
444
+ forbiddenBasenames: ['opencode.managed.json'],
445
+ forbiddenRoots: [join(openChamberDir, 'run', 'instances')],
229
446
  format: 'opencode-json',
447
+ entryDefaults: { oauth: false, codemode: false },
230
448
  },
231
449
  probe: {
232
450
  signals: [
@@ -240,12 +458,26 @@ export function builtinAssistants(options = {}) {
240
458
  verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
241
459
  activation: { kind: 'user-reload', note: 'OpenChamber:由用户在 App 侧重载/重启生效;产品不得发 opencode reload 干扰运行服务' },
242
460
  risks: [
243
- 'opencode.managed.json 为 App 所有且会被重写,禁写',
461
+ 'opencode.managed.json(含 run/instances/*)为 App 所有且会被重写,禁写',
244
462
  'opencode mcp list 经运行服务回答,只读但勿频繁调用',
463
+ '原生 memory 开启时,Mebular 沉浸式默认 tool-only,需显式 opt-in;不导入、不替换、不双写',
245
464
  ],
246
- skillsDirs: [join(userHome, '.config', 'opencode', 'skills')],
465
+ nativeMemoryProbe: 'openchamber',
466
+ coexistence: {
467
+ nativeMemory: {
468
+ detect: 'openchamber',
469
+ readOnly: true,
470
+ inputs: ['OPENCHAMBER_MEMORY_ENABLE', 'agentMemoryToolEnabled', 'memory.json'],
471
+ neverImport: true,
472
+ neverReplace: true,
473
+ neverWrite: true,
474
+ neverRegisterTool: true,
475
+ },
476
+ immersive: { defaultMode: 'tool-only', requiresExplicitOptIn: true },
477
+ },
478
+ skillsDirs: [join(userHome, '.config', 'opencode', 'skills'), join(cwd, '.opencode', 'skills')],
247
479
  reuseOf: 'opencode',
248
- note: 'OpenChamber 复用 OpenCode 的 global 配置(接一次即可)',
480
+ note: 'OpenChamber 复用 OpenCode 的 global 配置(接一次即可);原生 memory 只读共存,不导入/不替换/不双写',
249
481
  },
250
482
  {
251
483
  id: 'hermes', name: 'Hermes', kind: 'file', format: 'hermes-yaml',
@@ -253,6 +485,7 @@ export function builtinAssistants(options = {}) {
253
485
  probe: {
254
486
  signals: [
255
487
  { kind: 'config-path', paths: [hermesPath] },
488
+ { kind: 'dir', paths: [join(userHome, '.hermes')] },
256
489
  { kind: 'cli', command: 'hermes --version', timeoutMs: 2500 },
257
490
  { kind: 'path', paths: [join(userHome, '.local', 'bin', 'hermes')] },
258
491
  ],
@@ -267,7 +500,7 @@ export function builtinAssistants(options = {}) {
267
500
  'Hermes 无法 env 沙箱(HERMES_CONFIG_PATH 被剥离)→ 写前字节级备份 + 失败回滚为硬要求',
268
501
  '写入仅经 `hermes config set --force`(ruamel 保注释);未知子键必须 --force',
269
502
  ],
270
- skillsDirs: [join(userHome, '.agents', 'skills')],
503
+ skillsDirs: [join(userHome, '.hermes', 'skills')],
271
504
  reuseOf: null,
272
505
  note: 'Hermes 的 MCP 配置在 ~/.hermes/config.yaml',
273
506
  },
@@ -285,19 +518,19 @@ export function builtinAssistants(options = {}) {
285
518
  verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
286
519
  activation: { kind: 'user-reload', note: 'OpenCode 侧重载/重启后生效' },
287
520
  risks: ['opencode mcp list 经运行服务回答,只读但勿频繁调用'],
288
- skillsDirs: [join(userHome, '.config', 'opencode', 'skills'), join(userHome, '.agents', 'skills'), join(cwd, '.agents', 'skills'), join(cwd, '.opencode', 'skills')],
521
+ skillsDirs: [join(userHome, '.config', 'opencode', 'skills'), join(cwd, '.opencode', 'skills')],
289
522
  reuseOf: null,
290
523
  note: null,
291
524
  },
292
525
  {
293
526
  id: 'claude-code', name: 'Claude Code', kind: 'file', format: 'json-mcpServers',
294
527
  landing: { primaryPath: join(userHome, '.claude.json'), keyPath: 'mcpServers.mebular', forbiddenPaths: [], format: 'json-mcpServers', httpShape: 'claude-http' },
295
- probe: { signals: [{ kind: 'config-path', paths: [join(userHome, '.claude.json')] }, { kind: 'cli', command: 'claude --version', timeoutMs: 1500 }] },
528
+ probe: { signals: [{ kind: 'config-path', paths: [join(userHome, '.claude.json')] }, { kind: 'dir', paths: [join(userHome, '.claude')] }, { kind: 'cli', command: 'claude --version', timeoutMs: 1500 }] },
296
529
  writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
297
530
  verify: { configReadback: true },
298
531
  activation: { kind: 'user-reload', note: '重启 Claude Code 后生效' },
299
532
  risks: [],
300
- skillsDirs: [join(userHome, '.agents', 'skills'), join(cwd, '.agents', 'skills')],
533
+ skillsDirs: [join(userHome, '.claude', 'skills'), join(cwd, '.claude', 'skills')],
301
534
  reuseOf: null, note: null,
302
535
  },
303
536
  {
@@ -317,17 +550,24 @@ export function builtinAssistants(options = {}) {
317
550
  writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
318
551
  verify: { configReadback: true },
319
552
  activation: { kind: 'user-reload', note: '重启 Cursor 后生效' },
320
- risks: ['HTTP /mcp 默认只监听回环:客户端与守护须**同机**(跨机请在 config 里启用 TLS+鉴权并用可达主机名)'], skillsDirs: [], reuseOf: null, note: null,
553
+ risks: ['HTTP /mcp 默认只监听回环:客户端与守护须**同机**(跨机请在 config 里启用 TLS+鉴权并用可达主机名)'],
554
+ skillsDirs: [join(userHome, '.cursor', 'skills'), join(cwd, '.cursor', 'skills')], reuseOf: null, note: null,
321
555
  },
322
556
  {
323
557
  id: 'dsh', name: 'DeepSeek Harness (DSH)', kind: 'file', format: 'dsh',
324
558
  landing: { primaryPath: join(cwd, '.dsh', 'cordis.yml'), keyPath: 'plugins', forbiddenPaths: [], format: 'dsh' },
325
- probe: { signals: [{ kind: 'config-path', paths: [join(cwd, '.dsh', 'cordis.yml')] }, { kind: 'dir', paths: [join(cwd, '.dsh')] }] },
559
+ probe: {
560
+ signals: [
561
+ { kind: 'config-path', paths: [join(cwd, '.dsh', 'cordis.yml')] },
562
+ // DSH_HOME 默认 ~/.dsh;全局安装也要能被自动检测(Skill 仍写 ~/.agents/skills)。
563
+ { kind: 'dir', paths: [join(cwd, '.dsh'), join(userHome, '.dsh')] },
564
+ ],
565
+ },
326
566
  writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
327
567
  verify: { configReadback: true },
328
568
  activation: { kind: 'user-reload', note: '重启 DSH 后生效' },
329
569
  risks: ['DSH 配置为 YAML 插件列表:结构未知时不自动改写', 'HTTP /mcp 默认只监听回环:客户端与守护须同机(跨机请启用 TLS+鉴权并用可达主机名)'],
330
- skillsDirs: [join(cwd, '.dsh', 'skills'), join(userHome, '.agents', 'skills')], reuseOf: null, note: null,
570
+ skillsDirs: [join(userHome, '.agents', 'skills'), join(cwd, '.dsh', 'skills')], reuseOf: null, note: null,
331
571
  },
332
572
  {
333
573
  id: 'generic', name: '其他 AI 助手(复制片段)', kind: 'snippet', format: 'generic-snippet',
@@ -470,6 +710,8 @@ export function clientDescriptors(options = {}) {
470
710
  skillsDirs: a.skillsDirs ?? [],
471
711
  requiresRestart: a.activation.kind === 'user-reload',
472
712
  reuseOf: a.reuseOf ?? null, note: a.note ?? null,
713
+ description: a.description ?? null,
714
+ coexistence: a.coexistence ?? null,
473
715
  }));
474
716
  }
475
717
 
@@ -499,11 +741,165 @@ function walkGet(root, path) {
499
741
  return { value: node };
500
742
  }
501
743
 
744
+ function isPlainObject(value) {
745
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
746
+ }
747
+
748
+ /** 扫描 JSON 字符串(text[start] === '"')返回结束位置(不含引号之后)。 */
749
+ function scanJsonString(text, start) {
750
+ let i = start + 1;
751
+ while (i < text.length) {
752
+ if (text[i] === '\\') { i += 2; continue; }
753
+ if (text[i] === '"') return i + 1;
754
+ i += 1;
755
+ }
756
+ throw new Error('unterminated JSON string');
757
+ }
758
+
759
+ /** 轻量 JSON 区间解析(仅用于已有合法 JSON 的「只替换 mebular」写入,保留其他字节)。 */
760
+ function parseJsonRanges(text) {
761
+ let i = 0;
762
+ const skip = () => { while (i < text.length && /\s/.test(text[i])) i += 1; };
763
+ const value = () => {
764
+ skip();
765
+ const start = i;
766
+ const ch = text[i];
767
+ if (ch === '{') {
768
+ i += 1;
769
+ const members = [];
770
+ skip();
771
+ if (text[i] === '}') { i += 1; return { type: 'object', start, end: i, members }; }
772
+ for (;;) {
773
+ skip();
774
+ const keyStart = i;
775
+ if (text[i] !== '"') throw new Error('object key expected');
776
+ i = scanJsonString(text, i);
777
+ const key = JSON.parse(text.slice(keyStart, i));
778
+ skip();
779
+ if (text[i] !== ':') throw new Error('colon expected');
780
+ i += 1;
781
+ const child = value();
782
+ members.push({ key, keyStart, value: child });
783
+ skip();
784
+ if (text[i] === ',') { i += 1; continue; }
785
+ if (text[i] === '}') { i += 1; break; }
786
+ throw new Error('object delimiter expected');
787
+ }
788
+ return { type: 'object', start, end: i, members };
789
+ }
790
+ if (ch === '[') {
791
+ i += 1;
792
+ const items = [];
793
+ skip();
794
+ if (text[i] === ']') { i += 1; return { type: 'array', start, end: i, items }; }
795
+ for (;;) {
796
+ items.push(value());
797
+ skip();
798
+ if (text[i] === ',') { i += 1; continue; }
799
+ if (text[i] === ']') { i += 1; break; }
800
+ throw new Error('array delimiter expected');
801
+ }
802
+ return { type: 'array', start, end: i, items };
803
+ }
804
+ if (ch === '"') {
805
+ const end = scanJsonString(text, i);
806
+ i = end;
807
+ return { type: 'string', start, end };
808
+ }
809
+ while (i < text.length && !/[\s,\]}]/.test(text[i])) i += 1;
810
+ return { type: 'primitive', start, end: i };
811
+ };
812
+ return value();
813
+ }
814
+
815
+ function lineIndentAt(text, index) {
816
+ const lineStart = text.lastIndexOf('\n', Math.max(0, index - 1)) + 1;
817
+ const match = /^[ \t]*/.exec(text.slice(lineStart));
818
+ return match ? match[0] : '';
819
+ }
820
+
821
+ function indentJsonValue(value, text, start, indent) {
822
+ const target = indent ?? ' '.repeat(Math.max(0, start - (text.lastIndexOf('\n', Math.max(0, start - 1)) + 1)));
823
+ return JSON.stringify(value, null, 2).split('\n').join(`\n${target}`);
824
+ }
825
+
826
+ /** 把 `keys` 逐层包成对象(用于补齐缺失的中间键)。 */
827
+ function nestedJsonValue(keys, value) {
828
+ let out = value;
829
+ for (let index = keys.length - 1; index >= 0; index -= 1) {
830
+ out = { [keys[index]]: out };
831
+ }
832
+ return out;
833
+ }
834
+
835
+ /** 在已有 JSON 对象的最后一个成员之后插入一个属性(其他字节不动)。 */
836
+ function insertJsonProperty(text, node, key, value) {
837
+ const indent = `${lineIndentAt(text, node.start)} `;
838
+ const property = `${JSON.stringify(key)}: ${indentJsonValue(value, text, node.start + 1, indent)}`;
839
+ if (node.members.length > 0) {
840
+ const at = node.members[node.members.length - 1].value.end;
841
+ return text.slice(0, at) + `,\n${indent}${property}` + text.slice(at);
842
+ }
843
+ return text.slice(0, node.start + 1)
844
+ + `\n${indent}${property}\n${lineIndentAt(text, node.start)}`
845
+ + text.slice(node.start + 1);
846
+ }
847
+
848
+ /**
849
+ * 只改 `<keyPath>` 的 JSON 文本:已有条目 → 原位替换 value;缺失 → 插入父对象
850
+ * (中间键缺失时一并补齐);删除 → 摘除成员。其余字节(其他键、缩进、换行)原样保留。
851
+ * 结构异常 → null(调用方回落到整体序列化)。
852
+ */
853
+ function spliceJsonEntry(text, path, value) {
854
+ const root = parseJsonRanges(text);
855
+ let node = root;
856
+ for (let depth = 0; depth < path.length - 1; depth += 1) {
857
+ const key = path[depth];
858
+ if (node.type !== 'object') return null;
859
+ const member = node.members.find((item) => item.key === key);
860
+ if (!member) {
861
+ if (value === undefined) return text;
862
+ return insertJsonProperty(text, node, key, nestedJsonValue(path.slice(depth + 1), value));
863
+ }
864
+ node = member.value;
865
+ }
866
+ if (node.type !== 'object') return null;
867
+ const leaf = path[path.length - 1];
868
+ const index = node.members.findIndex((item) => item.key === leaf);
869
+
870
+ if (value === undefined) {
871
+ if (index < 0) return text;
872
+ const member = node.members[index];
873
+ if (node.members.length === 1) {
874
+ return text.slice(0, node.start + 1) + text.slice(node.end - 1);
875
+ }
876
+ if (index > 0) {
877
+ const previous = node.members[index - 1];
878
+ return text.slice(0, previous.value.end) + text.slice(member.value.end);
879
+ }
880
+ const next = node.members[index + 1];
881
+ return text.slice(0, member.keyStart) + text.slice(next.keyStart);
882
+ }
883
+
884
+ if (index >= 0) {
885
+ const member = node.members[index];
886
+ return text.slice(0, member.value.start)
887
+ + indentJsonValue(value, text, member.value.start)
888
+ + text.slice(member.value.end);
889
+ }
890
+
891
+ return insertJsonProperty(text, node, leaf, value);
892
+ }
893
+
502
894
  /**
503
895
  * JSON 合并:设置或删除 `<keyPath>`(默认含叶子 `mebular`),保留其余键。
504
896
  * 中间键存在但非对象 → error(结构未知,不自动改写)。
897
+ *
898
+ * `preserveEntryFields`:已有 Mebular 条目是对象时,仅覆盖新条目提供的字段(保留 headers、
899
+ * timeout、protocol 等用户字段;local → remote 升级时移除 command/cwd/environment)。
900
+ * `preserveFormatting`:用区间替换只动 mebular 文本,其他配置键字节不变(失败回落整体序列化)。
505
901
  */
506
- export function mergeJsonEntry(existingText, { format, entry, keyPath } = {}) {
902
+ export function mergeJsonEntry(existingText, { format, entry, keyPath, preserveEntryFields = false, preserveFormatting = false } = {}) {
507
903
  const path = keyPathOf(format, keyPath);
508
904
  let parsed;
509
905
  if (existingText === null || existingText === undefined || existingText.trim() === '') {
@@ -533,10 +929,44 @@ export function mergeJsonEntry(existingText, { format, entry, keyPath } = {}) {
533
929
  }
534
930
  cursor = cursor[key];
535
931
  }
536
- const changed = JSON.stringify(cursor[leaf] ?? null) !== JSON.stringify(entry ?? null);
932
+ const previous = cursor[leaf];
933
+ let nextEntry = entry;
934
+ if (preserveEntryFields && entry !== undefined && isPlainObject(previous) && isPlainObject(entry)) {
935
+ nextEntry = { ...previous, ...entry };
936
+ if (entry.type === 'remote' && previous.type !== 'remote') {
937
+ // local → remote:移除只对 stdio/local 有意义的字段,其他用户字段保留。
938
+ delete nextEntry.command;
939
+ delete nextEntry.cwd;
940
+ delete nextEntry.environment;
941
+ }
942
+ }
943
+ const changed = JSON.stringify(previous ?? null) !== JSON.stringify(nextEntry ?? null);
537
944
  if (entry === undefined) delete cursor[leaf];
538
- else cursor[leaf] = entry;
539
- return { changed, next, text: `${JSON.stringify(next, null, 2)}\n` };
945
+ else cursor[leaf] = nextEntry;
946
+
947
+ let text = `${JSON.stringify(next, null, 2)}\n`;
948
+ if (!changed && typeof existingText === 'string') {
949
+ text = existingText;
950
+ } else if (preserveFormatting && typeof existingText === 'string' && existingText.trim() !== '') {
951
+ try {
952
+ const spliced = spliceJsonEntry(existingText, path, nextEntry);
953
+ if (spliced !== null) text = spliced;
954
+ } catch {
955
+ // 区间解析失败:保持整体序列化的安全回落。
956
+ }
957
+ }
958
+ return { changed, next, text };
959
+ }
960
+
961
+ /** 只替换 DSH mebular 条目里的 `url:` 行(保留其他插件与键)。 */
962
+ function replaceDshMebularUrl(text, url) {
963
+ const block = dshMebularBlock(text);
964
+ if (block === null) return null;
965
+ const start = text.indexOf(block);
966
+ if (start < 0) return null;
967
+ const replaced = block.replace(/^(\s*url\s*:\s*)(?:"[^"]*"|'[^']*'|[^\s#]+)/m, `$1${url}`);
968
+ if (replaced === block) return null;
969
+ return `${text.slice(0, start)}${replaced}${text.slice(start + block.length)}`;
540
970
  }
541
971
 
542
972
  /** DSH(YAML) 合并:空文件 → 写片段;已含 serverName: mebular → 幂等;结构未知 → 不写。 */
@@ -544,10 +974,22 @@ export function mergeDsh(existingText, options = {}) {
544
974
  const snippet = snippetFor('dsh', options);
545
975
  if (existingText === null || existingText.trim() === '') return { changed: true, text: `${snippet}\n` };
546
976
  if (/serverName:\s*['"]?mebular['"]?/.test(existingText)) {
547
- // 已接入:仅当**形态等价**(HTTP vs stdio)才算幂等,否则需改写
977
+ // 已接入:仅当**形态/端点等价**才算幂等,否则只改 mebular 的 URL(保留其他插件)。
978
+ const block = dshMebularBlock(existingText);
979
+ const scope = block ?? existingText;
548
980
  const wantHttp = Boolean(options.url);
549
- const hasHttp = /transport:\s*streamable-http/.test(existingText);
550
- if (wantHttp === hasHttp) return { changed: false, text: existingText };
981
+ const hasHttp = /transport:\s*streamable-http/.test(scope);
982
+ if (wantHttp === hasHttp) {
983
+ if (wantHttp && hasHttp) {
984
+ const urlInfo = urlDiagnostics(yamlEntryUrl(scope), options.url);
985
+ if (urlInfo.staleUrl === true) {
986
+ const next = replaceDshMebularUrl(existingText, options.url);
987
+ if (next !== null) return { changed: true, text: next };
988
+ return { error: 'DSH 配置中的 mebular URL 无法定位:未自动改写(请按片段人工合并)' };
989
+ }
990
+ }
991
+ return { changed: false, text: existingText };
992
+ }
551
993
  return { changed: true, text: `${snippet}\n` };
552
994
  }
553
995
  return { error: 'DSH 配置已存在但未接入:YAML 结构未知,未自动改写(请按片段人工合并)' };
@@ -604,6 +1046,38 @@ export function yamlEntryBlock(text, parent, child) {
604
1046
  return block === null ? null : block.join('\n');
605
1047
  }
606
1048
 
1049
+ /** 提取 YAML 块里 `url:` 的标量值(支持单/双引号与行尾注释;无则 null)。 */
1050
+ export function yamlEntryUrl(block) {
1051
+ if (typeof block !== 'string') return null;
1052
+ const match = /^\s*url\s*:\s*(?:"([^"]*)"|'([^']*)'|([^\s#]+))/m.exec(block);
1053
+ const value = (match?.[1] ?? match?.[2] ?? match?.[3] ?? '').trim();
1054
+ return value.length > 0 ? value : null;
1055
+ }
1056
+
1057
+ /**
1058
+ * 提取 DSH YAML 插件列表中 `serverName: mebular` 的那一项(行式;无需 yaml 依赖)。
1059
+ * 只用于把 URL 判据/改写限制在 mebular 条目内,避免误碰其他插件。
1060
+ */
1061
+ export function dshMebularBlock(text) {
1062
+ const lines = String(text ?? '').split('\n');
1063
+ for (let i = 0; i < lines.length; i++) {
1064
+ if (!/^\s*-\s+name\s*:/.test(lines[i])) continue;
1065
+ const itemIndent = lines[i].match(/^\s*/)?.[0].length ?? 0;
1066
+ const item = [lines[i]];
1067
+ for (let j = i + 1; j < lines.length; j++) {
1068
+ const line = lines[j];
1069
+ const leading = line.match(/^\s*/)?.[0].length ?? 0;
1070
+ const nextItem = /^\s*-\s+/.test(line) && leading === itemIndent;
1071
+ const topLevel = line.trim().length > 0 && leading === 0;
1072
+ if (nextItem || topLevel) break;
1073
+ item.push(line);
1074
+ }
1075
+ const block = item.join('\n');
1076
+ if (/serverName:\s*['"]?mebular['"]?/.test(block)) return block;
1077
+ }
1078
+ return null;
1079
+ }
1080
+
607
1081
  /** 该格式下「HTTP/remote」形态(valid);`stdio` 形态守护运行中会被拒(MCP_STORAGE_LOCKED)。 */
608
1082
  export function entryIsHttp(format, entry) {
609
1083
  if (entry === null || typeof entry !== 'object') return false;
@@ -627,18 +1101,44 @@ export function landingState(assistant, options = {}) {
627
1101
  const text = safeReadText(primary);
628
1102
  if (text === null) return { exists: false, present: false, legacyShape: false, text: null };
629
1103
  if (format === 'dsh') {
630
- const has = /serverName:\s*['"]?mebular['"]?/.test(text);
631
- const present = has && /transport:\s*streamable-http/.test(text);
632
- return { exists: true, present, legacyShape: false, staleStdio: has && /transport:\s*stdio/.test(text) && !present, text };
1104
+ const block = dshMebularBlock(text);
1105
+ const scope = block ?? text;
1106
+ const has = /serverName:\s*['"]?mebular['"]?/.test(scope);
1107
+ const hasHttp = has && /transport:\s*streamable-http/.test(scope);
1108
+ const urlInfo = urlDiagnostics(yamlEntryUrl(scope), options.mcpUrl);
1109
+ const staleUrl = hasHttp && urlInfo.staleUrl === true;
1110
+ const needsConfirmation = hasHttp && urlInfo.needsConfirmation === true;
1111
+ return {
1112
+ exists: true,
1113
+ present: hasHttp && !staleUrl && !needsConfirmation,
1114
+ legacyShape: false,
1115
+ staleStdio: has && /transport:\s*stdio/.test(scope) && !hasHttp,
1116
+ ...urlInfo,
1117
+ staleUrl,
1118
+ needsConfirmation,
1119
+ text,
1120
+ };
633
1121
  }
634
1122
  if (adapter?.serialization === 'yaml') {
635
1123
  const path = keyPathOf(format);
636
1124
  const block = yamlEntryBlock(text, path[0], path[1]);
637
1125
  const hasUrl = block !== null && /^\s*url\s*:\s*\S+/m.test(block);
638
1126
  const hasCommand = block !== null && /^\s*command\s*:\s*\S+/m.test(block);
639
- // 语义判据:remote(有 url)→ present;stdio(有 command 无 url)→ stale;旧「逐字段错位追加」也归 stale
640
- const present = hasUrl && !hasCommand;
641
- return { exists: true, present, legacyShape: false, staleStdio: !present && hasCommand, text };
1127
+ const urlInfo = urlDiagnostics(yamlEntryUrl(block), options.mcpUrl);
1128
+ const staleUrl = hasUrl && urlInfo.staleUrl === true;
1129
+ const needsConfirmation = hasUrl && urlInfo.needsConfirmation === true;
1130
+ // 语义判据:remote(有 url 且端点未过期/未待确认)→ present;stdio 形态或旧 loopback 地址 → stale
1131
+ const present = hasUrl && !hasCommand && !staleUrl && !needsConfirmation;
1132
+ return {
1133
+ exists: true,
1134
+ present,
1135
+ legacyShape: false,
1136
+ staleStdio: !present && hasCommand,
1137
+ ...urlInfo,
1138
+ staleUrl,
1139
+ needsConfirmation,
1140
+ text,
1141
+ };
642
1142
  }
643
1143
  try {
644
1144
  const parsed = JSON.parse(text);
@@ -647,13 +1147,15 @@ export function landingState(assistant, options = {}) {
647
1147
  const legacy = adapter?.legacyKeyPath
648
1148
  ? walkGet(parsed, adapter.legacyKeyPath).value !== undefined
649
1149
  : false;
650
- // 语义判据(兼容迁移):remote/http 形态 → present;stdio 形态或**端口与当前守护端点不符** → stale
1150
+ // 语义判据(兼容迁移):remote/http 形态且端点未过期 → present;stdio 形态 → stale
651
1151
  const isHttp = entryIsHttp(format, stored);
652
1152
  const storedUrl = typeof stored?.url === 'string' ? stored.url : null;
653
- const urlOk = options.mcpUrl === undefined || options.mcpUrl === null || storedUrl === options.mcpUrl;
654
- const present = isHttp && urlOk;
655
- const staleStdio = !present && (entryIsStdio(format, stored) || (isHttp && !urlOk));
656
- return { exists: true, present, legacyShape: legacy && !present, staleStdio, text };
1153
+ const urlInfo = urlDiagnostics(isHttp ? storedUrl : null, options.mcpUrl);
1154
+ const staleUrl = isHttp && urlInfo.staleUrl === true;
1155
+ const needsConfirmation = isHttp && urlInfo.needsConfirmation === true;
1156
+ const present = isHttp && !staleUrl && !needsConfirmation;
1157
+ const staleStdio = !present && entryIsStdio(format, stored);
1158
+ return { exists: true, present, legacyShape: legacy && !present, staleStdio, ...urlInfo, staleUrl, needsConfirmation, text };
657
1159
  } catch {
658
1160
  return { exists: true, present: false, legacyShape: false, text, parseError: true };
659
1161
  }
@@ -785,20 +1287,48 @@ function builtinsCount(reg, options) {
785
1287
  function entryOptionsFor(assistant, options = {}) {
786
1288
  const url = options.mcpUrl ?? null;
787
1289
  const httpShape = assistant.landing?.httpShape;
788
- return { ...(url ? { url } : {}), ...(httpShape ? { httpShape } : {}) };
1290
+ const entryDefaults = assistant.landing?.entryDefaults;
1291
+ return {
1292
+ ...(url ? { url } : {}),
1293
+ ...(httpShape ? { httpShape } : {}),
1294
+ ...(url && entryDefaults ? { entryDefaults } : {}),
1295
+ };
789
1296
  }
790
1297
 
791
1298
  function buildStateItem(assistant, signals, landing, options = {}) {
792
1299
  const anyHit = signals.some((s) => s.hit);
793
1300
  const anyError = signals.some((s) => typeof s.detail === 'string' && s.detail.startsWith('探测异常'));
794
1301
  const strategy = assistant.writer?.strategy ?? 'merge-key';
1302
+ const staleUrl = landing.staleUrl === true;
1303
+ const staleStdio = landing.staleStdio === true;
1304
+ const needsConfirmation = landing.needsConfirmation === true;
795
1305
  let state;
796
1306
  if (strategy === 'manual' && !landing.present) state = anyHit ? 'manual' : 'not-installed';
797
1307
  else if (landing.present) state = 'connected';
798
- else if (landing.staleStdio) state = 'stale'; // 已写入但过时(stdio)→ 升级直连
1308
+ else if (needsConfirmation) state = 'needs-confirmation'; // 自定义远端 URL 与当前端点不一致:不自动覆盖
1309
+ else if (staleUrl) state = 'stale'; // 配置的 loopback MCP 地址已过期(旧端口/旧路径)
1310
+ else if (staleStdio) state = 'stale'; // 已写入但过时(stdio)→ 升级直连
799
1311
  else if (!anyHit) state = anyError ? 'detect-failed' : 'not-installed';
800
1312
  else state = 'not-connected';
801
- const STATE_LABEL = { 'not-installed': '未安装', 'not-connected': '未接入', connected: '已接入 ✓', manual: '需手动', 'detect-failed': '检测失败', stale: '已写入·需升级为直连' };
1313
+ const STATE_LABEL = { 'not-installed': '未安装', 'not-connected': '未接入', connected: '已接入 ✓', manual: '需手动', 'detect-failed': '检测失败', stale: '已写入·需升级为直连', 'needs-confirmation': '需要修复/请确认' };
1314
+ const staleReason = needsConfirmation || staleUrl ? (landing.staleReason ?? 'MCP 地址与当前端点不一致,请确认或手动修复') : null;
1315
+ const nativeMemory = assistant.nativeMemoryProbe === 'openchamber'
1316
+ ? detectOpenChamberNativeMemory(options)
1317
+ : null;
1318
+ const coexistence = assistant.coexistence
1319
+ ? {
1320
+ ...assistant.coexistence,
1321
+ nativeMemory: nativeMemory
1322
+ ? { ...(assistant.coexistence.nativeMemory ?? {}), ...nativeMemory }
1323
+ : (assistant.coexistence.nativeMemory ?? null),
1324
+ immersive: {
1325
+ ...(assistant.coexistence.immersive ?? {}),
1326
+ defaultMode: 'tool-only',
1327
+ requiresExplicitOptIn: true,
1328
+ nativeMemoryActive: nativeMemory?.enabled === true,
1329
+ },
1330
+ }
1331
+ : null;
802
1332
  return {
803
1333
  id: assistant.id,
804
1334
  name: assistant.name,
@@ -806,18 +1336,29 @@ function buildStateItem(assistant, signals, landing, options = {}) {
806
1336
  type: assistant.kind === 'snippet' ? 'snippet' : 'file', // file | snippet(descriptor 形态)
807
1337
  registryKind: assistant.registryKind ?? 'builtin',
808
1338
  state,
809
- stateLabel: STATE_LABEL[state] ?? state,
1339
+ stateLabel: needsConfirmation ? '需要修复/请确认' : staleUrl ? '配置已过期 · 请自动修复' : (STATE_LABEL[state] ?? state),
810
1340
  evidence: signals.map((s) => ({ ...s, detail: redactSecrets(s.detail) })),
811
1341
  anySignalHit: anyHit,
812
1342
  landing: {
813
1343
  primaryPath: assistant.landing?.primaryPath ?? null,
814
1344
  keyPath: assistant.landing?.keyPath ?? null,
815
1345
  forbiddenPaths: assistant.landing?.forbiddenPaths ?? [],
1346
+ forbiddenBasenames: assistant.landing?.forbiddenBasenames ?? [],
1347
+ forbiddenRoots: assistant.landing?.forbiddenRoots ?? [],
1348
+ entryDefaults: assistant.landing?.entryDefaults ?? null,
816
1349
  format: assistant.landing?.format ?? assistant.format,
817
1350
  strategy,
818
1351
  present: landing.present,
819
1352
  legacyShape: landing.legacyShape === true,
820
- staleStdio: landing.staleStdio === true,
1353
+ stale: staleUrl || staleStdio,
1354
+ staleKind: staleUrl ? 'url' : staleStdio ? 'stdio' : null,
1355
+ staleStdio,
1356
+ staleUrl,
1357
+ needsConfirmation,
1358
+ remoteUrl: landing.remoteUrl === true,
1359
+ staleReason,
1360
+ configuredUrl: landing.configuredUrl ?? null,
1361
+ expectedUrl: landing.expectedUrl ?? null,
821
1362
  exists: landing.exists,
822
1363
  parseError: landing.parseError === true,
823
1364
  },
@@ -831,8 +1372,20 @@ function buildStateItem(assistant, signals, landing, options = {}) {
831
1372
  configPath: assistant.landing?.primaryPath ?? null,
832
1373
  reuseOf: assistant.reuseOf ?? null,
833
1374
  note: assistant.note ?? null,
1375
+ description: assistant.description ?? null,
1376
+ nativeMemory,
1377
+ coexistence,
834
1378
  snippet: snippetFor(assistant.format, entryOptionsFor(assistant, options)),
835
1379
  mcpUrl: options.mcpUrl ?? null,
1380
+ // 陈旧配置诊断(顶层投影,UI/脚本无需深入 landing)
1381
+ stale: staleUrl || staleStdio,
1382
+ staleKind: staleUrl ? 'url' : staleStdio ? 'stdio' : null,
1383
+ staleUrl,
1384
+ needsConfirmation,
1385
+ remoteUrl: landing.remoteUrl === true,
1386
+ staleReason,
1387
+ configuredUrl: landing.configuredUrl ?? null,
1388
+ expectedUrl: landing.expectedUrl ?? null,
836
1389
  // 兼容既有 `/admin/api/clients` 字段(只扩展不破坏;UI 亦可继续用)
837
1390
  installed: signals.some((s) => s.kind !== 'always' && s.hit),
838
1391
  connected: state === 'connected',
@@ -946,16 +1499,24 @@ async function atomicWrite(path, text) {
946
1499
  }
947
1500
 
948
1501
  function isForbidden(assistant, path) {
949
- const forbidden = assistant.landing?.forbiddenPaths ?? [];
950
- return forbidden.some((f) => f === path);
1502
+ const landing = assistant.landing ?? {};
1503
+ if ((landing.forbiddenPaths ?? []).some((f) => f === path)) return true;
1504
+ // App 私有 managed config 的任何副本(如 run/instances/<id>/opencode.managed.json)。
1505
+ if ((landing.forbiddenBasenames ?? []).includes(basename(path))) return true;
1506
+ const roots = landing.forbiddenRoots ?? [];
1507
+ return roots.some((root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`));
951
1508
  }
952
1509
 
953
1510
  function computeMerged(assistant, existing, options = {}) {
954
1511
  if (assistant.format === 'dsh') return mergeDsh(existing, entryOptionsFor(assistant, options));
1512
+ const adapter = adapterFor(assistant.landing?.format ?? assistant.format);
1513
+ const preserve = adapter?.serialization === 'json';
955
1514
  return mergeJsonEntry(existing, {
956
1515
  format: assistant.format,
957
1516
  entry: mebularEntry(assistant.format, entryOptionsFor(assistant, options)),
958
1517
  keyPath: keyPathOf(assistant.landing?.format ?? assistant.format),
1518
+ preserveEntryFields: preserve,
1519
+ preserveFormatting: preserve,
959
1520
  });
960
1521
  }
961
1522
 
@@ -1032,6 +1593,19 @@ async function connectViaCli(assistant, options = {}) {
1032
1593
  };
1033
1594
  }
1034
1595
 
1596
+ /** 接入成功后顺带 ensure 该客户端的 Skill;失败只记录,绝不阻断 MCP 接入。 */
1597
+ async function attachSkills(result, id, options = {}) {
1598
+ if (!result?.ok || options.skipSkills === true) return result;
1599
+ const assistant = descriptorFor(id, options);
1600
+ if ((assistant?.skillsDirs ?? []).length === 0) return result;
1601
+ try {
1602
+ result.skills = await installSkills(id, options);
1603
+ } catch (error) {
1604
+ result.skills = { ok: false, id, reason: `Skill 安装失败:${redactSecrets(error?.message ?? error)}` };
1605
+ }
1606
+ return result;
1607
+ }
1608
+
1035
1609
  /** 接入:merge-key(备份 → 原子写)/ cli-set(官方 CLI)/ manual(仅片段)。 */
1036
1610
  export async function connectClient(id, options = {}) {
1037
1611
  const assistant = descriptorFor(id, options);
@@ -1044,7 +1618,7 @@ export async function connectClient(id, options = {}) {
1044
1618
  if (isForbidden(assistant, primary)) {
1045
1619
  return { ok: false, reason: `禁写路径(landing.forbiddenPaths):${primary}` };
1046
1620
  }
1047
- if (strategy === 'cli-set') return connectViaCli(assistant, options);
1621
+ if (strategy === 'cli-set') return attachSkills(await connectViaCli(assistant, options), id, options);
1048
1622
  const existing = safeReadText(primary);
1049
1623
  const merged = computeMerged(assistant, existing, options);
1050
1624
  if (merged.error) {
@@ -1052,7 +1626,7 @@ export async function connectClient(id, options = {}) {
1052
1626
  }
1053
1627
  const preview = lineDiff(existing ?? '', merged.text);
1054
1628
  if (!merged.changed) {
1055
- return { ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' };
1629
+ return attachSkills({ ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' }, id, options);
1056
1630
  }
1057
1631
  const backupPath = existing !== null ? `${primary}.bak-${tsStamp()}` : null;
1058
1632
  if (backupPath) await copyFile(primary, backupPath);
@@ -1063,15 +1637,122 @@ export async function connectClient(id, options = {}) {
1063
1637
  if (backupPath) await copyFile(backupPath, primary); // 失败回滚
1064
1638
  return { ok: false, changed: false, rolledBack: Boolean(backupPath), backupPath, reason: `写入失败已回滚:${redactSecrets(error?.message ?? error)}` };
1065
1639
  }
1066
- return { ok: true, changed: true, configPath: primary, backupPath, preview };
1640
+ return attachSkills({ ok: true, changed: true, configPath: primary, backupPath, preview }, id, options);
1641
+ }
1642
+
1643
+ /**
1644
+ * 自动 reconcile 的 JSON 专用写入:只改 `<keyPath>.url`,保留 mebular 条目里的
1645
+ * `type` / `headers` / 其他自定义字段;写前备份、失败回滚、原子写。
1646
+ * 结构未知/解析失败 → 返回错误,交回状态检测与手动兜底。
1647
+ */
1648
+ async function reconcileJsonMebularUrl(assistant, mcpUrl) {
1649
+ const primary = assistant.landing?.primaryPath ?? null;
1650
+ if (!primary) return { ok: false, reason: '缺少配置路径' };
1651
+ if (isForbidden(assistant, primary)) return { ok: false, reason: `禁写路径(landing.forbiddenPaths):${primary}` };
1652
+ const text = safeReadText(primary);
1653
+ if (text === null) return { ok: false, reason: '配置文件不存在' };
1654
+ let parsed;
1655
+ try {
1656
+ parsed = JSON.parse(text);
1657
+ } catch (error) {
1658
+ return { ok: false, reason: `配置不是合法 JSON(${error instanceof Error ? error.message : String(error)})` };
1659
+ }
1660
+ const path = keyPathOf(assistant.landing?.format ?? assistant.format);
1661
+ const stored = walkGet(parsed, path).value ?? null;
1662
+ if (stored === null || typeof stored !== 'object' || Array.isArray(stored)) {
1663
+ return { ok: false, reason: 'mebular 条目结构未知(不自动改写)' };
1664
+ }
1665
+ if (stored.url === mcpUrl) return { ok: true, changed: false, configPath: primary, backupPath: null };
1666
+ let node = parsed;
1667
+ for (const key of path.slice(0, -1)) node = node?.[key];
1668
+ if (node === null || typeof node !== 'object') return { ok: false, reason: 'mebular 父级结构未知(不自动改写)' };
1669
+ const defaults = assistant.landing?.entryDefaults ?? {};
1670
+ // 只补缺失的固定字段(oauth:false / codemode:false),已有字段一律保留。
1671
+ node[path[path.length - 1]] = { ...defaults, ...stored, url: mcpUrl };
1672
+ const backupPath = `${primary}.bak-${tsStamp()}`;
1673
+ await copyFile(primary, backupPath);
1674
+ try {
1675
+ await atomicWrite(primary, `${JSON.stringify(parsed, null, 2)}\n`);
1676
+ clearAssistantsCache();
1677
+ } catch (error) {
1678
+ await copyFile(backupPath, primary);
1679
+ return { ok: false, reason: `写入失败已回滚:${redactSecrets(error?.message ?? error)}` };
1680
+ }
1681
+ return { ok: true, changed: true, configPath: primary, backupPath };
1682
+ }
1683
+
1684
+ /**
1685
+ * 运行时就绪后的**自动自愈**(普通旧端口漂移的主路径):
1686
+ * 只把**已存在且配置为本机 loopback** 的 Mebular HTTP 条目幂等更新到当前 `mcpUrl`。
1687
+ *
1688
+ * 边界(刻意保守):
1689
+ * - 不创建新客户端配置(`exists !== true` 跳过);不 force Skill、不调用 installSkills;
1690
+ * - 非 loopback / 用户自定义远端 URL 不覆盖(留给状态检测显示“需要修复/请确认”与手动兜底);
1691
+ * - 只改 Mebular 自己的入口,保留其他 MCP servers / 其他配置;JSON 条目只改 url,保留其余字段;
1692
+ * - 不触碰 memory / identity / storage / sync / cloud / subscription / task / audit。
1693
+ *
1694
+ * 单项失败只记录,返回结构化报告;调用方(runtime ready)绝不因此阻断启动。
1695
+ */
1696
+ export async function reconcileClientEndpoints(options = {}) {
1697
+ const mcpUrl = typeof options.mcpUrl === 'string' && options.mcpUrl.trim().length > 0 ? options.mcpUrl.trim() : null;
1698
+ if (!mcpUrl) {
1699
+ return { ok: true, skipped: true, reason: 'no_mcp_url', scope: 'client-endpoint-reconcile', clients: [], summary: { total: 0, changed: 0, failed: 0 } };
1700
+ }
1701
+ const reg = registry(options);
1702
+ const clients = [];
1703
+ for (const assistant of reg.assistants) {
1704
+ const strategy = assistant.writer?.strategy ?? 'merge-key';
1705
+ if (strategy === 'manual' || !assistant.landing?.primaryPath) continue;
1706
+ let landing;
1707
+ try {
1708
+ landing = landingState(assistant, { ...options, mcpUrl });
1709
+ } catch (error) {
1710
+ clients.push({
1711
+ id: assistant.id, name: assistant.name, ok: false, changed: false,
1712
+ from: null, to: mcpUrl, reason: `状态探测失败:${redactSecrets(error?.message ?? error)}`,
1713
+ });
1714
+ continue;
1715
+ }
1716
+ // 主路径只自动处理 loopback 旧端点;stdio / 远端自定义 / 未接入都不在此处写。
1717
+ if (landing.exists !== true || landing.staleUrl !== true) continue;
1718
+ try {
1719
+ const adapter = adapterFor(assistant.landing?.format ?? assistant.format);
1720
+ const result = adapter?.serialization === 'json'
1721
+ ? await reconcileJsonMebularUrl(assistant, mcpUrl)
1722
+ : await connectClient(assistant.id, { ...options, mcpUrl, skipSkills: true });
1723
+ clients.push({
1724
+ id: assistant.id,
1725
+ name: assistant.name,
1726
+ ok: result.ok === true,
1727
+ changed: result.changed === true,
1728
+ from: landing.configuredUrl ?? null,
1729
+ to: mcpUrl,
1730
+ ...(result.ok === true ? {} : { reason: redactSecrets(result.reason ?? 'reconcile_failed') }),
1731
+ });
1732
+ } catch (error) {
1733
+ clients.push({
1734
+ id: assistant.id, name: assistant.name, ok: false, changed: false,
1735
+ from: landing.configuredUrl ?? null, to: mcpUrl,
1736
+ reason: redactSecrets(error?.message ?? error),
1737
+ });
1738
+ }
1739
+ }
1740
+ const failed = clients.filter((entry) => entry.ok !== true);
1741
+ const changed = clients.filter((entry) => entry.changed === true);
1742
+ return {
1743
+ ok: failed.length === 0,
1744
+ scope: 'client-endpoint-reconcile',
1745
+ clients,
1746
+ summary: { total: clients.length, changed: changed.length, failed: failed.length },
1747
+ };
1067
1748
  }
1068
1749
 
1069
1750
  /** 回滚:显式备份优先;否则最近一次备份;无备份则删除 mebular 条目(DSH 除外)。 */
1070
- /** 备份候选是否已含 mebular 条目——**与状态探针同一判据**(landingState:present ∪ staleStdio ∪ legacyShape),
1751
+ /** 备份候选是否已含 mebular 条目——**与状态探针同一判据**(landingState:present ∪ staleStdio ∪ staleUrl ∪ needsConfirmation ∪ legacyShape),
1071
1752
  * 避免自建弱判据(如 yamlHasKey)漏报导致回滚选错快照。 */
1072
1753
  function backupHasMebularEntry(assistant, backupPath) {
1073
1754
  const st = landingState({ ...assistant, landing: { ...assistant.landing, primaryPath: backupPath } }, {});
1074
- return Boolean(st.present || st.staleStdio || st.legacyShape);
1755
+ return Boolean(st.present || st.staleStdio || st.staleUrl || st.needsConfirmation || st.legacyShape);
1075
1756
  }
1076
1757
 
1077
1758
  export async function rollbackClient(id, options = {}) {
@@ -1096,7 +1777,13 @@ export async function rollbackClient(id, options = {}) {
1096
1777
  return { ok: true, restoredFrom: target, backupPath: safety, removed: false };
1097
1778
  }
1098
1779
  if (assistant.format === 'dsh') return { ok: false, reason: 'DSH 无备份可回滚:请按片段人工移除' };
1099
- const merged = mergeJsonEntry(existing, { format: assistant.format, entry: undefined, keyPath: keyPathOf(assistant.landing?.format ?? assistant.format) });
1780
+ const adapter = adapterFor(assistant.landing?.format ?? assistant.format);
1781
+ const merged = mergeJsonEntry(existing, {
1782
+ format: assistant.format,
1783
+ entry: undefined,
1784
+ keyPath: keyPathOf(assistant.landing?.format ?? assistant.format),
1785
+ preserveFormatting: adapter?.serialization === 'json',
1786
+ });
1100
1787
  if (merged.error) return { ok: false, reason: merged.error };
1101
1788
  await atomicWrite(primary, merged.text);
1102
1789
  clearAssistantsCache();
@@ -1113,6 +1800,8 @@ export function readbackCheck(assistant, options = {}) {
1113
1800
  if (!landing.exists) return { ok: false, detail: '配置文件不存在' };
1114
1801
  if (!landing.present) {
1115
1802
  if (landing.legacyShape) return { ok: false, detail: '只找到旧形状(不生效),建议重新接入' };
1803
+ if (landing.needsConfirmation) return { ok: false, detail: landing.staleReason ?? '自定义远端 MCP 地址与当前端点不一致,请确认或手动修复' };
1804
+ if (landing.staleUrl) return { ok: false, detail: landing.staleReason ?? 'MCP 地址已过期,请自动修复' };
1116
1805
  if (landing.staleStdio) return { ok: false, detail: '条目是 stdio 形态:守护运行中会被拒(MCP_STORAGE_LOCKED),建议重新接入为 HTTP /mcp' };
1117
1806
  return { ok: false, detail: '未找到 mebular 条目' };
1118
1807
  }
@@ -1206,37 +1895,452 @@ export async function verifyAssistant(id, options = {}) {
1206
1895
  }
1207
1896
 
1208
1897
  // ---------------------------------------------------------------------------
1209
- // Skill 安装
1898
+ // Skill 安装(单一实现:缺失安装 / 受管旧版更新 / 用户修改保留 / force 覆盖)
1210
1899
  // ---------------------------------------------------------------------------
1211
1900
 
1901
+ /**
1902
+ * 受管版本标记:每个 Skill 目录一份 `.mebular-skill.json`。
1903
+ *
1904
+ * - 有标记 ∧ `managedBy=mebular` ∧ 文件哈希与标记一致 → Mebular 管理且用户未改;
1905
+ * - 无标记 / 哈希不一致 → 用户自定义或用户改过 → 默认保留;
1906
+ * - `force`(自动修复)→ 完整覆盖已知 Skill 文件(不删除用户额外文件)。
1907
+ *
1908
+ * `files` 记录 **Mebular 写入的受管文件**哈希(含 `mcp/` 片段),因此「受管旧版」既能按版本号识别,
1909
+ * 也能识别同版本但内容漂移的安装;用户额外添加的文件不参与判定,也不会被删除。
1910
+ */
1911
+ export const SKILL_MANIFEST_FILE = '.mebular-skill.json';
1912
+ const SKILL_MANIFEST_SCHEMA = 1;
1913
+ const SKILL_SPECS = [
1914
+ {
1915
+ name: 'mebular-memory',
1916
+ files: [
1917
+ ['SKILL.md', 'SKILL.md'],
1918
+ ['MEMORY_POLICY.md', 'MEMORY_POLICY.md'],
1919
+ ['SETUP.md', 'SETUP.md'],
1920
+ ],
1921
+ copyDirs: [['mcp', 'mcp']],
1922
+ },
1923
+ {
1924
+ name: 'mebular-tasks',
1925
+ files: [
1926
+ ['tasks/SKILL.md', 'SKILL.md'],
1927
+ ['SETUP.md', 'SETUP.md'],
1928
+ ],
1929
+ copyDirs: [],
1930
+ },
1931
+ ];
1932
+
1212
1933
  function moduleSkillRoot() {
1213
1934
  return join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skill');
1214
1935
  }
1215
1936
 
1216
- /** 安装 mebular-memory + mebular-tasks 到该客户端首个已知 Skill 目录。 */
1217
- export async function installSkills(id, options = {}) {
1218
- const desc = descriptorFor(id, options);
1219
- if (!desc) return { ok: false, reason: `未知客户端:${id}` };
1220
- const dirs = (desc.skillsDirs ?? []).filter(Boolean);
1221
- if (dirs.length === 0) return { ok: false, reason: '该客户端没有已知的 Skill 目录' };
1222
- const candidates = [
1937
+ function skillRootCandidates(options = {}) {
1938
+ return [
1223
1939
  options.skillRoot,
1224
1940
  moduleSkillRoot(),
1225
1941
  join(options.repoRoot ?? process.cwd(), 'packages', 'skill'),
1226
1942
  ].filter((p) => typeof p === 'string' && p.length > 0);
1227
- const rootDir = candidates.find((p) => existsSync(join(p, 'SKILL.md')));
1943
+ }
1944
+
1945
+ function resolveSkillRoot(options = {}) {
1946
+ return skillRootCandidates(options).find((p) => existsSync(join(p, 'SKILL.md'))) ?? null;
1947
+ }
1948
+
1949
+ function skillSourceVersion(rootDir) {
1950
+ try {
1951
+ const pkg = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf-8'));
1952
+ if (typeof pkg.version === 'string' && pkg.version.length > 0) return pkg.version;
1953
+ } catch {
1954
+ // 独立/测试 Skill 源可以没有 package.json:回落到 MCP 对外版本。
1955
+ }
1956
+ return APP_VERSION;
1957
+ }
1958
+
1959
+ function sha256Buffer(buffer) {
1960
+ return createHash('sha256').update(buffer).digest('hex');
1961
+ }
1962
+
1963
+ function listRelativeFiles(root) {
1964
+ if (!existsSync(root)) return [];
1965
+ const out = [];
1966
+ const walk = (dir, prefix) => {
1967
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1968
+ if (entry.name === SKILL_MANIFEST_FILE || entry.name === '.DS_Store') continue;
1969
+ const rel = prefix.length > 0 ? `${prefix}/${entry.name}` : entry.name;
1970
+ if (entry.isDirectory()) walk(join(dir, entry.name), rel);
1971
+ else if (entry.isFile()) out.push(rel);
1972
+ }
1973
+ };
1974
+ walk(root, '');
1975
+ return out;
1976
+ }
1977
+
1978
+ function hashSkillDir(dir) {
1979
+ const out = {};
1980
+ for (const rel of listRelativeFiles(dir)) {
1981
+ out[rel] = sha256Buffer(readFileSync(join(dir, ...rel.split('/'))));
1982
+ }
1983
+ return out;
1984
+ }
1985
+
1986
+ /**
1987
+ * 受管文件相对路径校验(POSIX / Windows 共用):
1988
+ * 拒绝绝对路径、盘符、反斜杠分隔、空段、`.`/`..` 段与非字符串。
1989
+ * 只用于 `marker.files` 的清理;不安全的 key 直接跳过,绝不触碰 Skill 目录外。
1990
+ */
1991
+ export function isSafeManagedRelPath(rel) {
1992
+ if (typeof rel !== 'string' || rel.length === 0 || rel.includes('\0') || rel.includes('\\')) return false;
1993
+ if (rel.startsWith('/') || /^[A-Za-z]:/.test(rel)) return false;
1994
+ return rel.split('/').every((part) => part.length > 0 && part !== '.' && part !== '..');
1995
+ }
1996
+
1997
+ function readSkillMarker(dir) {
1998
+ try {
1999
+ const data = JSON.parse(readFileSync(join(dir, SKILL_MANIFEST_FILE), 'utf-8'));
2000
+ if (data?.schema !== SKILL_MANIFEST_SCHEMA || data?.managedBy !== 'mebular') return null;
2001
+ if (data.files === null || typeof data.files !== 'object' || Array.isArray(data.files)) return null;
2002
+ const files = {};
2003
+ for (const [key, value] of Object.entries(data.files)) {
2004
+ if (typeof value === 'string') files[key] = value;
2005
+ }
2006
+ return { ...data, files };
2007
+ } catch {
2008
+ return null;
2009
+ }
2010
+ }
2011
+
2012
+ function skillSourcePairs(rootDir, spec) {
2013
+ const pairs = [];
2014
+ for (const [src, rel] of spec.files) {
2015
+ const abs = join(rootDir, ...src.split('/'));
2016
+ if (!existsSync(abs)) throw new Error(`Skill 源缺少 ${src}`);
2017
+ pairs.push([abs, rel]);
2018
+ }
2019
+ for (const [srcDir, relDir] of spec.copyDirs ?? []) {
2020
+ const absDir = join(rootDir, srcDir);
2021
+ if (!existsSync(absDir)) throw new Error(`Skill 源缺少 ${srcDir}/(Skill 承诺随包安装接入片段)`);
2022
+ for (const rel of listRelativeFiles(absDir)) {
2023
+ pairs.push([join(absDir, ...rel.split('/')), `${relDir}/${rel}`]);
2024
+ }
2025
+ }
2026
+ return pairs;
2027
+ }
2028
+
2029
+ function hashesForPairs(pairs) {
2030
+ return Object.fromEntries(pairs.map(([abs, rel]) => [rel, sha256Buffer(readFileSync(abs))]));
2031
+ }
2032
+
2033
+ async function writeSkillFiles(dir, pairs, marker, { version, source, skill, managedHashes }) {
2034
+ for (const [abs, rel] of pairs) {
2035
+ const dest = join(dir, ...rel.split('/'));
2036
+ await mkdir(dirname(dest), { recursive: true });
2037
+ await copyFile(abs, dest);
2038
+ }
2039
+ // 受管旧版的多余文件(例如上一版有、这一版已移除)只按旧标记清理;绝不扫描/删除用户文件。
2040
+ if (marker) {
2041
+ const keep = new Set(pairs.map(([, rel]) => rel));
2042
+ for (const rel of Object.keys(marker.files ?? {})) {
2043
+ if (keep.has(rel) || !isSafeManagedRelPath(rel)) continue;
2044
+ await rm(join(dir, ...rel.split('/')), { force: true });
2045
+ }
2046
+ }
2047
+ const files = managedHashes ?? hashesForPairs(pairs);
2048
+ await writeFile(join(dir, SKILL_MANIFEST_FILE), `${JSON.stringify({
2049
+ schema: SKILL_MANIFEST_SCHEMA,
2050
+ managedBy: 'mebular',
2051
+ skill,
2052
+ version,
2053
+ installedAt: new Date().toISOString(),
2054
+ source,
2055
+ files,
2056
+ }, null, 2)}\n`, 'utf-8');
2057
+ return files;
2058
+ }
2059
+
2060
+ async function installSkillSpec(rootDir, targetDir, spec, { force = false, version, source } = {}) {
2061
+ const dir = join(targetDir, spec.name);
2062
+ const existed = existsSync(join(dir, 'SKILL.md'));
2063
+ const marker = existed ? readSkillMarker(dir) : null;
2064
+ const currentHashes = existed ? hashSkillDir(dir) : {};
2065
+ const pairs = skillSourcePairs(rootDir, spec);
2066
+ const sourceHashes = hashesForPairs(pairs);
2067
+
2068
+ if (existed && force !== true) {
2069
+ if (!marker) return { name: spec.name, status: 'kept', dir, reason: '无受管标记(用户自定义),未覆盖' };
2070
+ // 只比较标记登记的受管文件;用户额外添加的文件不阻止更新,也不会被删除。
2071
+ const managedUnchanged = Object.entries(marker.files).every(([rel, hash]) => currentHashes[rel] === hash);
2072
+ if (!managedUnchanged) {
2073
+ return { name: spec.name, status: 'kept', dir, reason: '文件与受管标记不一致(用户修改过),未覆盖' };
2074
+ }
2075
+ const sourceCurrent = Object.entries(sourceHashes).every(([rel, hash]) => marker.files[rel] === hash);
2076
+ if (marker.version === version && sourceCurrent) {
2077
+ return { name: spec.name, status: 'unchanged', dir, version };
2078
+ }
2079
+ }
2080
+
2081
+ await writeSkillFiles(dir, pairs, marker, { version, source, skill: spec.name, managedHashes: sourceHashes });
2082
+ return { name: spec.name, status: existed ? 'updated' : 'installed', dir, version };
2083
+ }
2084
+
2085
+ function summarizeSkillResults(targetDir, results, { version, source } = {}) {
2086
+ const failed = results.filter((r) => r.status === 'failed');
2087
+ const by = (status) => results.filter((r) => r.status === status).map((r) => r.dir);
2088
+ let status = 'unchanged';
2089
+ if (failed.length > 0) status = 'failed';
2090
+ else if (results.some((r) => r.status === 'installed')) status = 'installed';
2091
+ else if (results.some((r) => r.status === 'updated')) status = 'updated';
2092
+ else if (results.some((r) => r.status === 'kept')) status = 'kept';
2093
+ return {
2094
+ ok: failed.length === 0,
2095
+ status,
2096
+ targetDir,
2097
+ version: version ?? null,
2098
+ source: source ?? null,
2099
+ installed: by('installed'),
2100
+ updated: by('updated'),
2101
+ kept: by('kept'),
2102
+ unchanged: by('unchanged'),
2103
+ skills: results,
2104
+ ...(failed.length > 0 ? { reason: failed.map((r) => `${r.name}: ${r.reason ?? '安装失败'}`).join(';') } : {}),
2105
+ };
2106
+ }
2107
+
2108
+ /** 安装到指定目录(install.mjs / 显式安装共用;默认保留用户修改,force 覆盖)。 */
2109
+ export async function installSkillsToDir(targetDir, options = {}) {
2110
+ if (typeof targetDir !== 'string' || targetDir.length === 0) {
2111
+ return { ok: false, reason: '缺少 Skill 目标目录', skills: [], installed: [], updated: [], kept: [], unchanged: [] };
2112
+ }
2113
+ const rootDir = resolveSkillRoot(options);
1228
2114
  if (!rootDir) {
1229
- return { ok: false, reason: `未找到 Skill 源(试过:${candidates.join('、')})`, snippet: '请在仓库内运行,或手动复制 Skill 目录' };
1230
- }
1231
- const target = dirs[0];
1232
- const mem = join(target, 'mebular-memory');
1233
- const tasks = join(target, 'mebular-tasks');
1234
- await mkdir(mem, { recursive: true });
1235
- await mkdir(tasks, { recursive: true });
1236
- await copyFile(join(rootDir, 'SKILL.md'), join(mem, 'SKILL.md'));
1237
- await copyFile(join(rootDir, 'MEMORY_POLICY.md'), join(mem, 'MEMORY_POLICY.md'));
1238
- await copyFile(join(rootDir, 'SETUP.md'), join(mem, 'SETUP.md'));
1239
- await copyFile(join(rootDir, 'tasks', 'SKILL.md'), join(tasks, 'SKILL.md'));
1240
- await copyFile(join(rootDir, 'SETUP.md'), join(tasks, 'SETUP.md'));
1241
- return { ok: true, installed: [mem, tasks] };
2115
+ return {
2116
+ ok: false,
2117
+ reason: `未找到 Skill 源(试过:${skillRootCandidates(options).join('、')})`,
2118
+ targetDir,
2119
+ skills: [],
2120
+ installed: [],
2121
+ updated: [],
2122
+ kept: [],
2123
+ unchanged: [],
2124
+ };
2125
+ }
2126
+ const version = skillSourceVersion(rootDir);
2127
+ const source = 'mebular';
2128
+ const results = [];
2129
+ for (const spec of SKILL_SPECS) {
2130
+ try {
2131
+ results.push(await installSkillSpec(rootDir, targetDir, spec, { force: options.force === true, version, source }));
2132
+ } catch (error) {
2133
+ results.push({ name: spec.name, status: 'failed', dir: join(targetDir, spec.name), reason: redactSecrets(error?.message ?? error) });
2134
+ }
2135
+ }
2136
+ return summarizeSkillResults(targetDir, results, { version, source });
2137
+ }
2138
+
2139
+ function preferredSkillTarget(dirs) {
2140
+ // 与既有 installSkills 行为一致:descriptor 的首个目录 = 客户端全局 Skill 目录。
2141
+ // 不优先挑“已存在的 cwd 目录”,否则 cwd=仓库时会误把 Skill 写进项目。
2142
+ return dirs[0];
2143
+ }
2144
+
2145
+ /**
2146
+ * 安装 mebular-memory + mebular-tasks 到该客户端首个已知 Skill 目录。
2147
+ * 默认语义 = ensure:缺失安装、受管旧版更新、用户修改/无标记保留;`force:true` 完整覆盖。
2148
+ */
2149
+ export async function installSkills(id, options = {}) {
2150
+ const desc = descriptorFor(id, options);
2151
+ if (!desc) return { ok: false, id, reason: `未知客户端:${id}`, skills: [], installed: [], updated: [], kept: [], unchanged: [] };
2152
+ const dirs = (desc.skillsDirs ?? []).filter(Boolean);
2153
+ if (dirs.length === 0) return { ok: false, id, reason: '该客户端没有已知的 Skill 目录', skills: [], installed: [], updated: [], kept: [], unchanged: [] };
2154
+ const target = options.skillDir ?? preferredSkillTarget(dirs);
2155
+ const result = await installSkillsToDir(target, options);
2156
+ return { ...result, id };
2157
+ }
2158
+
2159
+ function skillStateDetected(state) {
2160
+ return Boolean(state?.anySignalHit || state?.installed);
2161
+ }
2162
+
2163
+ /**
2164
+ * 对所有**已检测到的客户端**做 Skill ensure(单一实现)。
2165
+ *
2166
+ * - 目录只来自 descriptor 的 `skillsDirs`;未检测到的客户端不创建任何目录;
2167
+ * - 同一 Skill 目录被多个客户端共享时只处理一次(OpenCode / OpenChamber);
2168
+ * - 单个 Skill/客户端失败只记录,不抛出。
2169
+ */
2170
+ export async function ensureSkills(options = {}) {
2171
+ const wanted = Array.isArray(options.clientIds) ? new Set(options.clientIds) : null;
2172
+ const reg = registry(options);
2173
+ const clients = [];
2174
+ const seenTargets = new Map();
2175
+ for (const assistant of reg.assistants) {
2176
+ if (wanted && !wanted.has(assistant.id)) continue;
2177
+ const dirs = (assistant.skillsDirs ?? []).filter(Boolean);
2178
+ if (dirs.length === 0) {
2179
+ clients.push({ id: assistant.id, name: assistant.name, detected: false, status: 'skipped', reason: '该客户端没有已知的 Skill 目录' });
2180
+ continue;
2181
+ }
2182
+ let state;
2183
+ try {
2184
+ state = await assistantStateAsync(assistant, options);
2185
+ } catch (error) {
2186
+ clients.push({ id: assistant.id, name: assistant.name, detected: false, status: 'failed', reason: `检测失败:${redactSecrets(error?.message ?? error)}` });
2187
+ continue;
2188
+ }
2189
+ if (!skillStateDetected(state)) {
2190
+ clients.push({ id: assistant.id, name: assistant.name, detected: false, status: 'skipped', reason: '未检测到该客户端' });
2191
+ continue;
2192
+ }
2193
+ const target = preferredSkillTarget(dirs);
2194
+ if (seenTargets.has(target)) {
2195
+ clients.push({
2196
+ id: assistant.id, name: assistant.name, detected: true, status: 'skipped',
2197
+ targetDir: target, reason: `与 ${seenTargets.get(target)} 共享 Skill 目录,已由前者处理`,
2198
+ });
2199
+ continue;
2200
+ }
2201
+ seenTargets.set(target, assistant.id);
2202
+ try {
2203
+ const result = await installSkills(assistant.id, options);
2204
+ clients.push({ ...result, name: assistant.name, detected: true });
2205
+ } catch (error) {
2206
+ clients.push({
2207
+ id: assistant.id, name: assistant.name, detected: true, status: 'failed',
2208
+ targetDir: target, reason: redactSecrets(error?.message ?? error), skills: [],
2209
+ installed: [], updated: [], kept: [], unchanged: [],
2210
+ });
2211
+ }
2212
+ }
2213
+ const failed = clients.filter((c) => c.status === 'failed');
2214
+ return {
2215
+ ok: failed.length === 0,
2216
+ clients,
2217
+ summary: {
2218
+ total: clients.length,
2219
+ installed: clients.filter((c) => c.status === 'installed').length,
2220
+ updated: clients.filter((c) => c.status === 'updated').length,
2221
+ kept: clients.filter((c) => c.status === 'kept').length,
2222
+ unchanged: clients.filter((c) => c.status === 'unchanged').length,
2223
+ skipped: clients.filter((c) => c.status === 'skipped').length,
2224
+ failed: failed.length,
2225
+ },
2226
+ };
2227
+ }
2228
+
2229
+ /**
2230
+ * 启动/初始化收敛入口(**永不阻断**调用方):
2231
+ * 测试环境默认关闭,避免验证脚本写真实 `~/.config/opencode/skills`;
2232
+ * 需要显式验证自动接线时设置 `MEBULAR_SKILL_AUTOWIRE=1`。
2233
+ */
2234
+ export async function autoEnsureSkills(options = {}) {
2235
+ const forcedOn = process.env.MEBULAR_SKILL_AUTOWIRE === '1';
2236
+ // 安全网:临时 MEBULAR home + 真实用户主目录 = 验证脚本形态,绝不写真实 Skill 目录。
2237
+ const tempHomeWithRealUser = typeof options.home === 'string'
2238
+ && options.home.startsWith(tmpdir())
2239
+ && typeof options.userHome === 'string'
2240
+ && !options.userHome.startsWith(tmpdir());
2241
+ const disabled = options.enabled === false
2242
+ || (!forcedOn && (process.env.MEBULAR_SKILL_AUTOWIRE === '0'
2243
+ || process.env.JEST_WORKER_ID !== undefined
2244
+ || process.env.NODE_ENV === 'test'
2245
+ || tempHomeWithRealUser));
2246
+ if (disabled) {
2247
+ return { ok: true, skipped: true, reason: 'skill auto-wire disabled', clients: [], summary: { total: 0, installed: 0, updated: 0, kept: 0, unchanged: 0, skipped: 0, failed: 0 } };
2248
+ }
2249
+ try {
2250
+ return await ensureSkills(options);
2251
+ } catch (error) {
2252
+ return {
2253
+ ok: false,
2254
+ skipped: false,
2255
+ reason: `Skill 自动安装失败:${redactSecrets(error?.message ?? error)}`,
2256
+ clients: [],
2257
+ summary: { total: 0, installed: 0, updated: 0, kept: 0, unchanged: 0, skipped: 0, failed: 1 },
2258
+ };
2259
+ }
2260
+ }
2261
+
2262
+ /**
2263
+ * 自动修复(只做客户端接入):
2264
+ * 对**已检测到的**助手逐个重新执行 MCP 接入(connectClient)+ Skill force 安装 + 验证。
2265
+ * 不触碰 memory / identity / cloud / task / audit;单项失败不影响其他项。
2266
+ */
2267
+ export async function repairClients(options = {}) {
2268
+ const list = await listAssistantsAsync({ ...options, refresh: true });
2269
+ const candidates = list.assistants.filter((assistant) => skillStateDetected(assistant));
2270
+ const clients = [];
2271
+ const seenSkillTargets = new Map();
2272
+ for (const assistant of candidates) {
2273
+ const base = {
2274
+ id: assistant.id,
2275
+ name: assistant.name,
2276
+ detected: true,
2277
+ stateBefore: assistant.state ?? null,
2278
+ connect: null,
2279
+ skills: null,
2280
+ verify: null,
2281
+ stateAfter: null,
2282
+ };
2283
+ if (assistant.writer?.strategy === 'manual' || !assistant.landing?.primaryPath) {
2284
+ clients.push({ ...base, connect: { ok: false, skipped: true, reason: '该客户端不支持自动写入:只提供片段' }, skills: { ok: true, skipped: true, reason: '无自动接入目录' } });
2285
+ continue;
2286
+ }
2287
+ try {
2288
+ base.connect = await connectClient(assistant.id, { ...options, skipSkills: true });
2289
+ } catch (error) {
2290
+ base.connect = { ok: false, reason: `接入失败:${redactSecrets(error?.message ?? error)}` };
2291
+ }
2292
+ const skillDirs = (assistant.skillsDirs ?? []).filter(Boolean);
2293
+ if (skillDirs.length > 0) {
2294
+ // 与 ensureSkills 同判据:共享全局目录(OpenChamber / OpenCode)只 force 安装一次。
2295
+ const target = preferredSkillTarget(skillDirs);
2296
+ const shared = seenSkillTargets.get(target);
2297
+ if (shared) {
2298
+ // 共享目录(OpenChamber / OpenCode)复用首次安装结果,但明确标注 skipped;实际只写一次。
2299
+ base.skills = {
2300
+ ...(shared.result ?? {}),
2301
+ id: assistant.id,
2302
+ ok: shared.result?.ok ?? true,
2303
+ skipped: true,
2304
+ targetDir: target,
2305
+ sharedWith: shared.id,
2306
+ reason: `与 ${shared.id} 共享 Skill 目录,已由前者处理`,
2307
+ };
2308
+ } else {
2309
+ seenSkillTargets.set(target, { id: assistant.id, result: null });
2310
+ try {
2311
+ const result = await installSkills(assistant.id, { ...options, force: true });
2312
+ seenSkillTargets.set(target, { id: assistant.id, result });
2313
+ base.skills = result;
2314
+ } catch (error) {
2315
+ const failure = { ok: false, targetDir: target, reason: `Skill 安装失败:${redactSecrets(error?.message ?? error)}` };
2316
+ seenSkillTargets.set(target, { id: assistant.id, result: failure });
2317
+ base.skills = failure;
2318
+ }
2319
+ }
2320
+ } else {
2321
+ base.skills = { ok: true, skipped: true, reason: '该客户端没有已知的 Skill 目录' };
2322
+ }
2323
+ try {
2324
+ base.verify = await verifyAssistant(assistant.id, options);
2325
+ base.stateAfter = base.verify?.state ?? null;
2326
+ } catch (error) {
2327
+ base.verify = { ok: false, reason: `验证失败:${redactSecrets(error?.message ?? error)}` };
2328
+ }
2329
+ clients.push(base);
2330
+ }
2331
+ const failed = clients.filter((entry) => (entry.connect?.ok === false && entry.connect?.skipped !== true)
2332
+ || entry.skills?.ok === false);
2333
+ const repaired = clients.filter((entry) => entry.connect?.ok === true && entry.connect?.skipped !== true);
2334
+ return {
2335
+ ok: failed.length === 0,
2336
+ scope: 'client-integration',
2337
+ repairedAt: new Date().toISOString(),
2338
+ clients,
2339
+ summary: {
2340
+ total: clients.length,
2341
+ repaired: repaired.length,
2342
+ failed: failed.length,
2343
+ skipped: clients.filter((entry) => entry.connect?.skipped === true).length,
2344
+ },
2345
+ };
1242
2346
  }