vod-devkit 0.5.4 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/QUICKSTART.md +47 -23
  3. package/README.en.md +7 -2
  4. package/README.md +6 -2
  5. package/bin/vod-devkit +12 -1166
  6. package/contract/tools.schema.json +1 -1
  7. package/integrations/atomcode/host.json +5 -3
  8. package/integrations/codeartsdoer/host.json +1 -2
  9. package/package.json +8 -2
  10. package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
  11. package/plugins/vod-devkit/build-info.json +3 -3
  12. package/plugins/vod-devkit/contract/tools.schema.json +446 -0
  13. package/plugins/vod-devkit/safety/policy.json +48 -0
  14. package/plugins/vod-devkit/skills/vod-feedback-collect/SKILL.md +13 -4
  15. package/plugins/vod-devkit/skills/vod-problem-classification-rules/SKILL.md +2 -1
  16. package/plugins/vod-devkit/skills/vod-scoring-rules/SKILL.md +2 -1
  17. package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
  18. package/plugins/vod-devkit/vod_mcp/__pycache__/__init__.cpython-314.pyc +0 -0
  19. package/plugins/vod-devkit/vod_mcp/__pycache__/attribution.cpython-314.pyc +0 -0
  20. package/plugins/vod-devkit/vod_mcp/__pycache__/net.cpython-314.pyc +0 -0
  21. package/plugins/vod-devkit/vod_mcp/__pycache__/paths.cpython-314.pyc +0 -0
  22. package/plugins/vod-devkit/vod_mcp/__pycache__/policy.cpython-314.pyc +0 -0
  23. package/plugins/vod-devkit/vod_mcp/__pycache__/provenance.cpython-314.pyc +0 -0
  24. package/plugins/vod-devkit/vod_mcp/__pycache__/runtime_state.cpython-314.pyc +0 -0
  25. package/plugins/vod-devkit/vod_mcp/__pycache__/skills_registry.cpython-314.pyc +0 -0
  26. package/plugins/vod-devkit/vod_mcp/__pycache__/tools.cpython-314.pyc +0 -0
  27. package/plugins/vod-devkit/vod_mcp/attribution.py +8 -8
  28. package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +3 -1
  29. package/plugins/vod-devkit/vod_mcp/host_adapters/codex.py +16 -3
  30. package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +99 -16
  31. package/plugins/vod-devkit/vod_mcp/hosts.py +3 -1
  32. package/plugins/vod-devkit/vod_mcp/net.py +251 -0
  33. package/plugins/vod-devkit/vod_mcp/packs/__pycache__/__init__.cpython-314.pyc +0 -0
  34. package/plugins/vod-devkit/vod_mcp/packs/__pycache__/collect.cpython-314.pyc +0 -0
  35. package/plugins/vod-devkit/vod_mcp/packs/__pycache__/core.cpython-314.pyc +0 -0
  36. package/plugins/vod-devkit/vod_mcp/packs/__pycache__/knowledge.cpython-314.pyc +0 -0
  37. package/plugins/vod-devkit/vod_mcp/packs/collect.py +684 -0
  38. package/plugins/vod-devkit/vod_mcp/packs/core.py +80 -0
  39. package/plugins/vod-devkit/vod_mcp/packs/knowledge.py +17 -0
  40. package/plugins/vod-devkit/vod_mcp/paths.py +38 -0
  41. package/plugins/vod-devkit/vod_mcp/payload.py +3 -1
  42. package/plugins/vod-devkit/vod_mcp/policy.py +3 -2
  43. package/plugins/vod-devkit/vod_mcp/provenance.py +3 -2
  44. package/plugins/vod-devkit/vod_mcp/remote_app.py +25 -0
  45. package/plugins/vod-devkit/vod_mcp/runtime_state.py +324 -0
  46. package/plugins/vod-devkit/vod_mcp/server.py +10 -7
  47. package/plugins/vod-devkit/vod_mcp/skills_registry.py +11 -9
  48. package/plugins/vod-devkit/vod_mcp/tools.py +23 -1300
  49. package/plugins/vod-devkit/vod_mcp/transport_remote.py +68 -8
  50. package/plugins/vod-devkit/vod_mcp/update_check.py +1 -1
  51. package/skills/vod-feedback-collect/SKILL.md +13 -4
  52. package/skills/vod-problem-classification-rules/SKILL.md +2 -1
  53. package/skills/vod-scoring-rules/SKILL.md +2 -1
  54. package/vod_mcp/__init__.py +1 -1
  55. package/vod_mcp/attribution.py +8 -8
  56. package/vod_mcp/host_adapters/__pycache__/__init__.cpython-39.pyc +0 -0
  57. package/vod_mcp/host_adapters/__pycache__/atomcode.cpython-39.pyc +0 -0
  58. package/vod_mcp/host_adapters/__pycache__/base.cpython-314.pyc +0 -0
  59. package/vod_mcp/host_adapters/__pycache__/base.cpython-39.pyc +0 -0
  60. package/vod_mcp/host_adapters/__pycache__/codearts.cpython-39.pyc +0 -0
  61. package/vod_mcp/host_adapters/__pycache__/codeartswork.cpython-39.pyc +0 -0
  62. package/vod_mcp/host_adapters/__pycache__/codex.cpython-314.pyc +0 -0
  63. package/vod_mcp/host_adapters/__pycache__/codex.cpython-39.pyc +0 -0
  64. package/vod_mcp/host_adapters/__pycache__/codex_desktop.cpython-39.pyc +0 -0
  65. package/vod_mcp/host_adapters/__pycache__/dsh.cpython-39.pyc +0 -0
  66. package/vod_mcp/host_adapters/__pycache__/generic.cpython-39.pyc +0 -0
  67. package/vod_mcp/host_adapters/__pycache__/hermes.cpython-314.pyc +0 -0
  68. package/vod_mcp/host_adapters/__pycache__/hermes.cpython-39.pyc +0 -0
  69. package/vod_mcp/host_adapters/__pycache__/opencode.cpython-39.pyc +0 -0
  70. package/vod_mcp/host_adapters/__pycache__/workbuddy.cpython-39.pyc +0 -0
  71. package/vod_mcp/host_adapters/base.py +3 -1
  72. package/vod_mcp/host_adapters/codex.py +16 -3
  73. package/vod_mcp/host_adapters/hermes.py +99 -16
  74. package/vod_mcp/hosts.py +3 -1
  75. package/vod_mcp/net.py +251 -0
  76. package/vod_mcp/packs/__pycache__/__init__.cpython-314.pyc +0 -0
  77. package/vod_mcp/packs/__pycache__/__init__.cpython-39.pyc +0 -0
  78. package/vod_mcp/packs/__pycache__/collect.cpython-314.pyc +0 -0
  79. package/vod_mcp/packs/__pycache__/collect.cpython-39.pyc +0 -0
  80. package/vod_mcp/packs/__pycache__/core.cpython-314.pyc +0 -0
  81. package/vod_mcp/packs/__pycache__/core.cpython-39.pyc +0 -0
  82. package/vod_mcp/packs/__pycache__/knowledge.cpython-314.pyc +0 -0
  83. package/vod_mcp/packs/__pycache__/knowledge.cpython-39.pyc +0 -0
  84. package/vod_mcp/packs/collect.py +684 -0
  85. package/vod_mcp/packs/core.py +80 -0
  86. package/vod_mcp/packs/knowledge.py +17 -0
  87. package/vod_mcp/paths.py +38 -0
  88. package/vod_mcp/payload.py +3 -1
  89. package/vod_mcp/policy.py +3 -2
  90. package/vod_mcp/provenance.py +3 -2
  91. package/vod_mcp/remote_app.py +25 -0
  92. package/vod_mcp/runtime_state.py +324 -0
  93. package/vod_mcp/server.py +10 -7
  94. package/vod_mcp/skills_registry.py +11 -9
  95. package/vod_mcp/tools.py +23 -1300
  96. package/vod_mcp/transport_remote.py +68 -8
  97. package/vod_mcp/update_check.py +1 -1
  98. package/vodkit_cli/__init__.py +10 -0
  99. package/vodkit_cli/__pycache__/__init__.cpython-314.pyc +0 -0
  100. package/vodkit_cli/__pycache__/__init__.cpython-39.pyc +0 -0
  101. package/vodkit_cli/__pycache__/cli.cpython-314.pyc +0 -0
  102. package/vodkit_cli/__pycache__/cli.cpython-39.pyc +0 -0
  103. package/vodkit_cli/__pycache__/common.cpython-314.pyc +0 -0
  104. package/vodkit_cli/__pycache__/common.cpython-39.pyc +0 -0
  105. package/vodkit_cli/__pycache__/doctor.cpython-314.pyc +0 -0
  106. package/vodkit_cli/__pycache__/doctor.cpython-39.pyc +0 -0
  107. package/vodkit_cli/__pycache__/install.cpython-314.pyc +0 -0
  108. package/vodkit_cli/__pycache__/install.cpython-39.pyc +0 -0
  109. package/vodkit_cli/__pycache__/remote.cpython-314.pyc +0 -0
  110. package/vodkit_cli/__pycache__/remote.cpython-39.pyc +0 -0
  111. package/vodkit_cli/__pycache__/uninstall.cpython-314.pyc +0 -0
  112. package/vodkit_cli/__pycache__/uninstall.cpython-39.pyc +0 -0
  113. package/vodkit_cli/__pycache__/update.cpython-314.pyc +0 -0
  114. package/vodkit_cli/__pycache__/update.cpython-39.pyc +0 -0
  115. package/vodkit_cli/cli.py +86 -0
  116. package/vodkit_cli/common.py +254 -0
  117. package/vodkit_cli/doctor.py +269 -0
  118. package/vodkit_cli/install.py +260 -0
  119. package/vodkit_cli/remote.py +200 -0
  120. package/vodkit_cli/uninstall.py +161 -0
  121. package/vodkit_cli/update.py +45 -0
  122. /package/plugins/vod-devkit/vod_mcp/{packs.py → packs/__init__.py} +0 -0
  123. /package/vod_mcp/{packs.py → packs/__init__.py} +0 -0
@@ -21,8 +21,11 @@ devkit 的契约(mcp-server-remote.ts + test/remote-mcp-server.test.ts 实测
21
21
  """
22
22
  import asyncio
23
23
  import json
24
+ import os
24
25
  import sys
25
26
  import threading
27
+
28
+ from vod_mcp import net, paths
26
29
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
30
 
28
31
  DEFAULT_HOST = "127.0.0.1"
@@ -30,6 +33,44 @@ DEFAULT_PORT = 9528
30
33
  MAX_BODY = 4 * 1024 * 1024
31
34
  LOOPBACK = ("127.0.0.1", "localhost", "::1")
32
35
 
36
+ # 载荷自校验缓存:远程面是长驻无鉴权服务,被改过的服务端载荷要当场拒绝服务,
37
+ # 不能等运维跑 doctor 才发现(devkit 的每请求 verifySkillTree 同思路)。
38
+ # TTL 缓存避免每个请求都做一遍 sha256 全集(40+ 文件)。
39
+ _PAYLOAD_GUARD = {"at": 0.0, "sig": None, "problems": []}
40
+ _PAYLOAD_GUARD_TTL = 30.0
41
+
42
+
43
+ def payload_problems(force: bool = False) -> list:
44
+ """远程面载荷完整性检查(载荷目录不存在/被改 → 非空列表)。
45
+
46
+ 只校验"载荷副本"形态:stdio/仓内直跑没有 payload.json,返回空(不误伤)。
47
+ """
48
+ import time as _t
49
+ from pathlib import Path
50
+ from vod_mcp import payload as _pl
51
+ _P = Path
52
+ # 显式 env 优先(安装期注入),否则按自身所在树推断——*不许* import
53
+ # host_adapters:它的 __init__ 会连带 import 各宿主适配模块,而载荷副本不含
54
+ # integrations/(2026-11-12 实锤:请求线程 KeyError → 每个请求 500)。
55
+ env_dir = (os.environ.get("VOD_PAYLOAD_DIR") or "").strip()
56
+ d = _P(env_dir) if env_dir else None
57
+ if d is None:
58
+ # 从载荷副本直接起来的服务(entry = <payload>/vod_mcp/server.py)没有
59
+ # install 期注入的 payload_dir —— 用自身所在树推断:载荷根里有 payload.json
60
+ # 就说明"我就是那份副本",必须自校验(否则被改的副本会一直对外服务)。
61
+ root = _P(paths.ROOT)
62
+ d = root if (root / "payload.json").exists() else None
63
+ if d is None:
64
+ return []
65
+ meta = _P(d) / "payload.json"
66
+ sig = (str(meta), meta.stat().st_mtime if meta.exists() else 0.0)
67
+ now = _t.time()
68
+ if not force and _PAYLOAD_GUARD["sig"] == sig and now - _PAYLOAD_GUARD["at"] < _PAYLOAD_GUARD_TTL:
69
+ return list(_PAYLOAD_GUARD["problems"])
70
+ problems = _pl.verify(_P(d))
71
+ _PAYLOAD_GUARD.update({"at": now, "sig": sig, "problems": list(problems)})
72
+ return problems
73
+
33
74
 
34
75
  class RemoteRuntime:
35
76
  """持有 asyncio 事件循环 + SDK session manager 的生命周期。"""
@@ -69,6 +110,13 @@ class RemoteRuntime:
69
110
  逐块而不是攒全再写:devkit 的 shell 也是 `for await (chunk of
70
111
  response.body) res.write(chunk)`——SSE 这种长响应攒全再写等于把流式
71
112
  语义废掉(客户端一个字节都看不到,直到响应结束)。
113
+
114
+ 身份传播(2026-11-13 真机实锤修复):contextvars 不跨线程——do_POST
115
+ 在 HTTP 线程 set 的 _REQ_KEY/_SERVER_FACE 到不了事件循环线程的
116
+ on_call_tool(submit 的 -32012 之所以还能触发,是走运的本地态分支)。
117
+ 修法:把 key/face 作为参数传入,投递协程体内 set——run_coroutine_threadsafe
118
+ 在 loop 线程为 run() 建任务,任务继承创建时刻的 context,体内 set 即对
119
+ handle_request 派生的整个协程链(含 asyncio.to_thread 复制)可见。
72
120
  """
73
121
  state = {"body_sent": False}
74
122
 
@@ -90,9 +138,14 @@ class RemoteRuntime:
90
138
  sink.body(chunk)
91
139
 
92
140
  async def run():
141
+ # 协程体内 set:见 request() docstring 的身份传播修复说明
142
+ tok_key = net._REQ_KEY.set(scope.get("x_vod_key") or None)
143
+ tok_face = net._SERVER_FACE.set(True)
93
144
  try:
94
145
  await self.manager.handle_request(scope, receive, send)
95
146
  finally:
147
+ net._SERVER_FACE.reset(tok_face)
148
+ net._REQ_KEY.reset(tok_key)
96
149
  sink.end()
97
150
 
98
151
  fut = asyncio.run_coroutine_threadsafe(run(), self._loop)
@@ -250,23 +303,30 @@ class _Handler(BaseHTTPRequestHandler):
250
303
  if isinstance(message, dict) and "id" not in message:
251
304
  self._empty(202)
252
305
  return
306
+ # 服务端载荷自校验:被改/缺文件的载荷不许继续对外服务
307
+ problems = payload_problems()
308
+ if problems:
309
+ self._json(503, {"jsonrpc": "2.0", "id": message.get("id") if isinstance(message, dict) else None,
310
+ "error": {"code": -32603,
311
+ "message": "服务端载荷校验未通过(拒绝服务):"
312
+ + ";".join(problems[:5])}})
313
+ return
314
+
253
315
  raw_auth = (self.headers.get("Authorization") or "").strip()
254
316
  key = raw_auth[7:].strip() if raw_auth.lower().startswith("bearer ") else ""
255
317
 
256
- from vod_mcp import tools
318
+ # 身份经 scope 传递(x_vod_key),由 RemoteRuntime.request 在事件循环线程
319
+ # 的协程体内 set _REQ_KEY/_SERVER_FACE——HTTP 线程直接 set 的 contextvar
320
+ # 过不了 run_coroutine_threadsafe 的线程边界(2026-11-13 真机实锤)。
321
+ scope = _scope(self, body)
322
+ scope["x_vod_key"] = key
257
323
  sink = _StreamSink(self)
258
- tok_key = tools._REQ_KEY.set(key or None)
259
- tok_face = tools._SERVER_FACE.set(True)
260
324
  try:
261
- self.server.runtime.request(_scope(self, body), body, sink)
325
+ self.server.runtime.request(scope, body, sink)
262
326
  except Exception as e: # 传输层异常:能答就答 500,已经流出去就断连
263
327
  if not sink.started:
264
328
  self._json(500, {"jsonrpc": "2.0", "id": None,
265
329
  "error": {"code": -32603, "message": str(e)}})
266
- return
267
- finally:
268
- tools._SERVER_FACE.reset(tok_face)
269
- tools._REQ_KEY.reset(tok_key)
270
330
 
271
331
 
272
332
  def serve(host: str, port: int) -> int:
@@ -52,7 +52,7 @@ def _version_tuple(v: str) -> tuple:
52
52
 
53
53
 
54
54
  def check(params: dict | None = None) -> dict:
55
- from vod_mcp import __version__, tools
55
+ from vod_mcp import __version__, runtime_state as tools
56
56
  params = params or {}
57
57
  dismiss = bool(params.get("dismiss"))
58
58
  skip = bool(params.get("skip"))
@@ -0,0 +1,10 @@
1
+ """installer CLI 实现包(bin/vod-devkit 是入口薄壳)。
2
+
3
+ 对外稳定面(入口与测试都依赖,改动视为破坏性):
4
+ main / PRESETS / detect_targets / build_info / write_build_info
5
+ """
6
+ from vodkit_cli.cli import main
7
+ from vodkit_cli.common import PRESETS, build_info, write_build_info
8
+ from vodkit_cli.install import detect_targets
9
+
10
+ __all__ = ["main", "PRESETS", "detect_targets", "build_info", "write_build_info"]
@@ -0,0 +1,86 @@
1
+ """CLI 装配:argparse 子命令表 + serve 直通 + 分派。"""
2
+ import argparse
3
+ import os
4
+ import sys
5
+
6
+ from vodkit_cli import common, doctor, install, uninstall, update
7
+
8
+
9
+ def main():
10
+ # `serve` 后的参数整体透传给 MCP server(argparse 的 REMAINDER 会把
11
+ # --transport 当成未知参数拦下,devkit 的二进制本身就是 server,同形处理)
12
+ if len(sys.argv) > 1 and sys.argv[1] == "serve":
13
+ # 显式声明这份副本的根(paths.py 读 VOD_DEVKIT_ROOT):插件/载荷根
14
+ # 不总是"CLI 所在包根",隐式相对深度正是此前副本装载失败的原因。
15
+ os.execve(sys.executable,
16
+ [sys.executable, str(common.ROOT / "vod_mcp" / "server.py"), *sys.argv[2:]],
17
+ {**os.environ, "VOD_DEVKIT_ROOT": str(common.ROOT)})
18
+ ap = argparse.ArgumentParser(prog="vod-devkit")
19
+ sub = ap.add_subparsers(dest="cmd", required=True)
20
+ sp = sub.add_parser("install")
21
+ sp.add_argument("--target", default="auto",
22
+ help="hermes|opencode|codeartsdoer|codeartswork|codex|codex-desktop|dsh|workbuddy|atomcode|generic|auto(默认探测)")
23
+ sp.add_argument("--preset", default="collect", choices=list(common.PRESETS),
24
+ help="collect=对外默认(采集者);full=内部全量")
25
+ sp.add_argument("--api-base", default="http://127.0.0.1:8000")
26
+ sp.add_argument("--java-api-base", default=None,
27
+ help="VOD 平台地址(缺省=https://vod-dev.topxtopx.com,勿用回环默认)")
28
+ sp.add_argument("--packs", default="", help="显式覆盖 preset(逗号分隔)")
29
+ sp.add_argument("--ack-suspension", action="store_true",
30
+ help="确认解除 codex 采集熔断(恢复门禁逃生口,D-codex-circuit-breaker-1)")
31
+ sp.add_argument("--product", default="",
32
+ help="归因绑定:本 agent 服务的产品(codearts/aishell 等;采集反馈默认归属)")
33
+ sp.add_argument("--distribution", default="devkit", choices=["devkit", "preset"],
34
+ help="devkit=开发/运维自装(默认);preset=产品随 agent 分发(禁 key 随包/"
35
+ "禁自更新/客户机首启重生成状态)")
36
+ sp.add_argument("--profile", dest="dsh_profile", default="",
37
+ help="dsh 专用:profile 名(--target dsh 时必填)")
38
+ sp.add_argument("--mcp-url", default="",
39
+ help="远程 attach 模式:宿主 MCP 配置指向该 Streamable HTTP 端点"
40
+ "(hermes/opencode/codex 支持;dsh 不走 MCP)")
41
+ sp.add_argument("--mcp-token", default="",
42
+ help="远程 attach 的身份(也可用 env VOD_MCP_TOKEN):远程面不代签身份,"
43
+ "缺 token 拒绝安装")
44
+ sp.add_argument("--mcp-config", default="",
45
+ help="通用宿主(--target generic)的 MCP 配置文件路径;不给则只打印可粘贴片段")
46
+ sp.add_argument("--skills-only", action="store_true",
47
+ help="只装技能,不动宿主 MCP 配置(MCP 已由别处/手工注册时用)")
48
+ sp.add_argument("--no-local-ledger", action="store_true",
49
+ help="关闭本地提交账本(企业数据驻留要求;vod_list_submitted 将不可用)")
50
+ sp.set_defaults(fn=install.cmd_install)
51
+ for name, fn in (("status", doctor.cmd_status), ("doctor", doctor.cmd_doctor),
52
+ ("verify", doctor.cmd_verify), ("update", update.cmd_update),
53
+ ("uninstall", uninstall.cmd_uninstall),
54
+ ("explain", doctor.cmd_explain),
55
+ ("detect", doctor.cmd_detect)):
56
+ s = sub.add_parser(name)
57
+ if name == "explain":
58
+ s.add_argument("text", nargs="+", help="错误文案或错误码(-32010 等)")
59
+ if name == "detect":
60
+ s.add_argument("--path", default="", help="要识别的项目目录(默认当前目录)")
61
+ if name == "update":
62
+ s.add_argument("--skip", action="store_true",
63
+ help="跳过当前 registry latest 的提醒(只压这一个版本,"
64
+ "下个版本仍提醒;不提供永久静音)")
65
+ s.add_argument("--clear-skip", action="store_true",
66
+ help="撤销版本跳过设置,恢复正常提醒")
67
+ s.set_defaults(fn=fn)
68
+ sub.add_parser("build-info").set_defaults(fn=lambda a: common.write_build_info(strict=False))
69
+
70
+ def _serve(a):
71
+ """MCP server 入口(codex 插件 .mcp.json 与远程面共用)。
72
+
73
+ 透传参数:`vod-devkit serve --transport remote --port 9528` 即起 HTTP 面
74
+ (与 huaweicloud-devkit 的 `--transport remote` 同形)。
75
+ """
76
+ extra = list(getattr(a, "server_args", []) or [])
77
+ os.execve(sys.executable,
78
+ [sys.executable, str(common.ROOT / "vod_mcp" / "server.py"), *extra],
79
+ {**os.environ, "VOD_DEVKIT_ROOT": str(common.ROOT)})
80
+ sp_serve = sub.add_parser("serve", help="启动 MCP server(默认 stdio;"
81
+ "--transport remote 起 Streamable HTTP)")
82
+ sp_serve.add_argument("server_args", nargs=argparse.REMAINDER,
83
+ help="透传给 vod_mcp.server(如 --transport remote --port 9528)")
84
+ sp_serve.set_defaults(fn=_serve)
85
+ args = ap.parse_args()
86
+ args.fn(args)
@@ -0,0 +1,254 @@
1
+ """安装器公共件:根定位、版本烧录、manifest 名册、技能指纹、分发形态位。
2
+
3
+ 从 bin/vod-devkit 拆出(F8):这些都跨多个子命令使用,属于"装配底座"。
4
+ """
5
+ import datetime
6
+ import json
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from vod_mcp import hosts as host_specs
13
+
14
+
15
+ ROOT = Path(__file__).resolve().parent.parent
16
+
17
+
18
+ _HERMES_SPEC = host_specs.load("hermes")
19
+
20
+
21
+ HERMES_MCP_DIR = Path(_HERMES_SPEC["configPath"]).parent # 约定:写入前打印供确认
22
+
23
+
24
+ HERMES_SKILLS_DIR = Path(_HERMES_SPEC["skillsDir"])
25
+
26
+
27
+ def git_sha(strict: bool) -> str | None:
28
+ dirty = bool(subprocess.run(["git", "status", "--porcelain"], cwd=ROOT,
29
+ capture_output=True).stdout.strip())
30
+ if strict and dirty:
31
+ print("工作区不干净,拒绝构建(构建纪律)", file=sys.stderr)
32
+ sys.exit(1)
33
+ sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT,
34
+ capture_output=True, text=True).stdout.strip()
35
+ return sha or None
36
+
37
+
38
+ def _safe_remote(url: str) -> str:
39
+ """凭据脱敏:oauth2:xxx@ / https://user:pass@ 一律剥离。"""
40
+ import re as _re
41
+ return _re.sub(r"(https?://)([^@/]+@)", r"\1", url)
42
+
43
+
44
+ def build_info(strict: bool = False) -> dict:
45
+ from vod_mcp import __version__
46
+ remote = subprocess.run(["git", "remote", "get-url", "origin"], cwd=ROOT,
47
+ capture_output=True, text=True).stdout.strip()
48
+ return {
49
+ "version": __version__,
50
+ "commitSha": git_sha(strict),
51
+ "builtAt": datetime.datetime.now().isoformat(timespec="seconds"),
52
+ "sourceRemote": _safe_remote(remote) if remote else None,
53
+ }
54
+
55
+
56
+ def write_build_info(strict: bool):
57
+ info = build_info(strict)
58
+ # 隔离跑法(宿主矩阵/CI 用例)不许改真实仓的 build-info:它会被重烧成当前
59
+ # HEAD,而包内副本停在发版提交 → 结构门禁"根/包内不一致"假红(本轮实锤)。
60
+ if os.environ.get("VOD_DEVKIT_NO_BUILD_INFO"):
61
+ print("build-info.json: 跳过写入(VOD_DEVKIT_NO_BUILD_INFO)")
62
+ return
63
+ (ROOT / "build-info.json").write_text(
64
+ json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8")
65
+ print("build-info.json:", json.dumps(info, ensure_ascii=False))
66
+
67
+
68
+ def manifest_path() -> Path:
69
+ """安装名册位置:默认仓根;VOD_DEVKIT_MANIFEST 可覆盖(多安装根/隔离测试)。
70
+
71
+ 契约上 manifest 落在"安装器所在的仓根"——npx 缓存下的仓被清掉时名册一起消失,
72
+ 所以 doctor/uninstall 只在同一个仓上下文里自洽;需要另置一份或多份时用该 env。
73
+ """
74
+ override = (os.environ.get("VOD_DEVKIT_MANIFEST") or "").strip()
75
+ return Path(override) if override else ROOT / "install-manifest.json"
76
+
77
+
78
+ PRESETS = {
79
+ # 对外默认:开发者=反馈采集者(workflow 不进对外默认集)
80
+ "collect": "core,collect",
81
+ # 内部:运营/可信第三方全量。2026-11-06 修正(深审 P0-2):原值
82
+ # "core,workflow,kb,collect" 与运行期 ALL_PACKS=(core,collect,knowledge)
83
+ # 命名漂移——workflow 包已随"运营归 vod-system 前端"净删、kb 是
84
+ # knowledge 的旧称,按原值安装 workflow/kb 被静默丢弃(安装口说装了
85
+ # 运行口不认=挪到别处而非消除)
86
+ "full": "core,collect,knowledge",
87
+ }
88
+
89
+
90
+ def _skill_installs(manifest_path: Path, extra_dirs) -> list:
91
+ """多宿主技能落点并集(名册对账):manifest 按「最近一次安装」覆盖会
92
+ 互相冲掉落点(实锤:codex 装完 opencode 落点消失),按 host+dir
93
+ 去重保留历史落点。"""
94
+ import json as _json
95
+ import os
96
+ home = str(Path.home()) + os.sep
97
+ prev = {}
98
+ if manifest_path.exists():
99
+ try:
100
+ for si in _json.loads(manifest_path.read_text(encoding="utf-8")).get("skillInstalls") or []:
101
+ d = si.get("dir") or ""
102
+ # 只保留「当前 HOME 之下且目录真实存在」的落点——隔离环境
103
+ # (fake-home 测试)不吞真实 HOME 的历史落点,卸载残留自动剪枝
104
+ if d.startswith(home) and Path(d).is_dir():
105
+ prev[(si["host"], d)] = si
106
+ except Exception:
107
+ pass
108
+ for h, d in [("hermes", HERMES_SKILLS_DIR)] + list(extra_dirs or []):
109
+ if d is not None:
110
+ prev[(h, str(d))] = {"host": h, "dir": str(d)}
111
+ return sorted(prev.values(), key=lambda x: (x["host"], x["dir"]))
112
+
113
+
114
+ def _dir_hashes(base: Path) -> dict:
115
+ """对既有目录树计算相对 sha256 指纹(roster 对账用)。"""
116
+ import hashlib
117
+ out = {}
118
+ for skill in sorted(Path(base).iterdir()):
119
+ if skill.is_dir():
120
+ for f in sorted(skill.rglob("*")):
121
+ if f.is_file():
122
+ out[f"{skill.name}/{f.relative_to(skill)}"] = (
123
+ hashlib.sha256(f.read_bytes()).hexdigest())
124
+ return out
125
+
126
+
127
+ def _skill_hashes() -> dict:
128
+ """技能拷贝件指纹(D-drift-lock):安装时记录 sha256,verify/doctor 比对
129
+ ——拷贝件与安装产物漂移可检(vendor 规则漂移实锤的针对性防线)。"""
130
+ import hashlib
131
+ out = {}
132
+ for entry in sorted((ROOT / "skills").iterdir()):
133
+ if entry.is_dir():
134
+ for f in sorted(entry.rglob("*")):
135
+ if f.is_file():
136
+ rel = f"{entry.name}/{f.relative_to(entry)}"
137
+ out[rel] = hashlib.sha256(f.read_bytes()).hexdigest()
138
+ return out
139
+
140
+
141
+ def _drifted_skills(manifest: dict) -> list:
142
+ """比对 skillsDir 拷贝件与 manifest.skillHashes,返回漂移文件清单。"""
143
+ import hashlib
144
+ base = Path(manifest["skillsDir"])
145
+ drifted = []
146
+ for rel, sha in (manifest.get("skillHashes") or {}).items():
147
+ f = base / rel
148
+ if not f.exists():
149
+ drifted.append(f"{rel}(缺失)")
150
+ elif hashlib.sha256(f.read_bytes()).hexdigest() != sha:
151
+ drifted.append(f"{rel}(内容被改)")
152
+ return drifted
153
+
154
+
155
+ def _read_manifest() -> dict:
156
+ p = manifest_path()
157
+ if not p.exists():
158
+ return {}
159
+ try:
160
+ return json.loads(p.read_text(encoding="utf-8"))
161
+ except Exception:
162
+ return {}
163
+
164
+
165
+ def _install_rows(prev: dict, row: dict) -> list:
166
+ """按 target 去重的安装行(D-installs-1):一个 manifest 记全部宿主安装。
167
+
168
+ 起因(结构债):顶电平字段只记「最近一次安装」,装 hermes 再装 codearts 后
169
+ uninstall 只清最后一个宿主的 MCP 条目,另一台宿主的配置永远留在那。
170
+ """
171
+ rows = [r for r in (prev.get("installs") or []) if r.get("target") != row["target"]]
172
+ rows.append(row)
173
+ return sorted(rows, key=lambda r: r.get("installedAt") or "")
174
+
175
+
176
+ def _write_install_manifest(args, target, packs, bound_product, mcp_conf,
177
+ extra_dirs, transport: str = "stdio",
178
+ mcp_url: str = "", payload_dir=None) -> None:
179
+ """manifest 段:落安装名册(版本/来源/归因/落点指纹),并给出 key
180
+ 配置提示。名册对账口径见各字段注释(原 install.cmd_install 尾段,整段平移)。"""
181
+ bi = json.loads((ROOT / "build-info.json").read_text(encoding="utf-8"))
182
+ manifest = {
183
+ "version": bi["version"],
184
+ "source": {"type": "git", "remote": bi["sourceRemote"],
185
+ "ref": subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"],
186
+ cwd=ROOT, capture_output=True, text=True).stdout.strip(),
187
+ "commitSha": bi["commitSha"]},
188
+ "target": target,
189
+ # 传输形态(D-attach-1):stdio=宿主本机拉起进程;remote=指向单独部署的
190
+ # 远程端点;skills-only=只装技能(MCP 由别处注册)
191
+ "transport": transport,
192
+ "mcpUrl": mcp_url or None,
193
+ "installedAt": datetime.datetime.now().isoformat(timespec="seconds"),
194
+ "preset": args.preset,
195
+ "distribution": getattr(args, "distribution", "devkit"),
196
+ "product": bound_product,
197
+ "packs": packs,
198
+ "dshProfile": (getattr(args, "dsh_profile", "") or "").strip() or None,
199
+ # dsh 修复用(S60/A 止血):patch 块被 dsh 运行时序列化冲掉后,
200
+ # doctor 可凭 product/apiBase 重建(块内容=安装期静态部署值)
201
+ "apiBase": (getattr(args, "java_api_base", "") or "") or None,
202
+ "mcpConfig": (str(mcp_conf) if mcp_conf else None),
203
+ "skillsDir": str(HERMES_SKILLS_DIR),
204
+ # 名册对账(huaweicloud-devkit doctor 模式借鉴,2026-11-06):
205
+ # 每个原生技能落点的独立指纹——漏装/漂移可被 doctor 逐落点抓出,
206
+ # 不再只盯 hermes 单目录(opencode 漏拷静默失效的针对性防线)。
207
+ # 多宿主并集合并:manifest 按「最近一次安装」覆盖会互相冲掉落点
208
+ # (实锤:codex 装完 opencode 落点消失),按 host+dir 去重保留历史
209
+ "skillInstalls": _skill_installs(manifest_path(), extra_dirs),
210
+ "skillHashes": _skill_hashes(),
211
+ # 载荷副本(D-payload-1):宿主入口指向这里,而不是仓/npx 缓存路径
212
+ "payloadDir": str(payload_dir) if payload_dir else None,
213
+ }
214
+ row = {k: manifest[k] for k in
215
+ ("target", "transport", "mcpUrl", "installedAt", "product", "packs",
216
+ "dshProfile", "apiBase", "mcpConfig", "skillsDir", "payloadDir")}
217
+ row["version"] = manifest["version"]
218
+ row["commitSha"] = manifest["source"]["commitSha"]
219
+ row["skillInstalls"] = [si for si in manifest["skillInstalls"]
220
+ if si["host"] == target]
221
+ prev = _read_manifest()
222
+ manifest["installs"] = _install_rows(prev, row)
223
+ manifest_path().write_text(json.dumps(manifest, ensure_ascii=False, indent=2),
224
+ encoding="utf-8")
225
+ print("installed:", json.dumps(manifest, ensure_ascii=False, indent=2))
226
+ missing = [k for k in ("VOD_JAVA_API_KEY",) if
227
+ not os.environ.get(k) and not _runtime_cfg_read().get("java_key")]
228
+ if missing and transport == "stdio":
229
+ print(f"提示:{missing} 未配置——首次提交将自动申请零字段匿名令牌(无需配置)")
230
+ elif transport == "remote":
231
+ print("远程形态提示:身份随请求头走(token 已由宿主配置承载);"
232
+ "本机 runtime.json 的匿名链不参与远程提交")
233
+
234
+
235
+ def _runtime_cfg_read() -> dict:
236
+ p = ROOT / "vod_mcp" / "runtime.json"
237
+ if p.exists():
238
+ try:
239
+ return json.loads(p.read_text(encoding="utf-8"))
240
+ except Exception:
241
+ return {}
242
+ return {}
243
+
244
+
245
+ def _distribution() -> str:
246
+ """分发形态位(D-key-guard-3):install --distribution 写入,构建期定死。
247
+ devkit=开发/运维形态(自装自管);preset=产品随 agent 分发(客户机只读)。"""
248
+ p = manifest_path()
249
+ if not p.exists():
250
+ return "devkit"
251
+ try:
252
+ return json.loads(p.read_text(encoding="utf-8")).get("distribution", "devkit")
253
+ except Exception:
254
+ return "devkit"