dsh-vscode-mode 0.1.14 → 0.1.16

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/lib/index.js CHANGED
@@ -2,8 +2,335 @@ import { createRequire } from "node:module";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { dirname, extname, join, normalize, resolve, sep } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { existsSync } from "node:fs";
5
+ import { existsSync, readFileSync } from "node:fs";
6
6
  import { createHash } from "node:crypto";
7
+ //#region src/mcp.ts
8
+ /**
9
+ * dsh-vscode-mode host — MCP 运行时管理适配层。
10
+ * 只操作已装配的 @deepseek-ai/dsh-mcp-client loader entry,不在浏览器侧连接 MCP。
11
+ * 身份常量(包名/条目前缀/新旧格式判定)统一由 compat 层持有,本模块再导出保持既有 import 面。
12
+ * 作者 ddj 2026年08月22号
13
+ */
14
+ /** 列出当前 loader 中的 MCP entry。 */
15
+ function entriesOf(ctx) {
16
+ const loader = ctx.get("loader");
17
+ if (!loader || typeof loader.entries !== "function") return [];
18
+ return [...loader.entries()].filter((entry) => entry?.options?.name === MCP_PACKAGE);
19
+ }
20
+ /** 脱敏配置并保留可编辑字段的存在性。 */
21
+ function publicConfig(config) {
22
+ const out = { ...config };
23
+ if (out.env && typeof out.env === "object") out.env = Object.fromEntries(Object.keys(out.env).map((key) => [key, "••••••"]));
24
+ if (out.headers && typeof out.headers === "object") out.headers = Object.fromEntries(Object.keys(out.headers).map((key) => [key, "••••••"]));
25
+ return out;
26
+ }
27
+ /** 从工具注册表读取服务器命名空间下的工具摘要。 */
28
+ function toolsOf(ctx, serverName) {
29
+ const visible = (ctx.get("tools")?.view?.(void 0))?.visible;
30
+ if (!(visible instanceof Map)) return [];
31
+ const prefix = `mcp__${serverName}__`;
32
+ return [...visible.entries()].filter(([name]) => String(name).startsWith(prefix)).map(([name, definition]) => ({
33
+ name: String(name).slice(prefix.length),
34
+ description: typeof definition?.description === "string" ? definition.description : void 0
35
+ }));
36
+ }
37
+ /** 将 loader entry 映射为设置页摘要。 */
38
+ function serverOf(ctx, entry) {
39
+ const config = entry.options?.config ?? {};
40
+ const serverName = typeof config.serverName === "string" ? config.serverName : entry.options?.id ?? "unknown";
41
+ const tools = toolsOf(ctx, serverName);
42
+ const state = entry.fiber?.state;
43
+ return {
44
+ id: String(entry.id ?? entry.options?.id ?? serverName),
45
+ serverName,
46
+ enabled: entry.disabled !== true,
47
+ transport: config.transport === "streamable-http" ? "streamable-http" : "stdio",
48
+ config: publicConfig(config),
49
+ status: state === 2 ? "connected" : state === 1 ? "connecting" : "error",
50
+ toolCount: tools.length,
51
+ tools,
52
+ error: state === 3 ? "MCP 插件未正常运行" : void 0
53
+ };
54
+ }
55
+ /** 校验 MCP 配置。 */
56
+ function validateConfig(config) {
57
+ if (!/^[A-Za-z0-9_-]{1,32}$/.test(config.serverName)) throw new Error("serverName 只能包含字母、数字、下划线和连字符(最多 32 位)");
58
+ if (config.transport === "stdio" && !config.command?.trim()) throw new Error("stdio MCP 必须填写 command");
59
+ if (config.transport === "streamable-http" && !/^https?:\/\//.test(config.url ?? "")) throw new Error("HTTP MCP 必须填写 http(s) URL");
60
+ }
61
+ /** 列出全局(profile)MCP 服务,过滤掉新旧格式的项目级条目。 */
62
+ function listMcp(ctx) {
63
+ return { servers: entriesOf(ctx).filter((entry) => !isProjectEntryId(String(entry.id ?? entry.options?.id ?? ""))).map((entry) => serverOf(ctx, entry)) };
64
+ }
65
+ /** 保存 MCP 服务配置并触发 loader 热更新。 */
66
+ async function saveMcp(ctx, config) {
67
+ validateConfig(config);
68
+ const loader = ctx.get("loader");
69
+ if (!loader) throw new Error("缺少 loader 服务");
70
+ const existing = entriesOf(ctx).find((entry) => !isProjectEntryId(String(entry.id ?? entry.options?.id ?? "")) && entry.options?.config?.serverName === config.serverName);
71
+ if (existing) {
72
+ await loader.update(existing.id, { config: { ...config } });
73
+ return serverOf(ctx, loader.resolve(existing.id));
74
+ }
75
+ const id = await loader.create({
76
+ name: MCP_PACKAGE,
77
+ config: { ...config }
78
+ });
79
+ return serverOf(ctx, loader.resolve(id));
80
+ }
81
+ /** 删除 MCP 服务。 */
82
+ async function removeMcp(ctx, id) {
83
+ const loader = ctx.get("loader");
84
+ if (!loader) throw new Error("缺少 loader 服务");
85
+ const entry = entriesOf(ctx).find((candidate) => String(candidate.id) === id);
86
+ if (!entry) throw new Error("MCP 服务不存在");
87
+ await loader.remove(entry.id);
88
+ }
89
+ /** 切换 MCP 服务启用状态。 */
90
+ async function toggleMcp(ctx, id, enabled) {
91
+ const loader = ctx.get("loader");
92
+ if (!loader) throw new Error("缺少 loader 服务");
93
+ const entry = entriesOf(ctx).find((candidate) => String(candidate.id) === id);
94
+ if (!entry) throw new Error("MCP 服务不存在");
95
+ await loader.update(entry.id, { disabled: !enabled });
96
+ return serverOf(ctx, loader.resolve(entry.id));
97
+ }
98
+ /** 重新加载 MCP 服务。 */
99
+ async function refreshMcp(ctx, id) {
100
+ const loader = ctx.get("loader");
101
+ if (!loader) throw new Error("缺少 loader 服务");
102
+ const entry = entriesOf(ctx).find((candidate) => String(candidate.id) === id);
103
+ if (!entry) throw new Error("MCP 服务不存在");
104
+ await loader.update(entry.id, { config: { ...entry.options?.config ?? {} } });
105
+ return serverOf(ctx, loader.resolve(entry.id));
106
+ }
107
+ //#endregion
108
+ //#region src/fileOpenSettings.ts
109
+ const FILE_OPEN_SETTINGS_NS = "dsh-vscode-mode";
110
+ const FILE_OPEN_DEFAULT = "auto";
111
+ let depsPromise;
112
+ /**
113
+ * 动态加载设置依赖(模块级缓存;任一缺失返回 null 而非抛错)。
114
+ * @author ddj 2026年08月24号
115
+ * @returns 设置依赖或 null
116
+ */
117
+ function loadSettingsDeps() {
118
+ if (!depsPromise) depsPromise = Promise.all([import("@deepseek-ai/dsh-settings"), import("schemastery")]).then(([dshSettings, schemastery]) => ({
119
+ installSettingsSection: dshSettings.installSettingsSection,
120
+ z: schemastery.default
121
+ })).catch(() => null);
122
+ return depsPromise;
123
+ }
124
+ function normalizeValue(value) {
125
+ if (typeof value !== "string" || value.trim() === "") return FILE_OPEN_DEFAULT;
126
+ return value.trim();
127
+ }
128
+ function configValue(config) {
129
+ return normalizeValue(config?.fileOpenTool);
130
+ }
131
+ /**
132
+ * 安装设置 section(动态依赖;缺失返回 false 不抛错)。
133
+ * @author ddj 2026年08月24号
134
+ * @param ctx DSH host 上下文
135
+ * @param ns 设置命名空间
136
+ * @param entry 初始设置值
137
+ * @param hooks 设置源绑定与变更回调
138
+ * @param loader 依赖装载器(测试注入)
139
+ * @returns 是否成功安装
140
+ */
141
+ async function installOpenSettingsSection(ctx, ns, entry, hooks, loader = loadSettingsDeps) {
142
+ const deps = await loader();
143
+ if (!deps) return false;
144
+ const schema = deps.z.object({ fileOpenTool: deps.z.string().default(FILE_OPEN_DEFAULT) });
145
+ deps.installSettingsSection(ctx, ns, schema, entry, hooks);
146
+ return true;
147
+ }
148
+ /**
149
+ * 注册设置命名空间,并提供 host 侧的读取与更新状态。
150
+ * @author ddj 2026年08月24号
151
+ * @param ctx DSH host 上下文
152
+ * @param config 插件组合配置
153
+ * @param onChange 设置变化回调
154
+ * @returns 设置状态
155
+ */
156
+ function setupOpenSettings(ctx, config, onChange) {
157
+ let current = configValue(config);
158
+ let revision;
159
+ let provider;
160
+ const notify = (value) => {
161
+ current = normalizeValue(value);
162
+ onChange(current);
163
+ };
164
+ const syncRevision = () => {
165
+ revision = (provider?.describe?.({ redactSecrets: true })?.find((item) => item.ns === FILE_OPEN_SETTINGS_NS))?.revision;
166
+ };
167
+ const setSource = (source) => notify(source().fileOpenTool);
168
+ const settingsChange = () => syncRevision();
169
+ installOpenSettingsSection(ctx, FILE_OPEN_SETTINGS_NS, { fileOpenTool: current }, {
170
+ setSource,
171
+ onChange: settingsChange
172
+ });
173
+ ctx.inject?.(["settings"], (settingsCtx) => {
174
+ provider = settingsCtx.get("settings");
175
+ syncRevision();
176
+ });
177
+ return {
178
+ get value() {
179
+ return current;
180
+ },
181
+ get revision() {
182
+ return revision;
183
+ },
184
+ update: async (value, expectedRevision) => {
185
+ const next = normalizeValue(value);
186
+ if (!provider?.update) {
187
+ notify(next);
188
+ return;
189
+ }
190
+ await provider.update(FILE_OPEN_SETTINGS_NS, { fileOpenTool: next }, expectedRevision);
191
+ const stored = (provider.describe?.({ redactSecrets: true })?.find((item) => item.ns === FILE_OPEN_SETTINGS_NS))?.value;
192
+ notify(stored?.fileOpenTool ?? next);
193
+ syncRevision();
194
+ }
195
+ };
196
+ }
197
+ function normalizeFileOpenTool(value) {
198
+ return normalizeValue(value);
199
+ }
200
+ //#endregion
201
+ //#region src/compat.ts
202
+ /**
203
+ * dsh-vscode-mode host — 兼容层:与其他插件 / DSH 版本的统一探测、适配、护栏与自诊断。
204
+ * 职责:身份常量(包名 / MCP 条目前缀 / 路由前缀)、外部插件探测、路由冲突与重复装配检测、
205
+ * 兼容性报告构建(RPC edrv.compat 与启动日志共用)。
206
+ * 注意:与 mcp.ts 存在模块环(compat 提供身份常量、mcp 提供 entriesOf),
207
+ * 双方仅在函数体内交叉使用导出,模块求值期无依赖,ESM 安全。
208
+ * 作者 ddj 2026-08-24
209
+ */
210
+ const PLUGIN_NAME = "dsh-vscode-mode";
211
+ const MCP_PACKAGE = "@deepseek-ai/dsh-mcp-client";
212
+ /** 项目级 MCP 的 loader entry id 固定前缀(区分 profile 全局 MCP;loader id 不能用 ':',故用 '.')。 */
213
+ const PROJECT_ENTRY_PREFIX = "vsm-mcp.";
214
+ /** webServer 路由前缀(RPC 精确路由 + 静态资源前缀共用)。 */
215
+ const ROUTE_PREFIX = "/edrv";
216
+ /** 判断新旧格式项目 MCP 条目 id(旧残留不被视为全局 MCP)。 */
217
+ function isProjectEntryId(id) {
218
+ return id.startsWith("vsm-mcp.") || id.startsWith("vsm-mcp:");
219
+ }
220
+ /** 从项目条目 id 解析 workspace hash(新旧格式通用)。 */
221
+ function entryHash(id) {
222
+ if (id.startsWith("vsm-mcp.")) return id.slice(8).split(".")[0];
223
+ if (id.startsWith("vsm-mcp:")) return id.slice(8).split(":")[0];
224
+ }
225
+ /** 读取随包 package.json 版本号(缺失/解析失败降级为空串)。 */
226
+ function pluginVersionOf() {
227
+ try {
228
+ const file = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
229
+ const pkg = JSON.parse(readFileSync(file, "utf8"));
230
+ return typeof pkg.version === "string" ? pkg.version : "";
231
+ } catch {
232
+ return "";
233
+ }
234
+ }
235
+ /** 探测外部插件/服务适配状态(depsAvailable 由调用方注入,便于测试)。 */
236
+ function detectExternal(ctx, depsAvailable) {
237
+ const mcpCount = entriesOf(ctx).length;
238
+ const settings = ctx.get("settings");
239
+ const hasSettings = Boolean(settings?.describe || settings?.update);
240
+ return [
241
+ {
242
+ name: MCP_PACKAGE,
243
+ active: mcpCount > 0,
244
+ note: mcpCount > 0 ? mcpCount + " 个 MCP 服务条目" : "未检测到 MCP 条目(MCP 管理页显示为空)"
245
+ },
246
+ {
247
+ name: "设置持久化(@deepseek-ai/dsh-settings)",
248
+ active: depsAvailable,
249
+ note: depsAvailable ? "设置 section 已安装" : "未安装:fileOpenTool 持久化降级为配置值"
250
+ },
251
+ {
252
+ name: "settings 服务",
253
+ active: hasSettings,
254
+ note: hasSettings ? "可读写设置" : "不可用(设置读写走配置回退)"
255
+ }
256
+ ];
257
+ }
258
+ /** 本插件已注册的路由(kind → path 集合),冲突检测时排除自身,避免自误报。 */
259
+ const ownRoutes = {
260
+ exact: /* @__PURE__ */ new Set(),
261
+ prefixes: /* @__PURE__ */ new Set()
262
+ };
263
+ /** 清空本插件路由记录(registerRoutes 装配开始时调用,热重载不残留)。 */
264
+ function resetOwnRoutes() {
265
+ ownRoutes.exact.clear();
266
+ ownRoutes.prefixes.clear();
267
+ }
268
+ /** 记录本插件路由(routes.ts 注册成功时调用)。 */
269
+ function noteOwnRoute(kind, path) {
270
+ (kind === "exact" ? ownRoutes.exact : ownRoutes.prefixes).add(path);
271
+ }
272
+ /** 检测路由前缀占用与重叠(排除本插件自有路由;内部表不可读视为无冲突)。 */
273
+ function routeConflict(web, prefix) {
274
+ try {
275
+ const w = web;
276
+ const exact = w?.exact;
277
+ const prefixes = w?.prefixes;
278
+ if (exact instanceof Map) for (const path of exact.keys()) {
279
+ const other = String(path);
280
+ if (other.startsWith(prefix + "/") && !ownRoutes.exact.has(other)) return "精确路由 " + other + " 与 " + prefix + " 前缀重叠(可能来自热重载残留或其他插件)";
281
+ }
282
+ if (prefixes instanceof Map) for (const path of prefixes.keys()) {
283
+ const other = String(path);
284
+ if (other !== prefix && (other.startsWith(prefix + "/") || prefix.startsWith(other + "/")) && !ownRoutes.prefixes.has(other)) return "路由前缀 " + prefix + " 与 " + other + " 重叠";
285
+ }
286
+ } catch {}
287
+ return null;
288
+ }
289
+ /** 检测本插件是否被重复装配(bundle 层 + 用户层重复 insert 的自诊断)。 */
290
+ function duplicateEntries(ctx) {
291
+ const loader = ctx.get("loader");
292
+ if (!loader || typeof loader.entries !== "function") return [];
293
+ const own = [...loader.entries()].filter((entry) => String(entry.options?.name ?? entry.id ?? "") === PLUGIN_NAME);
294
+ if (own.length > 1) return ["检测到 " + own.length + " 个 dsh-vscode-mode loader 条目(重复装配)。请删除 profile 用户层 cordis.patch.yml 的重复 insert(或运行 dev_fix_patch 清理)"];
295
+ return [];
296
+ }
297
+ /** 护栏适配状态:路由前缀唯一性 + 插件装配唯一性。 */
298
+ function detectGuards(ctx) {
299
+ const web = ctx.get("webServer");
300
+ const conflict = web ? routeConflict(web, ROUTE_PREFIX) : null;
301
+ const duplicates = duplicateEntries(ctx);
302
+ return [{
303
+ name: "路由前缀 /edrv",
304
+ active: !conflict,
305
+ note: conflict ?? "无冲突"
306
+ }, {
307
+ name: "插件装配唯一性",
308
+ active: duplicates.length === 0,
309
+ note: duplicates[0] ?? "唯一装配"
310
+ }];
311
+ }
312
+ /**
313
+ * 构建完整兼容性报告(RPC 与启动日志共用)。
314
+ * @author ddj 2026年08月24号
315
+ * @param ctx DSH host 上下文
316
+ * @param options 测试注入:depsAvailable 跳过动态导入、version 固定版本号
317
+ * @returns 兼容性报告
318
+ */
319
+ async function buildReport(ctx, options) {
320
+ const deps = options?.depsAvailable ?? await loadSettingsDeps() !== null;
321
+ const external = detectExternal(ctx, deps);
322
+ const guards = detectGuards(ctx);
323
+ const warnings = [];
324
+ if (!deps) warnings.push("未安装 @deepseek-ai/dsh-settings:文件打开工具设置持久化不可用(降级为配置值)");
325
+ for (const guard of guards) if (!guard.active && guard.note) warnings.push(guard.note);
326
+ return {
327
+ pluginVersion: options?.version ?? pluginVersionOf(),
328
+ external,
329
+ guards,
330
+ warnings
331
+ };
332
+ }
333
+ //#endregion
7
334
  //#region src/shared/rpc.ts
8
335
  /** webServer 精确路由。 */
9
336
  const RPC_PATH = "/edrv/rpc";
@@ -48,17 +375,32 @@ function imageDirOf(config) {
48
375
  /** Monaco AMD 静态目录(随包发布)。 */
49
376
  const vendorDir = join(dirname(fileURLToPath(import.meta.url)), "..", "assets", "vendor");
50
377
  /**
51
- * 注册全部 webServer 路由。
378
+ * 注册全部 webServer 路由(带兼容护栏:前缀冲突预警 + 注册失败降级跳过)。
52
379
  * @author ddj 2026年08月20号
53
380
  * @param ctx DSH 上下文
54
381
  * @param config 插件配置(可选 imageDir 等)
55
382
  * @param handleRpc RPC 分发入口(method,args → RpcResult)
383
+ * @param onWarning 兼容性警告收集(可选)
56
384
  */
57
- function registerRoutes(ctx, config, handleRpc) {
385
+ function registerRoutes(ctx, config, handleRpc, onWarning) {
58
386
  const imgDir = imageDirOf(config);
59
387
  const web = ctx.get("webServer");
60
388
  if (!web) return;
61
- ctx.effect(() => web.register({
389
+ resetOwnRoutes();
390
+ const conflict = routeConflict(web, ROUTE_PREFIX);
391
+ if (conflict) onWarning?.("兼容性:" + conflict);
392
+ /** 护栏注册:重复路由抛错时降级为警告并跳过,不让单条路由拖垮装配。 */
393
+ const guarded = (route, label) => {
394
+ try {
395
+ const dispose = web.register(route);
396
+ noteOwnRoute(route.kind, route.path);
397
+ return dispose;
398
+ } catch (error) {
399
+ onWarning?.("兼容性:" + label + " 注册失败(" + String(error) + ")");
400
+ return;
401
+ }
402
+ };
403
+ ctx.effect(() => guarded({
62
404
  kind: "exact",
63
405
  path: RPC_PATH,
64
406
  handler: async (req, res) => {
@@ -83,8 +425,8 @@ function registerRoutes(ctx, config, handleRpc) {
83
425
  }));
84
426
  }
85
427
  }
86
- }), "edrv: /edrv/rpc route");
87
- for (const r of IMG_ROUTES) ctx.effect(() => web.register({
428
+ }, "/edrv/rpc 精确路由"), "edrv: routes");
429
+ for (const r of IMG_ROUTES) ctx.effect(() => guarded({
88
430
  kind: "exact",
89
431
  path: r.url,
90
432
  handler: async (req, res) => {
@@ -99,8 +441,8 @@ function registerRoutes(ctx, config, handleRpc) {
99
441
  res.end();
100
442
  }
101
443
  }
102
- }), "edrv: static " + r.file);
103
- ctx.effect(() => web.register({
444
+ }, "静态资源 " + r.file), "edrv: routes");
445
+ ctx.effect(() => guarded({
104
446
  kind: "prefix",
105
447
  path: VENDOR_PREFIX,
106
448
  handler: async (req, res) => {
@@ -133,7 +475,7 @@ function registerRoutes(ctx, config, handleRpc) {
133
475
  res.end();
134
476
  }
135
477
  }
136
- }), "edrv: /edrv/vendor prefix");
478
+ }, "/edrv/vendor 前缀路由"), "edrv: routes");
137
479
  }
138
480
  //#endregion
139
481
  //#region src/shared/diff.ts
@@ -890,9 +1232,6 @@ async function captureToolResult(ctx, registry, exec, result) {
890
1232
  }
891
1233
  record.batch = fileMaxBatch(bucket, path) + 1;
892
1234
  bucket.set(exec.callId, record);
893
- const prior = [];
894
- for (const r of bucket.values()) if (r.path === path && r.callId !== exec.callId && !r.archived && (r.batch ?? 0) < record.batch) prior.push(r);
895
- if (prior.length) await archiveRecords(ctx, session, cwd, bucket, prior, prior.every(recordResolved) ? "已处理且被后续修改取代" : "被后续修改融合(内容已含其效果)");
896
1235
  prune(bucket);
897
1236
  await saveBucket(ctx, cwd, bucket, session);
898
1237
  } catch (error) {
@@ -1647,109 +1986,6 @@ async function restoreFile(ctx, session, rec) {
1647
1986
  }
1648
1987
  }
1649
1988
  //#endregion
1650
- //#region src/mcp.ts
1651
- const MCP_PACKAGE = "@deepseek-ai/dsh-mcp-client";
1652
- /** 项目级 MCP 的 loader entry id 固定前缀(区分 profile 全局 MCP;注意 loader id 不能用 ':' 分隔,故用 '.')。 */
1653
- const PROJECT_ENTRY_PREFIX = "vsm-mcp.";
1654
- const LEGACY_PROJECT_PREFIX = "vsm-mcp:";
1655
- /** 判断新旧格式项目 entry id,避免旧残留被显示为全局 MCP。 */
1656
- function isProjectEntryId(id) {
1657
- return id.startsWith("vsm-mcp.") || id.startsWith(LEGACY_PROJECT_PREFIX);
1658
- }
1659
- /** 列出当前 loader 中的 MCP entry。 */
1660
- function entriesOf(ctx) {
1661
- const loader = ctx.get("loader");
1662
- if (!loader || typeof loader.entries !== "function") return [];
1663
- return [...loader.entries()].filter((entry) => entry?.options?.name === MCP_PACKAGE);
1664
- }
1665
- /** 脱敏配置并保留可编辑字段的存在性。 */
1666
- function publicConfig(config) {
1667
- const out = { ...config };
1668
- if (out.env && typeof out.env === "object") out.env = Object.fromEntries(Object.keys(out.env).map((key) => [key, "••••••"]));
1669
- if (out.headers && typeof out.headers === "object") out.headers = Object.fromEntries(Object.keys(out.headers).map((key) => [key, "••••••"]));
1670
- return out;
1671
- }
1672
- /** 从工具注册表读取服务器命名空间下的工具摘要。 */
1673
- function toolsOf(ctx, serverName) {
1674
- const visible = (ctx.get("tools")?.view?.(void 0))?.visible;
1675
- if (!(visible instanceof Map)) return [];
1676
- const prefix = `mcp__${serverName}__`;
1677
- return [...visible.entries()].filter(([name]) => String(name).startsWith(prefix)).map(([name, definition]) => ({
1678
- name: String(name).slice(prefix.length),
1679
- description: typeof definition?.description === "string" ? definition.description : void 0
1680
- }));
1681
- }
1682
- /** 将 loader entry 映射为设置页摘要。 */
1683
- function serverOf(ctx, entry) {
1684
- const config = entry.options?.config ?? {};
1685
- const serverName = typeof config.serverName === "string" ? config.serverName : entry.options?.id ?? "unknown";
1686
- const tools = toolsOf(ctx, serverName);
1687
- const state = entry.fiber?.state;
1688
- return {
1689
- id: String(entry.id ?? entry.options?.id ?? serverName),
1690
- serverName,
1691
- enabled: entry.disabled !== true,
1692
- transport: config.transport === "streamable-http" ? "streamable-http" : "stdio",
1693
- config: publicConfig(config),
1694
- status: state === 2 ? "connected" : state === 1 ? "connecting" : "error",
1695
- toolCount: tools.length,
1696
- tools,
1697
- error: state === 3 ? "MCP 插件未正常运行" : void 0
1698
- };
1699
- }
1700
- /** 校验 MCP 配置。 */
1701
- function validateConfig(config) {
1702
- if (!/^[A-Za-z0-9_-]{1,32}$/.test(config.serverName)) throw new Error("serverName 只能包含字母、数字、下划线和连字符(最多 32 位)");
1703
- if (config.transport === "stdio" && !config.command?.trim()) throw new Error("stdio MCP 必须填写 command");
1704
- if (config.transport === "streamable-http" && !/^https?:\/\//.test(config.url ?? "")) throw new Error("HTTP MCP 必须填写 http(s) URL");
1705
- }
1706
- /** 列出全局(profile)MCP 服务,过滤掉新旧格式的项目级条目。 */
1707
- function listMcp(ctx) {
1708
- return { servers: entriesOf(ctx).filter((entry) => !isProjectEntryId(String(entry.id ?? entry.options?.id ?? ""))).map((entry) => serverOf(ctx, entry)) };
1709
- }
1710
- /** 保存 MCP 服务配置并触发 loader 热更新。 */
1711
- async function saveMcp(ctx, config) {
1712
- validateConfig(config);
1713
- const loader = ctx.get("loader");
1714
- if (!loader) throw new Error("缺少 loader 服务");
1715
- const existing = entriesOf(ctx).find((entry) => !isProjectEntryId(String(entry.id ?? entry.options?.id ?? "")) && entry.options?.config?.serverName === config.serverName);
1716
- if (existing) {
1717
- await loader.update(existing.id, { config: { ...config } });
1718
- return serverOf(ctx, loader.resolve(existing.id));
1719
- }
1720
- const id = await loader.create({
1721
- name: MCP_PACKAGE,
1722
- config: { ...config }
1723
- });
1724
- return serverOf(ctx, loader.resolve(id));
1725
- }
1726
- /** 删除 MCP 服务。 */
1727
- async function removeMcp(ctx, id) {
1728
- const loader = ctx.get("loader");
1729
- if (!loader) throw new Error("缺少 loader 服务");
1730
- const entry = entriesOf(ctx).find((candidate) => String(candidate.id) === id);
1731
- if (!entry) throw new Error("MCP 服务不存在");
1732
- await loader.remove(entry.id);
1733
- }
1734
- /** 切换 MCP 服务启用状态。 */
1735
- async function toggleMcp(ctx, id, enabled) {
1736
- const loader = ctx.get("loader");
1737
- if (!loader) throw new Error("缺少 loader 服务");
1738
- const entry = entriesOf(ctx).find((candidate) => String(candidate.id) === id);
1739
- if (!entry) throw new Error("MCP 服务不存在");
1740
- await loader.update(entry.id, { disabled: !enabled });
1741
- return serverOf(ctx, loader.resolve(entry.id));
1742
- }
1743
- /** 重新加载 MCP 服务。 */
1744
- async function refreshMcp(ctx, id) {
1745
- const loader = ctx.get("loader");
1746
- if (!loader) throw new Error("缺少 loader 服务");
1747
- const entry = entriesOf(ctx).find((candidate) => String(candidate.id) === id);
1748
- if (!entry) throw new Error("MCP 服务不存在");
1749
- await loader.update(entry.id, { config: { ...entry.options?.config ?? {} } });
1750
- return serverOf(ctx, loader.resolve(entry.id));
1751
- }
1752
- //#endregion
1753
1989
  //#region src/mcpProject.ts
1754
1990
  /**
1755
1991
  * dsh-vscode-mode host — 项目级 MCP 管理。
@@ -2519,7 +2755,42 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx)) {
2519
2755
  error: String(error)
2520
2756
  };
2521
2757
  }
2522
- }
2758
+ },
2759
+ "vscode.fileOpenSettingsGet": async () => {
2760
+ const descriptor = ctx.get("settings")?.describe?.({ redactSecrets: true })?.find((item) => item.ns === FILE_OPEN_SETTINGS_NS);
2761
+ const value = descriptor?.value;
2762
+ return {
2763
+ ok: true,
2764
+ fileOpenTool: normalizeFileOpenTool(value?.fileOpenTool ?? "auto"),
2765
+ revision: descriptor?.revision
2766
+ };
2767
+ },
2768
+ "vscode.fileOpenSettingsUpdate": async (args) => {
2769
+ const settings = ctx.get("settings");
2770
+ if (!settings?.update) return {
2771
+ ok: false,
2772
+ error: "设置服务不可用"
2773
+ };
2774
+ try {
2775
+ await settings.update(FILE_OPEN_SETTINGS_NS, { fileOpenTool: normalizeFileOpenTool(args.fileOpenTool) }, args.expectedRevision);
2776
+ const descriptor = settings.describe?.({ redactSecrets: true })?.find((item) => item.ns === FILE_OPEN_SETTINGS_NS);
2777
+ const value = descriptor?.value;
2778
+ return {
2779
+ ok: true,
2780
+ fileOpenTool: normalizeFileOpenTool(value?.fileOpenTool),
2781
+ revision: descriptor?.revision
2782
+ };
2783
+ } catch (error) {
2784
+ return {
2785
+ ok: false,
2786
+ error: String(error)
2787
+ };
2788
+ }
2789
+ },
2790
+ "compat": async () => ({
2791
+ ok: true,
2792
+ report: await buildReport(ctx)
2793
+ })
2523
2794
  };
2524
2795
  }
2525
2796
  /**
@@ -2542,7 +2813,6 @@ async function handleRpc(ctx, registry, method, args, searcher = newSearcher(ctx
2542
2813
  * tools.restrict() 负责模型可见性,tools.guard() 负责执行层兜底拒绝。
2543
2814
  * 作者 ddj 2026年08月22号
2544
2815
  */
2545
- const LEGACY_PREFIX = "vsm-mcp:";
2546
2816
  const UNKNOWN_PROJECT = "__unknown_project__";
2547
2817
  /** 统一 workspace 路径,供 cwd 父路径匹配。 */
2548
2818
  function normalizePath(path) {
@@ -2559,15 +2829,8 @@ function matchWorkspace(cwd, paths) {
2559
2829
  matches.sort((a, b) => normalizePath(b).length - normalizePath(a).length);
2560
2830
  return matches[0];
2561
2831
  }
2562
- /** 根据 entry id 判断是否为新旧格式项目 MCP。 */
2563
- function isProjectEntry(id) {
2564
- return id.startsWith("vsm-mcp.") || id.startsWith(LEGACY_PREFIX);
2565
- }
2566
- /** 从项目 entry id 解析 workspace hash。 */
2567
- function entryHash(id) {
2568
- if (id.startsWith("vsm-mcp.")) return id.slice(8).split(".")[0];
2569
- if (id.startsWith(LEGACY_PREFIX)) return id.slice(8).split(":")[0];
2570
- }
2832
+ /** 根据 entry id 判断是否为新旧格式项目 MCP(兼容层统一判定)。 */
2833
+ const isProjectEntry = isProjectEntryId;
2571
2834
  /** 返回一个 agent 不应继承的项目工具名。 */
2572
2835
  function denyTools(toolProjects, currentPath) {
2573
2836
  return [...toolProjects.entries()].filter(([, owner]) => owner !== currentPath).map(([name]) => name).sort();
@@ -2681,9 +2944,10 @@ function dropFileIndex(cwd) {
2681
2944
  //#region src/index.ts
2682
2945
  /**
2683
2946
  * @dsh-external 生态 → dsh-vscode-mode:DSH 上的类 VSCode 编码体验(Host 半入口)。
2684
- * 职责:装配 capture(tools/result 捕获 edit/write 差异)、RPC 分发(11 个 edrv.* 方法)、
2685
- * webServer 路由(/edrv/rpc、/edrv/assets/*、/edrv/vendor/*)、工作区旁车持久化。
2686
- * 结构:shared/(双面契约) + model/store/capture/workspace/revert/registry/rpc/routes(host 模块)。
2947
+ * 职责:装配 capture(tools/result 捕获 edit/write 差异)、RPC 分发(edrv.* / mcp.* / vscode.* / compat)、
2948
+ * webServer 路由(/edrv/rpc、/edrv/assets/*、/edrv/vendor/*)、工作区旁车持久化、
2949
+ * 兼容层装配(依赖守卫 + 重复装配自诊断 + 启动日志兼容性报告)。
2950
+ * 结构:shared/(双面契约) + model/store/capture/workspace/revert/registry/rpc/routes/compat(host 模块)。
2687
2951
  * 作者 ddj 2026-08-20
2688
2952
  */
2689
2953
  const name = "dsh-vscode-mode";
@@ -2697,7 +2961,7 @@ const inject = [
2697
2961
  "agents"
2698
2962
  ];
2699
2963
  /**
2700
- * 装配插件:挂事件监听、注册路由。
2964
+ * 装配插件:挂事件监听、注册路由、安装兼容层。
2701
2965
  * @author ddj 2026年08月20号
2702
2966
  * @param ctx DSH 上下文(sessions/fs/webServer 由 inject 提供;sandboxPolicy/subprocess 惰性获取)
2703
2967
  * @param config 插件配置(可选 imageDir 覆盖图标目录)
@@ -2705,6 +2969,9 @@ const inject = [
2705
2969
  function apply(ctx, config) {
2706
2970
  const registry = /* @__PURE__ */ new Map();
2707
2971
  const searcher = newSearcher(ctx);
2972
+ /** 兼容性警告收集(route 护栏等写入,启动日志一并输出)。 */
2973
+ const warnings = [];
2974
+ setupOpenSettings(ctx, config, () => {});
2708
2975
  ctx.on("tools/result", (exec, result) => {
2709
2976
  captureToolResult(ctx, registry, exec, result);
2710
2977
  });
@@ -2716,10 +2983,30 @@ function apply(ctx, config) {
2716
2983
  searcher.dispose(cwd);
2717
2984
  }
2718
2985
  });
2719
- registerRoutes(ctx, config, (method, args) => handleRpc(ctx, registry, method, args, searcher));
2986
+ registerRoutes(ctx, config, (method, args) => handleRpc(ctx, registry, method, args, searcher), (warning) => warnings.push(warning));
2720
2987
  installIsolation(ctx);
2988
+ logCompatSummary(ctx, warnings);
2721
2989
  ctx.logger?.info?.("[dsh-vscode-mode] 编辑差异审查已装配(/edrv/rpc 路由就绪,项目 MCP 隔离已启用)");
2722
2990
  }
2991
+ /**
2992
+ * 异步输出兼容性报告摘要(含重复装配/路由冲突自诊断)。
2993
+ * @author ddj 2026年08月24号
2994
+ * @param ctx DSH host 上下文
2995
+ * @param warnings 装配期收集的兼容性警告
2996
+ */
2997
+ async function logCompatSummary(ctx, warnings) {
2998
+ try {
2999
+ const report = await buildReport(ctx);
3000
+ for (const warning of warnings) report.warnings.push(warning);
3001
+ const logger = ctx.logger;
3002
+ if (!logger?.info) return;
3003
+ const head = "[dsh-vscode-mode] 兼容性:" + report.external.length + " 项外部适配 / " + report.guards.length + " 项护栏";
3004
+ if (report.warnings.length) logger.warn?.(head + ",警告 " + report.warnings.length + " 条:" + report.warnings.join(";"));
3005
+ else logger.info?.(head + ",无警告");
3006
+ } catch (error) {
3007
+ ctx.logger?.warn?.("[dsh-vscode-mode] 兼容性报告生成失败:" + String(error));
3008
+ }
3009
+ }
2723
3010
  //#endregion
2724
3011
  export { apply, inject, name };
2725
3012