vod-devkit 0.5.0 → 0.5.1

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/QUICKSTART.md +1 -1
  3. package/README.en.md +190 -57
  4. package/README.md +194 -75
  5. package/bin/vod-devkit +436 -426
  6. package/contract/tools.schema.json +78 -8
  7. package/integrations/codeartsdoer/host.json +11 -0
  8. package/package.json +4 -1
  9. package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
  10. package/plugins/vod-devkit/build-info.json +3 -3
  11. package/plugins/vod-devkit/skills/vod-core/SKILL.md +12 -4
  12. package/plugins/vod-devkit/skills/vod-core/references/acceptance-criteria.md +9 -0
  13. package/plugins/vod-devkit/skills/vod-core/references/verification-method.md +29 -0
  14. package/plugins/vod-devkit/skills/vod-feedback-collect/SKILL.md +57 -11
  15. package/plugins/vod-devkit/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  16. package/plugins/vod-devkit/skills/vod-feedback-collect/references/verification-method.md +31 -0
  17. package/plugins/vod-devkit/skills/vod-problem-classification-rules/SKILL.md +3 -1
  18. package/plugins/vod-devkit/skills/vod-scoring-rules/SKILL.md +22 -1
  19. package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
  20. package/plugins/vod-devkit/vod_mcp/attribution.py +378 -0
  21. package/plugins/vod-devkit/vod_mcp/host_adapters/__init__.py +26 -0
  22. package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +73 -0
  23. package/plugins/vod-devkit/vod_mcp/host_adapters/codearts.py +57 -0
  24. package/plugins/vod-devkit/vod_mcp/host_adapters/codex.py +209 -0
  25. package/plugins/vod-devkit/vod_mcp/host_adapters/dsh.py +176 -0
  26. package/plugins/vod-devkit/vod_mcp/host_adapters/generic.py +132 -0
  27. package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +76 -0
  28. package/plugins/vod-devkit/vod_mcp/host_adapters/opencode.py +52 -0
  29. package/plugins/vod-devkit/vod_mcp/hosts.py +20 -0
  30. package/plugins/vod-devkit/vod_mcp/packs.py +3 -1
  31. package/plugins/vod-devkit/vod_mcp/payload.py +174 -0
  32. package/plugins/vod-devkit/vod_mcp/server.py +13 -1
  33. package/plugins/vod-devkit/vod_mcp/tools.py +385 -46
  34. package/plugins/vod-devkit/vod_mcp/update_check.py +31 -3
  35. package/skills/vod-core/SKILL.md +12 -4
  36. package/skills/vod-core/references/acceptance-criteria.md +9 -0
  37. package/skills/vod-core/references/verification-method.md +29 -0
  38. package/skills/vod-feedback-collect/SKILL.md +57 -11
  39. package/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  40. package/skills/vod-feedback-collect/references/verification-method.md +31 -0
  41. package/skills/vod-problem-classification-rules/SKILL.md +3 -1
  42. package/skills/vod-scoring-rules/SKILL.md +22 -1
  43. package/vod_mcp/__init__.py +1 -1
  44. package/vod_mcp/attribution.py +378 -0
  45. package/vod_mcp/host_adapters/__init__.py +26 -0
  46. package/vod_mcp/host_adapters/__pycache__/__init__.cpython-314.pyc +0 -0
  47. package/vod_mcp/host_adapters/__pycache__/base.cpython-314.pyc +0 -0
  48. package/vod_mcp/host_adapters/__pycache__/codearts.cpython-314.pyc +0 -0
  49. package/vod_mcp/host_adapters/__pycache__/codex.cpython-314.pyc +0 -0
  50. package/vod_mcp/host_adapters/__pycache__/dsh.cpython-314.pyc +0 -0
  51. package/vod_mcp/host_adapters/__pycache__/generic.cpython-314.pyc +0 -0
  52. package/vod_mcp/host_adapters/__pycache__/hermes.cpython-314.pyc +0 -0
  53. package/vod_mcp/host_adapters/__pycache__/opencode.cpython-314.pyc +0 -0
  54. package/vod_mcp/host_adapters/base.py +73 -0
  55. package/vod_mcp/host_adapters/codearts.py +57 -0
  56. package/vod_mcp/host_adapters/codex.py +209 -0
  57. package/vod_mcp/host_adapters/dsh.py +176 -0
  58. package/vod_mcp/host_adapters/generic.py +132 -0
  59. package/vod_mcp/host_adapters/hermes.py +76 -0
  60. package/vod_mcp/host_adapters/opencode.py +52 -0
  61. package/vod_mcp/hosts.py +20 -0
  62. package/vod_mcp/packs.py +3 -1
  63. package/vod_mcp/payload.py +174 -0
  64. package/vod_mcp/server.py +13 -1
  65. package/vod_mcp/tools.py +385 -46
  66. package/vod_mcp/update_check.py +31 -3
package/bin/vod-devkit CHANGED
@@ -17,7 +17,9 @@ from pathlib import Path
17
17
  ROOT = Path(__file__).resolve().parent.parent
18
18
  sys.path.insert(0, str(ROOT))
19
19
 
20
- from vod_mcp import hosts as host_specs # noqa: E402 宿主适配层(数据驱动)
20
+ from vod_mcp import hosts as host_specs # noqa: E402 宿主适配层(数据驱动:路径/探测/生成物)
21
+ from vod_mcp.host_adapters import REGISTRY as HOST_ADAPTERS # noqa: E402 宿主安装逻辑(每宿主一模块)
22
+ from vod_mcp.host_adapters import generic as generic_host # noqa: E402
21
23
 
22
24
  # 路径常量一律来自 integrations/<host>/host.json(单一来源):新增宿主=加
23
25
  # 目录,不改这里;平台差异也在数据里(opencode 的 windows 分叉)。
@@ -78,21 +80,6 @@ PRESETS = {
78
80
  }
79
81
 
80
82
 
81
- def _server_entry() -> str:
82
- return str(ROOT / "vod_mcp" / "server.py")
83
-
84
-
85
- def _server_env(args, packs: str) -> dict:
86
- # 无 key 不写空串(空串会让探针/严格解析器误当字面值;运行时空=未设置,
87
- # 自动兜底 runtime.json java_key 或首提申请匿名令牌)
88
- env = {"VOD_PACKS": packs,
89
- "VOD_JAVA_API_BASE": args.java_api_base}
90
- key = os.environ.get("VOD_JAVA_API_KEY", "")
91
- if key:
92
- env["VOD_JAVA_API_KEY"] = key
93
- return env
94
-
95
-
96
83
  def _skill_installs(manifest_path: Path, extra_dirs) -> list:
97
84
  """多宿主技能落点并集(名册对账):manifest 按「最近一次安装」覆盖会
98
85
  互相冲掉落点(实锤:codex 装完 opencode 落点消失),按 host+dir
@@ -158,362 +145,74 @@ def _drifted_skills(manifest: dict) -> list:
158
145
  return drifted
159
146
 
160
147
 
161
- def _install_hermes(args, packs: str) -> Path:
162
- """Hermes:官方途径 hermes mcp add(config.yaml mcp_servers)。"""
163
- conf = HERMES_MCP_DIR / "vod-devkit.json"
164
- conf.parent.mkdir(parents=True, exist_ok=True)
165
- conf.write_text(json.dumps({
166
- "name": "vod-devkit", "command": sys.executable,
167
- "args": [_server_entry()], "env": _server_env(args, packs),
168
- }, ensure_ascii=False, indent=2), encoding="utf-8")
169
- env_args = []
170
- for k, v in _server_env(args, packs).items():
171
- env_args.extend([k + "=" + v])
172
- r = subprocess.run(
173
- ["hermes", "mcp", "add", "vod-devkit", "--command", sys.executable,
174
- *["--env"] + env_args, "--args", _server_entry()],
175
- input="y\ny\n", capture_output=True, text=True)
176
- # D-hook-1:强制评估路由插件(pre_llm_call 确定性意图路由,业界 forced-eval 模式)
177
- import shutil as _sh
178
- plug_src = ROOT / "hermes-plugin" / "vod-feedback-router"
179
- plug_dst = Path.home() / ".hermes" / "plugins" / "vod-feedback-router"
180
- if plug_src.is_dir():
181
- if plug_dst.exists():
182
- _sh.rmtree(plug_dst)
183
- _sh.copytree(plug_src, plug_dst)
184
- print("已安装 vod-feedback-router 路由插件(~/.hermes/plugins/);"
185
- "需在 plugins.enabled 加入该名单后生效"
186
- "(hermes config set plugins.enabled ...,重启会话生效)")
187
- if r.returncode == 0:
188
- print("已注册 Hermes MCP(hermes mcp list 可见;重启会话生效)")
189
- else:
190
- print(f"提示:hermes mcp add 未成功({r.stderr.strip()[:150]});"
191
- f"可将 {conf} 内容并入 Hermes 配置")
192
- return conf
193
-
194
-
195
- def _install_opencode(args, packs: str) -> Path:
196
- """OpenCode:~/.config/opencode/opencode.json 的 mcp 段无损合并。
197
-
198
- schema 实测要求:command=数组、enabled 必填;既有内容(provider 等)
199
- 原样保留(读改写,只动 mcp.vod-devkit 键)。
200
- """
201
- spec = host_specs.load("opencode")
202
- conf = Path(spec["configPath"])
203
- conf.parent.mkdir(parents=True, exist_ok=True)
204
- cfg = {}
205
- if conf.exists():
206
- try:
207
- cfg = json.loads(conf.read_text(encoding="utf-8"))
208
- except Exception:
209
- cfg = {}
210
- cfg.setdefault("mcp", {})["vod-devkit"] = {
211
- "type": "local",
212
- "command": [sys.executable, _server_entry()],
213
- "enabled": True,
214
- "environment": _server_env(args, packs),
215
- }
216
- conf.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
217
- print(f"已写入 OpenCode 配置:{conf}(重启 OpenCode 会话生效)")
218
- # 随装生成物走 integrations/opencode/ 的模板(单一来源——此前模板正文
219
- # 硬编码在本函数里,改文案要同时改代码与文档两处)
220
- for g in spec["generated"]:
221
- dest = Path(g["dest"])
222
- dest.parent.mkdir(parents=True, exist_ok=True)
223
- dest.write_text(Path(g["template"]).read_text(encoding="utf-8"),
224
- encoding="utf-8")
225
- print(f"已写入 OpenCode 自检命令:/vod-doctor({dest})")
226
- return conf
227
-
228
-
229
- def _strip_codex_vod_blocks(text: str) -> str:
230
- """幂等剥离:删除 [mcp_servers.vod-devkit] **及其全部子表**。
231
-
232
- 不能用行内正则截断式剥离——args = ["…"] 行内的 '[' 会让正则提前断块。
233
- 也不能只删父表(旧实现):留下 [mcp_servers.vod-devkit.env] 在 TOML
234
- 语义里会重建父表,装出一个没有 command 的假 server。扫描/删除语义
235
- 统一在 vod_mcp/config_forms.py(单一实现),形态不受支持时抛
236
- RuntimeError——调用方必须原样放弃修改。
237
- """
238
- from vod_mcp import config_forms as cf
239
- try:
240
- verdict, reason = cf.classify_codex_toml(text)
241
- except cf.Refused as e:
242
- raise RuntimeError(f"codex config.toml 形态不受支持:{e}") from e
243
- if verdict == "refuse":
244
- raise RuntimeError(f"codex config.toml 形态不受支持:{reason}")
245
- cleaned, _removed = cf.strip_managed_toml(text)
246
- return cleaned
247
-
248
-
249
148
  _AGENTS_MARKER_BEGIN = "<!-- vod-devkit:feedback-skill BEGIN -->"
250
149
  _AGENTS_MARKER_END = "<!-- vod-devkit:feedback-skill END -->"
251
150
 
252
151
 
253
- def _strip_agents_vod_block(text: str) -> str:
254
- """幂等剥离 AGENTS.md 中带标记的 vod-devkit 技能块(历史方案清理)。
255
-
256
- P2(深审 2026-11-06):只有 BEGIN 没有 END 时不得静默吞掉文件剩余
257
- 全部内容——抛错拒绝(调用方 exit 2 不落盘),宁可装不上不可删用户文件。
258
- """
259
- lines, skipping, out = text.splitlines(), False, []
260
- for line in lines:
261
- if line.strip() == _AGENTS_MARKER_BEGIN:
262
- skipping = True
263
- continue
264
- if line.strip() == _AGENTS_MARKER_END:
265
- skipping = False
266
- continue
267
- if not skipping:
268
- out.append(line)
269
- if skipping:
270
- raise RuntimeError(
271
- "AGENTS.md 存在 vod-devkit BEGIN 标记但缺失 END 标记"
272
- "(文件可能被手动截断)——拒绝自动清理,请手动检查该文件")
273
- return "\n".join(out).rstrip()
274
-
275
-
276
- def _install_codex(args, packs: str) -> Path:
277
- """Codex(D-codex-agents-1 终态):原生插件路径——
278
- codex plugin marketplace add <仓>/plugins + plugin add vod-devkit@vod-local,
279
- 打包 skills(渐进式按需加载的采集工作流)+ .mcp.json(vod-devkit serve)。
280
- 历史遗留清理:旧 config.toml [mcp_servers.vod-devkit] 段与 AGENTS.md 技能块
281
- 一并移除(与原生插件同名会双注册;AGENTS.md 方案被原生 skill 取代)。
282
- 前置:codex CLI 与 vod-devkit 命令在 PATH(npm i -g vod-devkit ≥0.1.12)。"""
283
- codex = shutil.which("codex")
284
- if not codex:
285
- print("[vod-devkit] 未找到 codex CLI,无法走原生插件安装", file=sys.stderr)
286
- sys.exit(2)
287
- spec = host_specs.load("codex")
288
- conf = Path(spec["configPath"])
289
- if conf.exists(): # 历史遗留:config.toml MCP 段与插件同名=双注册,移除
290
- text = conf.read_text(encoding="utf-8")
291
- try:
292
- cleaned = _strip_codex_vod_blocks(text)
293
- except RuntimeError as e:
294
- # 形态守卫:非已知形态宁可不装——改坏用户整份 codex 配置的代价
295
- # 远高于装不上(字节未动)
296
- print(f"[vod-devkit] {e}。安装中止,未改动该文件。", file=sys.stderr)
297
- sys.exit(2)
298
- if cleaned != text.rstrip():
299
- conf.write_text(cleaned + "\n", encoding="utf-8")
300
- print(f"已移除旧 config.toml MCP 段(原生插件取代):{conf}")
301
- agents = Path.home() / ".codex" / "AGENTS.md"
302
- if agents.exists(): # 历史遗留:AGENTS.md 技能块已被原生 skill 取代
303
- text = agents.read_text(encoding="utf-8")
304
- try:
305
- cleaned = _strip_agents_vod_block(text)
306
- except RuntimeError as e:
307
- print(f"[vod-devkit] {e}", file=sys.stderr)
308
- sys.exit(2)
309
- if cleaned != text.rstrip():
310
- agents.write_text(cleaned + "\n", encoding="utf-8")
311
- print(f"已移除旧 AGENTS.md 技能块(原生 skill 取代):{agents}")
312
- mp_root = ROOT / "plugins"
313
-
314
- def _run(cmd):
315
- r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
316
- if r.returncode != 0:
317
- raise RuntimeError(f"{' '.join(cmd)} → {r.stderr.strip() or r.stdout.strip()}")
318
- return r.stdout
319
-
320
- mp_name = "vod-local"
321
- # devkit 卫生实践:stale cache 先清——codex 插件缓存不自动失效,不清则
322
- # 重装/升级后旧版本残留(marketplace 指向与 cache 内容漂移)
323
- for stale in (Path.home() / ".codex" / "plugins" / "marketplaces" / mp_name,
324
- Path.home() / ".codex" / "plugins" / "cache" / mp_name):
325
- if stale.exists():
326
- shutil.rmtree(stale)
327
- print(f"已清理 stale 插件缓存:{stale}")
328
- ml = subprocess.run([codex, "plugin", "marketplace", "list"], capture_output=True, text=True, timeout=120).stdout
329
- if mp_name not in ml:
330
- _run([codex, "plugin", "marketplace", "add", str(mp_root)])
331
- print(f"已注册本地 marketplace:{mp_root}")
332
- _run([codex, "plugin", "add", f"vod-devkit@{mp_name}"])
333
- print("已安装 codex 原生插件 vod-devkit(skills + MCP,重启 Codex 会话生效)")
334
- # P1-5(深审 2026-11-06):插件自带的 .mcp.json 硬编码 env.VOD_PACKS=
335
- # core,collect——--packs 对 codex 半失效(运行期仍注册 collect 工具)。
336
- # plugin add 后把缓存内 .mcp.json 的 packs 对齐本次安装值。
337
- import glob as _glob
338
- mcp_jsons = sorted(
339
- _glob.glob(str(Path.home() / ".codex" / "plugins" / "cache"
340
- / mp_name / "vod-devkit" / "*" / ".mcp.json")),
341
- key=lambda p: Path(p).stat().st_mtime, reverse=True)
342
- if mcp_jsons:
343
- try:
344
- mj = json.loads(Path(mcp_jsons[0]).read_text(encoding="utf-8"))
345
- srv = mj.get("mcpServers", {}).get("vod-devkit")
346
- if srv is not None:
347
- srv.setdefault("env", {})["VOD_PACKS"] = packs
348
- Path(mcp_jsons[0]).write_text(
349
- json.dumps(mj, ensure_ascii=False, indent=2) + "\n",
350
- encoding="utf-8")
351
- print(f"已对齐插件 MCP packs:{mcp_jsons[0]}(VOD_PACKS={packs})")
352
- except Exception as e:
353
- print(f"[vod-devkit] warn: 插件 .mcp.json packs 对齐失败({e})——"
354
- "运行期熔断门禁仍会兜底", file=sys.stderr)
355
- return Path(mcp_jsons[0])
356
- # 深审 P0-3:绝不再返回 ~/.codex/config.toml——它是用户整份 codex 配置,
357
- # uninstall 对 mcpConfig 是删除语义,指向它=卸载删光用户配置(破坏性)
358
- print("[vod-devkit] warn: 未定位到插件 .mcp.json(uninstall 将跳过 MCP 清理,"
359
- "可手动删除插件缓存目录)", file=sys.stderr)
360
- return None
361
-
362
-
363
- def _install_dsh(args, packs: str) -> Path:
364
- """dsh 工具壳(D-dsh-install-1,2026-11-06 用户拍板 A):三壳口径统一——
365
- --product 安装期硬校验(cmd_install 已先行,到达此处必已过)+ 校验先于
366
- add + 幂等写 profile cordis.patch.yml config override。
367
- 生效通道真机实测(2026-11-06,dsh 0.2.1-rc.5):profile cordis.patch.yml
368
- 的 id-targeted config override 是工具壳读取 product/apiBase/uiBase/
369
- confirmWrites 的唯一运行时通道(启动 banner + 桩引擎提交链实证)。
370
- uiBase(D-uiBase-direct):浏览器半(反馈按钮)直连引擎——apiBase 是
371
- server 半(Node)自用,浏览器同源策略下用不上;缺 uiBase 时 UI 提交
372
- 发往 dsh 同源(404→本地暂存),嵌入方真机实锤。dsh plugin add 会自建
373
- profile,无需前置。"""
374
- dsh = shutil.which("dsh")
375
- profile = (getattr(args, "dsh_profile", "") or "").strip()
376
- if not profile:
377
- # argparse 进入安装前校验(cmd_install 已兜底,直调防御)
378
- print("[vod-devkit] --profile 必填:dsh 按 profile 组织插件与配置"
379
- "(--profile <name>)", file=sys.stderr)
380
- sys.exit(2)
381
- if not dsh:
382
- print("[vod-devkit] 未找到 dsh CLI(PATH),拒绝安装(宁可不装不可装错)。"
383
- "前置:npm i -g @deepseek-ai/dsh(需 pnpm)", file=sys.stderr)
384
- sys.exit(2)
385
- r = subprocess.run([dsh, "plugin", "--profile", profile,
386
- "add", "dsh-vod-devkit"],
387
- capture_output=True, text=True, timeout=300)
388
- if r.returncode != 0:
389
- print(f"[vod-devkit] dsh plugin add 失败:{(r.stderr or r.stdout).strip()[-300:]}",
390
- file=sys.stderr)
391
- sys.exit(1)
392
- print(f"已安装 dsh 插件 dsh-vod-devkit(profile={profile},dsh plugin list 可见)")
393
-
394
- patch = Path(host_specs.load("dsh", profile)["configPath"])
395
- # name 行必须保留:cordis.patch.yml 的 insert 块靠 name 绑定 client 半
396
- # (反馈按钮)——只写 id+config 会在重装幂等替换时把 name 吞掉,UI 静默
397
- # 失激活(2026-11-06 真机实锤:重装后入口消失)
398
- # 嵌套铁律(2026-11-10 真机实锤):块必须缩进在 `- insert:` 之下——平铺
399
- # 形态被 dsh 组合层丢弃,插件掉出组合树(banner/工具/UI 全消失)。
400
- block = ("- insert:\n"
401
- " - id: vod-devkit\n"
402
- " name: dsh-vod-devkit\n"
403
- " config:\n"
404
- f" product: {args.product}\n"
405
- f" apiBase: {args.java_api_base}\n"
406
- f" uiBase: {args.java_api_base}\n" # D-uiBase-direct:浏览器半直连引擎
407
- " # headless 无审批通道:原生 ask 门禁会永久阻断写工具(四宿主实测实锤:\n"
408
- " # requires approval, but no approval channel)。同意确认由 SKILL 话术层\n"
409
- " # 承担(draft→用户确认→commit / 明确指令直发),web 端如需硬门禁按\n"
410
- " # profile 覆盖回 true。\n"
411
- " confirmWrites: false\n")
412
- try:
413
- written = _upsert_dsh_patch(patch, block)
414
- except Exception as e:
415
- # 回滚/修复指引:插件已装但配置未写 = 半成品,给明确的手动修复格式。
416
- # 区分两类失败:形态守卫拒绝(文件合法但不在已知形态内,字节未动)
417
- # 与真实 IO 失败——两者的处置动作不同,文案必须能分辨。
418
- print(f"[vod-devkit] 插件已装入 profile={profile},但配置写入失败"
419
- f"({e.__class__.__name__}: {e};该文件未被改动)。请手动把下段并入 {patch}"
420
- f"(顶层 YAML 数组元素,已有 - id: vod-devkit 段则原位替换):\n"
421
- f"{block}", file=sys.stderr)
422
- sys.exit(1)
423
- if written:
424
- print(f"已写入归因/引擎配置(幂等 upsert):{patch}")
425
- else:
426
- print(f"配置未变化(幂等跳过):{patch}")
427
- return patch
152
+ def _expected_remote_tools() -> set:
153
+ """远程面应当暴露的工具集 = 契约全集 - REMOTE_WITHHELD(写面本机工具不进远程)。"""
154
+ from vod_mcp import packs as _packs
155
+ contract = json.loads((ROOT / "contract" / "tools.schema.json").read_text(encoding="utf-8"))
156
+ return set(contract["tools"]) - set(_packs.REMOTE_WITHHELD)
428
157
 
429
158
 
430
- def _find_dsh_block(lines):
431
- """定位 cordis.patch.yml 中 vod-devkit 块的 (start, end)。
159
+ def _probe_remote(url: str, token: str, timeout: int = 15) -> list:
160
+ """远程 MCP 端点探活:initialize + tools/list,返回工具名清单(失败抛 RuntimeError)。
432
161
 
433
- 扫描/边界语义统一在 vod_mcp/config_forms.find_dsh_block(单一实现,
434
- install 的幂等 upsert、uninstall 摘除、doctor 自愈三处共用——两处扫描
435
- 规则漂移在本仓 dsh 壳上实锤过)。本函数只保留名字兼容调用点。
162
+ 走 stdlib urllib(安装器零第三方依赖红线);Accept 双类型,兼容 SSE 单事件响应。
163
+ 探活在**写入任何配置之前**执行——装不上就不留半成品。
436
164
  """
437
- from vod_mcp import config_forms as cf
438
- return cf.find_dsh_block(lines)
439
-
440
-
441
- def _upsert_dsh_patch(patch: Path, block: str) -> bool:
442
- """幂等写 profile cordis.patch.yml:已存在 `- id: vod-devkit` 段则原位整块
443
- 替换(不重复插入);无则追加。按行扫描块边界(下一行 `- ` 顶层元素或 EOF),
444
- 不引 YAML 依赖(本仓零第三方依赖红线)。返回是否有写入。"""
445
- from vod_mcp import config_forms as cf
446
- lines = patch.read_text(encoding="utf-8").splitlines() if patch.exists() else []
447
- # 形态守卫(先分类后改字节):非已知形态一律拒绝——这个文件坏掉等于
448
- # 整个 dsh profile 起不来(`[]` 占位实锤),比装不上代价高得多
449
- try:
450
- verdict, reason = cf.classify_dsh_patch(lines)
451
- except cf.Refused as e:
452
- raise RuntimeError(f"cordis.patch.yml 形态不受支持:{e}") from e
453
- if verdict == "refuse":
454
- raise RuntimeError(f"cordis.patch.yml 形态不受支持:{reason}")
455
- start, end = _find_dsh_block(lines)
456
- if start is None:
457
- # 空数组占位清除(四宿主实测实锤:dsh plugin add 自建的模板含字面量
458
- # `[]` 顶层行,直接追加块 = `[]` 后跟 `- id:` 顶层元素 = 非法 YAML,
459
- # 整个 profile 启动崩溃)。`[]` 语义=空数组,被块 entries 取代即删。
460
- lines = [ln for ln in lines if ln.strip() != "[]"]
461
- new = lines + ([""] if lines and lines[-1].strip() else []) + block.splitlines()
462
- else:
463
- new = lines[:start] + block.splitlines() + lines[end:]
464
- new_text = "\n".join(new).rstrip("\n") + "\n"
465
- # 空 `- insert:` 组头清理(损坏态自愈):孤儿组头(下一个顶层元素前无
466
- # 子项)来自历史平铺替换的残留——留它在 dsh 组合层是空组,可能拖垮
467
- # 整个 patch 解析。upsert 后顺手摘除(幂等,不碰正常组)。
468
- cleaned = []
469
- for idx, ln in enumerate(new):
470
- if ln.strip() == "- insert:":
471
- nxt = new[idx + 1] if idx + 1 < len(new) else ""
472
- if nxt.startswith("- ") or (not nxt.strip() and idx + 2 >= len(new)):
473
- continue # 孤儿组头:下一行已是新顶层元素(无子项)→ 摘除
474
- cleaned.append(ln)
475
- new_text = "\n".join(cleaned).rstrip("\n") + "\n"
476
- old_text = patch.read_text(encoding="utf-8") if patch.exists() else ""
477
- if new_text == old_text:
478
- return False
479
- patch.parent.mkdir(parents=True, exist_ok=True)
480
- patch.write_text(new_text, encoding="utf-8")
481
- return True
482
-
165
+ import urllib.request
483
166
 
484
- def _remove_dsh_patch_block(patch: Path) -> bool:
485
- """从 cordis.patch.yml 摘除 vod-devkit 块(uninstall 用)。返回是否摘除。"""
486
- if not patch.exists():
487
- return False
488
- from vod_mcp import config_forms as cf
489
- lines = patch.read_text(encoding="utf-8").splitlines()
167
+ def _post(payload: dict) -> dict:
168
+ req = urllib.request.Request(
169
+ url, data=json.dumps(payload).encode(), method="POST",
170
+ headers={"content-type": "application/json",
171
+ "accept": "application/json, text/event-stream",
172
+ **({"Authorization": f"Bearer {token}"} if token else {})})
173
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
174
+ body = resp.read().decode("utf-8", "replace")
175
+ if body.startswith("event:") or body.startswith("data:"):
176
+ for line in body.splitlines():
177
+ if line.startswith("data:"):
178
+ body = line[5:].strip()
179
+ break
180
+ data = json.loads(body or "{}")
181
+ if isinstance(data, dict) and data.get("error"):
182
+ raise RuntimeError(f"JSON-RPC 错误:{data['error']}")
183
+ return data
184
+
185
+ _post({"jsonrpc": "2.0", "id": 1, "method": "initialize",
186
+ "params": {"protocolVersion": "2025-06-18",
187
+ "clientInfo": {"name": "vod-devkit-installer", "version": "1"},
188
+ "capabilities": {}}})
189
+ listed = _post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
190
+ names = [t.get("name") for t in (listed.get("result") or {}).get("tools") or []]
191
+ if not names:
192
+ raise RuntimeError("tools/list 返回空——端点可能不是 Streamable HTTP MCP")
193
+ return names
194
+
195
+
196
+ def _remote_reachable(url: str, timeout: int = 6) -> bool:
197
+ """端点是否可达:GET 得到任何 HTTP 响应(405 是远程面契约的正常应答)即算通。"""
198
+ import urllib.error
199
+ import urllib.request
490
200
  try:
491
- verdict, reason = cf.classify_dsh_patch(lines)
492
- except cf.Refused as e:
493
- verdict, reason = "refuse", str(e)
494
- if verdict == "refuse":
495
- # 卸载路径同样不动字节:文件已经坏了,再"尽力删"只会让故障更难定位
496
- print(f"[vod-devkit] skip(cordis.patch.yml 形态不受支持,未改动):{reason}",
497
- file=sys.stderr)
498
- return False
499
- start, end = _find_dsh_block(lines)
500
- if start is None:
201
+ with urllib.request.urlopen(url, timeout=timeout):
202
+ return True
203
+ except urllib.error.HTTPError:
204
+ return True # 405/401/406 都证明端点活着
205
+ except Exception:
501
206
  return False
502
- patch.write_text(
503
- "\n".join(lines[:start] + lines[end:]).rstrip("\n") + "\n",
504
- encoding="utf-8")
505
- return True
506
207
 
507
208
 
508
- _INSTALLERS = {"hermes": _install_hermes, "opencode": _install_opencode,
509
- "codex": _install_codex, "dsh": _install_dsh}
510
209
 
511
210
 
512
211
  def detect_targets() -> list:
513
212
  """0/1/N 探测:按 host.json 的 detect 段判断宿主是否在场(CLI 或配置目录)。"""
514
213
  found = []
515
214
  for host in host_specs.hosts():
516
- spec = host_specs.load(host)
215
+ spec = host_specs.raw(host) # 探测不解析路径(dsh 的 {profile} 占位符必填)
517
216
  if spec.get("detectCLI") and shutil.which(spec["detectCLI"]):
518
217
  found.append(host)
519
218
  elif spec.get("detectPath") and Path(spec["detectPath"]).exists():
@@ -602,19 +301,36 @@ def cmd_install(args):
602
301
  target = args.target
603
302
  if target == "auto":
604
303
  found = detect_targets()
304
+ generic_found = generic_host.detect_known()
605
305
  if len(found) == 1:
606
306
  target = found[0]
307
+ elif not found and len(generic_found) == 1:
308
+ # A 层兜底:没有专属模块但有已知通用 MCP 宿主 → 走通用写入
309
+ #(探到唯一一个才自动写,多个/零个都要人选定,不许猜)
310
+ target = "generic"
311
+ if not getattr(args, "mcp_config", ""):
312
+ args.mcp_config = str(generic_host._expand(generic_found[0]["config"]))
313
+ print(f"探测到通用 MCP 宿主: {generic_found[0]['label']} → 通用写入 "
314
+ f"({args.mcp_config})")
607
315
  elif not found:
608
- print("未探测到任何宿主;用 --target hermes|opencode|codex 显式指定",
609
- file=sys.stderr)
316
+ known = "、".join(h["label"] + "(" + h["config"] + ")" for h in generic_found)
317
+ print("未探测到可自动安装的宿主;用 --target hermes|opencode|codeartsdoer|codex|dsh 显式指定"
318
+ + (f",或通用写入:--target generic --mcp-config <配置>(探测到 {known})"
319
+ if generic_found else ""), file=sys.stderr)
610
320
  sys.exit(2)
611
321
  else:
612
- print(f"探测到多个宿主: {found};请 --target 显式指定其一", file=sys.stderr)
322
+ print(f"探测到多个宿主: {found + [h['id'] for h in generic_found]};"
323
+ "请 --target 显式指定其一", file=sys.stderr)
613
324
  sys.exit(2)
614
325
  print(f"探测到宿主: {target}")
615
- installer = _INSTALLERS.get(target)
616
- if installer is None:
617
- print(f"不支持目标: {target}(可选 hermes|opencode|codex|auto)", file=sys.stderr)
326
+ adapter = HOST_ADAPTERS.get(target)
327
+ if adapter is None:
328
+ g = [(h["id"], h["config"]) for h in generic_host.detect_known()]
329
+ hint = ("\n 探测到通用 MCP 宿主:" + ";".join(f"{i}({c})" for i, c in g)
330
+ if g else "")
331
+ print(f"不支持目标: {target}(可选 hermes|opencode|codeartsdoer|codex|dsh|generic|auto){hint}\n"
332
+ " 通用宿主:install --target generic --mcp-config <配置文件>",
333
+ file=sys.stderr)
618
334
  sys.exit(2)
619
335
  packs = args.packs or PRESETS.get(args.preset, "")
620
336
  # 恢复门禁(D-codex-circuit-breaker-1,2026-11-06 负责人确认):
@@ -635,19 +351,10 @@ def cmd_install(args):
635
351
  "(draft→commit 审计链/重复 commit 被拒/未确认可检测)。",
636
352
  file=sys.stderr)
637
353
  sys.exit(2)
638
- # 归因绑定(T7d 统一:安装必配,与 dsh UI 加载必配同口径):--product 必填——
639
- # 缺省宿主名在生态部署是错归陷阱(高校AI开发者平台 agent 底座=hermes,
640
- # 不填则反馈全归 hermes)。宿主名仍是合法值(自反馈场景显式传
641
- # --product hermes),但必须显式选择,不做静默默认(归因错误比没数据更糟)。
642
- if not args.product:
643
- print(
644
- "[vod-devkit] --product 必填:产品归因是安装必配项(与 UI 嵌入注入同口径)。\n"
645
- " 取值=生态看板产品名(可用 GET /external/products 查询权威名单),如:\n"
646
- " --product \"高校AI开发者平台\" / --product \"GTD\" / --product \"Skills门户\"\n"
647
- " 取值必须在产品名录内(安装期硬校验,D-product-id-2);完整名单:\n"
648
- " GET /external/products",
649
- file=sys.stderr)
650
- sys.exit(2)
354
+ # 归因绑定降级(D-attrib-B,2026-11-11 负责人拍板 P1-P4 全 A):--product
355
+ # 由必填改为**可选先验**——归因主路径改成运行期从用户原话解析(证据唯一
356
+ # 命中才采信),安装绑定只在「无字面证据且无记忆」时兜底。保留「给了就
357
+ # 必须对」:显式提供时仍做名录硬校验(拼错照样 exit 2),不给不拦装。
651
358
  # D-dsh-install-1:--profile 必填在进入任何安装动作前校验(先校验后写入)
652
359
  if target == "dsh" and not (args.dsh_profile or "").strip():
653
360
  print("[vod-devkit] --profile 必填:dsh 按 profile 组织插件与配置。\n"
@@ -662,7 +369,8 @@ def cmd_install(args):
662
369
  # 目录不可达(离线/引擎异常)同样拒绝——宁可不装不可装错(postinstall 拒绝
663
370
  # 猜测同源纪律)。插件提交链的 name 兼容通道不受影响(那是老版本插件兼容,
664
371
  # 不是安装期放行理由)。
665
- _validate_product_or_exit(args.product, args.java_api_base)
372
+ if args.product: # 可选先验:给了就校验,不给不拦装(D-attrib-B)
373
+ _validate_product_or_exit(args.product, args.java_api_base)
666
374
  # D-key-guard-2 红线:preset(产品分发)形态下 key 禁止随包——环境变量里的
667
375
  # key 不透传给宿主配置(客户机一律走匿名令牌自领),并当场告警
668
376
  distribution = args.distribution
@@ -682,10 +390,58 @@ def cmd_install(args):
682
390
  cfg["local_ledger"] = False
683
391
  # base 同步落 runtime.json:宿主 env 透传不稳是实测坑,透传挂了静默落回
684
392
  # 127.0.0.1:8090;文件兑底与 env 同值不构成双真源(优先级链 env>文件)
393
+ # 宿主产品(host_default 兜底用,D-product-ask-1):只有 integrations 声明了才写
394
+ spec_raw = host_specs.raw(target) if target in host_specs.hosts() else {}
395
+ if spec_raw.get("productDefault"):
396
+ cfg["host_product"] = spec_raw["productDefault"]
685
397
  cfg["java_base"] = args.java_api_base
686
398
  rt.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
687
399
 
688
- mcp_conf = installer(args, packs)
400
+ # ── 远程 attach / skills-only(D-attach-1)───────────────────────────
401
+ # 形态:MCP 单独部署一个远程端点,宿主只把 MCP 配置指向它(+ 本地技能)。
402
+ # 约束:远程面无匿名链(缺 key fail fast)→ token 必填;探活先于写入,
403
+ # 失败零副作用。dsh 壳不走 MCP,这两种模式对 dsh 无意义(显式拒绝)。
404
+ remote_url = (getattr(args, "mcp_url", "") or "").strip()
405
+ skills_only = bool(getattr(args, "skills_only", False))
406
+ if remote_url or skills_only:
407
+ if not getattr(adapter, "SUPPORTS_REMOTE", False):
408
+ what = "dsh 壳不走 MCP" if target == "dsh" else f"{target} 不走 MCP"
409
+ print(f"[vod-devkit] {what},不支持 --mcp-url / --skills-only\n"
410
+ f" {target} 请用本地形态:install --target {target} "
411
+ + ("--profile <name>" if target == "dsh" else ""),
412
+ file=sys.stderr)
413
+ sys.exit(2)
414
+ token = (getattr(args, "mcp_token", "") or os.environ.get("VOD_MCP_TOKEN") or "").strip()
415
+ if remote_url:
416
+ if not token:
417
+ print("[vod-devkit] 远程 attach 必须提供 --mcp-token 或 env VOD_MCP_TOKEN:\n"
418
+ " 远程面不代签匿名令牌(身份只从请求头来),无 token 装上也提交不了",
419
+ file=sys.stderr)
420
+ sys.exit(2)
421
+ try:
422
+ names = _probe_remote(remote_url, token)
423
+ except Exception as e: # noqa: BLE001
424
+ print(f"[vod-devkit] 远程 MCP 探活失败(未写入任何配置):{e}", file=sys.stderr)
425
+ sys.exit(2)
426
+ expected = _expected_remote_tools()
427
+ missing = expected - set(names)
428
+ if missing:
429
+ print(f"[vod-devkit] 远程面工具面不符:缺 {sorted(missing)}\n"
430
+ f" 实际 = {sorted(names)}\n"
431
+ " 该端点可能不是 vod-devkit 远程面,或版本/角色不匹配;拒绝安装",
432
+ file=sys.stderr)
433
+ sys.exit(2)
434
+ print(f"远程面探活通过:{len(names)} 个工具({', '.join(sorted(names))})")
435
+ mcp_conf = None if skills_only else adapter.install_remote(args, remote_url, token)
436
+ extra_dirs = _install_skills(target, packs, args,
437
+ (getattr(args, "dsh_profile", "") or "").strip() or None)
438
+ _write_install_manifest(args, target, packs, bound_product, mcp_conf, extra_dirs,
439
+ transport=("skills-only" if skills_only else "remote"),
440
+ mcp_url=remote_url)
441
+ return
442
+
443
+ payload_dir = _stage_payload() # 载荷固化:入口指向这份副本,不再指向 npx 缓存
444
+ mcp_conf = adapter.install(args, packs)
689
445
 
690
446
  # P1-4 修正:ack 解除后置——安装全部成功才落(解除先于安装=失败安装
691
447
  # 也绕过了恢复门禁语义)
@@ -700,14 +456,41 @@ def cmd_install(args):
700
456
  print(f"[vod-devkit] 已显式解除 codex 采集熔断(安装成功),审计已记录:{audit}")
701
457
 
702
458
  # G1 修复:技能全量拷贝(目录型技能+平铺规则文档),按 packs 过滤
703
- extra_dirs = _install_skills(target, packs,
459
+ extra_dirs = _install_skills(target, packs, args,
704
460
  (getattr(args, "dsh_profile", "") or "").strip() or None)
705
461
 
706
462
  _write_install_manifest(args, target, packs, bound_product, mcp_conf,
707
- extra_dirs)
463
+ extra_dirs, payload_dir=payload_dir)
708
464
 
709
465
 
710
- def _install_skills(target: str, packs: str, profile: str | None = None):
466
+ def _stage_payload():
467
+ """把 server/contract/safety/skills 拷进 ~/.vod-devkit/payloads/<ver>/ 并指过去。
468
+
469
+ 对标 devkit 的 copyServerPayload(D-payload-1):npx 安装时仓在
470
+ ~/.npm/_npx/<hash>/,npm 清缓存/换版本后入口指向已删除路径 → 宿主 MCP 静默掉线。
471
+ """
472
+ from vod_mcp import payload as _payload
473
+ from vod_mcp.host_adapters import base as _base
474
+ dest = _payload.stage()
475
+ # 把安装期运行配置种进载荷(载荷 runtime 与仓内 runtime 是两份文件):
476
+ # 否则 host_product/product/java_base 只写在仓内,真正跑起来的副本看不到
477
+ seeded = {k: v for k, v in _runtime_cfg_read().items()
478
+ if k in ("product", "host_product", "java_base", "local_ledger")}
479
+ if seeded:
480
+ rt = dest / "vod_mcp" / "runtime.json"
481
+ cur = {}
482
+ if rt.exists():
483
+ try:
484
+ cur = json.loads(rt.read_text(encoding="utf-8"))
485
+ except Exception:
486
+ cur = {}
487
+ cur.update(seeded)
488
+ rt.write_text(json.dumps(cur, ensure_ascii=False, indent=2), encoding="utf-8")
489
+ _base.set_payload_dir(dest)
490
+ return dest
491
+
492
+
493
+ def _install_skills(target: str, packs: str, args, profile: str | None = None):
711
494
  """技能段:按 packs 过滤后拷到 hermes 主目录 + 目标宿主的技能发现目录。
712
495
 
713
496
  目标宿主列表由 integrations/<host>/host.json 的 skillsDir 决定——2026-11-11
@@ -720,9 +503,9 @@ def _install_skills(target: str, packs: str, profile: str | None = None):
720
503
  # ~/.config/opencode/skills/ 并经 skill 工具按需加载——此前安装器漏拷,
721
504
  # opencode 只有工具描述一条约束通道,话术类约束全部失效)
722
505
  extra_dirs = [] # [(host, Path)]
723
- spec = host_specs.load(target, profile)
724
- if spec.get("skillsDir") and target != "hermes":
725
- dst = Path(spec["skillsDir"])
506
+ adapter = HOST_ADAPTERS.get(target)
507
+ dst = adapter.skills_dir(args) if adapter and target != "hermes" else None
508
+ if dst is not None:
726
509
  dst.mkdir(parents=True, exist_ok=True)
727
510
  extra_dirs.append((target, dst))
728
511
  pack_set = set(p for p in packs.split(",") if p)
@@ -742,12 +525,34 @@ def _install_skills(target: str, packs: str, profile: str | None = None):
742
525
  if dst2.exists():
743
526
  shutil.rmtree(dst2)
744
527
  shutil.copytree(entry, dst2)
745
- # vendored 领域规则已由 vendor_rules.py 落成技能目录结构
528
+ # 领域规则技能为静态副本,与引擎真源的对账见 scripts/rules_provenance.py
746
529
  return extra_dirs
747
530
 
748
531
 
532
+ def _read_manifest() -> dict:
533
+ p = manifest_path()
534
+ if not p.exists():
535
+ return {}
536
+ try:
537
+ return json.loads(p.read_text(encoding="utf-8"))
538
+ except Exception:
539
+ return {}
540
+
541
+
542
+ def _install_rows(prev: dict, row: dict) -> list:
543
+ """按 target 去重的安装行(D-installs-1):一个 manifest 记全部宿主安装。
544
+
545
+ 起因(结构债):顶电平字段只记「最近一次安装」,装 hermes 再装 codearts 后
546
+ uninstall 只清最后一个宿主的 MCP 条目,另一台宿主的配置永远留在那。
547
+ """
548
+ rows = [r for r in (prev.get("installs") or []) if r.get("target") != row["target"]]
549
+ rows.append(row)
550
+ return sorted(rows, key=lambda r: r.get("installedAt") or "")
551
+
552
+
749
553
  def _write_install_manifest(args, target, packs, bound_product, mcp_conf,
750
- extra_dirs) -> None:
554
+ extra_dirs, transport: str = "stdio",
555
+ mcp_url: str = "", payload_dir=None) -> None:
751
556
  """manifest 段:落安装名册(版本/来源/归因/落点指纹),并给出 key
752
557
  配置提示。名册对账口径见各字段注释(原 cmd_install 尾段,整段平移)。"""
753
558
  bi = json.loads((ROOT / "build-info.json").read_text(encoding="utf-8"))
@@ -758,6 +563,10 @@ def _write_install_manifest(args, target, packs, bound_product, mcp_conf,
758
563
  cwd=ROOT, capture_output=True, text=True).stdout.strip(),
759
564
  "commitSha": bi["commitSha"]},
760
565
  "target": target,
566
+ # 传输形态(D-attach-1):stdio=宿主本机拉起进程;remote=指向单独部署的
567
+ # 远程端点;skills-only=只装技能(MCP 由别处注册)
568
+ "transport": transport,
569
+ "mcpUrl": mcp_url or None,
761
570
  "installedAt": datetime.datetime.now().isoformat(timespec="seconds"),
762
571
  "preset": args.preset,
763
572
  "distribution": getattr(args, "distribution", "devkit"),
@@ -776,14 +585,28 @@ def _write_install_manifest(args, target, packs, bound_product, mcp_conf,
776
585
  # (实锤:codex 装完 opencode 落点消失),按 host+dir 去重保留历史
777
586
  "skillInstalls": _skill_installs(manifest_path(), extra_dirs),
778
587
  "skillHashes": _skill_hashes(),
588
+ # 载荷副本(D-payload-1):宿主入口指向这里,而不是仓/npx 缓存路径
589
+ "payloadDir": str(payload_dir) if payload_dir else None,
779
590
  }
591
+ row = {k: manifest[k] for k in
592
+ ("target", "transport", "mcpUrl", "installedAt", "product", "packs",
593
+ "dshProfile", "apiBase", "mcpConfig", "skillsDir", "payloadDir")}
594
+ row["version"] = manifest["version"]
595
+ row["commitSha"] = manifest["source"]["commitSha"]
596
+ row["skillInstalls"] = [si for si in manifest["skillInstalls"]
597
+ if si["host"] == target]
598
+ prev = _read_manifest()
599
+ manifest["installs"] = _install_rows(prev, row)
780
600
  manifest_path().write_text(json.dumps(manifest, ensure_ascii=False, indent=2),
781
601
  encoding="utf-8")
782
602
  print("installed:", json.dumps(manifest, ensure_ascii=False, indent=2))
783
603
  missing = [k for k in ("VOD_JAVA_API_KEY",) if
784
604
  not os.environ.get(k) and not _runtime_cfg_read().get("java_key")]
785
- if missing:
605
+ if missing and transport == "stdio":
786
606
  print(f"提示:{missing} 未配置——首次提交将自动申请零字段匿名令牌(无需配置)")
607
+ elif transport == "remote":
608
+ print("远程形态提示:身份随请求头走(token 已由宿主配置承载);"
609
+ "本机 runtime.json 的匿名链不参与远程提交")
787
610
 
788
611
 
789
612
  def _runtime_cfg_read() -> dict:
@@ -806,6 +629,9 @@ def cmd_status(_args):
806
629
  text = p.read_text(encoding="utf-8")
807
630
  text = re.sub(r'"apiBase": "http://127\.0\.0\.1:\d+"',
808
631
  '"apiBase": "http://127.0.0.1:<PORT>"', text)
632
+ # 载荷路径含 HOME/版本,按 <PAYLOAD> 归一(golden 不随环境漂)
633
+ text = re.sub(r'"payloadDir": ".*?/payloads/[^"]+"',
634
+ '"payloadDir": "<PAYLOAD>"', text)
809
635
  print(text)
810
636
 
811
637
 
@@ -883,6 +709,25 @@ def cmd_doctor(_args):
883
709
  problems.append("install-manifest 与 build-info 的 commitSHA 不一致")
884
710
  if mf.get("mcpConfig") and not Path(mf["mcpConfig"]).exists():
885
711
  problems.append("MCP 配置文件缺失")
712
+ if mf.get("transport") == "remote" and mf.get("mcpUrl"):
713
+ url = mf["mcpUrl"]
714
+ token = (os.environ.get("VOD_MCP_TOKEN")
715
+ or os.environ.get("MCP_VOD_DEVKIT_API_KEY") or "").strip()
716
+ try:
717
+ names = _probe_remote(url, token, timeout=8)
718
+ missing = _expected_remote_tools() - set(names)
719
+ if missing:
720
+ problems.append(f"远程面工具面不符(缺 {sorted(missing)}):{url}")
721
+ else:
722
+ print(f"[doctor] 远程面可达:{url}({len(names)} 工具)")
723
+ except Exception as e: # noqa: BLE001
724
+ if not _remote_reachable(url):
725
+ problems.append(f"远程 MCP 端点不可达:{url}")
726
+ elif not token:
727
+ print("[doctor] 远程端点可达,但未提供 token(401 属预期):"
728
+ "设 VOD_MCP_TOKEN 可验工具面")
729
+ else:
730
+ problems.append(f"远程面探活失败(带 token):{e}")
886
731
  if not Path(mf["skillsDir"]).exists():
887
732
  problems.append("skills 目录缺失")
888
733
  drifted = _drifted_skills(mf)
@@ -904,6 +749,45 @@ def cmd_doctor(_args):
904
749
  problems.append(f"技能文件缺失({si['host']}):{rel}")
905
750
  elif hashlib.sha256(f.read_bytes()).hexdigest() != sha:
906
751
  problems.append(f"技能文件漂移({si['host']}):{rel}")
752
+ # 载荷(D-payload-1):MCP 入口指向副本 → 副本必须在且未被改
753
+ from vod_mcp import payload as _payload
754
+ pd = mf.get("payloadDir")
755
+ if pd:
756
+ if not Path(pd).is_dir():
757
+ problems.append(f"载荷目录缺失:{pd}(MCP 入口指向它,宿主起不来)——重跑 install")
758
+ else:
759
+ bad = _payload.verify(Path(pd))
760
+ if bad:
761
+ problems.append("载荷被改动:" + ";".join(bad[:5]))
762
+ if _payload.marker_path().exists():
763
+ print(f"[doctor] 载荷已换({pd})——重启宿主会话生效")
764
+ else:
765
+ print("[doctor] 提示:本次安装无载荷副本(旧版),入口指向仓内路径;重跑 install 可固化")
766
+ for res in _payload.residue():
767
+ print(f"[doctor] 载荷残留(无 payload.json):{res}——可手动删除")
768
+ # 旧一代 AGENTS.md 注入(2026-11-05 之前的 one-liner):教模型跳过同意 +
769
+ # 归因由安装绑定。实测 1705 个 codex 会话带着它 → 不动它就等于红线失效。
770
+ legacy_agents = Path.home() / ".codex" / "AGENTS.md"
771
+ if legacy_agents.exists() and "vod-submit-one-liner" in legacy_agents.read_text(
772
+ encoding="utf-8"):
773
+ problems.append(f"AGENTS.md 仍含旧一代注入(教模型跳过同意):{legacy_agents}"
774
+ "——重跑 install --target codex 自动清理")
775
+ # 路由插件副本(hermes):仓内话术改了但装机副本没刷新 → 宿主还在注入旧口径
776
+ # (2026-11-11 实锤:仓里已把"归因由安装绑定决定"改成"原话解析",装机副本仍是旧的)
777
+ rp_dst = Path.home() / ".hermes" / "plugins" / "vod-feedback-router" / "router.py"
778
+ rp_src = ROOT / "hermes-plugin" / "vod-feedback-router" / "router.py"
779
+ if rp_dst.exists() and rp_src.exists() and rp_dst.read_text(encoding="utf-8") != \
780
+ rp_src.read_text(encoding="utf-8"):
781
+ problems.append(f"路由插件副本落后于仓内:{rp_dst}(重跑 install --target hermes)")
782
+ # CodeArts Agent 冒烟:官方 CLI 在就 list 一次(实测通道=codearts_cli.json 的 mcp 段)
783
+ if mf.get("target") == "codeartsdoer" and shutil.which("codearts"):
784
+ r = subprocess.run(["codearts", "mcp", "list"], capture_output=True,
785
+ text=True, timeout=60)
786
+ if "vod-devkit" in (r.stdout or ""):
787
+ print("[doctor] CodeArts Agent 已识别 vod-devkit(codearts mcp list)")
788
+ else:
789
+ problems.append("CodeArts Agent 未列出 vod-devkit"
790
+ "(codearts mcp list)——检查 codearts_cli.json 的 mcp 段")
907
791
  if problems:
908
792
  for x in problems:
909
793
  print("FAIL:", x)
@@ -971,8 +855,20 @@ def cmd_verify(_args):
971
855
  print(f"verify: OK(commit {sha[:12]} 存在于本仓/origin)")
972
856
 
973
857
 
974
- def cmd_update(_args):
975
- """更新:git fetch 比较 origin/main,落后则 ff 拉取并重烧 build-info。"""
858
+ def cmd_update(args=None):
859
+ """更新:git fetch 比较 origin/main,落后则 ff 拉取并重烧 build-info。
860
+
861
+ --skip / --clear-skip(D-devtoolchain-7,对齐 devkit update-skip 裁剪版):
862
+ 只维护「跳过某个版本提醒」的运行时状态,不动代码——所以放在 git 拉取之前返回。
863
+ """
864
+ if getattr(args, "skip", False) or getattr(args, "clear_skip", False):
865
+ from vod_mcp import update_check as uc
866
+ out = uc.check({"clearSkip": True} if getattr(args, "clear_skip", False)
867
+ else {"skip": True})
868
+ print(out.get("note") or "")
869
+ if out.get("latestVersion"):
870
+ print(f"latest = {out['latestVersion']}(clearSkip=true 可撤销)")
871
+ return
976
872
  if _distribution() == "preset":
977
873
  # D-key-guard-3②:产品分发形态插件版本随 agent 发版管理,客户机禁止自更新
978
874
  #(绕过产品版本管理=未测试代码进客户现场)
@@ -999,53 +895,151 @@ def cmd_update(_args):
999
895
  print(" 并重启 agent 会话")
1000
896
 
1001
897
 
1002
- def cmd_uninstall(_args):
1003
- p = manifest_path()
1004
- if p.exists():
1005
- mf = json.loads(p.read_text(encoding="utf-8"))
1006
- for key in ("mcpConfig", "skillsDir"):
1007
- path_s = mf.get(key)
1008
- if not path_s:
1009
- continue # codex 等宿主 mcpConfig 可为 None(P0-3:无托管配置文件)
1010
- path = Path(path_s)
1011
- # 深审 P0-3(破坏性路径一票否决):config.toml 是用户整份 codex
1012
- # 配置,永不在 uninstall 删除——旧版 manifest 曾把它记成 mcpConfig
1013
- if path.name == "config.toml":
1014
- print(f"skip(用户配置文件,uninstall 永不删除):{path}")
1015
- continue
1016
- if path.exists():
1017
- shutil.rmtree(path) if path.is_dir() else path.unlink()
1018
- print("removed:", path)
1019
- # codex 原生插件摘除(best-effort:CLI 命令名随版本可能变化,失败不阻塞)
1020
- if mf.get("target") == "codex":
1021
- codex = shutil.which("codex")
1022
- if codex:
1023
- r = subprocess.run([codex, "plugin", "remove",
1024
- "vod-devkit@vod-local"],
1025
- capture_output=True, text=True, timeout=120)
1026
- print("codex plugin remove:",
1027
- "OK" if r.returncode == 0
1028
- else (r.stderr or r.stdout).strip()[-120:])
898
+ # 共享用户配置文件:uninstall 只摘「我们的托管条目」,绝不删除文件
899
+ #(深审 P0-3 只挡了 config.toml;opencode.json 同类且更危险——里面有用户整份
900
+ # provider 配置。2026-11-11 远程 attach 落地时一并收口。)
901
+ _SHARED_CONFIG_NAMES = {"config.toml", "config.yaml", "config.yml",
902
+ "opencode.json", "opencode.jsonc"}
903
+
904
+
905
+ def _remove_managed_mcp_entry(target: str, path: Path) -> None:
906
+ """从宿主共享配置里摘掉 vod-devkit 条目(保留其它键/其它 server)。"""
907
+ section = {"opencode": "mcp", "codeartsdoer": "mcp", "generic": "mcpServers"}.get(target)
908
+ if section:
909
+ if not path.exists():
910
+ return
911
+ try:
912
+ cfg = json.loads(path.read_text(encoding="utf-8"))
913
+ except Exception:
914
+ print(f"skip({path} 不是合法 JSON,未改动)")
915
+ return
916
+ block = cfg.get(section) or {}
917
+ if "vod-devkit" not in block:
918
+ return
919
+ block.pop("vod-devkit")
920
+ if not block:
921
+ cfg.pop(section, None)
922
+ else:
923
+ cfg[section] = block
924
+ path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
925
+ print(f"removed {section}.vod-devkit: {path}")
926
+ return
927
+ cli, args = None, None
928
+ if target == "hermes" and shutil.which("hermes"):
929
+ cli, args = "hermes", ["mcp", "remove", "vod-devkit"]
930
+ elif target == "codex" and shutil.which("codex"):
931
+ cli, args = "codex", ["mcp", "remove", "vod-devkit"]
932
+ if cli:
933
+ r = subprocess.run([cli, *args], capture_output=True, text=True, timeout=120)
934
+ print(f"{cli} mcp remove:", "OK" if r.returncode == 0
935
+ else (r.stderr or r.stdout).strip()[-120:])
936
+
937
+
938
+ def _remove_managed_skills(mf: dict, path: Path, target: str) -> None:
939
+ """技能摘除:hermes 目录是专属的(整目录删);其它宿主技能目录是**共享**的
940
+ (opencode ~/.config/opencode/skills 等),只摘本插件改名下的技能。
941
+ 2026-11-11 与 uninstall 共享配置收口同批修:整目录删会连带删掉用户的其它技能。"""
942
+ if target == "hermes":
943
+ if path.exists():
944
+ shutil.rmtree(path)
945
+ print("removed:", path)
946
+ return
947
+ names = {rel.split("/")[0] for rel in (mf.get("skillHashes") or {})}
948
+ removed = []
949
+ for n in sorted(names):
950
+ d = path / n
951
+ if d.is_dir():
952
+ shutil.rmtree(d)
953
+ removed.append(n)
954
+ print(f"removed skills: {removed}(共享目录保留):{path}") if removed \
955
+ else print(f"skip(无需摘除的技能):{path}")
956
+
957
+
958
+ def _cleanup_install_row(row: dict, skill_hashes: dict | None = None) -> None:
959
+ """按一条安装记录清理:MCP 条目 / 技能落点 / 宿主专属产物。
960
+
961
+ 技能名清单来自 manifest 顶层 skillHashes(各安装行共用同一份技能集合)。
962
+ """
963
+ target = row.get("target")
964
+ mf = dict(row)
965
+ mf["skillHashes"] = skill_hashes or {}
966
+ for key in ("mcpConfig", "skillsDir"):
967
+ path_s = row.get(key)
968
+ if not path_s:
969
+ continue # codex 等宿主 mcpConfig 可为 None(P0-3:无托管配置文件)
970
+ if key == "skillsDir":
971
+ _remove_managed_skills(mf, Path(path_s), target)
972
+ continue
973
+ path = Path(path_s)
974
+ # 深审 P0-3(破坏性路径一票否决):共享用户配置永不整文件删除
975
+ #(config.toml/opencode.json/codearts_cli.json/.claude.json 里有用户自己的
976
+ # provider、其它 server)。JSON 合并型宿主一律走"摘条目",与文件名无关——
977
+ # codearts_cli.json 第一版没进 _SHARED_CONFIG_NAMES,卸载把整份配置删了(实锤)。
978
+ if target in ("opencode", "codeartsdoer", "generic") or path.name in _SHARED_CONFIG_NAMES:
979
+ print(f"skip(用户配置文件,uninstall 只摘托管条目):{path}")
980
+ _remove_managed_mcp_entry(target, path)
981
+ continue
982
+ if path.exists():
983
+ shutil.rmtree(path) if path.is_dir() else path.unlink()
984
+ print("removed:", path)
985
+ # codex 摘除:remote 形态摘 MCP 条目;stdio 形态摘原生插件(best-effort)
986
+ if target == "codex":
987
+ codex = shutil.which("codex")
988
+ if codex and (row.get("transport") or "stdio") == "remote":
989
+ _remove_managed_mcp_entry("codex", Path.home() / ".codex" / "config.toml")
990
+ elif codex:
991
+ r = subprocess.run([codex, "plugin", "remove", "vod-devkit@vod-local"],
992
+ capture_output=True, text=True, timeout=120)
993
+ print("codex plugin remove:",
994
+ "OK" if r.returncode == 0 else (r.stderr or r.stdout).strip()[-120:])
995
+ # opencode 随装生成物(/vod-doctor 命令)
996
+ if target == "opencode":
1029
997
  for g in host_specs.load("opencode")["generated"]:
1030
998
  gen = Path(g["dest"])
1031
999
  if gen.exists():
1032
1000
  gen.unlink()
1033
1001
  print("removed:", gen)
1034
- # dsh 壳(D-dsh-install-1):摘插件 + 从 profile patch 移除 config 段
1002
+ # dsh 壳(D-dsh-install-1):摘插件 + 从 profile patch 移除 config 段
1003
+ if target == "dsh":
1035
1004
  dsh = shutil.which("dsh")
1036
- if dsh:
1037
- prof = (mf.get("dshProfile") or "").strip()
1038
- if prof:
1039
- subprocess.run([dsh, "plugin", "--profile", prof, "remove",
1040
- "dsh-vod-devkit"], capture_output=True, text=True)
1041
- if prof: # 无 profile 记录=没写过 patch,无需(也无法)摘除
1042
- patch = Path(host_specs.load("dsh", prof)["configPath"])
1043
- if _remove_dsh_patch_block(patch):
1044
- print("removed vod-devkit config block:", patch)
1045
- p.unlink()
1046
- print("removed:", p)
1047
- else:
1005
+ prof = (row.get("dshProfile") or "").strip()
1006
+ if dsh and prof:
1007
+ subprocess.run([dsh, "plugin", "--profile", prof, "remove",
1008
+ "dsh-vod-devkit"], capture_output=True, text=True)
1009
+ if prof: # 无 profile 记录=没写过 patch,无需(也无法)摘除
1010
+ patch_path = Path(host_specs.load("dsh", prof)["configPath"])
1011
+ from vod_mcp.host_adapters import dsh as dsh_adapter
1012
+ if dsh_adapter.remove_patch_block(patch_path):
1013
+ print("removed vod-devkit config block:", patch_path)
1014
+ # codeartsdoer / opencode / generic 共用 JSON 配置:条目已在上面按 mcpConfig 摘除
1015
+
1016
+
1017
+ def cmd_uninstall(_args):
1018
+ p = manifest_path()
1019
+ if not p.exists():
1048
1020
  print("未安装")
1021
+ return
1022
+ mf = json.loads(p.read_text(encoding="utf-8"))
1023
+ rows = mf.get("installs") or [mf] # 老 manifest(无 installs[])退化为单条
1024
+ for row in rows:
1025
+ _cleanup_install_row(row, mf.get("skillHashes"))
1026
+ # 载荷清理(D-payload-1):所有安装记录共用的副本,逐目录去重后删,再删 marker
1027
+ from vod_mcp import payload as _payload
1028
+ seen = set()
1029
+ for row in rows:
1030
+ pd = row.get("payloadDir")
1031
+ if not pd or pd in seen:
1032
+ continue
1033
+ seen.add(pd)
1034
+ if Path(pd).is_dir():
1035
+ shutil.rmtree(pd, ignore_errors=True)
1036
+ print("removed payload:", pd)
1037
+ try:
1038
+ _payload.marker_path().unlink(missing_ok=True)
1039
+ except Exception:
1040
+ pass
1041
+ p.unlink()
1042
+ print("removed:", p)
1049
1043
 
1050
1044
 
1051
1045
  def main():
@@ -1058,7 +1052,7 @@ def main():
1058
1052
  sub = ap.add_subparsers(dest="cmd", required=True)
1059
1053
  sp = sub.add_parser("install")
1060
1054
  sp.add_argument("--target", default="auto",
1061
- help="hermes|opencode|codex|dsh|auto(默认探测)")
1055
+ help="hermes|opencode|codeartsdoer|codex|dsh|generic|auto(默认探测)")
1062
1056
  sp.add_argument("--preset", default="collect", choices=list(PRESETS),
1063
1057
  help="collect=对外默认(采集者);full=内部全量")
1064
1058
  sp.add_argument("--api-base", default="http://127.0.0.1:8000")
@@ -1074,6 +1068,16 @@ def main():
1074
1068
  "禁自更新/客户机首启重生成状态)")
1075
1069
  sp.add_argument("--profile", dest="dsh_profile", default="",
1076
1070
  help="dsh 专用:profile 名(--target dsh 时必填)")
1071
+ sp.add_argument("--mcp-url", default="",
1072
+ help="远程 attach 模式:宿主 MCP 配置指向该 Streamable HTTP 端点"
1073
+ "(hermes/opencode/codex 支持;dsh 不走 MCP)")
1074
+ sp.add_argument("--mcp-token", default="",
1075
+ help="远程 attach 的身份(也可用 env VOD_MCP_TOKEN):远程面不代签身份,"
1076
+ "缺 token 拒绝安装")
1077
+ sp.add_argument("--mcp-config", default="",
1078
+ help="通用宿主(--target generic)的 MCP 配置文件路径;不给则只打印可粘贴片段")
1079
+ sp.add_argument("--skills-only", action="store_true",
1080
+ help="只装技能,不动宿主 MCP 配置(MCP 已由别处/手工注册时用)")
1077
1081
  sp.add_argument("--no-local-ledger", action="store_true",
1078
1082
  help="关闭本地提交账本(企业数据驻留要求;vod_list_submitted 将不可用)")
1079
1083
  sp.set_defaults(fn=cmd_install)
@@ -1081,6 +1085,12 @@ def main():
1081
1085
  ("verify", cmd_verify), ("update", cmd_update),
1082
1086
  ("uninstall", cmd_uninstall)):
1083
1087
  s = sub.add_parser(name)
1088
+ if name == "update":
1089
+ s.add_argument("--skip", action="store_true",
1090
+ help="跳过当前 registry latest 的提醒(只压这一个版本,"
1091
+ "下个版本仍提醒;不提供永久静音)")
1092
+ s.add_argument("--clear-skip", action="store_true",
1093
+ help="撤销版本跳过设置,恢复正常提醒")
1084
1094
  s.set_defaults(fn=fn)
1085
1095
  sub.add_parser("build-info").set_defaults(fn=lambda a: write_build_info(strict=False))
1086
1096