vod-devkit 0.0.0-stage → 0.1.0
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 +13 -0
- package/LICENSE.txt +21 -0
- package/QUICKSTART.md +79 -0
- package/README.en.md +75 -0
- package/README.md +84 -2
- package/bin/vod-devkit +464 -0
- package/contract/tools.schema.json +187 -0
- package/npm/cli.js +39 -0
- package/package.json +28 -4
- package/safety/policy.json +48 -0
- package/skills/vod-core/SKILL.md +23 -0
- package/skills/vod-feedback-collect/SKILL.md +90 -0
- package/skills/vod-problem-classification-rules/SKILL.md +45 -0
- package/skills/vod-scoring-rules/SKILL.md +37 -0
- package/vod_mcp/__init__.py +11 -0
- package/vod_mcp/__pycache__/__init__.cpython-314.pyc +0 -0
- package/vod_mcp/__pycache__/packs.cpython-314.pyc +0 -0
- package/vod_mcp/__pycache__/policy.cpython-314.pyc +0 -0
- package/vod_mcp/__pycache__/provenance.cpython-314.pyc +0 -0
- package/vod_mcp/__pycache__/server.cpython-314.pyc +0 -0
- package/vod_mcp/__pycache__/tools.cpython-314.pyc +0 -0
- package/vod_mcp/packs.py +30 -0
- package/vod_mcp/policy.py +98 -0
- package/vod_mcp/provenance.py +43 -0
- package/vod_mcp/runtime.example.json +6 -0
- package/vod_mcp/runtime.json +1473 -0
- package/vod_mcp/server.py +105 -0
- package/vod_mcp/tools.py +620 -0
package/vod_mcp/tools.py
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
"""工具实现:唯一事实源=contract/tools.schema.json;单上游(纯采集插件)。
|
|
2
|
+
|
|
3
|
+
方案 A 收敛(2026-11-03 拍板):插件只做用户声音采集,运营能力归
|
|
4
|
+
vod-system 前端(既有工作台)。workflow 三工具与 kb_search 已删除
|
|
5
|
+
(git 历史可查;删除依据=零真实使用+受众耦合,负复杂度决策)。
|
|
6
|
+
|
|
7
|
+
唯一上游:Java backend(VOD_JAVA_API_BASE + VOD_JAVA_API_KEY,
|
|
8
|
+
ExternalApiKeyFilter Bearer)。
|
|
9
|
+
POST …/external/voice/submit(现有接口,提交即分析)
|
|
10
|
+
POST …/external/token(VOD-KEY,零字段匿名令牌)
|
|
11
|
+
"""
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import stat
|
|
15
|
+
import urllib.request
|
|
16
|
+
import urllib.error
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from vod_mcp import provenance
|
|
20
|
+
from vod_mcp import DEFAULT_JAVA_BASE
|
|
21
|
+
|
|
22
|
+
_CONTRACT_PATH = Path(__file__).resolve().parent.parent / "contract" / "tools.schema.json"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _runtime_path() -> Path:
|
|
26
|
+
return Path(__file__).resolve().parent / "runtime.json"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _runtime_cfg() -> dict:
|
|
30
|
+
# 路径单源:一律走 _runtime_path()(曾与 _save_runtime 双写路径,
|
|
31
|
+
# 注入/重定位场景读写分叉——测试实锤的真缺陷)
|
|
32
|
+
p = _runtime_path()
|
|
33
|
+
if p.exists():
|
|
34
|
+
try:
|
|
35
|
+
return json.loads(p.read_text(encoding="utf-8"))
|
|
36
|
+
except Exception:
|
|
37
|
+
return {}
|
|
38
|
+
return {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# 上游配置:env 优先,runtime.json 兜底——不依赖宿主 env 透传
|
|
42
|
+
# (实测部分 MCP 宿主对子进程 env 过滤/丢失,如 Hermes 多 --env 只存活一个)
|
|
43
|
+
_RT = _runtime_cfg()
|
|
44
|
+
JAVA_BASE = os.environ.get("VOD_JAVA_API_BASE") or _RT.get("java_base") or DEFAULT_JAVA_BASE
|
|
45
|
+
JAVA_KEY = os.environ.get("VOD_JAVA_API_KEY", "") or _RT.get("java_key", "") # ExternalApiKeyFilter Bearer
|
|
46
|
+
|
|
47
|
+
_META_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/meta"
|
|
48
|
+
_META_TTL = 24 * 3600
|
|
49
|
+
# 快照兜底(引擎 meta 端点未上线/不可达时用;stale 语义见 _load_meta)
|
|
50
|
+
_META_SNAPSHOT = {"products": ["agentarts", "codearts", "dataarts", "maas", "obs",
|
|
51
|
+
"officeclaw", "modelarts"]}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _load_meta(force: bool = False) -> dict:
|
|
55
|
+
"""可漂移值(product 白名单等)动态取:缓存 TTL 24h,
|
|
56
|
+
引擎端点不可达时回退快照并标 stale。真源=引擎 submit 校验常量。"""
|
|
57
|
+
import time
|
|
58
|
+
cache = _RT.get("meta_cache") or {}
|
|
59
|
+
now = time.time()
|
|
60
|
+
if not force and cache.get("data") and now - cache.get("fetchedAt", 0) < _META_TTL:
|
|
61
|
+
return {"products": cache["data"].get("products", _META_SNAPSHOT["products"]),
|
|
62
|
+
"stale": False, "source": "cache"}
|
|
63
|
+
try:
|
|
64
|
+
out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=JAVA_KEY, timeout=10)
|
|
65
|
+
data = out.get("data") or {}
|
|
66
|
+
if isinstance(data.get("products"), list) and data["products"]:
|
|
67
|
+
_save_runtime({"meta_cache": {"fetchedAt": int(now), "data": data}})
|
|
68
|
+
return {"products": data["products"], "stale": False, "source": "meta"}
|
|
69
|
+
except ToolError:
|
|
70
|
+
pass
|
|
71
|
+
return {"products": _META_SNAPSHOT["products"], "stale": True, "source": "snapshot"}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ToolError(Exception):
|
|
75
|
+
def __init__(self, message: str, code: int = -32000):
|
|
76
|
+
super().__init__(message)
|
|
77
|
+
self.code = code
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def load_contract() -> dict:
|
|
81
|
+
with open(_CONTRACT_PATH, encoding="utf-8") as f:
|
|
82
|
+
return json.load(f)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def tool_specs(only: list) -> list:
|
|
86
|
+
"""按 packs 启用清单生成 tools/list 的 MCP 工具描述。"""
|
|
87
|
+
contract = load_contract()
|
|
88
|
+
specs = []
|
|
89
|
+
for name, spec in contract["tools"].items():
|
|
90
|
+
if name not in only:
|
|
91
|
+
continue
|
|
92
|
+
specs.append({
|
|
93
|
+
"name": name,
|
|
94
|
+
"description": spec["description"],
|
|
95
|
+
"inputSchema": spec["input"],
|
|
96
|
+
})
|
|
97
|
+
return specs
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _http(method: str, path: str, body: dict | None = None,
|
|
101
|
+
base: str | None = None, key: str | None = None, timeout: int = 30) -> dict:
|
|
102
|
+
"""统一出口:一律携带 Authorization Bearer(E1 修复:认证头缺失)。
|
|
103
|
+
|
|
104
|
+
base/key 缺省在调用时解析模块级配置(不能用函数默认值——定义时即冻结,
|
|
105
|
+
环境变更/测试 monkeypatch 均无法生效)。
|
|
106
|
+
"""
|
|
107
|
+
base = base if base is not None else JAVA_BASE
|
|
108
|
+
key = key if key is not None else JAVA_KEY
|
|
109
|
+
# 传输协议守卫:非本机回环一律要求 https(Bearer 不得明文过公网)
|
|
110
|
+
_host = base.split("//", 1)[-1].split("/", 1)[0].split(":")[0]
|
|
111
|
+
if not base.startswith("https://") and _host not in ("127.0.0.1", "localhost", "::1"):
|
|
112
|
+
raise ToolError(
|
|
113
|
+
f"上游 {base} 非 https 且非本机回环——Bearer key 明文外发被拒"
|
|
114
|
+
"(配置 VOD_JAVA_API_BASE 为 https:// 地址)", code=-32014)
|
|
115
|
+
url = base.rstrip("/") + path
|
|
116
|
+
_log(f"http {method} {url} key={'yes' if key else 'no'}")
|
|
117
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
118
|
+
headers = {"Content-Type": "application/json",
|
|
119
|
+
# VOD-DEVICE:设备锚点(install_nonce=首启自生成常驻,零新增状态)——
|
|
120
|
+
# 引擎据此建每设备独立锚点(NAT/产品分发不再收敛);服务端缺失回落 legacy
|
|
121
|
+
"X-Vod-Device-Id": _install_nonce()}
|
|
122
|
+
if key:
|
|
123
|
+
headers["Authorization"] = f"Bearer {key}"
|
|
124
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
125
|
+
try:
|
|
126
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
127
|
+
return json.loads(resp.read().decode())
|
|
128
|
+
except urllib.error.HTTPError as e:
|
|
129
|
+
detail = e.read().decode()[:200]
|
|
130
|
+
if e.code == 401:
|
|
131
|
+
raise ToolError(
|
|
132
|
+
f"鉴权失败({base}):检查 VOD_JAVA_API_KEY 配置",
|
|
133
|
+
code=-32012) from e
|
|
134
|
+
raise ToolError(f"上游返回 {e.code}: {detail}", code=e.code) from e
|
|
135
|
+
except urllib.error.URLError as e:
|
|
136
|
+
raise ToolError(f"上游不可达({base}): {e.reason}", code=-32001) from e
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# 引擎 submit 校验白名单(ExternalVoiceServiceImpl.VALID_PRODUCTS 实测:
|
|
140
|
+
# CODEARTS/AGENTARTS/OFFICECLAW/DATAARTS/MAAS/OBS + 别名归一 MODELARTS→MAAS)
|
|
141
|
+
_PRODUCT_MAP = {
|
|
142
|
+
"agentarts": "AgentArts", "codearts": "CodeArts", "dataarts": "DataArts",
|
|
143
|
+
"maas": "MaaS", "obs": "OBS", "officeclaw": "OfficeClaw",
|
|
144
|
+
"modelarts": "MaaS", # 引擎别名归一实测
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _resolve_product(params: dict) -> str | None:
|
|
149
|
+
"""归因(「宿主即产品」口径,2026-11-03 拍板·不设白名单):
|
|
150
|
+
①调用方显式传参 ②安装绑定(runtime.json product——安装器默认写入宿主名,
|
|
151
|
+
hermes/opencode/codex 装在哪就归哪)③都没有 → 返回 None(body 不带
|
|
152
|
+
product,引擎落 UNKNOWN 档人工归因解析,V19)——不再 -32013 本地拦截。
|
|
153
|
+
白名单校验已废除:宿主工具自报产品原样上送,由引擎宽松归一收编。"""
|
|
154
|
+
raw = str(params.get("product") or _RT.get("product") or "").strip()
|
|
155
|
+
if not raw:
|
|
156
|
+
return None
|
|
157
|
+
return _PRODUCT_MAP.get(raw.lower(), raw)
|
|
158
|
+
_SUBMIT_HOARDING = "/rest/developer/manager/hdvodmngservice/v1/external/voices"
|
|
159
|
+
_EXISTING_SUBMIT = "/rest/developer/manager/hdvodmngservice/v1/external/voice/submit" # 过渡期 404 回落
|
|
160
|
+
_TOKEN_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/token"
|
|
161
|
+
|
|
162
|
+
# 结构化引导(devkit error-table 模式:步骤=可执行动作,不是"参考文档")
|
|
163
|
+
_KEY_GUIDANCE = [
|
|
164
|
+
{"order": 1, "action": "auto-token", "label": "首次提交时插件自动申请零字段匿名令牌(默认路径,无需注册)"},
|
|
165
|
+
{"order": 2, "action": "upgrade", "label": "提交量达上限后升级正式 key:联系 VOD 运营(低信任档→正式档)"},
|
|
166
|
+
{"order": 3, "action": "host", "label": "宿主平台整体对接可获宿主 key:由宿主运维持有(高信任档)"},
|
|
167
|
+
]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _install_nonce() -> str:
|
|
171
|
+
"""per-install 8 位 hex:runtime.json 首次生成常驻——legacy 共用 key 场景下
|
|
172
|
+
source 命名空间 per-machine 化,杜绝不同用户提交同款内容被确定性
|
|
173
|
+
voiceId 合并成一条(跨用户吞声量,切换补丁前置修复)。"""
|
|
174
|
+
n = _RT.get("install_nonce")
|
|
175
|
+
if not n:
|
|
176
|
+
import uuid
|
|
177
|
+
n = uuid.uuid4().hex[:8]
|
|
178
|
+
try:
|
|
179
|
+
_save_runtime({"install_nonce": n})
|
|
180
|
+
except Exception:
|
|
181
|
+
pass
|
|
182
|
+
return str(n)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _voice_id(source: str, content: str, nonce: str) -> str:
|
|
186
|
+
"""voiceId = f(source, content, 调用级nonce)。
|
|
187
|
+
|
|
188
|
+
R1 修正(声量保真):跨调用不去重——不同用户提交同款反馈必须各占
|
|
189
|
+
一行(声量是分析核心信号);同调用内重试复用同 nonce 保幂等。
|
|
190
|
+
"""
|
|
191
|
+
import hashlib
|
|
192
|
+
return f"ext_{source}_{hashlib.sha1((content + nonce).encode('utf-8')).hexdigest()[:12]}"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _explicit_key() -> bool:
|
|
196
|
+
"""当前 JAVA_KEY 是否为显式配置(正式/宿主 key)而非本会话自动领取的匿名令牌。
|
|
197
|
+
|
|
198
|
+
判据:环境变量显式注入(权威,env 优先级最高的既有口径)或
|
|
199
|
+
token_tier != "anonymous"。匿名令牌过期/被吊销时 401 应走重领链;
|
|
200
|
+
显式 key 被 401 拒绝时必须 fail fast(静默降级匿名=配置错误被吞=归因错位,
|
|
201
|
+
「注入 appkey」场景的锚定承诺会变成假的)。
|
|
202
|
+
"""
|
|
203
|
+
if bool(os.environ.get("VOD_JAVA_API_KEY")):
|
|
204
|
+
return True
|
|
205
|
+
return bool(JAVA_KEY) and str(_RT.get("token_tier") or "") != "anonymous"
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def submit_voices(params: dict, client_info: dict | None = None) -> dict:
|
|
209
|
+
"""V16 切换:主路径=囤积端点 POST /external/voices(Bearer,批式,不触发分析);
|
|
210
|
+
引擎未部署(404)自动回落老链 /external/voice/submit(提交即分析,过渡语义,
|
|
211
|
+
部署后 404 分支自然失效)。
|
|
212
|
+
|
|
213
|
+
- voiceId:囤积链由引擎确定性计算(per-token/per-install 命名空间),回执
|
|
214
|
+
voiceIds 为权威对账键;回落老链仍用客户端 nonce id(R1 声量保真)
|
|
215
|
+
- title=用户原文截断;tags=采集层三分类(problem_type:)正式入库通道
|
|
216
|
+
- source:key 持有者被引擎锚定为 host_name;legacy 共用 key 场景带
|
|
217
|
+
per-install nonce 后缀(杜绝跨用户共享命名空间吞声量)
|
|
218
|
+
"""
|
|
219
|
+
import uuid
|
|
220
|
+
host = (client_info or {}).get("name") or "unknown-host"
|
|
221
|
+
product = _resolve_product(params)
|
|
222
|
+
accepted, voice_ids, task_ids, rejected = 0, [], [], []
|
|
223
|
+
global JAVA_KEY
|
|
224
|
+
voices_in = params.get("voices", [])
|
|
225
|
+
items = [] # (index, voice_map, content)
|
|
226
|
+
for i, v in enumerate(voices_in):
|
|
227
|
+
content = str(v.get("content", "")).strip()
|
|
228
|
+
if not content:
|
|
229
|
+
rejected.append({"index": i, "reason": "content 为空"})
|
|
230
|
+
continue
|
|
231
|
+
if len(content) > 2000: # 契约 maxLength 2000:内容边界(防超大 payload)
|
|
232
|
+
rejected.append({"index": i, "reason": f"content 超 2000 字({len(content)})"})
|
|
233
|
+
continue
|
|
234
|
+
items.append((i, v, content))
|
|
235
|
+
if not items:
|
|
236
|
+
return {"accepted": 0, "voiceIds": [], "taskIds": [], "rejected": rejected}
|
|
237
|
+
|
|
238
|
+
def _ledger(vids, tids):
|
|
239
|
+
import time as _time
|
|
240
|
+
entries = [{"voiceId": vid, "taskId": tid,
|
|
241
|
+
"title": items[min(i, len(items) - 1)][2][:40],
|
|
242
|
+
"product": product, "at": _time.strftime("%Y-%m-%dT%H:%M:%S")}
|
|
243
|
+
for i, (vid, tid) in enumerate(zip(vids, tids))]
|
|
244
|
+
_ledger_append(entries)
|
|
245
|
+
|
|
246
|
+
def _legacy_submit(i, v, content):
|
|
247
|
+
"""过渡回落:老链单条提交(提交即分析语义,仅 404 触发)。"""
|
|
248
|
+
nonce = uuid.uuid4().hex[:8] # 调用级:重试复用,跨调用不重复
|
|
249
|
+
vid = _voice_id(host, content, nonce)
|
|
250
|
+
desc = content if len(content) >= 10 else f"{content} [vod-devkit]"
|
|
251
|
+
body = {
|
|
252
|
+
"voiceId": vid,
|
|
253
|
+
"title": content[:128],
|
|
254
|
+
"description": desc,
|
|
255
|
+
"source": f"{host}-{_install_nonce()}", # per-install 命名空间(legacy 吞声量修复)
|
|
256
|
+
"customer": v.get("userType"),
|
|
257
|
+
}
|
|
258
|
+
if product:
|
|
259
|
+
body["product"] = product
|
|
260
|
+
out = _http("POST", _EXISTING_SUBMIT, body, base=JAVA_BASE, key=JAVA_KEY)
|
|
261
|
+
return vid, (out.get("data") or {}).get("taskId")
|
|
262
|
+
|
|
263
|
+
# ---- 主路径:囤积端点批式提交 ----
|
|
264
|
+
hoard_voices = []
|
|
265
|
+
for i, v, content in items:
|
|
266
|
+
hv = {"title": content[:60], "content": content}
|
|
267
|
+
tags = v.get("tags") # 采集层三分类(problem_type:值)→【类型名】标题前缀正式入库
|
|
268
|
+
if tags:
|
|
269
|
+
hv["tags"] = tags
|
|
270
|
+
ut = v.get("userType")
|
|
271
|
+
if ut:
|
|
272
|
+
hv["userType"] = ut
|
|
273
|
+
hoard_voices.append(hv)
|
|
274
|
+
body = {"voices": hoard_voices}
|
|
275
|
+
if product: # 无归因不带 product(引擎 UNKNOWN 档),不本地拦截
|
|
276
|
+
body["product"] = product
|
|
277
|
+
out = None
|
|
278
|
+
fallback = False
|
|
279
|
+
try:
|
|
280
|
+
out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
|
|
281
|
+
except ToolError as ex:
|
|
282
|
+
if ex.code == 404:
|
|
283
|
+
fallback = True # 囤积端点未部署 → 落到下方 legacy 回落
|
|
284
|
+
elif not JAVA_KEY or ex.code == -32012:
|
|
285
|
+
if _explicit_key():
|
|
286
|
+
# 显式 key(安装注入/正式档)被引擎 401 拒绝 → fail fast:
|
|
287
|
+
# 不取匿名令牌、不覆盖配置——静默降级匿名档=配置错误被吞
|
|
288
|
+
#(归因错位比报错更糟,同 AIShell 错归病根)
|
|
289
|
+
raise ToolError(
|
|
290
|
+
f"注入的 key 被引擎拒绝(指纹 {_fingerprint(JAVA_KEY)}):"
|
|
291
|
+
"请核对 key 是否过期/被吊销,或移除 key 走匿名档(删除 "
|
|
292
|
+
"VOD_JAVA_API_KEY 环境变量与 runtime.json java_key)",
|
|
293
|
+
code=-32012)
|
|
294
|
+
# 缺 key/匿名令牌失效 → 零字段匿名令牌 → 落 runtime.json → 重试一次
|
|
295
|
+
token = _fetch_anon_token()
|
|
296
|
+
if not token:
|
|
297
|
+
raise ToolError(
|
|
298
|
+
"未配置接入 key 且匿名令牌端点不可用。引导:" +
|
|
299
|
+
";".join(g["label"] for g in _KEY_GUIDANCE), code=-32012)
|
|
300
|
+
JAVA_KEY = token
|
|
301
|
+
_save_runtime({"java_key": token, "token_tier": "anonymous"})
|
|
302
|
+
out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
|
|
303
|
+
else:
|
|
304
|
+
raise # 网络/413 等如实上抛
|
|
305
|
+
if not fallback:
|
|
306
|
+
server_ids = (out.get("voiceIds") or out.get("data", {}).get("voiceIds")
|
|
307
|
+
or [])
|
|
308
|
+
accepted = len(server_ids) or len(hoard_voices)
|
|
309
|
+
voice_ids.extend(server_ids if server_ids else [""] * len(hoard_voices))
|
|
310
|
+
task_ids.extend([None] * len(hoard_voices)) # 囤积语义:无即时任务
|
|
311
|
+
result = {"accepted": accepted, "voiceIds": voice_ids,
|
|
312
|
+
"taskIds": task_ids, "rejected": rejected,
|
|
313
|
+
"analysis": "deferred", # 囤积语义明示(V6 运营批量消费)
|
|
314
|
+
"path": "hoarding"}
|
|
315
|
+
if out.get("productRegistered") is not None:
|
|
316
|
+
result["productRegistered"] = out.get("productRegistered")
|
|
317
|
+
_ledger(voice_ids, task_ids)
|
|
318
|
+
return result
|
|
319
|
+
# ---- 过渡回落:老链单条提交(仅囤积端点 404 触发) ----
|
|
320
|
+
for i, v, content in items:
|
|
321
|
+
try:
|
|
322
|
+
vid, tid = _legacy_submit(i, v, content)
|
|
323
|
+
accepted += 1
|
|
324
|
+
voice_ids.append(vid)
|
|
325
|
+
task_ids.append(tid)
|
|
326
|
+
except ToolError as e:
|
|
327
|
+
msg = str(e)
|
|
328
|
+
if "Duplicate entry" in msg: # 极端重放场景:DB 唯一键兜底
|
|
329
|
+
accepted += 1
|
|
330
|
+
voice_ids.append(vid)
|
|
331
|
+
task_ids.append(None)
|
|
332
|
+
elif (not JAVA_KEY or e.code == -32012) and not voice_ids:
|
|
333
|
+
if _explicit_key():
|
|
334
|
+
# 显式 key 被拒 → fail fast(同囤积主路径口径,防静默降级)
|
|
335
|
+
raise ToolError(
|
|
336
|
+
f"注入的 key 被引擎拒绝(指纹 {_fingerprint(JAVA_KEY)}):"
|
|
337
|
+
"请核对 key 是否过期/被吊销,或移除 key 走匿名档", code=-32012)
|
|
338
|
+
# 零字段匿名令牌:缺 key/401 → 自动取令牌 → 落 runtime.json → 重试一次
|
|
339
|
+
token = _fetch_anon_token()
|
|
340
|
+
if token:
|
|
341
|
+
JAVA_KEY = token
|
|
342
|
+
_save_runtime({"java_key": token, "token_tier": "anonymous"})
|
|
343
|
+
vid, tid = _legacy_submit(i, v, content)
|
|
344
|
+
accepted += 1
|
|
345
|
+
voice_ids.append(vid)
|
|
346
|
+
task_ids.append(tid)
|
|
347
|
+
else:
|
|
348
|
+
raise ToolError(
|
|
349
|
+
"未配置接入 key 且匿名令牌端点不可用。引导:" +
|
|
350
|
+
";".join(g["label"] for g in _KEY_GUIDANCE), code=-32012)
|
|
351
|
+
else:
|
|
352
|
+
rejected.append({"index": i, "reason": msg[:120]})
|
|
353
|
+
result = {"accepted": accepted, "voiceIds": voice_ids,
|
|
354
|
+
"taskIds": task_ids, "rejected": rejected,
|
|
355
|
+
"path": "legacy-fallback"}
|
|
356
|
+
_ledger(voice_ids, task_ids)
|
|
357
|
+
return result
|
|
358
|
+
|
|
359
|
+
# 本地账本落账(层级①查询的源)
|
|
360
|
+
import time as _time
|
|
361
|
+
_contents = [str(v.get("content", ""))[:40]
|
|
362
|
+
for v in params.get("voices", []) if str(v.get("content", "")).strip()]
|
|
363
|
+
ledger_entries = [
|
|
364
|
+
{"voiceId": vid, "taskId": tid,
|
|
365
|
+
"title": (_contents[i] if i < len(_contents) else ""),
|
|
366
|
+
"product": product, "at": _time.strftime("%Y-%m-%dT%H:%M:%S")}
|
|
367
|
+
for i, (vid, tid) in enumerate(zip(voice_ids, task_ids))
|
|
368
|
+
]
|
|
369
|
+
_ledger_append(ledger_entries)
|
|
370
|
+
return {"accepted": accepted, "voiceIds": voice_ids,
|
|
371
|
+
"taskIds": task_ids, "rejected": rejected}
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _fingerprint(key: str) -> str | None:
|
|
375
|
+
import hashlib
|
|
376
|
+
return hashlib.sha1(key.encode()).hexdigest()[:8] if key else None
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def probe_key(key: str | None = None, timeout: int = 8) -> dict:
|
|
380
|
+
"""key 有效性探针:带 key 调只读端点 GET /external/meta(Filter 网内)。
|
|
381
|
+
|
|
382
|
+
判定语义(引擎是唯一权威,本地零判定):
|
|
383
|
+
- 200 → {"ok": True}:key 有效且在网内
|
|
384
|
+
- 401/-32012 → {"ok": False, "reason": "rejected"}:引擎判无效(过期/吊销/不存在)
|
|
385
|
+
- 其他错误(网络不可达/超时/5xx)→ {"ok": None, "reason": "unreachable"}:
|
|
386
|
+
不判定——网络问题不是 key 问题,报"无法验证"而非"无效"
|
|
387
|
+
"""
|
|
388
|
+
key = key if key is not None else JAVA_KEY
|
|
389
|
+
fp = _fingerprint(key)
|
|
390
|
+
if not key:
|
|
391
|
+
return {"ok": None, "reason": "no-key", "fingerprint": None}
|
|
392
|
+
try:
|
|
393
|
+
_http("GET", _META_PATH, None, key=key, timeout=timeout)
|
|
394
|
+
return {"ok": True, "reason": "verified", "fingerprint": fp}
|
|
395
|
+
except ToolError as ex:
|
|
396
|
+
code = ex.code
|
|
397
|
+
if code == 401 or code == -32012:
|
|
398
|
+
return {"ok": False, "reason": "rejected", "fingerprint": fp}
|
|
399
|
+
return {"ok": None, "reason": "unreachable", "fingerprint": fp}
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
_META_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/meta"
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _key_state() -> dict:
|
|
406
|
+
return {"configured": bool(JAVA_KEY), "fingerprint": _fingerprint(JAVA_KEY),
|
|
407
|
+
"base": JAVA_BASE,
|
|
408
|
+
"note": "已配置" if JAVA_KEY else "未配置(首次提交自动取匿名令牌)"}
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def auth_status(params: dict, client_info: dict | None = None) -> dict:
|
|
412
|
+
"""认证自检:指纹化输出(明文永不出现),无 key 也跑并给引导。"""
|
|
413
|
+
out = {
|
|
414
|
+
"javaKey": _key_state(),
|
|
415
|
+
"packs": sorted(__import__("vod_mcp.packs", fromlist=["enabled_packs"]).enabled_packs()),
|
|
416
|
+
}
|
|
417
|
+
meta = _load_meta()
|
|
418
|
+
out["meta"] = {"source": meta["source"], "stale": meta["stale"],
|
|
419
|
+
"productCount": len(meta["products"])}
|
|
420
|
+
if JAVA_KEY:
|
|
421
|
+
# 主动探针(devkit auth init 真调 IAM 的廉价版):用户问"key 好没好"有确定答案
|
|
422
|
+
out["keyCheck"] = probe_key()
|
|
423
|
+
if not JAVA_KEY:
|
|
424
|
+
out["guidance"] = _KEY_GUIDANCE
|
|
425
|
+
out["tokenReady"] = "首次提交时将自动申请匿名令牌(零字段,日限额低)"
|
|
426
|
+
return out
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
_LEDGER_KEY = "submissions"
|
|
430
|
+
_LEDGER_CAP = 200
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _ledger_append(entries: list) -> None:
|
|
434
|
+
"""本地提交账本(层级①):本机提交记录,供 vod_list_submitted 对账。
|
|
435
|
+
cap 200 条(环形截断,防 runtime.json 膨胀)。
|
|
436
|
+
实现纪律:每次从文件读改写、只动 submissions 键——不从内存 _RT
|
|
437
|
+
合并(陈旧配置会整体回写,覆盖其他键,且把无关配置泄入调用方)。
|
|
438
|
+
D-key-guard-3④:local_ledger=false(企业数据驻留要求)→ 账本关闭,
|
|
439
|
+
vod_list_submitted 随之不可用——留痕是可选项不是义务。"""
|
|
440
|
+
if not entries:
|
|
441
|
+
return
|
|
442
|
+
fresh = _runtime_cfg()
|
|
443
|
+
if fresh.get("local_ledger") is False:
|
|
444
|
+
return
|
|
445
|
+
ledger = (fresh.get(_LEDGER_KEY) or [])[-_LEDGER_CAP:]
|
|
446
|
+
ledger.extend(entries)
|
|
447
|
+
_save_runtime({_LEDGER_KEY: ledger[-_LEDGER_CAP:]})
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def list_submitted(params: dict, client_info: dict | None = None) -> dict:
|
|
451
|
+
"""查询本机已提交的声音(只读,采集者对账闭环)。
|
|
452
|
+
引擎级跨机查询随 VOD-VOI 列表端点;终端用户自助查询维持 P2(签名回执)。"""
|
|
453
|
+
limit = params.get("limit", 20)
|
|
454
|
+
try:
|
|
455
|
+
limit = max(1, min(int(limit), 100))
|
|
456
|
+
except (TypeError, ValueError):
|
|
457
|
+
limit = 20
|
|
458
|
+
ledger = _runtime_cfg().get(_LEDGER_KEY) or [] # 文件现读(进程内账本可能刚更新)
|
|
459
|
+
return {"total": len(ledger),
|
|
460
|
+
"submissions": ledger[-limit:][::-1], # 最新在前
|
|
461
|
+
"scope": "本机提交记录(换机/重装不保留;引擎级查询随 VOD-VOI)"}
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
_RUNTIME_STATE_KEYS = ("java_key", "token_tier", "install_nonce", "submissions",
|
|
465
|
+
"meta_cache")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _distribution() -> str:
|
|
469
|
+
"""分发形态位(D-key-guard-3):install --distribution preset 写入 manifest。
|
|
470
|
+
devkit=自装自管;preset=产品随 agent 分发(客户机首启重生成运行时状态)。"""
|
|
471
|
+
p = Path(__file__).resolve().parent.parent / "install-manifest.json"
|
|
472
|
+
if not p.exists():
|
|
473
|
+
return "devkit"
|
|
474
|
+
try:
|
|
475
|
+
return json.loads(p.read_text(encoding="utf-8")).get("distribution", "devkit")
|
|
476
|
+
except Exception:
|
|
477
|
+
return "devkit"
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _ensure_first_boot(rt_path: Path | None = None) -> dict:
|
|
481
|
+
"""首启标记 + 构建机残留清理(D-key-guard-3①,preset 形态兜底)。
|
|
482
|
+
|
|
483
|
+
主防线是打包排除(分发产物不含 runtime.json);本函数兜底打包者漏排:
|
|
484
|
+
preset 形态 + runtime.json 存在但无 firstBootAt + 携带运行时状态
|
|
485
|
+
(key/nonce/账本/缓存)→ 判构建机残留 → 自动清空这些状态(保留
|
|
486
|
+
product/java_base 等装机配置)+ 重新生成 per-install nonce + 告警。
|
|
487
|
+
处置用自动重生成而非拒绝启动:残留状态全是本机可再生数据,
|
|
488
|
+
自动清零伤害半径为零,拒启会把误判放大成全功能瘫痪。
|
|
489
|
+
firstBootAt 首启写入,此后不再触发(防误伤正常运行中的安装)。"""
|
|
490
|
+
p = rt_path or _runtime_path()
|
|
491
|
+
if not p.exists():
|
|
492
|
+
return {"action": "none"}
|
|
493
|
+
try:
|
|
494
|
+
cfg = json.loads(p.read_text(encoding="utf-8"))
|
|
495
|
+
except Exception:
|
|
496
|
+
return {"action": "none"}
|
|
497
|
+
if cfg.get("firstBootAt"):
|
|
498
|
+
_warn_if_cloned(cfg, p)
|
|
499
|
+
return {"action": "none"}
|
|
500
|
+
residual = [k for k in _RUNTIME_STATE_KEYS if cfg.get(k)]
|
|
501
|
+
import time as _t
|
|
502
|
+
if _distribution() == "preset" and residual:
|
|
503
|
+
# 残留清理=整体重建(合并删不掉旧键),但保留装机配置(product/java_base 等)
|
|
504
|
+
_save_runtime({**{k: v for k, v in cfg.items() if k not in _RUNTIME_STATE_KEYS},
|
|
505
|
+
"firstBootAt": _t.strftime("%Y-%m-%dT%H:%M:%S")},
|
|
506
|
+
replace=True)
|
|
507
|
+
_warn(f"检测到构建机残留状态({','.join(residual)})已自动清空重生成——"
|
|
508
|
+
"分发产物应只含代码与配置,不含安装结果(D-key-guard-3①)")
|
|
509
|
+
return {"action": "cleaned", "removed": residual}
|
|
510
|
+
_save_runtime({"firstBootAt": _t.strftime("%Y-%m-%dT%H:%M:%S")})
|
|
511
|
+
return {"action": "stamped"}
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _warn_if_cloned(cfg: dict, p: Path) -> None:
|
|
515
|
+
"""preset 克隆镜像检测(D-key-guard-3①延伸,仅告警不阻断):
|
|
516
|
+
firstBootAt 距今显著超过本机 uptime(>1h 容差)→ 本机状态大概率来自
|
|
517
|
+
母机镜像克隆——所有克隆机共享同一 device 锚点/账本,声量与配额会收敛。
|
|
518
|
+
判据:firstBootAt 的"年龄" > uptime+容差 ⇒ 首启发生在"这台机器"存在之前。"""
|
|
519
|
+
import time as _t
|
|
520
|
+
try:
|
|
521
|
+
if _distribution() != "preset":
|
|
522
|
+
return
|
|
523
|
+
boot = _t.mktime(_t.strptime(cfg["firstBootAt"], "%Y-%m-%dT%H:%M:%S"))
|
|
524
|
+
uptime_s = float(open("/proc/uptime").read().split()[0])
|
|
525
|
+
if _t.time() - boot > uptime_s + 3600:
|
|
526
|
+
_warn("疑似镜像克隆机:firstBootAt 早于本机 uptime——克隆分发未清 "
|
|
527
|
+
"runtime.json,所有克隆机共享同一设备锚点/账本。请在镜像冻结前 "
|
|
528
|
+
"uninstall 或删除 runtime.json(装机 checklist ②)")
|
|
529
|
+
except Exception:
|
|
530
|
+
pass
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _save_runtime(update: dict, replace: bool = False) -> None:
|
|
534
|
+
p = _runtime_path()
|
|
535
|
+
cfg = {}
|
|
536
|
+
if p.exists() and not replace:
|
|
537
|
+
try:
|
|
538
|
+
cfg = json.loads(p.read_text(encoding="utf-8"))
|
|
539
|
+
except Exception:
|
|
540
|
+
cfg = {}
|
|
541
|
+
cfg.update(update)
|
|
542
|
+
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
543
|
+
# S1 式写后验(借 huaweicloud-devkit ensurePrivateMode 模式):写完 chmod 0600
|
|
544
|
+
# 并 stat 回验——不假设 chmod 按文档工作(WSL/drvfs 会静默忽略 chmod),
|
|
545
|
+
# 验的是效果不是动作;runtime.json 含 java_key 明文,权限失效必须告警
|
|
546
|
+
try:
|
|
547
|
+
os.chmod(p, 0o600)
|
|
548
|
+
mode = stat.S_IMODE(os.stat(p).st_mode)
|
|
549
|
+
if mode != 0o600:
|
|
550
|
+
_warn(f"runtime.json 权限异常({oct(mode)},期望 0600)——"
|
|
551
|
+
"key 可能被同机其他用户读取,请检查文件系统(WSL 挂载盘建议移回 Linux 原生盘)")
|
|
552
|
+
except OSError as e:
|
|
553
|
+
_warn(f"runtime.json 权限校验失败:{e}")
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _log(line: str, path: str = "/tmp/vod_mcp_server.log") -> None:
|
|
557
|
+
"""统一日志出口,1MB 截断轮转
|
|
558
|
+
(D-key-guard-3⑤:客户机长期运行防无限增长;截断保留尾部近期日志)。"""
|
|
559
|
+
try:
|
|
560
|
+
p = path
|
|
561
|
+
if os.path.exists(p) and os.path.getsize(p) > 1024 * 1024:
|
|
562
|
+
with open(p, "r", encoding="utf-8", errors="replace") as f:
|
|
563
|
+
tail = f.read()[-200 * 1024:]
|
|
564
|
+
os.replace(p, p + ".old")
|
|
565
|
+
with open(p, "w", encoding="utf-8") as f:
|
|
566
|
+
f.write("== truncated ==\n" + tail)
|
|
567
|
+
with open(p, "a", encoding="utf-8") as f:
|
|
568
|
+
f.write(line.rstrip("\n") + "\n")
|
|
569
|
+
except Exception:
|
|
570
|
+
pass
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _warn(msg: str) -> None:
|
|
574
|
+
"""告警出口:server 日志(排障真源),失败静默——不阻断业务主链。"""
|
|
575
|
+
_log(f"warn {msg}")
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _extract_anon_token(out: object) -> str | None:
|
|
579
|
+
"""从令牌端点响应提取 token(真源契约:引擎 ApiResponse 信封
|
|
580
|
+
{"code":200,"data":{"token":...}};顶层扁平 {"token":...} 兼容历史形态)。"""
|
|
581
|
+
if not isinstance(out, dict):
|
|
582
|
+
return None
|
|
583
|
+
data = out.get("data")
|
|
584
|
+
token = data.get("token") if isinstance(data, dict) else None
|
|
585
|
+
if not token:
|
|
586
|
+
token = out.get("token")
|
|
587
|
+
return token if isinstance(token, str) and token else None
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _fetch_anon_token() -> str | None:
|
|
591
|
+
"""零字段匿名令牌(T7b 定稿):渠道由引擎囤积入库侧固定赋值 vod-agent
|
|
592
|
+
(链路即渠道,客户端不自报)——本端保持空 body(方案 C 原样)。
|
|
593
|
+
D-anon-verify(2026-11-05 真机实锤):引擎返回 ApiResponse 信封,
|
|
594
|
+
顶层取 token 恒 None → 无 key 首提必 -32012,信封解析为必经路径。"""
|
|
595
|
+
try:
|
|
596
|
+
out = _http("POST", _TOKEN_PATH, {}, base=JAVA_BASE, key="", timeout=15)
|
|
597
|
+
return _extract_anon_token(out)
|
|
598
|
+
except ToolError:
|
|
599
|
+
return None
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def devkit_info(params: dict, client_info: dict | None = None) -> dict:
|
|
603
|
+
return provenance.info_payload(client_info)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
# 工具名 → 处理器(是否接收 client_info)
|
|
607
|
+
_HANDLERS = {
|
|
608
|
+
"vod_submit_voices": submit_voices,
|
|
609
|
+
"vod_list_submitted": list_submitted,
|
|
610
|
+
"vod_devkit_info": devkit_info,
|
|
611
|
+
"vod_auth_status": auth_status,
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def dispatch(name: str, params: dict, client_info: dict | None = None) -> dict:
|
|
616
|
+
handler = _HANDLERS.get(name)
|
|
617
|
+
if handler is None:
|
|
618
|
+
raise ToolError(f"未知工具: {name}", code=-32601)
|
|
619
|
+
needs_host = handler in (devkit_info, submit_voices, auth_status)
|
|
620
|
+
return handler(params, client_info) if needs_host else handler(params)
|