vod-devkit 0.5.5 → 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.
- package/CHANGELOG.md +32 -0
- package/QUICKSTART.md +47 -23
- package/README.en.md +7 -2
- package/README.md +6 -2
- package/bin/vod-devkit +12 -1164
- package/contract/tools.schema.json +1 -1
- package/package.json +8 -2
- package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
- package/plugins/vod-devkit/build-info.json +3 -3
- package/plugins/vod-devkit/contract/tools.schema.json +446 -0
- package/plugins/vod-devkit/safety/policy.json +48 -0
- package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
- package/plugins/vod-devkit/vod_mcp/__pycache__/__init__.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/attribution.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/net.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/paths.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/policy.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/provenance.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/runtime_state.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/skills_registry.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/__pycache__/tools.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +3 -1
- package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +88 -11
- package/plugins/vod-devkit/vod_mcp/hosts.py +3 -1
- package/plugins/vod-devkit/vod_mcp/net.py +251 -0
- package/plugins/vod-devkit/vod_mcp/packs/__pycache__/__init__.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/packs/__pycache__/collect.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/packs/__pycache__/core.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/packs/__pycache__/knowledge.cpython-314.pyc +0 -0
- package/plugins/vod-devkit/vod_mcp/packs/collect.py +684 -0
- package/plugins/vod-devkit/vod_mcp/packs/core.py +80 -0
- package/plugins/vod-devkit/vod_mcp/packs/knowledge.py +17 -0
- package/plugins/vod-devkit/vod_mcp/paths.py +38 -0
- package/plugins/vod-devkit/vod_mcp/payload.py +3 -1
- package/plugins/vod-devkit/vod_mcp/policy.py +3 -2
- package/plugins/vod-devkit/vod_mcp/provenance.py +3 -2
- package/plugins/vod-devkit/vod_mcp/runtime_state.py +324 -0
- package/plugins/vod-devkit/vod_mcp/server.py +10 -7
- package/plugins/vod-devkit/vod_mcp/skills_registry.py +5 -4
- package/plugins/vod-devkit/vod_mcp/tools.py +23 -1298
- package/plugins/vod-devkit/vod_mcp/transport_remote.py +21 -9
- package/plugins/vod-devkit/vod_mcp/update_check.py +1 -1
- package/vod_mcp/__init__.py +1 -1
- package/vod_mcp/host_adapters/__pycache__/__init__.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/atomcode.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/base.cpython-314.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/base.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/codearts.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/codeartswork.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/codex.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/codex_desktop.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/dsh.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/generic.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/hermes.cpython-314.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/hermes.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/opencode.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/__pycache__/workbuddy.cpython-39.pyc +0 -0
- package/vod_mcp/host_adapters/base.py +3 -1
- package/vod_mcp/host_adapters/hermes.py +88 -11
- package/vod_mcp/hosts.py +3 -1
- package/vod_mcp/net.py +251 -0
- package/vod_mcp/packs/__pycache__/__init__.cpython-314.pyc +0 -0
- package/vod_mcp/packs/__pycache__/__init__.cpython-39.pyc +0 -0
- package/vod_mcp/packs/__pycache__/collect.cpython-314.pyc +0 -0
- package/vod_mcp/packs/__pycache__/collect.cpython-39.pyc +0 -0
- package/vod_mcp/packs/__pycache__/core.cpython-314.pyc +0 -0
- package/vod_mcp/packs/__pycache__/core.cpython-39.pyc +0 -0
- package/vod_mcp/packs/__pycache__/knowledge.cpython-314.pyc +0 -0
- package/vod_mcp/packs/__pycache__/knowledge.cpython-39.pyc +0 -0
- package/vod_mcp/packs/collect.py +684 -0
- package/vod_mcp/packs/core.py +80 -0
- package/vod_mcp/packs/knowledge.py +17 -0
- package/vod_mcp/paths.py +38 -0
- package/vod_mcp/payload.py +3 -1
- package/vod_mcp/policy.py +3 -2
- package/vod_mcp/provenance.py +3 -2
- package/vod_mcp/runtime_state.py +324 -0
- package/vod_mcp/server.py +10 -7
- package/vod_mcp/skills_registry.py +5 -4
- package/vod_mcp/tools.py +23 -1298
- package/vod_mcp/transport_remote.py +21 -9
- package/vod_mcp/update_check.py +1 -1
- package/vodkit_cli/__init__.py +10 -0
- package/vodkit_cli/__pycache__/__init__.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/__init__.cpython-39.pyc +0 -0
- package/vodkit_cli/__pycache__/cli.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/cli.cpython-39.pyc +0 -0
- package/vodkit_cli/__pycache__/common.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/common.cpython-39.pyc +0 -0
- package/vodkit_cli/__pycache__/doctor.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/doctor.cpython-39.pyc +0 -0
- package/vodkit_cli/__pycache__/install.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/install.cpython-39.pyc +0 -0
- package/vodkit_cli/__pycache__/remote.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/remote.cpython-39.pyc +0 -0
- package/vodkit_cli/__pycache__/uninstall.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/uninstall.cpython-39.pyc +0 -0
- package/vodkit_cli/__pycache__/update.cpython-314.pyc +0 -0
- package/vodkit_cli/__pycache__/update.cpython-39.pyc +0 -0
- package/vodkit_cli/cli.py +86 -0
- package/vodkit_cli/common.py +254 -0
- package/vodkit_cli/doctor.py +269 -0
- package/vodkit_cli/install.py +260 -0
- package/vodkit_cli/remote.py +200 -0
- package/vodkit_cli/uninstall.py +161 -0
- package/vodkit_cli/update.py +45 -0
- /package/plugins/vod-devkit/vod_mcp/{packs.py → packs/__init__.py} +0 -0
- /package/vod_mcp/{packs.py → packs/__init__.py} +0 -0
|
@@ -24,6 +24,8 @@ import json
|
|
|
24
24
|
import os
|
|
25
25
|
import sys
|
|
26
26
|
import threading
|
|
27
|
+
|
|
28
|
+
from vod_mcp import net, paths
|
|
27
29
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
28
30
|
|
|
29
31
|
DEFAULT_HOST = "127.0.0.1"
|
|
@@ -56,7 +58,7 @@ def payload_problems(force: bool = False) -> list:
|
|
|
56
58
|
# 从载荷副本直接起来的服务(entry = <payload>/vod_mcp/server.py)没有
|
|
57
59
|
# install 期注入的 payload_dir —— 用自身所在树推断:载荷根里有 payload.json
|
|
58
60
|
# 就说明"我就是那份副本",必须自校验(否则被改的副本会一直对外服务)。
|
|
59
|
-
root = _P(
|
|
61
|
+
root = _P(paths.ROOT)
|
|
60
62
|
d = root if (root / "payload.json").exists() else None
|
|
61
63
|
if d is None:
|
|
62
64
|
return []
|
|
@@ -108,6 +110,13 @@ class RemoteRuntime:
|
|
|
108
110
|
逐块而不是攒全再写:devkit 的 shell 也是 `for await (chunk of
|
|
109
111
|
response.body) res.write(chunk)`——SSE 这种长响应攒全再写等于把流式
|
|
110
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 复制)可见。
|
|
111
120
|
"""
|
|
112
121
|
state = {"body_sent": False}
|
|
113
122
|
|
|
@@ -129,9 +138,14 @@ class RemoteRuntime:
|
|
|
129
138
|
sink.body(chunk)
|
|
130
139
|
|
|
131
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)
|
|
132
144
|
try:
|
|
133
145
|
await self.manager.handle_request(scope, receive, send)
|
|
134
146
|
finally:
|
|
147
|
+
net._SERVER_FACE.reset(tok_face)
|
|
148
|
+
net._REQ_KEY.reset(tok_key)
|
|
135
149
|
sink.end()
|
|
136
150
|
|
|
137
151
|
fut = asyncio.run_coroutine_threadsafe(run(), self._loop)
|
|
@@ -301,20 +315,18 @@ class _Handler(BaseHTTPRequestHandler):
|
|
|
301
315
|
raw_auth = (self.headers.get("Authorization") or "").strip()
|
|
302
316
|
key = raw_auth[7:].strip() if raw_auth.lower().startswith("bearer ") else ""
|
|
303
317
|
|
|
304
|
-
|
|
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
|
|
305
323
|
sink = _StreamSink(self)
|
|
306
|
-
tok_key = tools._REQ_KEY.set(key or None)
|
|
307
|
-
tok_face = tools._SERVER_FACE.set(True)
|
|
308
324
|
try:
|
|
309
|
-
self.server.runtime.request(
|
|
325
|
+
self.server.runtime.request(scope, body, sink)
|
|
310
326
|
except Exception as e: # 传输层异常:能答就答 500,已经流出去就断连
|
|
311
327
|
if not sink.started:
|
|
312
328
|
self._json(500, {"jsonrpc": "2.0", "id": None,
|
|
313
329
|
"error": {"code": -32603, "message": str(e)}})
|
|
314
|
-
return
|
|
315
|
-
finally:
|
|
316
|
-
tools._SERVER_FACE.reset(tok_face)
|
|
317
|
-
tools._REQ_KEY.reset(tok_key)
|
|
318
330
|
|
|
319
331
|
|
|
320
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"))
|
package/vod_mcp/__init__.py
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -32,7 +32,13 @@ PLUGIN_NAME = "vod-feedback-router"
|
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
def _enabled_plugins() -> list:
|
|
35
|
-
"""读 hermes 配置里的 plugins.enabled(CLI 输出是 "- name" 行)。
|
|
35
|
+
"""读 hermes 配置里的 plugins.enabled(CLI 输出是 "- name" 行)。
|
|
36
|
+
|
|
37
|
+
无 CLI 直接返回空:裸 subprocess 会抛 FileNotFoundError 打崩整个 install
|
|
38
|
+
(CI/无宿主机器上实测)——缺 CLI 是"降级"不是"失败"。
|
|
39
|
+
"""
|
|
40
|
+
if not shutil.which("hermes"):
|
|
41
|
+
return []
|
|
36
42
|
r = subprocess.run(["hermes", "config", "get", "plugins.enabled"],
|
|
37
43
|
capture_output=True, text=True, timeout=60)
|
|
38
44
|
if r.returncode != 0:
|
|
@@ -82,10 +88,18 @@ def install(args, packs: str) -> Path:
|
|
|
82
88
|
env_args = []
|
|
83
89
|
for k, v in server_env(args, packs).items():
|
|
84
90
|
env_args.extend([k + "=" + v])
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
91
|
+
# 无 CLI 时不裸 exec(FileNotFoundError 会打崩 install):JSON 已落盘,
|
|
92
|
+
# 用户可手工并入 config.yaml —— 缺 CLI 是降级,不是失败。
|
|
93
|
+
if shutil.which("hermes"):
|
|
94
|
+
r = subprocess.run(
|
|
95
|
+
["hermes", "mcp", "add", "vod-devkit", "--command", sys.executable,
|
|
96
|
+
*["--env"] + env_args, "--args", server_entry()],
|
|
97
|
+
input="y\ny\n", capture_output=True, text=True)
|
|
98
|
+
else:
|
|
99
|
+
r = None
|
|
100
|
+
print(f"提示:未找到 hermes CLI(PATH),已写出配置片段:{conf}\n"
|
|
101
|
+
" 将其并入 ~/.hermes/config.yaml 的 mcp_servers 后重启会话生效",
|
|
102
|
+
file=sys.stderr)
|
|
89
103
|
# D-hook-1:强制评估路由插件(pre_llm_call 确定性意图路由,业界 forced-eval 模式)
|
|
90
104
|
plug_src = ROOT / "hermes-plugin" / "vod-feedback-router"
|
|
91
105
|
plug_dst = Path.home() / ".hermes" / "plugins" / PLUGIN_NAME
|
|
@@ -98,7 +112,9 @@ def install(args, packs: str) -> Path:
|
|
|
98
112
|
"unchanged": "已在 plugins.enabled 中",
|
|
99
113
|
"skipped": "未自动启用(见上方提示)"}[state]
|
|
100
114
|
print(f"已安装 {PLUGIN_NAME} 路由插件(~/.hermes/plugins/,{verb};重启会话生效)")
|
|
101
|
-
if r
|
|
115
|
+
if r is None:
|
|
116
|
+
pass # 无 CLI:上面已经给过指引
|
|
117
|
+
elif r.returncode == 0:
|
|
102
118
|
print("已注册 Hermes MCP(hermes mcp list 可见;重启会话生效)")
|
|
103
119
|
else:
|
|
104
120
|
print(f"提示:hermes mcp add 未成功({r.stderr.strip()[:150]});"
|
|
@@ -107,16 +123,40 @@ def install(args, packs: str) -> Path:
|
|
|
107
123
|
|
|
108
124
|
|
|
109
125
|
def install_remote(args, url, token):
|
|
110
|
-
"""hermes mcp add --url:token 经 env 注入,配置里只留 ${MCP_VOD_DEVKIT_API_KEY} 引用。
|
|
126
|
+
"""hermes mcp add --url:token 经 env 注入,配置里只留 ${MCP_VOD_DEVKIT_API_KEY} 引用。
|
|
127
|
+
|
|
128
|
+
B1(2026-11-13 真机实锤):hermes mcp add 对已存在条目的交互链是三问
|
|
129
|
+
(Overwrite? → 认证? → Enable all tools?),管道 input 只给两个 y 时第三问
|
|
130
|
+
读不到输入 → hermes 端 Cancelled 且仍 exit 0 → 安装器打印"已注册"但
|
|
131
|
+
config.yaml 纹丝不动(静默假绿)。修法两道:
|
|
132
|
+
①stdin 喂不封顶的 y 流(迭代器持续供给,hermes 问几问答几个——多问多答、
|
|
133
|
+
少问即 EOF 收尾),不再数提示个数;
|
|
134
|
+
②rc=0 不算数——读回 hermes 配置真源(config.yaml mcp_servers.vod-devkit
|
|
135
|
+
的 url),断言远程条目真的写进去了;没写进去就非零退出报"未注册",
|
|
136
|
+
绝不静默。
|
|
137
|
+
"""
|
|
111
138
|
import os
|
|
112
139
|
env = os.environ.copy()
|
|
113
140
|
env["MCP_VOD_DEVKIT_API_KEY"] = token
|
|
141
|
+
|
|
142
|
+
def _yes_forever():
|
|
143
|
+
# 交互问数随 hermes 版本变化(首次装=2 问,覆盖装=3 问),流式供给不数数
|
|
144
|
+
for _ in range(64):
|
|
145
|
+
yield "y\n"
|
|
146
|
+
|
|
114
147
|
r = subprocess.run(
|
|
115
148
|
["hermes", "mcp", "add", "vod-devkit", "--url", url, "--auth", "header"],
|
|
116
|
-
input="
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
149
|
+
input="".join(_yes_forever()), capture_output=True, text=True, env=env,
|
|
150
|
+
timeout=180)
|
|
151
|
+
# 防静默:读回 config.yaml 断言远程条目在(Cancelled 会 rc=0 但不落配置)
|
|
152
|
+
registered = _hermes_registration_is_remote(url)
|
|
153
|
+
if r.returncode != 0 or not registered:
|
|
154
|
+
reason = (f"hermes mcp add rc={r.returncode},"
|
|
155
|
+
+ ("配置读回未见远程条目(交互确认被跳过即静默取消)" if not registered
|
|
156
|
+
else f"stderr={(r.stderr or '').strip()[-150:]}"))
|
|
157
|
+
print(f"[vod-devkit] Hermes 远程 MCP 注册未落盘:{reason}\n"
|
|
158
|
+
" 可手工执行:hermes mcp add vod-devkit --url <url> --auth header "
|
|
159
|
+
"(逐问回答 y)", file=sys.stderr)
|
|
120
160
|
sys.exit(1)
|
|
121
161
|
conf = Path(_spec()["configPath"]).parent / "vod-devkit.json"
|
|
122
162
|
conf.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -125,3 +165,40 @@ def install_remote(args, url, token):
|
|
|
125
165
|
ensure_ascii=False, indent=2), encoding="utf-8")
|
|
126
166
|
print(f"已注册 Hermes 远程 MCP({url};token 存 ~/.hermes/.env,配置内只留引用)")
|
|
127
167
|
return conf
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _hermes_registration_is_remote(url: str) -> bool:
|
|
171
|
+
"""读回 hermes 内部注册真源(config.yaml mcp_servers),断言 vod-devkit 是远程条目。
|
|
172
|
+
|
|
173
|
+
hermes mcp add 写 ~/.hermes/config.yaml 的 mcp_servers.vod-devkit(url 字段
|
|
174
|
+
为远程形态标志);Cancelled 的假绿在这里现形。无 yaml 依赖红线:远端
|
|
175
|
+
安装器零第三方依赖,这里用受限文本扫描(顶层 mcp_servers: 段下缩进块内
|
|
176
|
+
找 vod-devkit 与 url 行),而非完整 yaml 解析。
|
|
177
|
+
"""
|
|
178
|
+
cfg = Path.home() / ".hermes" / "config.yaml"
|
|
179
|
+
if not cfg.is_file():
|
|
180
|
+
return False
|
|
181
|
+
in_section = False
|
|
182
|
+
saw_entry = False
|
|
183
|
+
saw_url = False
|
|
184
|
+
for raw_line in cfg.read_text(encoding="utf-8").splitlines():
|
|
185
|
+
if not raw_line.strip() or raw_line.lstrip().startswith("#"):
|
|
186
|
+
continue
|
|
187
|
+
indented = raw_line[0] == " "
|
|
188
|
+
stripped = raw_line.strip()
|
|
189
|
+
if not indented:
|
|
190
|
+
in_section = stripped.startswith("mcp_servers:")
|
|
191
|
+
continue
|
|
192
|
+
if not in_section:
|
|
193
|
+
continue
|
|
194
|
+
# mcp_servers 段内的行:条目名(一级缩进)与字段(更深缩进)
|
|
195
|
+
if stripped.startswith("vod-devkit:"):
|
|
196
|
+
saw_entry = True
|
|
197
|
+
elif saw_entry and stripped.startswith("url:"):
|
|
198
|
+
if url in stripped:
|
|
199
|
+
saw_url = True
|
|
200
|
+
break
|
|
201
|
+
elif saw_entry and not raw_line.startswith(" vod-devkit") and stripped.endswith(":"):
|
|
202
|
+
if not raw_line.startswith(" " * 4): # 下一个一级条目:停止
|
|
203
|
+
break
|
|
204
|
+
return saw_entry and saw_url
|
package/vod_mcp/hosts.py
CHANGED
package/vod_mcp/net.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""出口与身份:HTTP 调用、meta 缓存、key 探针、匿名令牌、请求身份 contextvars。
|
|
2
|
+
|
|
3
|
+
与 runtime_state 的分工:本模块负责"跟引擎说话",状态落盘一律转调 runtime_state。
|
|
4
|
+
共享符号必须用**模块属性访问**(net._http / net.JAVA_KEY)——`from net import _http`
|
|
5
|
+
会把引用冻结在导入期,测试 monkeypatch 就静默失效(P2 的 patch 面纪律)。
|
|
6
|
+
"""
|
|
7
|
+
import contextvars
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
|
|
13
|
+
from vod_mcp import DEFAULT_JAVA_BASE
|
|
14
|
+
from vod_mcp import runtime_state as rt
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
_REQ_KEY = contextvars.ContextVar("vod_req_key", default=None)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_SERVER_FACE = contextvars.ContextVar("vod_server_face", default=False)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _eff_key(explicit=None) -> str:
|
|
24
|
+
"""当前生效的 key:显式参数 > 请求头(HTTP 面)> env/runtime(stdio 面)。"""
|
|
25
|
+
if explicit is not None:
|
|
26
|
+
return explicit
|
|
27
|
+
return _REQ_KEY.get() or JAVA_KEY
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
JAVA_BASE = os.environ.get("VOD_JAVA_API_BASE") or rt._RT.get("java_base") or DEFAULT_JAVA_BASE
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
JAVA_KEY = os.environ.get("VOD_JAVA_API_KEY", "") or rt._RT.get("java_key", "") # ExternalApiKeyFilter Bearer
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_META_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/meta"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
_META_TTL = 24 * 3600
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_META_SNAPSHOT: dict = {"products": []}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _load_meta(force: bool = False) -> dict:
|
|
46
|
+
"""可漂移值动态取:缓存 TTL 24h,引擎端点不可达时回退快照并标 stale。
|
|
47
|
+
真源=引擎 meta 接口(productCatalog/products)——**本模块不维护任何产品
|
|
48
|
+
清单**,离线时宁可不归因也不拿本地表猜。
|
|
49
|
+
|
|
50
|
+
T7i:productCatalog=[{id,name}](t_vod_product 运营预置,meta 组装)——
|
|
51
|
+
提交产品归因按平台主键 id 的解析真源;老引擎无该键=catalog 空。
|
|
52
|
+
|
|
53
|
+
**2026-11-12 引擎契约收紧**:
|
|
54
|
+
· `nameAliases` / `aliases` 已由引擎删除 → 本函数不再读取;别名能力改由
|
|
55
|
+
attribution 的规则派生 + BRAND_ALIASES 提供。
|
|
56
|
+
· `problemTypes` 改为按产品下发(`?productId=`):**无参请求不含该键**。
|
|
57
|
+
分类白名单必须用 `collect._allowed_tags(product_id)` 按产品取,见下。
|
|
58
|
+
"""
|
|
59
|
+
import time
|
|
60
|
+
cache = rt._RT.get("meta_cache") or {}
|
|
61
|
+
now = time.time()
|
|
62
|
+
if not force and cache.get("data") and now - cache.get("fetchedAt", 0) < _META_TTL:
|
|
63
|
+
return {"products": cache["data"].get("products", _META_SNAPSHOT["products"]),
|
|
64
|
+
"catalog": cache["data"].get("productCatalog") or [],
|
|
65
|
+
"dictVersion": cache["data"].get("dictVersion"),
|
|
66
|
+
"stale": False, "source": "cache"}
|
|
67
|
+
try:
|
|
68
|
+
out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
|
|
69
|
+
data = out.get("data") or {}
|
|
70
|
+
if isinstance(data.get("products"), list) and data["products"]:
|
|
71
|
+
rt._runtime_update({"meta_cache": {"fetchedAt": int(now), "data": data}})
|
|
72
|
+
return {"products": data["products"],
|
|
73
|
+
"catalog": data.get("productCatalog") or [],
|
|
74
|
+
"dictVersion": data.get("dictVersion"),
|
|
75
|
+
"stale": False, "source": "meta"}
|
|
76
|
+
except ToolError:
|
|
77
|
+
pass
|
|
78
|
+
# 快照不含分类白名单:collect._allowed_tags 取不到产品分类时 allowed 为空=不校验
|
|
79
|
+
# (宁可放行也不误杀采集)
|
|
80
|
+
return {"products": _META_SNAPSHOT["products"], "catalog": [],
|
|
81
|
+
"dictVersion": None,
|
|
82
|
+
"stale": True, "source": "snapshot"}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ToolError(Exception):
|
|
86
|
+
def __init__(self, message: str, code: int = -32000):
|
|
87
|
+
super().__init__(message)
|
|
88
|
+
self.code = code
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _http(method: str, path: str, body: dict | None = None,
|
|
92
|
+
base: str | None = None, key: str | None = None, timeout: int = 30) -> dict:
|
|
93
|
+
"""统一出口:一律携带 Authorization Bearer(E1 修复:认证头缺失)。
|
|
94
|
+
|
|
95
|
+
base/key 缺省在调用时解析模块级配置(不能用函数默认值——定义时即冻结,
|
|
96
|
+
环境变更/测试 monkeypatch 均无法生效)。
|
|
97
|
+
"""
|
|
98
|
+
base = base if base is not None else JAVA_BASE
|
|
99
|
+
key = key if key is not None else JAVA_KEY
|
|
100
|
+
# 传输协议守卫:非本机回环一律要求 https(Bearer 不得明文过公网)
|
|
101
|
+
_host = base.split("//", 1)[-1].split("/", 1)[0].split(":")[0]
|
|
102
|
+
if not base.startswith("https://") and _host not in ("127.0.0.1", "localhost", "::1"):
|
|
103
|
+
raise ToolError(
|
|
104
|
+
f"上游 {base} 非 https 且非本机回环——Bearer key 明文外发被拒"
|
|
105
|
+
"(配置 VOD_JAVA_API_BASE 为 https:// 地址)", code=-32014)
|
|
106
|
+
url = base.rstrip("/") + path
|
|
107
|
+
rt._log(f"http {method} {url} key={'yes' if key else 'no'}")
|
|
108
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
109
|
+
headers = {"Content-Type": "application/json",
|
|
110
|
+
# VOD-DEVICE:设备锚点(install_nonce=首启自生成常驻,零新增状态)——
|
|
111
|
+
# 引擎据此建每设备独立锚点(NAT/产品分发不再收敛);服务端缺失回落 legacy
|
|
112
|
+
"X-Vod-Device-Id": rt._install_nonce()}
|
|
113
|
+
if key:
|
|
114
|
+
headers["Authorization"] = f"Bearer {key}"
|
|
115
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
116
|
+
try:
|
|
117
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
118
|
+
return json.loads(resp.read().decode())
|
|
119
|
+
except urllib.error.HTTPError as e:
|
|
120
|
+
detail = e.read().decode()[:200]
|
|
121
|
+
if e.code == 401:
|
|
122
|
+
# 引擎 401 原文透传(probe_key 靠它区分"设备绑定校验失败"=匿名令牌
|
|
123
|
+
# 跨设备(token 有效,本机没用过)vs "API Key 无效"=真坏 key;丢原文
|
|
124
|
+
# 会让探针把正常匿名场景误判成 rejected)
|
|
125
|
+
raise ToolError(
|
|
126
|
+
f"鉴权失败({base}):{detail or '检查 VOD_JAVA_API_KEY 配置'}",
|
|
127
|
+
code=-32012) from e
|
|
128
|
+
raise ToolError(f"上游返回 {e.code}: {detail}", code=e.code) from e
|
|
129
|
+
except urllib.error.URLError as e:
|
|
130
|
+
raise ToolError(f"上游不可达({base}): {e.reason}", code=-32001) from e
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _fingerprint(key: str) -> str | None:
|
|
134
|
+
import hashlib
|
|
135
|
+
return hashlib.sha1(key.encode()).hexdigest()[:8] if key else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def probe_key(key: str | None = None, timeout: int = 8) -> dict:
|
|
139
|
+
"""key 有效性探针:带 key 调只读端点 GET /external/meta(Filter 网内)。
|
|
140
|
+
|
|
141
|
+
判定语义(引擎是唯一权威,本地零判定):
|
|
142
|
+
- 200 → {"ok": True}:key 有效且在网内
|
|
143
|
+
- 401/-32012 → {"ok": False, "reason": "rejected"}:引擎判无效(过期/吊销/不存在)
|
|
144
|
+
- 其他错误(网络不可达/超时/5xx)→ {"ok": None, "reason": "unreachable"}:
|
|
145
|
+
不判定——网络问题不是 key 问题,报"无法验证"而非"无效"
|
|
146
|
+
"""
|
|
147
|
+
explicit = key is not None # 显式传参(服务面=请求头 Bearer)按显式口径判
|
|
148
|
+
key = key if key is not None else JAVA_KEY
|
|
149
|
+
fp = _fingerprint(key)
|
|
150
|
+
if not key:
|
|
151
|
+
return {"ok": None, "reason": "no-key", "fingerprint": None}
|
|
152
|
+
try:
|
|
153
|
+
_http("GET", _META_PATH, None, key=key, timeout=timeout)
|
|
154
|
+
return {"ok": True, "reason": "verified", "fingerprint": fp}
|
|
155
|
+
except ToolError as ex:
|
|
156
|
+
code = ex.code
|
|
157
|
+
msg = str(ex)
|
|
158
|
+
if code == 401 or code == -32012:
|
|
159
|
+
# 引擎 401 两类语义(原文区分,实锤 2026-11-13):
|
|
160
|
+
# - "设备绑定校验失败":匿名令牌是设备锚点绑定的——token 本身有效,
|
|
161
|
+
# 只是本机(nonce)不是签发设备。这是正常场景(换机/重装/仓内与
|
|
162
|
+
# payloads 两份 runtime 的 nonce 漂移),不是 key 坏。归
|
|
163
|
+
# device-mismatch:不拦(放行),提示在本设备重领。
|
|
164
|
+
# - "API Key 无效或已失效":真坏 key → rejected(fail fast 不变)。
|
|
165
|
+
# 旧语义(显式→rejected / 非显式→expired-anonymous)保留为无原文
|
|
166
|
+
# 时的兜底分类。
|
|
167
|
+
if "设备绑定校验失败" in msg:
|
|
168
|
+
return {"ok": False, "reason": "device-mismatch", "fingerprint": fp,
|
|
169
|
+
"note": "匿名令牌与本设备不匹配:令牌本身有效,"
|
|
170
|
+
"在本设备重新申请令牌后可继续(POST /external/token,"
|
|
171
|
+
"首次提交自动完成)"}
|
|
172
|
+
if not (explicit or _explicit_key()):
|
|
173
|
+
# 匿名令牌 401 ≠ 配置错误:报"过期待重领"而非"rejected",
|
|
174
|
+
# 避免 runtime 残留过期匿名令牌时被误读为正式 key 失效
|
|
175
|
+
# (显式 key 被拒仍报 rejected——fail fast 口径不变)
|
|
176
|
+
return {"ok": False, "reason": "expired-anonymous", "fingerprint": fp,
|
|
177
|
+
"note": "匿名令牌已过期:下次提交自动重领,无需操作"}
|
|
178
|
+
return {"ok": False, "reason": "rejected", "fingerprint": fp}
|
|
179
|
+
return {"ok": None, "reason": "unreachable", "fingerprint": fp}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _key_state() -> dict:
|
|
183
|
+
return {"configured": bool(JAVA_KEY), "fingerprint": _fingerprint(JAVA_KEY),
|
|
184
|
+
"base": JAVA_BASE,
|
|
185
|
+
"note": "已配置" if JAVA_KEY else "未配置(首次提交自动取匿名令牌)"}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _explicit_key() -> bool:
|
|
189
|
+
"""当前 JAVA_KEY 是否为显式配置(正式/宿主 key)而非本会话自动领取的匿名令牌。
|
|
190
|
+
|
|
191
|
+
判据:环境变量显式注入(权威,env 优先级最高的既有口径)或
|
|
192
|
+
token_tier != "anonymous"。匿名令牌过期/被吊销时 401 应走重领链;
|
|
193
|
+
显式 key 被 401 拒绝时必须 fail fast(静默降级匿名=配置错误被吞=归因错位,
|
|
194
|
+
「注入 appkey」场景的锚定承诺会变成假的)。
|
|
195
|
+
"""
|
|
196
|
+
if bool(os.environ.get("VOD_JAVA_API_KEY")):
|
|
197
|
+
return True
|
|
198
|
+
return bool(JAVA_KEY) and str(rt._RT.get("token_tier") or "") != "anonymous"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _legacy_key_hint() -> str:
|
|
202
|
+
"""旧版残留凭据自愈提示(评审拍板项):出错时给可操作路径,不发公告靠用户撞。
|
|
203
|
+
含当前插件版本与重装命令——重装会刷新 runtime/清掉旧 key 残留。"""
|
|
204
|
+
version = getattr(__import__("vod_mcp"), "__version__", "unknown")
|
|
205
|
+
return ("若为旧版安装残留凭据:更新插件(当前 v" + version + ")并重装即可清除——"
|
|
206
|
+
"npx vod-devkit@latest install --target <宿主> --product <产品名>;"
|
|
207
|
+
"或移除 VOD_JAVA_API_KEY 环境变量走匿名档")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
_KEY_GUIDANCE: list[dict[str, object]] = [
|
|
211
|
+
{"order": 1, "action": "auto-token", "label": "首次提交时插件自动申请零字段匿名令牌(默认路径,无需注册)"},
|
|
212
|
+
{"order": 2, "action": "upgrade", "label": "提交量达上限后升级正式 key:联系 VOD 运营(低信任档→正式档)"},
|
|
213
|
+
{"order": 3, "action": "host", "label": "宿主平台整体对接可获宿主 key:由宿主运维持有(高信任档)"},
|
|
214
|
+
]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
_TOKEN_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/token"
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _extract_anon_token(out: object) -> str | None:
|
|
221
|
+
"""从令牌端点响应提取 token(真源契约:引擎 ApiResponse 信封
|
|
222
|
+
{"code":200,"data":{"token":...}};顶层扁平 {"token":...} 兼容历史形态)。"""
|
|
223
|
+
if not isinstance(out, dict):
|
|
224
|
+
return None
|
|
225
|
+
data = out.get("data")
|
|
226
|
+
token = data.get("token") if isinstance(data, dict) else None
|
|
227
|
+
if not token:
|
|
228
|
+
token = out.get("token")
|
|
229
|
+
return token if isinstance(token, str) and token else None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _fetch_anon_token() -> str | None:
|
|
233
|
+
"""零字段匿名令牌(T7b 定稿):渠道由引擎囤积入库侧固定赋值 vod-agent
|
|
234
|
+
(链路即渠道,客户端不自报)——本端保持空 body(方案 C 原样)。
|
|
235
|
+
D-anon-verify(2026-11-05 真机实锤):引擎返回 ApiResponse 信封,
|
|
236
|
+
顶层取 token 恒 None → 无 key 首提必 -32012,信封解析为必经路径。"""
|
|
237
|
+
try:
|
|
238
|
+
out = _http("POST", _TOKEN_PATH, {}, base=JAVA_BASE, key="", timeout=15)
|
|
239
|
+
return _extract_anon_token(out)
|
|
240
|
+
except ToolError:
|
|
241
|
+
return None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _acquire_anon_token_or_raise() -> str:
|
|
245
|
+
"""缺 key/匿名令牌失效 → 领零字段匿名令牌;端点不可用则如实报错。"""
|
|
246
|
+
token = _fetch_anon_token()
|
|
247
|
+
if not token:
|
|
248
|
+
raise ToolError(
|
|
249
|
+
"未配置接入 key 且匿名令牌端点不可用。引导:"
|
|
250
|
+
+ ";".join(str(g["label"]) for g in _KEY_GUIDANCE), code=-32012)
|
|
251
|
+
return token
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|