@mebular/mcp 0.2.4 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/clients.mjs CHANGED
@@ -25,7 +25,7 @@ import { chmod, copyFile, mkdir, readFile, rename, rm, writeFile } from 'node:fs
25
25
  import { exec, spawnSync } from 'node:child_process';
26
26
  import { promisify } from 'node:util';
27
27
  import { homedir, tmpdir } from 'node:os';
28
- import { delimiter, dirname, join, sep } from 'node:path';
28
+ import { basename, delimiter, dirname, join, resolve, sep } from 'node:path';
29
29
  import { fileURLToPath } from 'node:url';
30
30
  import { APP_VERSION } from './version.mjs';
31
31
 
@@ -102,6 +102,123 @@ export function daemonMcpUrl({ host, encrypted } = {}) {
102
102
  return `${encrypted ? 'https' : 'http'}://${target}:${port}/mcp`;
103
103
  }
104
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
+
105
222
  /** 形状选择:给 url → HTTP 形态;否则 stdio(descriptor 可用 `landing.httpShape` 覆盖)。 */
106
223
  function shapeFor(format, options = {}) {
107
224
  const adapter = adapterFor(format);
@@ -118,7 +235,13 @@ function shapeFor(format, options = {}) {
118
235
  export function mebularEntry(format, options = {}) {
119
236
  const adapter = adapterFor(format);
120
237
  if (!adapter) return { command: 'mebular', args: ['mcp'] };
121
- 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;
122
245
  }
123
246
 
124
247
  /** 各客户端 MCP 片段(与 `mebular print-config --client …` 同源);有 `url` → HTTP 形态。 */
@@ -181,6 +304,93 @@ export function assistantUserHome(options = {}) {
181
304
  return homedir();
182
305
  }
183
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
+
184
394
  /** 桌面壳/守护常驻的 opencode 捆绑目录(存在才注入 PATH)。 */
185
395
  export const OPENCODE_BUNDLE_BIN = '/Applications/OpenChamber.app/Contents/Resources/opencode-cli';
186
396
 
@@ -220,15 +430,21 @@ export function builtinAssistants(options = {}) {
220
430
  : (env.XDG_CONFIG_HOME ?? join(userHome, '.config'));
221
431
  const opencodePath = expandHome(HOME_OPENCODE, userHome);
222
432
  const hermesPath = expandHome(HOME_HERMES, userHome);
433
+ const openChamberDir = join(userHome, '.config', 'openchamber');
223
434
 
224
435
  return [
225
436
  {
226
437
  id: 'openchamber', name: 'OpenChamber', kind: 'file', format: 'opencode-json',
438
+ description: '复用 OpenCode global 配置:只写 mcp.servers.mebular(remote /mcp);不接管原生 memory',
227
439
  landing: {
228
440
  primaryPath: opencodePath,
229
441
  keyPath: 'mcp.servers.mebular',
230
- 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')],
231
446
  format: 'opencode-json',
447
+ entryDefaults: { oauth: false, codemode: false },
232
448
  },
233
449
  probe: {
234
450
  signals: [
@@ -242,12 +458,26 @@ export function builtinAssistants(options = {}) {
242
458
  verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
243
459
  activation: { kind: 'user-reload', note: 'OpenChamber:由用户在 App 侧重载/重启生效;产品不得发 opencode reload 干扰运行服务' },
244
460
  risks: [
245
- 'opencode.managed.json 为 App 所有且会被重写,禁写',
461
+ 'opencode.managed.json(含 run/instances/*)为 App 所有且会被重写,禁写',
246
462
  'opencode mcp list 经运行服务回答,只读但勿频繁调用',
463
+ '原生 memory 开启时,Mebular 沉浸式默认 tool-only,需显式 opt-in;不导入、不替换、不双写',
247
464
  ],
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
+ },
248
478
  skillsDirs: [join(userHome, '.config', 'opencode', 'skills'), join(cwd, '.opencode', 'skills')],
249
479
  reuseOf: 'opencode',
250
- note: 'OpenChamber 复用 OpenCode 的 global 配置(接一次即可)',
480
+ note: 'OpenChamber 复用 OpenCode 的 global 配置(接一次即可);原生 memory 只读共存,不导入/不替换/不双写',
251
481
  },
252
482
  {
253
483
  id: 'hermes', name: 'Hermes', kind: 'file', format: 'hermes-yaml',
@@ -480,6 +710,8 @@ export function clientDescriptors(options = {}) {
480
710
  skillsDirs: a.skillsDirs ?? [],
481
711
  requiresRestart: a.activation.kind === 'user-reload',
482
712
  reuseOf: a.reuseOf ?? null, note: a.note ?? null,
713
+ description: a.description ?? null,
714
+ coexistence: a.coexistence ?? null,
483
715
  }));
484
716
  }
485
717
 
@@ -509,11 +741,165 @@ function walkGet(root, path) {
509
741
  return { value: node };
510
742
  }
511
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
+
512
894
  /**
513
895
  * JSON 合并:设置或删除 `<keyPath>`(默认含叶子 `mebular`),保留其余键。
514
896
  * 中间键存在但非对象 → error(结构未知,不自动改写)。
897
+ *
898
+ * `preserveEntryFields`:已有 Mebular 条目是对象时,仅覆盖新条目提供的字段(保留 headers、
899
+ * timeout、protocol 等用户字段;local → remote 升级时移除 command/cwd/environment)。
900
+ * `preserveFormatting`:用区间替换只动 mebular 文本,其他配置键字节不变(失败回落整体序列化)。
515
901
  */
516
- export function mergeJsonEntry(existingText, { format, entry, keyPath } = {}) {
902
+ export function mergeJsonEntry(existingText, { format, entry, keyPath, preserveEntryFields = false, preserveFormatting = false } = {}) {
517
903
  const path = keyPathOf(format, keyPath);
518
904
  let parsed;
519
905
  if (existingText === null || existingText === undefined || existingText.trim() === '') {
@@ -543,10 +929,44 @@ export function mergeJsonEntry(existingText, { format, entry, keyPath } = {}) {
543
929
  }
544
930
  cursor = cursor[key];
545
931
  }
546
- 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);
547
944
  if (entry === undefined) delete cursor[leaf];
548
- else cursor[leaf] = entry;
549
- 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)}`;
550
970
  }
551
971
 
552
972
  /** DSH(YAML) 合并:空文件 → 写片段;已含 serverName: mebular → 幂等;结构未知 → 不写。 */
@@ -554,10 +974,22 @@ export function mergeDsh(existingText, options = {}) {
554
974
  const snippet = snippetFor('dsh', options);
555
975
  if (existingText === null || existingText.trim() === '') return { changed: true, text: `${snippet}\n` };
556
976
  if (/serverName:\s*['"]?mebular['"]?/.test(existingText)) {
557
- // 已接入:仅当**形态等价**(HTTP vs stdio)才算幂等,否则需改写
977
+ // 已接入:仅当**形态/端点等价**才算幂等,否则只改 mebular 的 URL(保留其他插件)。
978
+ const block = dshMebularBlock(existingText);
979
+ const scope = block ?? existingText;
558
980
  const wantHttp = Boolean(options.url);
559
- const hasHttp = /transport:\s*streamable-http/.test(existingText);
560
- 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
+ }
561
993
  return { changed: true, text: `${snippet}\n` };
562
994
  }
563
995
  return { error: 'DSH 配置已存在但未接入:YAML 结构未知,未自动改写(请按片段人工合并)' };
@@ -614,6 +1046,38 @@ export function yamlEntryBlock(text, parent, child) {
614
1046
  return block === null ? null : block.join('\n');
615
1047
  }
616
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
+
617
1081
  /** 该格式下「HTTP/remote」形态(valid);`stdio` 形态守护运行中会被拒(MCP_STORAGE_LOCKED)。 */
618
1082
  export function entryIsHttp(format, entry) {
619
1083
  if (entry === null || typeof entry !== 'object') return false;
@@ -637,18 +1101,44 @@ export function landingState(assistant, options = {}) {
637
1101
  const text = safeReadText(primary);
638
1102
  if (text === null) return { exists: false, present: false, legacyShape: false, text: null };
639
1103
  if (format === 'dsh') {
640
- const has = /serverName:\s*['"]?mebular['"]?/.test(text);
641
- const present = has && /transport:\s*streamable-http/.test(text);
642
- 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
+ };
643
1121
  }
644
1122
  if (adapter?.serialization === 'yaml') {
645
1123
  const path = keyPathOf(format);
646
1124
  const block = yamlEntryBlock(text, path[0], path[1]);
647
1125
  const hasUrl = block !== null && /^\s*url\s*:\s*\S+/m.test(block);
648
1126
  const hasCommand = block !== null && /^\s*command\s*:\s*\S+/m.test(block);
649
- // 语义判据:remote(有 url)→ present;stdio(有 command 无 url)→ stale;旧「逐字段错位追加」也归 stale
650
- const present = hasUrl && !hasCommand;
651
- 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
+ };
652
1142
  }
653
1143
  try {
654
1144
  const parsed = JSON.parse(text);
@@ -657,13 +1147,15 @@ export function landingState(assistant, options = {}) {
657
1147
  const legacy = adapter?.legacyKeyPath
658
1148
  ? walkGet(parsed, adapter.legacyKeyPath).value !== undefined
659
1149
  : false;
660
- // 语义判据(兼容迁移):remote/http 形态 → present;stdio 形态或**端口与当前守护端点不符** → stale
1150
+ // 语义判据(兼容迁移):remote/http 形态且端点未过期 → present;stdio 形态 → stale
661
1151
  const isHttp = entryIsHttp(format, stored);
662
1152
  const storedUrl = typeof stored?.url === 'string' ? stored.url : null;
663
- const urlOk = options.mcpUrl === undefined || options.mcpUrl === null || storedUrl === options.mcpUrl;
664
- const present = isHttp && urlOk;
665
- const staleStdio = !present && (entryIsStdio(format, stored) || (isHttp && !urlOk));
666
- 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 };
667
1159
  } catch {
668
1160
  return { exists: true, present: false, legacyShape: false, text, parseError: true };
669
1161
  }
@@ -795,20 +1287,48 @@ function builtinsCount(reg, options) {
795
1287
  function entryOptionsFor(assistant, options = {}) {
796
1288
  const url = options.mcpUrl ?? null;
797
1289
  const httpShape = assistant.landing?.httpShape;
798
- return { ...(url ? { url } : {}), ...(httpShape ? { httpShape } : {}) };
1290
+ const entryDefaults = assistant.landing?.entryDefaults;
1291
+ return {
1292
+ ...(url ? { url } : {}),
1293
+ ...(httpShape ? { httpShape } : {}),
1294
+ ...(url && entryDefaults ? { entryDefaults } : {}),
1295
+ };
799
1296
  }
800
1297
 
801
1298
  function buildStateItem(assistant, signals, landing, options = {}) {
802
1299
  const anyHit = signals.some((s) => s.hit);
803
1300
  const anyError = signals.some((s) => typeof s.detail === 'string' && s.detail.startsWith('探测异常'));
804
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;
805
1305
  let state;
806
1306
  if (strategy === 'manual' && !landing.present) state = anyHit ? 'manual' : 'not-installed';
807
1307
  else if (landing.present) state = 'connected';
808
- 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)→ 升级直连
809
1311
  else if (!anyHit) state = anyError ? 'detect-failed' : 'not-installed';
810
1312
  else state = 'not-connected';
811
- 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;
812
1332
  return {
813
1333
  id: assistant.id,
814
1334
  name: assistant.name,
@@ -816,18 +1336,29 @@ function buildStateItem(assistant, signals, landing, options = {}) {
816
1336
  type: assistant.kind === 'snippet' ? 'snippet' : 'file', // file | snippet(descriptor 形态)
817
1337
  registryKind: assistant.registryKind ?? 'builtin',
818
1338
  state,
819
- stateLabel: STATE_LABEL[state] ?? state,
1339
+ stateLabel: needsConfirmation ? '需要修复/请确认' : staleUrl ? '配置已过期 · 请自动修复' : (STATE_LABEL[state] ?? state),
820
1340
  evidence: signals.map((s) => ({ ...s, detail: redactSecrets(s.detail) })),
821
1341
  anySignalHit: anyHit,
822
1342
  landing: {
823
1343
  primaryPath: assistant.landing?.primaryPath ?? null,
824
1344
  keyPath: assistant.landing?.keyPath ?? null,
825
1345
  forbiddenPaths: assistant.landing?.forbiddenPaths ?? [],
1346
+ forbiddenBasenames: assistant.landing?.forbiddenBasenames ?? [],
1347
+ forbiddenRoots: assistant.landing?.forbiddenRoots ?? [],
1348
+ entryDefaults: assistant.landing?.entryDefaults ?? null,
826
1349
  format: assistant.landing?.format ?? assistant.format,
827
1350
  strategy,
828
1351
  present: landing.present,
829
1352
  legacyShape: landing.legacyShape === true,
830
- 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,
831
1362
  exists: landing.exists,
832
1363
  parseError: landing.parseError === true,
833
1364
  },
@@ -841,8 +1372,20 @@ function buildStateItem(assistant, signals, landing, options = {}) {
841
1372
  configPath: assistant.landing?.primaryPath ?? null,
842
1373
  reuseOf: assistant.reuseOf ?? null,
843
1374
  note: assistant.note ?? null,
1375
+ description: assistant.description ?? null,
1376
+ nativeMemory,
1377
+ coexistence,
844
1378
  snippet: snippetFor(assistant.format, entryOptionsFor(assistant, options)),
845
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,
846
1389
  // 兼容既有 `/admin/api/clients` 字段(只扩展不破坏;UI 亦可继续用)
847
1390
  installed: signals.some((s) => s.kind !== 'always' && s.hit),
848
1391
  connected: state === 'connected',
@@ -956,16 +1499,24 @@ async function atomicWrite(path, text) {
956
1499
  }
957
1500
 
958
1501
  function isForbidden(assistant, path) {
959
- const forbidden = assistant.landing?.forbiddenPaths ?? [];
960
- 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}`));
961
1508
  }
962
1509
 
963
1510
  function computeMerged(assistant, existing, options = {}) {
964
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';
965
1514
  return mergeJsonEntry(existing, {
966
1515
  format: assistant.format,
967
1516
  entry: mebularEntry(assistant.format, entryOptionsFor(assistant, options)),
968
1517
  keyPath: keyPathOf(assistant.landing?.format ?? assistant.format),
1518
+ preserveEntryFields: preserve,
1519
+ preserveFormatting: preserve,
969
1520
  });
970
1521
  }
971
1522
 
@@ -1089,12 +1640,119 @@ export async function connectClient(id, options = {}) {
1089
1640
  return attachSkills({ ok: true, changed: true, configPath: primary, backupPath, preview }, id, options);
1090
1641
  }
1091
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
+ };
1748
+ }
1749
+
1092
1750
  /** 回滚:显式备份优先;否则最近一次备份;无备份则删除 mebular 条目(DSH 除外)。 */
1093
- /** 备份候选是否已含 mebular 条目——**与状态探针同一判据**(landingState:present ∪ staleStdio ∪ legacyShape),
1751
+ /** 备份候选是否已含 mebular 条目——**与状态探针同一判据**(landingState:present ∪ staleStdio ∪ staleUrl ∪ needsConfirmation ∪ legacyShape),
1094
1752
  * 避免自建弱判据(如 yamlHasKey)漏报导致回滚选错快照。 */
1095
1753
  function backupHasMebularEntry(assistant, backupPath) {
1096
1754
  const st = landingState({ ...assistant, landing: { ...assistant.landing, primaryPath: backupPath } }, {});
1097
- return Boolean(st.present || st.staleStdio || st.legacyShape);
1755
+ return Boolean(st.present || st.staleStdio || st.staleUrl || st.needsConfirmation || st.legacyShape);
1098
1756
  }
1099
1757
 
1100
1758
  export async function rollbackClient(id, options = {}) {
@@ -1119,7 +1777,13 @@ export async function rollbackClient(id, options = {}) {
1119
1777
  return { ok: true, restoredFrom: target, backupPath: safety, removed: false };
1120
1778
  }
1121
1779
  if (assistant.format === 'dsh') return { ok: false, reason: 'DSH 无备份可回滚:请按片段人工移除' };
1122
- 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
+ });
1123
1787
  if (merged.error) return { ok: false, reason: merged.error };
1124
1788
  await atomicWrite(primary, merged.text);
1125
1789
  clearAssistantsCache();
@@ -1136,6 +1800,8 @@ export function readbackCheck(assistant, options = {}) {
1136
1800
  if (!landing.exists) return { ok: false, detail: '配置文件不存在' };
1137
1801
  if (!landing.present) {
1138
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 地址已过期,请自动修复' };
1139
1805
  if (landing.staleStdio) return { ok: false, detail: '条目是 stdio 形态:守护运行中会被拒(MCP_STORAGE_LOCKED),建议重新接入为 HTTP /mcp' };
1140
1806
  return { ok: false, detail: '未找到 mebular 条目' };
1141
1807
  }