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.
- package/CHANGELOG.md +43 -0
- package/QUICKSTART.md +47 -23
- package/README.en.md +7 -2
- package/README.md +6 -2
- package/bin/vod-devkit +12 -1166
- package/contract/tools.schema.json +1 -1
- package/integrations/atomcode/host.json +5 -3
- package/integrations/codeartsdoer/host.json +1 -2
- 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/skills/vod-feedback-collect/SKILL.md +13 -4
- package/plugins/vod-devkit/skills/vod-problem-classification-rules/SKILL.md +2 -1
- package/plugins/vod-devkit/skills/vod-scoring-rules/SKILL.md +2 -1
- 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/attribution.py +8 -8
- package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +3 -1
- package/plugins/vod-devkit/vod_mcp/host_adapters/codex.py +16 -3
- package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +99 -16
- 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/remote_app.py +25 -0
- 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 +11 -9
- package/plugins/vod-devkit/vod_mcp/tools.py +23 -1300
- package/plugins/vod-devkit/vod_mcp/transport_remote.py +68 -8
- package/plugins/vod-devkit/vod_mcp/update_check.py +1 -1
- package/skills/vod-feedback-collect/SKILL.md +13 -4
- package/skills/vod-problem-classification-rules/SKILL.md +2 -1
- package/skills/vod-scoring-rules/SKILL.md +2 -1
- package/vod_mcp/__init__.py +1 -1
- package/vod_mcp/attribution.py +8 -8
- 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-314.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/codex.py +16 -3
- package/vod_mcp/host_adapters/hermes.py +99 -16
- 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/remote_app.py +25 -0
- package/vod_mcp/runtime_state.py +324 -0
- package/vod_mcp/server.py +10 -7
- package/vod_mcp/skills_registry.py +11 -9
- package/vod_mcp/tools.py +23 -1300
- package/vod_mcp/transport_remote.py +68 -8
- 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
|
@@ -1,141 +1,20 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""工具面装配入口(P2 后的 shim):契约装载 + tools/list 规格 + 分派表。
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
实现已按 pack 纵切到 vod_mcp/packs/{core,collect,knowledge}.py,共享件在
|
|
4
|
+
vod_mcp/net.py(出口/身份)与 vod_mcp/runtime_state.py(状态)。本文件只保留
|
|
5
|
+
"契约 → 规格 → 分派"这三件装配职责,不承载任何业务逻辑。
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
POST …/external/token(VOD-KEY,零字段匿名令牌)
|
|
7
|
+
纪律:此处**不 re-export 私有符号**(_http/_save_runtime/...)。历史测试用
|
|
8
|
+
monkeypatch.setattr(tools, "_http", fake) 打桩,迁到实现模块后若仍在 shim 上打桩
|
|
9
|
+
会静默不生效——宁可直接 AttributeError(tests/test_structure_guards.py 有断言)。
|
|
11
10
|
"""
|
|
12
|
-
import contextvars
|
|
13
11
|
import json
|
|
14
|
-
import os
|
|
15
|
-
import stat
|
|
16
|
-
import urllib.request
|
|
17
|
-
import urllib.error
|
|
18
|
-
from pathlib import Path
|
|
19
12
|
|
|
20
|
-
from vod_mcp import
|
|
21
|
-
from vod_mcp import
|
|
22
|
-
from vod_mcp import
|
|
13
|
+
from vod_mcp import paths
|
|
14
|
+
from vod_mcp.net import ToolError # noqa: F401 唯一异常类,供 `except tools.ToolError`
|
|
15
|
+
from vod_mcp.packs import collect, core, knowledge
|
|
23
16
|
|
|
24
|
-
|
|
25
|
-
# 每个请求由 transport_remote 注入,逐请求隔离(contextvars 随 asyncio 任务/
|
|
26
|
-
# 线程传播),因此并发客户端不会互相覆盖 key。
|
|
27
|
-
# 身份:stdio 面=装在哪台机器;HTTP 面=这个请求带了谁的 key。
|
|
28
|
-
# 插件自己不产生身份(不代签、不落盘),只把请求头的 Bearer 转成引擎鉴权。
|
|
29
|
-
_REQ_KEY = contextvars.ContextVar("vod_req_key", default=None)
|
|
30
|
-
_SERVER_FACE = contextvars.ContextVar("vod_server_face", default=False)
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def _eff_key(explicit=None) -> str:
|
|
34
|
-
"""当前生效的 key:显式参数 > 请求头(HTTP 面)> env/runtime(stdio 面)。"""
|
|
35
|
-
if explicit is not None:
|
|
36
|
-
return explicit
|
|
37
|
-
return _REQ_KEY.get() or JAVA_KEY
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
# D-followup-impl-2:追问拒答语义词集(答"没有"类=两字段不上送)。
|
|
41
|
-
# 契约话术承诺了"不方便回复没有",客户端必须技术兜底——模型不守话术纪律时
|
|
42
|
-
# 键集合仍零漂移(test_followup_declined_or_blank_omitted 回归锁)。
|
|
43
|
-
_FOLLOWUP_DECLINES = frozenset({
|
|
44
|
-
"没有", "无", "没有。", "没了", "跳过", "不方便", "不用了", "不用",
|
|
45
|
-
"不补充", "算了", "没有了", "没有了。", "不方便说", "no", "none", "skip", "n/a",
|
|
46
|
-
})
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
def _followup_fields(voice: dict) -> dict:
|
|
50
|
-
"""D-followup-impl-2 单源提取(submit 主路径与 draft 暂存共用,禁双边漂移):
|
|
51
|
-
仅 trim 非空且非拒答词才含键;引擎同口径截 2000;内容永不回流 content。
|
|
52
|
-
followupStatus(评审八点 #3 引擎侧承载的插件上报):三态白名单归一
|
|
53
|
-
(strip+lower),白名单外/缺失省键——引擎侧降 NULL 不拒收,插件侧同口径双保险。"""
|
|
54
|
-
out = {}
|
|
55
|
-
for _f in ("reproSteps", "expectedBehavior"):
|
|
56
|
-
_val = str(voice.get(_f) or "").strip()
|
|
57
|
-
if _val and _val.lower() not in _FOLLOWUP_DECLINES:
|
|
58
|
-
out[_f] = _val[:2000]
|
|
59
|
-
_st = str(voice.get("followupStatus") or "").strip().lower()
|
|
60
|
-
if _st in ("not_asked", "declined", "answered"):
|
|
61
|
-
out["followupStatus"] = _st
|
|
62
|
-
return out
|
|
63
|
-
|
|
64
|
-
_CONTRACT_PATH = Path(__file__).resolve().parent.parent / "contract" / "tools.schema.json"
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
def _runtime_path() -> Path:
|
|
68
|
-
return Path(__file__).resolve().parent / "runtime.json"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def _runtime_cfg() -> dict:
|
|
72
|
-
# 路径单源:一律走 _runtime_path()(曾与 _save_runtime 双写路径,
|
|
73
|
-
# 注入/重定位场景读写分叉——测试实锤的真缺陷)
|
|
74
|
-
p = _runtime_path()
|
|
75
|
-
if p.exists():
|
|
76
|
-
try:
|
|
77
|
-
return json.loads(p.read_text(encoding="utf-8"))
|
|
78
|
-
except Exception:
|
|
79
|
-
return {}
|
|
80
|
-
return {}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
# 上游配置:env 优先,runtime.json 兜底——不依赖宿主 env 透传
|
|
84
|
-
# (实测部分 MCP 宿主对子进程 env 过滤/丢失,如 Hermes 多 --env 只存活一个)
|
|
85
|
-
_RT = _runtime_cfg()
|
|
86
|
-
JAVA_BASE = os.environ.get("VOD_JAVA_API_BASE") or _RT.get("java_base") or DEFAULT_JAVA_BASE
|
|
87
|
-
JAVA_KEY = os.environ.get("VOD_JAVA_API_KEY", "") or _RT.get("java_key", "") # ExternalApiKeyFilter Bearer
|
|
88
|
-
|
|
89
|
-
_META_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/meta"
|
|
90
|
-
_META_TTL = 24 * 3600
|
|
91
|
-
# 快照兜底(引擎 meta 端点未上线/不可达时用;stale 语义见 _load_meta)
|
|
92
|
-
_META_SNAPSHOT = {"products": ["agentarts", "codearts", "dataarts", "maas", "obs",
|
|
93
|
-
"officeclaw", "modelarts"]}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
def _load_meta(force: bool = False) -> dict:
|
|
97
|
-
"""可漂移值动态取:缓存 TTL 24h,引擎端点不可达时回退快照并标 stale。
|
|
98
|
-
真源=引擎 submit 校验常量。
|
|
99
|
-
|
|
100
|
-
T7i:productCatalog=[{id,name}](t_vod_product 运营预置,meta 组装)——
|
|
101
|
-
提交产品归因按平台主键 id 的解析真源;老引擎无该键=catalog 空。
|
|
102
|
-
|
|
103
|
-
**2026-11-12 引擎契约收紧**:
|
|
104
|
-
· `nameAliases` / `aliases` 已由引擎删除 → 本函数不再读取;别名能力改由
|
|
105
|
-
attribution 的规则派生 + BRAND_ALIASES 提供。
|
|
106
|
-
· `problemTypes` 改为按产品下发(`?productId=`):**无参请求不含该键**。
|
|
107
|
-
分类白名单必须用 `_allowed_tags(product_id)` 按产品取,见下。
|
|
108
|
-
"""
|
|
109
|
-
import time
|
|
110
|
-
cache = _RT.get("meta_cache") or {}
|
|
111
|
-
now = time.time()
|
|
112
|
-
if not force and cache.get("data") and now - cache.get("fetchedAt", 0) < _META_TTL:
|
|
113
|
-
return {"products": cache["data"].get("products", _META_SNAPSHOT["products"]),
|
|
114
|
-
"catalog": cache["data"].get("productCatalog") or [],
|
|
115
|
-
"dictVersion": cache["data"].get("dictVersion"),
|
|
116
|
-
"stale": False, "source": "cache"}
|
|
117
|
-
try:
|
|
118
|
-
out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
|
|
119
|
-
data = out.get("data") or {}
|
|
120
|
-
if isinstance(data.get("products"), list) and data["products"]:
|
|
121
|
-
_save_runtime({"meta_cache": {"fetchedAt": int(now), "data": data}})
|
|
122
|
-
return {"products": data["products"],
|
|
123
|
-
"catalog": data.get("productCatalog") or [],
|
|
124
|
-
"dictVersion": data.get("dictVersion"),
|
|
125
|
-
"stale": False, "source": "meta"}
|
|
126
|
-
except ToolError:
|
|
127
|
-
pass
|
|
128
|
-
# 快照不含分类白名单:_allowed_tags 取不到产品分类时 allowed 为空=不校验
|
|
129
|
-
# (宁可放行也不误杀采集)
|
|
130
|
-
return {"products": _META_SNAPSHOT["products"], "catalog": [],
|
|
131
|
-
"dictVersion": None,
|
|
132
|
-
"stale": True, "source": "snapshot"}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
class ToolError(Exception):
|
|
136
|
-
def __init__(self, message: str, code: int = -32000):
|
|
137
|
-
super().__init__(message)
|
|
138
|
-
self.code = code
|
|
17
|
+
_CONTRACT_PATH = paths.CONTRACT
|
|
139
18
|
|
|
140
19
|
|
|
141
20
|
def load_contract() -> dict:
|
|
@@ -158,1174 +37,17 @@ def tool_specs(only: list) -> list:
|
|
|
158
37
|
return specs
|
|
159
38
|
|
|
160
39
|
|
|
161
|
-
def _http(method: str, path: str, body: dict | None = None,
|
|
162
|
-
base: str | None = None, key: str | None = None, timeout: int = 30) -> dict:
|
|
163
|
-
"""统一出口:一律携带 Authorization Bearer(E1 修复:认证头缺失)。
|
|
164
|
-
|
|
165
|
-
base/key 缺省在调用时解析模块级配置(不能用函数默认值——定义时即冻结,
|
|
166
|
-
环境变更/测试 monkeypatch 均无法生效)。
|
|
167
|
-
"""
|
|
168
|
-
base = base if base is not None else JAVA_BASE
|
|
169
|
-
key = key if key is not None else JAVA_KEY
|
|
170
|
-
# 传输协议守卫:非本机回环一律要求 https(Bearer 不得明文过公网)
|
|
171
|
-
_host = base.split("//", 1)[-1].split("/", 1)[0].split(":")[0]
|
|
172
|
-
if not base.startswith("https://") and _host not in ("127.0.0.1", "localhost", "::1"):
|
|
173
|
-
raise ToolError(
|
|
174
|
-
f"上游 {base} 非 https 且非本机回环——Bearer key 明文外发被拒"
|
|
175
|
-
"(配置 VOD_JAVA_API_BASE 为 https:// 地址)", code=-32014)
|
|
176
|
-
url = base.rstrip("/") + path
|
|
177
|
-
_log(f"http {method} {url} key={'yes' if key else 'no'}")
|
|
178
|
-
data = json.dumps(body).encode() if body is not None else None
|
|
179
|
-
headers = {"Content-Type": "application/json",
|
|
180
|
-
# VOD-DEVICE:设备锚点(install_nonce=首启自生成常驻,零新增状态)——
|
|
181
|
-
# 引擎据此建每设备独立锚点(NAT/产品分发不再收敛);服务端缺失回落 legacy
|
|
182
|
-
"X-Vod-Device-Id": _install_nonce()}
|
|
183
|
-
if key:
|
|
184
|
-
headers["Authorization"] = f"Bearer {key}"
|
|
185
|
-
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
186
|
-
try:
|
|
187
|
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
188
|
-
return json.loads(resp.read().decode())
|
|
189
|
-
except urllib.error.HTTPError as e:
|
|
190
|
-
detail = e.read().decode()[:200]
|
|
191
|
-
if e.code == 401:
|
|
192
|
-
raise ToolError(
|
|
193
|
-
f"鉴权失败({base}):检查 VOD_JAVA_API_KEY 配置",
|
|
194
|
-
code=-32012) from e
|
|
195
|
-
raise ToolError(f"上游返回 {e.code}: {detail}", code=e.code) from e
|
|
196
|
-
except urllib.error.URLError as e:
|
|
197
|
-
raise ToolError(f"上游不可达({base}): {e.reason}", code=-32001) from e
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
# 引擎 submit 校验白名单(ExternalVoiceServiceImpl.VALID_PRODUCTS 实测:
|
|
201
|
-
# CODEARTS/AGENTARTS/OFFICECLAW/DATAARTS/MAAS/OBS + 别名归一 MODELARTS→MAAS)
|
|
202
|
-
_PRODUCT_MAP = {
|
|
203
|
-
"agentarts": "AgentArts", "codearts": "CodeArts", "dataarts": "DataArts",
|
|
204
|
-
"maas": "MaaS", "obs": "OBS", "officeclaw": "OfficeClaw",
|
|
205
|
-
"modelarts": "MaaS", # 引擎别名归一实测
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
_SESSION_TTL = 30 * 60 # 会话内滑动记忆(D-product-ask-1)
|
|
210
|
-
_SESSION_MEM: dict = {} # 进程=一次宿主会话:重启即清,跨会话不继承
|
|
211
|
-
_UNRESOLVED_CODE = -32010 # 「需要先问用户是哪个产品」的可执行错误码
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
def _session_key(client_info) -> str:
|
|
215
|
-
"""记忆作用域(Scope):宿主 + 身份。
|
|
216
|
-
|
|
217
|
-
进程内即一次 stdio 会话;远程面是多租户共享进程,所以身份也必须进 key,
|
|
218
|
-
否则 A 用户的"不知道→CodeArts"会串到 B 用户。
|
|
219
|
-
"""
|
|
220
|
-
ci = client_info or {}
|
|
221
|
-
import hashlib
|
|
222
|
-
ident = _eff_key() or ""
|
|
223
|
-
ident_hash = hashlib.sha256(ident.encode()).hexdigest()[:8] if ident else _install_nonce()
|
|
224
|
-
return f"{ci.get('name') or 'unknown'}|{ident_hash}"
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
def _memory_get(client_info) -> dict:
|
|
228
|
-
import time as _t
|
|
229
|
-
cur = _SESSION_MEM.get(_session_key(client_info)) or {}
|
|
230
|
-
if cur and _t.time() - float(cur.get("at") or 0) > _SESSION_TTL:
|
|
231
|
-
return {}
|
|
232
|
-
return dict(cur)
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
def _memory_put(client_info, **fields) -> None:
|
|
236
|
-
import time as _t
|
|
237
|
-
key = _session_key(client_info)
|
|
238
|
-
cur = _memory_get(client_info)
|
|
239
|
-
cur.update(fields)
|
|
240
|
-
cur["at"] = int(_t.time()) # 滑动过期
|
|
241
|
-
_SESSION_MEM[key] = cur
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
def _host_product() -> str | None:
|
|
245
|
-
"""宿主产品(兜底用):安装期写入 runtime.host_product,env 可覆盖。"""
|
|
246
|
-
return (os.environ.get("VOD_HOST_PRODUCT")
|
|
247
|
-
or str(_RT.get("host_product") or "").strip()
|
|
248
|
-
or str(_runtime_cfg().get("host_product") or "").strip() or None)
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
def search_products(params: dict) -> dict:
|
|
252
|
-
"""产品候选检索(只读):给模型 3-5 个候选去问用户,而不是从 103 条里瞎猜。"""
|
|
253
|
-
query = str(params.get("query") or "").strip()
|
|
254
|
-
limit = int(params.get("limit") or 5)
|
|
255
|
-
limit = max(1, min(limit, 20))
|
|
256
|
-
meta = _load_meta()
|
|
257
|
-
catalog = meta.get("catalog") or []
|
|
258
|
-
if not query:
|
|
259
|
-
return {"candidates": [], "total": len(catalog)}
|
|
260
|
-
idx = _attrib.build_alias_index(meta)
|
|
261
|
-
hits = _attrib.match_products(query, idx)
|
|
262
|
-
seen, cands = set(), []
|
|
263
|
-
for h in hits:
|
|
264
|
-
pid = str(h.get("id") or "")
|
|
265
|
-
if not pid or pid in seen:
|
|
266
|
-
continue
|
|
267
|
-
seen.add(pid)
|
|
268
|
-
cands.append({"id": pid, "name": h["product"],
|
|
269
|
-
"score": round(min(1.0, len(h["alias"]) / max(len(query), 1)), 2),
|
|
270
|
-
"matchReason": f"alias:{h['alias']}"})
|
|
271
|
-
if not cands: # 别名没命中:退回名字子串(用户可能打错/只说一半)
|
|
272
|
-
q = query.lower()
|
|
273
|
-
for item in catalog:
|
|
274
|
-
name = str(item.get("name") or "")
|
|
275
|
-
if q and (q in name.lower() or name.lower() in q):
|
|
276
|
-
cands.append({"id": str(item.get("id")), "name": name, "score": 0.5,
|
|
277
|
-
"matchReason": "name-substring"})
|
|
278
|
-
if not cands: # 完全无关联词:给名录前 N 个当"可选项"(问用户用)
|
|
279
|
-
for item in catalog[:limit]:
|
|
280
|
-
cands.append({"id": str(item.get("id")), "name": str(item.get("name") or ""),
|
|
281
|
-
"score": 0.0, "matchReason": "catalog-default"})
|
|
282
|
-
cands.sort(key=lambda c: (c["score"], len(c["name"])), reverse=True)
|
|
283
|
-
return {"candidates": cands[:limit], "total": len(catalog)}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
def _attribute_product(items: list, params: dict, client_info: dict | None = None) -> dict:
|
|
287
|
-
"""归因(D-product-ask-1,2026-11-11 负责人拍板:不许裸 UNKNOWN,缺产品先问)。
|
|
288
|
-
|
|
289
|
-
优先级(按拍板口径,不是"原话永远第一"):
|
|
290
|
-
① 用户明确回答/确认(params.product,仅问过用户后由模型填)
|
|
291
|
-
② 原话唯一且高置信提及(多产品/歧义=低置信,转去问)
|
|
292
|
-
③ 会话记忆(30 分钟滑动,进程内;跨会话不继承)
|
|
293
|
-
④ 安装先验
|
|
294
|
-
⑤ host_default:仅当用户明确说"不知道/随便"(params.productNotSpecified)
|
|
295
|
-
都拿不到 → 返回 source=unknown + confidence=low,由调用方抛可执行错误要求追问。
|
|
296
|
-
"""
|
|
297
|
-
text = "\n".join(content for _i, _v, content in items)
|
|
298
|
-
meta = _load_meta()
|
|
299
|
-
answer = str(params.get("product") or "").strip()
|
|
300
|
-
mem = _memory_get(client_info)
|
|
301
|
-
binding = str(_RT.get("product") or "").strip() or None
|
|
302
|
-
|
|
303
|
-
if answer:
|
|
304
|
-
rid = _attrib.resolve_id(answer, meta)
|
|
305
|
-
hit = [c for c in (meta.get("catalog") or [])
|
|
306
|
-
if str(c.get("id")) == str(rid)
|
|
307
|
-
or str(c.get("name") or "").lower() == answer.lower()]
|
|
308
|
-
if not hit and not (meta.get("catalog") or []):
|
|
309
|
-
# 名录不可用(离线/快照/老引擎):没有校验依据,不能假装能核。
|
|
310
|
-
# 按用户回答原样上报,标 low(引擎侧仍会按表解析,未命中落未知池)。
|
|
311
|
-
return {"product": answer, "productName": answer, "source": "user_answer",
|
|
312
|
-
"confidence": "low", "rawText": answer,
|
|
313
|
-
"evidence": [{"reason": "catalog-unavailable", "rawText": answer}],
|
|
314
|
-
"ignored": None}
|
|
315
|
-
if not hit:
|
|
316
|
-
# 用户说了名录里没有的产品("智果"/"XYZ"/打错):**不拿原名硬提交**,
|
|
317
|
-
# 也不要自己猜最像的——把候选交回去,让模型按名录再问一次。
|
|
318
|
-
cands = search_products({"query": answer, "limit": 5})["candidates"]
|
|
319
|
-
return {"product": None, "productName": None, "source": "unknown",
|
|
320
|
-
"confidence": "low", "rawText": answer, "unmatched_answer": answer,
|
|
321
|
-
"candidates": cands,
|
|
322
|
-
"evidence": [{"reason": "unmatched-answer", "rawText": answer}],
|
|
323
|
-
"ignored": None}
|
|
324
|
-
name = hit[0].get("name")
|
|
325
|
-
return {"product": str(hit[0].get("id")), "productName": name,
|
|
326
|
-
"source": "user_answer", "confidence": "high", "rawText": answer,
|
|
327
|
-
"evidence": [{"product": name, "alias": "用户回答", "snippet": answer}],
|
|
328
|
-
"ignored": None}
|
|
329
|
-
|
|
330
|
-
result = _attrib.attribute(text, meta,
|
|
331
|
-
memory={k: v for k, v in mem.items()
|
|
332
|
-
if k in ("product", "productName", "alias",
|
|
333
|
-
"snippet", "at")},
|
|
334
|
-
binding=binding)
|
|
335
|
-
result["rawText"] = None
|
|
336
|
-
result["ignored"] = None
|
|
337
|
-
if result["source"] == "user_input":
|
|
338
|
-
result["confidence"] = "high"
|
|
339
|
-
return result
|
|
340
|
-
if result["source"] == "memory" and mem.get("product") and not mem.get("not_specified"):
|
|
341
|
-
result["confidence"] = "medium"
|
|
342
|
-
return result
|
|
343
|
-
if result["source"] == "install_binding":
|
|
344
|
-
result["confidence"] = "medium"
|
|
345
|
-
return result
|
|
346
|
-
|
|
347
|
-
not_specified = bool(params.get("productNotSpecified")) or bool(mem.get("not_specified"))
|
|
348
|
-
if not_specified:
|
|
349
|
-
# 用户明确说不知道:**不做任何猜测**(不按宿主产品兜底——那也是一次推断,
|
|
350
|
-
# 且产品会进引擎幂等域,错归代价比丢一条高)。交给调用方提示用户"缺产品不提交"。
|
|
351
|
-
pass
|
|
352
|
-
ev = list(result.get("evidence") or [])
|
|
353
|
-
if not_specified:
|
|
354
|
-
ev = [{"reason": "user-not-specified"}] + ev
|
|
355
|
-
return {"product": None, "productName": None, "source": "unknown",
|
|
356
|
-
"not_specified": not_specified,
|
|
357
|
-
"confidence": "low", "rawText": None,
|
|
358
|
-
"evidence": (ev or [{"reason": "no-evidence"}]),
|
|
359
|
-
"ignored": None}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
def _require_product_or_ask(attr: dict, items: list, client_info: dict | None = None) -> None:
|
|
363
|
-
"""缺产品且用户没说不知道 → 可执行错误:先问一次(D-product-ask-1)。
|
|
364
|
-
|
|
365
|
-
错误里带候选(来自原话关键词),模型照着问一句就能补齐;不是"参考文档"。
|
|
366
|
-
"""
|
|
367
|
-
if attr.get("product"):
|
|
368
|
-
return
|
|
369
|
-
# 追问轮次上限(2026-11-12 评审采纳):同一会话最多追问 2 次,之后明确终止——
|
|
370
|
-
# 避免"用户连续给两个都查不到的名字"时模型无限重问。
|
|
371
|
-
mem = _memory_get(client_info)
|
|
372
|
-
fails = int(mem.get("ask_failures") or 0) + 1
|
|
373
|
-
_memory_put(client_info, ask_failures=fails)
|
|
374
|
-
stop = fails > 2
|
|
375
|
-
tail = "(已追问 2 次仍未确认:别再问了,直接告诉用户这条反馈因为没有产品归属而不提交)"
|
|
376
|
-
|
|
377
|
-
if attr.get("unmatched_answer"):
|
|
378
|
-
cands = attr.get("candidates") or []
|
|
379
|
-
hint = "、".join(f"{c['name']}({c['id']})" for c in cands) or "(名录为空)"
|
|
380
|
-
raise ToolError(
|
|
381
|
-
f"用户说的产品「{attr['rawText']}」不在产品名录里,不能按它提交。"
|
|
382
|
-
f"请按名录再确认一次是哪一个:{hint};用户仍说不出来就说明这条先不提交。"
|
|
383
|
-
+ (tail if stop else ""),
|
|
384
|
-
code=_UNRESOLVED_CODE)
|
|
385
|
-
if attr.get("not_specified"):
|
|
386
|
-
raise ToolError(
|
|
387
|
-
"用户没有提供产品,这条反馈**不能提交**:请告诉用户「没有产品归属的反馈我不提交,"
|
|
388
|
-
"因为不知道要转给哪个产品团队」,并请他补充是哪个产品;他仍不想说就说明这条先不提交。"
|
|
389
|
-
f"可选候选:{'、'.join(c['name'] + '(' + str(c['id']) + ')' for c in search_products({'query': '\n'.join(x[2] for x in items), 'limit': 5})['candidates'])}"
|
|
390
|
-
+ (tail if stop else ""),
|
|
391
|
-
code=_UNRESOLVED_CODE)
|
|
392
|
-
if os.environ.get("VOD_ALLOW_UNKNOWN_PRODUCT") == "1":
|
|
393
|
-
# 旧客户端兼容(业界口径:可选字段 + 明确默认值,不做破坏性变更):
|
|
394
|
-
# 缺 product 的老客户端不让它直接失败,回执标 legacy_default/low,可追溯。
|
|
395
|
-
attr["source"] = "legacy_default"
|
|
396
|
-
attr["confidence"] = "low"
|
|
397
|
-
return
|
|
398
|
-
text = "\n".join(c for _i, _v, c in items)
|
|
399
|
-
cands = search_products({"query": text, "limit": 5})["candidates"]
|
|
400
|
-
hint = "、".join(f"{c['name']}({c['id']})" for c in cands) or "(名录未命中,可问用户直接说产品名)"
|
|
401
|
-
raise ToolError(
|
|
402
|
-
"这条反馈还没确定是哪个产品:请先问用户一次『这条是哪个产品的反馈?』,"
|
|
403
|
-
"把回答填进 product(产品名或 ID);用户明确说不知道/随便时,传 productNotSpecified=true。"
|
|
404
|
-
f"候选:{hint}", code=_UNRESOLVED_CODE)
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
def _attach_attribution(result: dict, attr: dict) -> None:
|
|
408
|
-
"""回执留痕(D-product-ask-1):来源 + 置信 + 原始回答 + 证据。
|
|
409
|
-
|
|
410
|
-
productSource 枚举:user_input | user_answer | memory | install_binding |
|
|
411
|
-
host_default(后者恒 confidence=low,必须可人工修正)。
|
|
412
|
-
"""
|
|
413
|
-
result["productSource"] = attr.get("source") or "unknown"
|
|
414
|
-
result["productConfidence"] = attr.get("confidence") or "low"
|
|
415
|
-
if attr.get("productName"):
|
|
416
|
-
result["productName"] = attr["productName"]
|
|
417
|
-
if attr.get("product") is not None:
|
|
418
|
-
result["productId"] = str(attr["product"])
|
|
419
|
-
if attr.get("rawText"):
|
|
420
|
-
result["productRawText"] = attr["rawText"]
|
|
421
|
-
if attr.get("evidence"):
|
|
422
|
-
result["productEvidence"] = attr["evidence"]
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
def _merge_ledger(extra: dict | None, attr: dict) -> dict:
|
|
426
|
-
"""账本条目带上归因来源与证据:错归可回溯到用户原话(S99)。"""
|
|
427
|
-
out = dict(extra or {})
|
|
428
|
-
out["productSource"] = attr.get("source") or "unknown"
|
|
429
|
-
if attr.get("evidence"):
|
|
430
|
-
out["productEvidence"] = attr["evidence"]
|
|
431
|
-
return out
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
_ATTR_HISTORY_CAP = 10
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
def _remember_attribution(result: dict, client_info: dict | None = None) -> None:
|
|
438
|
-
"""写记忆:只接受「字面证据唯一命中」,歧义/无证据/记忆本身不写(S100)。
|
|
439
|
-
|
|
440
|
-
覆盖时留快照(D-attrib-B 追加,评审意见采纳项):旧条目进
|
|
441
|
-
attribution_history(cap 10,带 replacedAt),事后能回答「当时为什么归
|
|
442
|
-
到 A 而不是 B」——单条记忆被覆盖后判据不可追是排障黑洞。
|
|
443
|
-
"""
|
|
444
|
-
# 会话记忆(D-product-ask-1):只记「有证据/用户明确回答/用户说不知道」三种
|
|
445
|
-
src = result.get("source")
|
|
446
|
-
if result.get("product"):
|
|
447
|
-
_memory_put(client_info, ask_failures=0)
|
|
448
|
-
if src in ("user_input", "user_answer"):
|
|
449
|
-
_memory_put(client_info, product=result.get("product"),
|
|
450
|
-
productName=result.get("productName"),
|
|
451
|
-
alias=(result.get("evidence") or [{}])[0].get("alias"))
|
|
452
|
-
elif src == "host_default":
|
|
453
|
-
_memory_put(client_info, not_specified=True,
|
|
454
|
-
product=result.get("product"), productName=result.get("productName"))
|
|
455
|
-
mem = _attrib.remember_if_evidenced(result)
|
|
456
|
-
if not mem:
|
|
457
|
-
return
|
|
458
|
-
prev = _RT.get("attribution_memory") or {}
|
|
459
|
-
if prev and prev.get("product"):
|
|
460
|
-
hist = list(_RT.get("attribution_history") or [])
|
|
461
|
-
hist.append({**prev, "replacedAt": mem["at"]})
|
|
462
|
-
hist = hist[-_ATTR_HISTORY_CAP:]
|
|
463
|
-
_save_runtime({"attribution_history": hist})
|
|
464
|
-
_RT["attribution_history"] = hist # 进程内同步:否则同会话读不到新记忆
|
|
465
|
-
_save_runtime({"attribution_memory": mem})
|
|
466
|
-
_RT["attribution_memory"] = mem
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
_SUBMIT_HOARDING = "/rest/developer/manager/hdvodmngservice/v1/external/voices"
|
|
470
|
-
_EXISTING_SUBMIT = "/rest/developer/manager/hdvodmngservice/v1/external/voice/submit" # 过渡期 404 回落
|
|
471
|
-
_TOKEN_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/token"
|
|
472
|
-
|
|
473
|
-
# 结构化引导(devkit error-table 模式:步骤=可执行动作,不是"参考文档")
|
|
474
|
-
_KEY_GUIDANCE = [
|
|
475
|
-
{"order": 1, "action": "auto-token", "label": "首次提交时插件自动申请零字段匿名令牌(默认路径,无需注册)"},
|
|
476
|
-
{"order": 2, "action": "upgrade", "label": "提交量达上限后升级正式 key:联系 VOD 运营(低信任档→正式档)"},
|
|
477
|
-
{"order": 3, "action": "host", "label": "宿主平台整体对接可获宿主 key:由宿主运维持有(高信任档)"},
|
|
478
|
-
]
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
def _install_nonce() -> str:
|
|
482
|
-
"""per-install 8 位 hex:runtime.json 首次生成常驻——legacy 共用 key 场景下
|
|
483
|
-
source 命名空间 per-machine 化,杜绝不同用户提交同款内容被确定性
|
|
484
|
-
voiceId 合并成一条(跨用户吞声量,切换补丁前置修复)。"""
|
|
485
|
-
n = _RT.get("install_nonce")
|
|
486
|
-
if not n:
|
|
487
|
-
import uuid
|
|
488
|
-
n = uuid.uuid4().hex[:8]
|
|
489
|
-
# 首装 nonce 必须同步回写内存态 _RT(D-dev-nonce-sync,2026-11-09 真机实锤):
|
|
490
|
-
# _RT 仅模块导入时加载一次,_save_runtime 只落盘——不同步则同进程内每次调用
|
|
491
|
-
# 生成新 nonce:领令牌(设备 A)与提交(设备 B)设备绑定校验失败,重试仍
|
|
492
|
-
# 新 nonce(设备 C)再 401——全新安装首次提交必失败冒给用户(存量安装
|
|
493
|
-
# runtime.json 已有 nonce 不受影响)。同步后领令牌/提交同设备,401→领令牌
|
|
494
|
-
# →重试全程进程内无感。
|
|
495
|
-
_RT["install_nonce"] = n
|
|
496
|
-
try:
|
|
497
|
-
_save_runtime({"install_nonce": n})
|
|
498
|
-
except Exception:
|
|
499
|
-
pass
|
|
500
|
-
return str(n)
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
def _voice_id(source: str, content: str, nonce: str) -> str:
|
|
504
|
-
"""voiceId = f(source, content, 调用级nonce)。
|
|
505
|
-
|
|
506
|
-
R1 修正(声量保真):跨调用不去重——不同用户提交同款反馈必须各占
|
|
507
|
-
一行(声量是分析核心信号);同调用内重试复用同 nonce 保幂等。
|
|
508
|
-
"""
|
|
509
|
-
import hashlib
|
|
510
|
-
return f"ext_{source}_{hashlib.sha1((content + nonce).encode('utf-8')).hexdigest()[:12]}"
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
def _legacy_key_hint() -> str:
|
|
514
|
-
"""旧版残留凭据自愈提示(评审拍板项):出错时给可操作路径,不发公告靠用户撞。
|
|
515
|
-
含当前插件版本与重装命令——重装会刷新 runtime/清掉旧 key 残留。"""
|
|
516
|
-
version = getattr(__import__("vod_mcp"), "__version__", "unknown")
|
|
517
|
-
return ("若为旧版安装残留凭据:更新插件(当前 v" + version + ")并重装即可清除——"
|
|
518
|
-
"npx vod-devkit@latest install --target <宿主> --product <产品名>;"
|
|
519
|
-
"或移除 VOD_JAVA_API_KEY 环境变量走匿名档")
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
def _explicit_key() -> bool:
|
|
523
|
-
"""当前 JAVA_KEY 是否为显式配置(正式/宿主 key)而非本会话自动领取的匿名令牌。
|
|
524
|
-
|
|
525
|
-
判据:环境变量显式注入(权威,env 优先级最高的既有口径)或
|
|
526
|
-
token_tier != "anonymous"。匿名令牌过期/被吊销时 401 应走重领链;
|
|
527
|
-
显式 key 被 401 拒绝时必须 fail fast(静默降级匿名=配置错误被吞=归因错位,
|
|
528
|
-
「注入 appkey」场景的锚定承诺会变成假的)。
|
|
529
|
-
"""
|
|
530
|
-
if bool(os.environ.get("VOD_JAVA_API_KEY")):
|
|
531
|
-
return True
|
|
532
|
-
return bool(JAVA_KEY) and str(_RT.get("token_tier") or "") != "anonymous"
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
# ── D-pending-1:无通道期 pending 反馈 flush(方案 A,2026-11-09)──
|
|
536
|
-
|
|
537
|
-
def _flush_pending(product):
|
|
538
|
-
"""补提交 ~/.vod-devkit/pending-feedback.jsonl 里 status=pending 的条目。
|
|
539
|
-
|
|
540
|
-
口径(D-pending-1 定稿):同步执行但失败只记日志、绝不回滚主提交;
|
|
541
|
-
幂等键=条目级(sha1(content+confirmAt+source)),内容级去重由引擎
|
|
542
|
-
uk_voice_id 承担(同内容重提=skipped);重写+原子 rename,失败条目
|
|
543
|
-
保留 pending;单次上限 100 条最早优先,超 30 天标记 expired 剔除。
|
|
544
|
-
双通道消息分离:本函数结果只进工具内部诊断(result.pendingFlush),
|
|
545
|
-
用户侧话术由 skill 层承担(已暂存/自动补交,禁止出现路径)。
|
|
546
|
-
"""
|
|
547
|
-
from vod_mcp import pending as _pq
|
|
548
|
-
path = _pq.default_path()
|
|
549
|
-
entries = _pq.load_entries(path)
|
|
550
|
-
if not entries:
|
|
551
|
-
return {"scanned": 0}
|
|
552
|
-
plan = _pq.plan_flush(entries)
|
|
553
|
-
kept = list(plan["kept"])
|
|
554
|
-
flushed, failed, corrected = 0, 0, 0
|
|
555
|
-
for e in plan["to_flush"]:
|
|
556
|
-
content = _pq.canonical_content(e) # D-pending-1 补强:originalLines 权威拼接,剥模型加的标点
|
|
557
|
-
if content != str(e.get("content", "")):
|
|
558
|
-
corrected += 1
|
|
559
|
-
_log("pending flush: content 与 originalLines 拼接不一致,以 originalLines 为准(剥除模型拼接改动)")
|
|
560
|
-
hv = {"title": str(content)[:60], "content": str(content)}
|
|
561
|
-
if e.get("tags"):
|
|
562
|
-
hv["tags"] = e["tags"]
|
|
563
|
-
body = {"voices": [hv]}
|
|
564
|
-
if product:
|
|
565
|
-
body["product"] = product
|
|
566
|
-
try:
|
|
567
|
-
out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
|
|
568
|
-
ids = (out or {}).get("voiceIds") or ((out or {}).get("data") or {}).get("voiceIds")
|
|
569
|
-
if ids is None:
|
|
570
|
-
failed += 1
|
|
571
|
-
kept.append(e)
|
|
572
|
-
_log("pending flush: 回执未含 voiceIds,条目保留")
|
|
573
|
-
else:
|
|
574
|
-
flushed += 1 # 含幂等 skipped(同内容重提=引擎 skipped,零重复)
|
|
575
|
-
except Exception as err:
|
|
576
|
-
failed += 1
|
|
577
|
-
kept.append(e)
|
|
578
|
-
_log(f"pending flush failed (kept pending): {err}")
|
|
579
|
-
_pq.save_entries(path, kept)
|
|
580
|
-
return {"scanned": len(entries), "flushed": flushed,
|
|
581
|
-
"failed": failed, "expired": len(plan["expired"]),
|
|
582
|
-
"corrected": corrected}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
def _allowed_tags(product_id=None) -> set:
|
|
587
|
-
"""分类白名单(引擎 meta.problemTypes,单一真源)。
|
|
588
|
-
|
|
589
|
-
2026-11-12 引擎契约变更:problemTypes 不再随无参 meta 下发(那是"全部分类"
|
|
590
|
-
的假全集),改为 `GET /external/meta?productId=<id>` 按产品下发——真源是
|
|
591
|
-
t_vod_problem_category 按 product_id 分组,不同产品的分类集不同。
|
|
592
|
-
|
|
593
|
-
取不到(无 product_id / 老引擎 / 快照降级 / 该产品无分类)→ 空集=不知道
|
|
594
|
-
白名单 → 不过滤:宁可放行也不误杀采集。
|
|
595
|
-
"""
|
|
596
|
-
pid = str(product_id or "").strip()
|
|
597
|
-
if not pid or not pid.isdigit():
|
|
598
|
-
return set()
|
|
599
|
-
import time
|
|
600
|
-
cache = _RT.get("ptype_cache") or {}
|
|
601
|
-
now = time.time()
|
|
602
|
-
if now - float(cache.get("at") or 0) < _META_TTL and pid in (cache.get("by") or {}):
|
|
603
|
-
return set(cache["by"][pid] or [])
|
|
604
|
-
by = dict(cache.get("by") or {})
|
|
605
|
-
try:
|
|
606
|
-
path = f"{_META_PATH}?productId={pid}"
|
|
607
|
-
out = _http("GET", path, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
|
|
608
|
-
data = out.get("data") or {}
|
|
609
|
-
types = [str(t) for t in (data.get("problemTypes") or []) if str(t).strip()]
|
|
610
|
-
by[pid] = types
|
|
611
|
-
cache = {"at": int(now), "by": by}
|
|
612
|
-
_save_runtime({"ptype_cache": cache})
|
|
613
|
-
_RT["ptype_cache"] = cache # 同进程后续调用要能命中,否则每次提交都外呼
|
|
614
|
-
return set(types)
|
|
615
|
-
except Exception:
|
|
616
|
-
# 任何取不到(网络/超时/引擎异常)= 不知道值域 → 不过滤,绝不阻断提交
|
|
617
|
-
return set(by.get(pid) or [])
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
_PROBLEM_TYPE_PREFIX = "problem_type:"
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
def _filter_tags(tags, allowed: set) -> tuple:
|
|
624
|
-
"""tags 白名单过滤 → (kept, dropped)。
|
|
625
|
-
|
|
626
|
-
引擎约定(ExternalVoicesServiceImpl.extractProblemType):分类标注写
|
|
627
|
-
`problem_type:<值>`,值域=meta.problemTypes(六类)。其它语义的 tag 不参与
|
|
628
|
-
分类校验、原样保留;只有 problem_type 的值会被白名单过滤——脏值丢弃不拒收
|
|
629
|
-
声音(对标 vod-skill 的 check_classification:分类必须存在于知识库)。
|
|
630
|
-
"""
|
|
631
|
-
kept, dropped = [], []
|
|
632
|
-
for t in tags or []:
|
|
633
|
-
s = str(t).strip()
|
|
634
|
-
if not s:
|
|
635
|
-
continue
|
|
636
|
-
if allowed and s.startswith(_PROBLEM_TYPE_PREFIX):
|
|
637
|
-
val = s[len(_PROBLEM_TYPE_PREFIX):].strip()
|
|
638
|
-
if val not in allowed:
|
|
639
|
-
dropped.append(s)
|
|
640
|
-
continue
|
|
641
|
-
s = _PROBLEM_TYPE_PREFIX + val # 归一(去多余空白)
|
|
642
|
-
if s not in kept:
|
|
643
|
-
kept.append(s)
|
|
644
|
-
return kept, dropped
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
def _collect_voice_items(params: dict) -> tuple[list, list]:
|
|
648
|
-
"""校验段:content 非空+≤2000 字(契约 maxLength,防超大 payload)。
|
|
649
|
-
返回 (items[(index, voice, content)], rejected 明细)。"""
|
|
650
|
-
items, rejected = [], []
|
|
651
|
-
for i, v in enumerate(params.get("voices", [])):
|
|
652
|
-
content = str(v.get("content", "")).strip()
|
|
653
|
-
if not content:
|
|
654
|
-
rejected.append({"index": i, "reason": "content 为空"})
|
|
655
|
-
elif len(content) > 2000:
|
|
656
|
-
rejected.append({"index": i, "reason": f"content 超 2000 字({len(content)})"})
|
|
657
|
-
else:
|
|
658
|
-
items.append((i, v, content))
|
|
659
|
-
return items, rejected
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
def _echo_plan(items: list, vids: list) -> dict:
|
|
663
|
-
"""回显段(方案 A,2026-11-06 拍板):提交回执强制携带原话回显。
|
|
664
|
-
检测型防线——宿主模型改写用户原话(实锤:"体验不好"→"不友好")
|
|
665
|
-
在回执处当场可见;agent 必须原样转述,改写露馅。"""
|
|
666
|
-
ok = [(vid, items[min(i, len(items) - 1)][2])
|
|
667
|
-
for i, vid in enumerate(vids) if vid]
|
|
668
|
-
return {
|
|
669
|
-
"requiresUserEcho": bool(ok),
|
|
670
|
-
"instruction": ("请向用户原样转述已收录内容:每条以「已收录原话:」开头,"
|
|
671
|
-
"后接 content 全文。禁止改写、概括、增删字词。"),
|
|
672
|
-
"contents": [{"voiceId": vid, "content": c} for vid, c in ok],
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
def _ledger_submit(items: list, vids: list, tids: list, product: str | None,
|
|
677
|
-
extra: dict | None = None) -> None:
|
|
678
|
-
"""账本段:回执 voiceIds/taskIds 逐条落本地账本(层级①查询的源)。"""
|
|
679
|
-
import time as _time
|
|
680
|
-
entries = [{"voiceId": vid, "taskId": tid,
|
|
681
|
-
"title": items[min(i, len(items) - 1)][2][:40],
|
|
682
|
-
"product": product, "at": _time.strftime("%Y-%m-%dT%H:%M:%S")}
|
|
683
|
-
for i, (vid, tid) in enumerate(zip(vids, tids))]
|
|
684
|
-
if extra:
|
|
685
|
-
for e in entries:
|
|
686
|
-
e.update(extra) # 两段式:stage=committed + draftId 关联(验收③)
|
|
687
|
-
_ledger_append(entries)
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
def _hoard_voice(v: dict, content: str) -> dict:
|
|
691
|
-
"""载荷段:单条囤积端点 voice 载荷(title/content + tags/userType +
|
|
692
|
-
D-followup-impl-2 追问补充透传:单源 _followup_fields,拒答词集兜底)。"""
|
|
693
|
-
hv = {"title": content[:60], "content": content}
|
|
694
|
-
if v.get("tags"): # 采集层三分类(problem_type:值)→正式入库
|
|
695
|
-
hv["tags"] = v["tags"]
|
|
696
|
-
if v.get("userType"):
|
|
697
|
-
hv["userType"] = v["userType"]
|
|
698
|
-
hv.update(_followup_fields(v))
|
|
699
|
-
return hv
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
def _raise_explicit_key_rejected(key: str) -> None:
|
|
703
|
-
"""显式 key(安装注入/正式档)被引擎 401 拒绝 → fail fast:
|
|
704
|
-
不取匿名令牌、不覆盖配置——静默降级匿名档=配置错误被吞
|
|
705
|
-
(归因错位比报错更糟,同 AIShell 错归病根)。囤积/legacy 两路径同口径。"""
|
|
706
|
-
raise ToolError(
|
|
707
|
-
f"注入的 key 被引擎拒绝(指纹 {_fingerprint(key)}):"
|
|
708
|
-
"请核对 key 是否过期/被吊销,或移除 key 走匿名档。"
|
|
709
|
-
+ _legacy_key_hint(),
|
|
710
|
-
code=-32012)
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
def _acquire_anon_token_or_raise() -> str:
|
|
714
|
-
"""缺 key/匿名令牌失效 → 领零字段匿名令牌;端点不可用则如实报错。"""
|
|
715
|
-
token = _fetch_anon_token()
|
|
716
|
-
if not token:
|
|
717
|
-
raise ToolError(
|
|
718
|
-
"未配置接入 key 且匿名令牌端点不可用。引导:"
|
|
719
|
-
+ ";".join(g["label"] for g in _KEY_GUIDANCE), code=-32012)
|
|
720
|
-
return token
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
def submit_voices(params: dict, client_info: dict | None = None,
|
|
724
|
-
ledger_extra: dict | None = None) -> dict:
|
|
725
|
-
"""V16 切换:主路径=囤积端点 POST /external/voices(Bearer,批式,不触发分析);
|
|
726
|
-
引擎未部署(404)自动回落老链 /external/voice/submit(提交即分析,过渡语义,
|
|
727
|
-
部署后 404 分支自然失效)。
|
|
728
|
-
|
|
729
|
-
- voiceId:囤积链由引擎确定性计算(per-token/per-install 命名空间),回执
|
|
730
|
-
voiceIds 为权威对账键;回落老链仍用客户端 nonce id(R1 声量保真)
|
|
731
|
-
- title=用户原文截断;tags=采集层三分类(problem_type:)正式入库通道
|
|
732
|
-
- source:key 持有者被引擎锚定为 host_name;legacy 共用 key 场景带
|
|
733
|
-
per-install nonce 后缀(杜绝跨用户共享命名空间吞声量)
|
|
734
|
-
"""
|
|
735
|
-
import uuid
|
|
736
|
-
host = (client_info or {}).get("name") or "unknown-host"
|
|
737
|
-
global JAVA_KEY
|
|
738
|
-
accepted, voice_ids, task_ids = 0, [], []
|
|
739
|
-
items, rejected = _collect_voice_items(params)
|
|
740
|
-
if not items:
|
|
741
|
-
return {"accepted": 0, "voiceIds": [], "taskIds": [], "rejected": rejected}
|
|
742
|
-
# 归因(D-attrib-B):证据来自用户原话,模型自报不参战
|
|
743
|
-
# 归因(D-product-ask-1):身份/鉴权优先于产品追问,产品校验放在下面 key 守卫之后
|
|
744
|
-
attr = _attribute_product(items, params, client_info)
|
|
745
|
-
product = attr["product"]
|
|
746
|
-
|
|
747
|
-
def _legacy_submit(i, v, content):
|
|
748
|
-
"""过渡回落:老链单条提交(提交即分析语义,仅 404 触发)。"""
|
|
749
|
-
nonce = uuid.uuid4().hex[:8] # 调用级:重试复用,跨调用不重复
|
|
750
|
-
vid = _voice_id(host, content, nonce)
|
|
751
|
-
desc = content if len(content) >= 10 else f"{content} [vod-devkit]"
|
|
752
|
-
body = {
|
|
753
|
-
"voiceId": vid,
|
|
754
|
-
"title": content[:128],
|
|
755
|
-
"description": desc,
|
|
756
|
-
"source": f"{host}-{_install_nonce()}", # per-install 命名空间(legacy 吞声量修复)
|
|
757
|
-
"customer": v.get("userType"),
|
|
758
|
-
}
|
|
759
|
-
if product:
|
|
760
|
-
body["product"] = product
|
|
761
|
-
out = _http("POST", _EXISTING_SUBMIT, body, base=JAVA_BASE, key=_eff_key())
|
|
762
|
-
return vid, (out.get("data") or {}).get("taskId")
|
|
763
|
-
|
|
764
|
-
# 服务面(HTTP):身份只能来自请求头。缺 key 时 fail fast——不先打引擎再
|
|
765
|
-
# 靠 401 兜底(那会多一次无意义外呼,且引擎若宽容 200 就绕过了守卫)。
|
|
766
|
-
if _SERVER_FACE.get() and not _eff_key():
|
|
767
|
-
raise ToolError(
|
|
768
|
-
"服务面(HTTP 传输)不代签身份:请在本请求带上 Authorization: Bearer "
|
|
769
|
-
"<VOD key>(插件只搬运身份,不产生身份;落库与配额都在服务端)",
|
|
770
|
-
code=-32012)
|
|
771
|
-
|
|
772
|
-
# 缺产品且用户没说不知道 → 可执行错误(先问一次),不许裸提交 UNKNOWN
|
|
773
|
-
_require_product_or_ask(attr, items, client_info)
|
|
774
|
-
# ---- 主路径:囤积端点批式提交 ----
|
|
775
|
-
# 分类白名单按产品取(引擎 ?productId= 下发);product 非数字 id 时取不到→不过滤
|
|
776
|
-
allowed_tags = _allowed_tags(product)
|
|
777
|
-
hoard, invalid_tags = [], []
|
|
778
|
-
for i, v, content in items:
|
|
779
|
-
hv = _hoard_voice(v, content)
|
|
780
|
-
if hv.get("tags"):
|
|
781
|
-
kept, dropped = _filter_tags(hv["tags"], allowed_tags)
|
|
782
|
-
if kept:
|
|
783
|
-
hv["tags"] = kept
|
|
784
|
-
else:
|
|
785
|
-
hv.pop("tags", None)
|
|
786
|
-
if dropped:
|
|
787
|
-
invalid_tags.append({"index": i, "tags": dropped})
|
|
788
|
-
hoard.append(hv)
|
|
789
|
-
body = {"voices": hoard}
|
|
790
|
-
if product: # 无归因不带 product(引擎 UNKNOWN 档),不本地拦截
|
|
791
|
-
body["product"] = product
|
|
792
|
-
out = None
|
|
793
|
-
fallback = False
|
|
794
|
-
try:
|
|
795
|
-
out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
|
|
796
|
-
except ToolError as ex:
|
|
797
|
-
if ex.code == 404:
|
|
798
|
-
fallback = True # 囤积端点未部署 → 落到下方 legacy 回落
|
|
799
|
-
elif not _eff_key() or ex.code == -32012:
|
|
800
|
-
if _SERVER_FACE.get():
|
|
801
|
-
# 服务面(HTTP):不代签身份。匿名令牌按设备锚点签发,一进程
|
|
802
|
-
# 一锚点会把配额/声量/归因全搅在一起(服务端多用户形态的
|
|
803
|
-
# 已拍板口径:formal/host key + 按请求透传)。
|
|
804
|
-
raise ToolError(
|
|
805
|
-
"服务面(HTTP 传输)不代签身份:请在本请求带上 "
|
|
806
|
-
"Authorization: Bearer <VOD key>,或改用 stdio 形态的匿名链",
|
|
807
|
-
code=-32012)
|
|
808
|
-
if _explicit_key():
|
|
809
|
-
_raise_explicit_key_rejected(_eff_key())
|
|
810
|
-
# 缺 key/匿名令牌失效 → 零字段匿名令牌 → 落 runtime.json → 重试一次
|
|
811
|
-
token = _acquire_anon_token_or_raise()
|
|
812
|
-
JAVA_KEY = token
|
|
813
|
-
_save_runtime({"java_key": token, "token_tier": "anonymous"})
|
|
814
|
-
out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
|
|
815
|
-
else:
|
|
816
|
-
raise # 网络/413 等如实上抛
|
|
817
|
-
if not fallback:
|
|
818
|
-
server_ids = (out.get("voiceIds") or out.get("data", {}).get("voiceIds")
|
|
819
|
-
or [])
|
|
820
|
-
# 引擎侧 rejected(产品校验拒绝等)透出,不吞(对齐 widget rejected 口径)
|
|
821
|
-
engine_rejected = ((out or {}).get("rejected")
|
|
822
|
-
or ((out or {}).get("data") or {}).get("rejected")
|
|
823
|
-
or [])
|
|
824
|
-
if server_ids:
|
|
825
|
-
accepted = len(server_ids)
|
|
826
|
-
voice_ids.extend(server_ids)
|
|
827
|
-
else:
|
|
828
|
-
# 回执缺失/整批被拒 → 不得兜底计成功(实锤缺陷:空 voiceId 记成功
|
|
829
|
-
# 且宿主模型据此谎报"已提交")。accepted 以真实回执为准。
|
|
830
|
-
accepted = 0
|
|
831
|
-
voice_ids.extend([""] * len(items))
|
|
832
|
-
if not engine_rejected:
|
|
833
|
-
engine_rejected = [{"reason": "引擎回执未含 voiceIds(提交结果未知),请勿视为已收录"}]
|
|
834
|
-
task_ids.extend([None] * len(items)) # 囤积语义:无即时任务
|
|
835
|
-
result = {"accepted": accepted, "voiceIds": voice_ids,
|
|
836
|
-
"taskIds": task_ids, "rejected": rejected + engine_rejected,
|
|
837
|
-
"analysis": "deferred", # 囤积语义明示(V6 运营批量消费)
|
|
838
|
-
"path": "hoarding",
|
|
839
|
-
"echo": _echo_plan(items, voice_ids)}
|
|
840
|
-
if invalid_tags: # 分类白名单外值被丢弃(不拒收声音,只丢 tag)
|
|
841
|
-
result["invalidTags"] = invalid_tags
|
|
842
|
-
if out.get("productRegistered") is not None:
|
|
843
|
-
result["productRegistered"] = out.get("productRegistered")
|
|
844
|
-
_attach_attribution(result, attr) # 来源+证据留痕(S99)
|
|
845
|
-
_remember_attribution(attr, client_info) # 会话记忆 + 审计(S95/S100)
|
|
846
|
-
_ledger_submit(items, voice_ids, task_ids, product,
|
|
847
|
-
_merge_ledger(ledger_extra, attr))
|
|
848
|
-
result["pendingFlush"] = _flush_pending(product)
|
|
849
|
-
return result
|
|
850
|
-
# ---- 过渡回落:老链单条提交(仅囤积端点 404 触发) ----
|
|
851
|
-
for i, v, content in items:
|
|
852
|
-
try:
|
|
853
|
-
vid, tid = _legacy_submit(i, v, content)
|
|
854
|
-
accepted += 1
|
|
855
|
-
voice_ids.append(vid)
|
|
856
|
-
task_ids.append(tid)
|
|
857
|
-
except ToolError as e:
|
|
858
|
-
msg = str(e)
|
|
859
|
-
if "Duplicate entry" in msg: # 极端重放场景:DB 唯一键兜底
|
|
860
|
-
accepted += 1
|
|
861
|
-
voice_ids.append(vid)
|
|
862
|
-
task_ids.append(None)
|
|
863
|
-
elif (not _eff_key() or e.code == -32012) and not voice_ids:
|
|
864
|
-
if _SERVER_FACE.get():
|
|
865
|
-
rejected.append({"index": i, "reason":
|
|
866
|
-
"服务面(HTTP 传输)不代签身份:请带 Authorization: Bearer <VOD key>"})
|
|
867
|
-
continue
|
|
868
|
-
if _explicit_key():
|
|
869
|
-
_raise_explicit_key_rejected(_eff_key())
|
|
870
|
-
# 零字段匿名令牌:缺 key/401 → 自动取令牌 → 落 runtime.json → 重试一次
|
|
871
|
-
token = _acquire_anon_token_or_raise()
|
|
872
|
-
JAVA_KEY = token
|
|
873
|
-
_save_runtime({"java_key": token, "token_tier": "anonymous"})
|
|
874
|
-
vid, tid = _legacy_submit(i, v, content)
|
|
875
|
-
accepted += 1
|
|
876
|
-
voice_ids.append(vid)
|
|
877
|
-
task_ids.append(tid)
|
|
878
|
-
else:
|
|
879
|
-
rejected.append({"index": i, "reason": msg[:120]})
|
|
880
|
-
result = {"accepted": accepted, "voiceIds": voice_ids,
|
|
881
|
-
"taskIds": task_ids, "rejected": rejected,
|
|
882
|
-
"path": "legacy-fallback",
|
|
883
|
-
"echo": _echo_plan(items, voice_ids)}
|
|
884
|
-
_attach_attribution(result, attr)
|
|
885
|
-
if accepted:
|
|
886
|
-
_remember_attribution(attr, client_info)
|
|
887
|
-
_ledger_submit(items, voice_ids, task_ids, product,
|
|
888
|
-
_merge_ledger(ledger_extra, attr))
|
|
889
|
-
result["pendingFlush"] = _flush_pending(product)
|
|
890
|
-
return result
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
def _fingerprint(key: str) -> str | None:
|
|
894
|
-
import hashlib
|
|
895
|
-
return hashlib.sha1(key.encode()).hexdigest()[:8] if key else None
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
def probe_key(key: str | None = None, timeout: int = 8) -> dict:
|
|
899
|
-
"""key 有效性探针:带 key 调只读端点 GET /external/meta(Filter 网内)。
|
|
900
|
-
|
|
901
|
-
判定语义(引擎是唯一权威,本地零判定):
|
|
902
|
-
- 200 → {"ok": True}:key 有效且在网内
|
|
903
|
-
- 401/-32012 → {"ok": False, "reason": "rejected"}:引擎判无效(过期/吊销/不存在)
|
|
904
|
-
- 其他错误(网络不可达/超时/5xx)→ {"ok": None, "reason": "unreachable"}:
|
|
905
|
-
不判定——网络问题不是 key 问题,报"无法验证"而非"无效"
|
|
906
|
-
"""
|
|
907
|
-
key = key if key is not None else JAVA_KEY
|
|
908
|
-
fp = _fingerprint(key)
|
|
909
|
-
if not key:
|
|
910
|
-
return {"ok": None, "reason": "no-key", "fingerprint": None}
|
|
911
|
-
try:
|
|
912
|
-
_http("GET", _META_PATH, None, key=key, timeout=timeout)
|
|
913
|
-
return {"ok": True, "reason": "verified", "fingerprint": fp}
|
|
914
|
-
except ToolError as ex:
|
|
915
|
-
code = ex.code
|
|
916
|
-
if code == 401 or code == -32012:
|
|
917
|
-
# 匿名令牌 401 ≠ 配置错误:报"过期待重领"而非"rejected",
|
|
918
|
-
# 避免 runtime 残留过期匿名令牌时被误读为正式 key 失效
|
|
919
|
-
# (显式 key 被拒仍报 rejected——fail fast 口径不变)
|
|
920
|
-
if not _explicit_key():
|
|
921
|
-
return {"ok": False, "reason": "expired-anonymous", "fingerprint": fp,
|
|
922
|
-
"note": "匿名令牌已过期:下次提交自动重领,无需操作"}
|
|
923
|
-
return {"ok": False, "reason": "rejected", "fingerprint": fp}
|
|
924
|
-
return {"ok": None, "reason": "unreachable", "fingerprint": fp}
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
_META_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/meta"
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
def _key_state() -> dict:
|
|
931
|
-
return {"configured": bool(JAVA_KEY), "fingerprint": _fingerprint(JAVA_KEY),
|
|
932
|
-
"base": JAVA_BASE,
|
|
933
|
-
"note": "已配置" if JAVA_KEY else "未配置(首次提交自动取匿名令牌)"}
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
def auth_status(params: dict, client_info: dict | None = None) -> dict:
|
|
937
|
-
"""认证自检:指纹化输出(明文永不出现),无 key 也跑并给引导。"""
|
|
938
|
-
out = {
|
|
939
|
-
"javaKey": _key_state(),
|
|
940
|
-
"packs": sorted(__import__("vod_mcp.packs", fromlist=["enabled_packs"]).enabled_packs()),
|
|
941
|
-
}
|
|
942
|
-
meta = _load_meta()
|
|
943
|
-
out["meta"] = {"source": meta["source"], "stale": meta["stale"],
|
|
944
|
-
"productCount": len(meta["products"])}
|
|
945
|
-
if JAVA_KEY:
|
|
946
|
-
# 主动探针(devkit auth init 真调 IAM 的廉价版):用户问"key 好没好"有确定答案
|
|
947
|
-
out["keyCheck"] = probe_key()
|
|
948
|
-
if _explicit_key():
|
|
949
|
-
# 旧版残留凭据检测位(评审拍板项):显式 key 存活即在位提示自愈路径,
|
|
950
|
-
# 不等提交撞 401 才发现(codex 0.2.3 残留 key 挡匿名链的实锤教训)
|
|
951
|
-
out["legacyKeyHint"] = _legacy_key_hint()
|
|
952
|
-
if not JAVA_KEY:
|
|
953
|
-
out["guidance"] = _KEY_GUIDANCE
|
|
954
|
-
out["tokenReady"] = "首次提交时将自动申请匿名令牌(零字段,日限额低)"
|
|
955
|
-
return out
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
_LEDGER_KEY = "submissions"
|
|
959
|
-
_LEDGER_CAP = 200
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
def _ledger_append(entries: list) -> None:
|
|
963
|
-
"""本地提交账本(层级①):本机提交记录,供 vod_list_submitted 对账。
|
|
964
|
-
cap 200 条(环形截断,防 runtime.json 膨胀)。
|
|
965
|
-
实现纪律:每次从文件读改写、只动 submissions 键——不从内存 _RT
|
|
966
|
-
合并(陈旧配置会整体回写,覆盖其他键,且把无关配置泄入调用方)。
|
|
967
|
-
D-key-guard-3④:local_ledger=false(企业数据驻留要求)→ 账本关闭,
|
|
968
|
-
vod_list_submitted 随之不可用——留痕是可选项不是义务。"""
|
|
969
|
-
if not entries:
|
|
970
|
-
return
|
|
971
|
-
fresh = _runtime_cfg()
|
|
972
|
-
if fresh.get("local_ledger") is False:
|
|
973
|
-
return
|
|
974
|
-
ledger = (fresh.get(_LEDGER_KEY) or [])[-_LEDGER_CAP:]
|
|
975
|
-
ledger.extend(entries)
|
|
976
|
-
_save_runtime({_LEDGER_KEY: ledger[-_LEDGER_CAP:]})
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
def list_submitted(params: dict, client_info: dict | None = None) -> dict:
|
|
980
|
-
"""查询本机已提交的声音(只读,采集者对账闭环)。
|
|
981
|
-
引擎级跨机查询随 VOD-VOI 列表端点;终端用户自助查询维持 P2(签名回执)。"""
|
|
982
|
-
limit = params.get("limit", 20)
|
|
983
|
-
try:
|
|
984
|
-
limit = max(1, min(int(limit), 100))
|
|
985
|
-
except (TypeError, ValueError):
|
|
986
|
-
limit = 20
|
|
987
|
-
ledger = _runtime_cfg().get(_LEDGER_KEY) or [] # 文件现读(进程内账本可能刚更新)
|
|
988
|
-
return {"total": len(ledger),
|
|
989
|
-
"submissions": ledger[-limit:][::-1], # 最新在前
|
|
990
|
-
"scope": "本机提交记录(换机/重装不保留;引擎级查询随 VOD-VOI)"}
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
_RUNTIME_STATE_KEYS = ("java_key", "token_tier", "install_nonce", "submissions",
|
|
994
|
-
"meta_cache")
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
def _distribution() -> str:
|
|
998
|
-
"""分发形态位(D-key-guard-3):install --distribution preset 写入 manifest。
|
|
999
|
-
devkit=自装自管;preset=产品随 agent 分发(客户机首启重生成运行时状态)。"""
|
|
1000
|
-
p = Path(__file__).resolve().parent.parent / "install-manifest.json"
|
|
1001
|
-
if not p.exists():
|
|
1002
|
-
return "devkit"
|
|
1003
|
-
try:
|
|
1004
|
-
return json.loads(p.read_text(encoding="utf-8")).get("distribution", "devkit")
|
|
1005
|
-
except Exception:
|
|
1006
|
-
return "devkit"
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
def _ensure_first_boot(rt_path: Path | None = None) -> dict:
|
|
1010
|
-
"""首启标记 + 构建机残留清理(D-key-guard-3①,preset 形态兜底)。
|
|
1011
|
-
|
|
1012
|
-
主防线是打包排除(分发产物不含 runtime.json);本函数兜底打包者漏排:
|
|
1013
|
-
preset 形态 + runtime.json 存在但无 firstBootAt + 携带运行时状态
|
|
1014
|
-
(key/nonce/账本/缓存)→ 判构建机残留 → 自动清空这些状态(保留
|
|
1015
|
-
product/java_base 等装机配置)+ 重新生成 per-install nonce + 告警。
|
|
1016
|
-
处置用自动重生成而非拒绝启动:残留状态全是本机可再生数据,
|
|
1017
|
-
自动清零伤害半径为零,拒启会把误判放大成全功能瘫痪。
|
|
1018
|
-
firstBootAt 首启写入,此后不再触发(防误伤正常运行中的安装)。"""
|
|
1019
|
-
p = rt_path or _runtime_path()
|
|
1020
|
-
if not p.exists():
|
|
1021
|
-
return {"action": "none"}
|
|
1022
|
-
try:
|
|
1023
|
-
cfg = json.loads(p.read_text(encoding="utf-8"))
|
|
1024
|
-
except Exception:
|
|
1025
|
-
return {"action": "none"}
|
|
1026
|
-
if cfg.get("firstBootAt"):
|
|
1027
|
-
_warn_if_cloned(cfg, p)
|
|
1028
|
-
return {"action": "none"}
|
|
1029
|
-
residual = [k for k in _RUNTIME_STATE_KEYS if cfg.get(k)]
|
|
1030
|
-
import time as _t
|
|
1031
|
-
if _distribution() == "preset" and residual:
|
|
1032
|
-
# 残留清理=整体重建(合并删不掉旧键),但保留装机配置(product/java_base 等)
|
|
1033
|
-
_save_runtime({**{k: v for k, v in cfg.items() if k not in _RUNTIME_STATE_KEYS},
|
|
1034
|
-
"firstBootAt": _t.strftime("%Y-%m-%dT%H:%M:%S")},
|
|
1035
|
-
replace=True)
|
|
1036
|
-
_warn(f"检测到构建机残留状态({','.join(residual)})已自动清空重生成——"
|
|
1037
|
-
"分发产物应只含代码与配置,不含安装结果(D-key-guard-3①)")
|
|
1038
|
-
return {"action": "cleaned", "removed": residual}
|
|
1039
|
-
_save_runtime({"firstBootAt": _t.strftime("%Y-%m-%dT%H:%M:%S")})
|
|
1040
|
-
return {"action": "stamped"}
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
def _uptime_seconds() -> float:
|
|
1044
|
-
"""本机 uptime(秒)。独立函数:测试可 monkeypatch,消除对宿主机器的依赖
|
|
1045
|
-
(实锤:test_clone_image_detection_warns 曾硬编码 boot_age=7 天与真机
|
|
1046
|
-
/proc/uptime 实值比较,uptime>7 天的机器必红——环境相关测试缺陷)。"""
|
|
1047
|
-
return float(open("/proc/uptime").read().split()[0])
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
def _warn_if_cloned(cfg: dict, p: Path) -> None:
|
|
1051
|
-
"""preset 克隆镜像检测(D-key-guard-3①延伸,仅告警不阻断):
|
|
1052
|
-
firstBootAt 距今显著超过本机 uptime(>1h 容差)→ 本机状态大概率来自
|
|
1053
|
-
母机镜像克隆——所有克隆机共享同一 device 锚点/账本,声量与配额会收敛。
|
|
1054
|
-
判据:firstBootAt 的"年龄" > uptime+容差 ⇒ 首启发生在"这台机器"存在之前。"""
|
|
1055
|
-
import time as _t
|
|
1056
|
-
if _distribution() != "preset":
|
|
1057
|
-
return
|
|
1058
|
-
try:
|
|
1059
|
-
boot = _t.mktime(_t.strptime(cfg["firstBootAt"], "%Y-%m-%dT%H:%M:%S"))
|
|
1060
|
-
uptime_s = _uptime_seconds()
|
|
1061
|
-
except (KeyError, ValueError, OSError) as ex:
|
|
1062
|
-
# 收窄捕获(原 except Exception: pass 吞掉真实异常,告警失效不可见):
|
|
1063
|
-
# 只吞解析类异常(缺字段/格式坏/读不到 /proc),其余如实上抛
|
|
1064
|
-
_log(f"clone 检测跳过(无法解析 firstBootAt/uptime):{ex}")
|
|
1065
|
-
return
|
|
1066
|
-
if _t.time() - boot > uptime_s + 3600:
|
|
1067
|
-
_warn("疑似镜像克隆机:firstBootAt 早于本机 uptime——克隆分发未清 "
|
|
1068
|
-
"runtime.json,所有克隆机共享同一设备锚点/账本。请在镜像冻结前 "
|
|
1069
|
-
"uninstall 或删除 runtime.json(装机 checklist ②)")
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
def _save_runtime(update: dict, replace: bool = False) -> None:
|
|
1073
|
-
p = _runtime_path()
|
|
1074
|
-
cfg = {}
|
|
1075
|
-
if p.exists() and not replace:
|
|
1076
|
-
try:
|
|
1077
|
-
cfg = json.loads(p.read_text(encoding="utf-8"))
|
|
1078
|
-
except Exception:
|
|
1079
|
-
cfg = {}
|
|
1080
|
-
cfg.update(update)
|
|
1081
|
-
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
1082
|
-
# S1 式写后验(借 huaweicloud-devkit ensurePrivateMode 模式):写完 chmod 0600
|
|
1083
|
-
# 并 stat 回验——不假设 chmod 按文档工作(WSL/drvfs 会静默忽略 chmod),
|
|
1084
|
-
# 验的是效果不是动作;runtime.json 含 java_key 明文,权限失效必须告警
|
|
1085
|
-
try:
|
|
1086
|
-
os.chmod(p, 0o600)
|
|
1087
|
-
mode = stat.S_IMODE(os.stat(p).st_mode)
|
|
1088
|
-
if mode != 0o600:
|
|
1089
|
-
_warn(f"runtime.json 权限异常({oct(mode)},期望 0600)——"
|
|
1090
|
-
"key 可能被同机其他用户读取,请检查文件系统(WSL 挂载盘建议移回 Linux 原生盘)")
|
|
1091
|
-
except OSError as e:
|
|
1092
|
-
_warn(f"runtime.json 权限校验失败:{e}")
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
def _log(line: str, path: str = "/tmp/vod_mcp_server.log") -> None:
|
|
1096
|
-
"""统一日志出口,1MB 截断轮转
|
|
1097
|
-
(D-key-guard-3⑤:客户机长期运行防无限增长;截断保留尾部近期日志)。"""
|
|
1098
|
-
try:
|
|
1099
|
-
p = path
|
|
1100
|
-
if os.path.exists(p) and os.path.getsize(p) > 1024 * 1024:
|
|
1101
|
-
with open(p, "r", encoding="utf-8", errors="replace") as f:
|
|
1102
|
-
tail = f.read()[-200 * 1024:]
|
|
1103
|
-
os.replace(p, p + ".old")
|
|
1104
|
-
with open(p, "w", encoding="utf-8") as f:
|
|
1105
|
-
f.write("== truncated ==\n" + tail)
|
|
1106
|
-
with open(p, "a", encoding="utf-8") as f:
|
|
1107
|
-
f.write(line.rstrip("\n") + "\n")
|
|
1108
|
-
except Exception:
|
|
1109
|
-
pass
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
def _warn(msg: str) -> None:
|
|
1113
|
-
"""告警出口:server 日志(排障真源),失败静默——不阻断业务主链。"""
|
|
1114
|
-
_log(f"warn {msg}")
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
def _extract_anon_token(out: object) -> str | None:
|
|
1118
|
-
"""从令牌端点响应提取 token(真源契约:引擎 ApiResponse 信封
|
|
1119
|
-
{"code":200,"data":{"token":...}};顶层扁平 {"token":...} 兼容历史形态)。"""
|
|
1120
|
-
if not isinstance(out, dict):
|
|
1121
|
-
return None
|
|
1122
|
-
data = out.get("data")
|
|
1123
|
-
token = data.get("token") if isinstance(data, dict) else None
|
|
1124
|
-
if not token:
|
|
1125
|
-
token = out.get("token")
|
|
1126
|
-
return token if isinstance(token, str) and token else None
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
def _fetch_anon_token() -> str | None:
|
|
1130
|
-
"""零字段匿名令牌(T7b 定稿):渠道由引擎囤积入库侧固定赋值 vod-agent
|
|
1131
|
-
(链路即渠道,客户端不自报)——本端保持空 body(方案 C 原样)。
|
|
1132
|
-
D-anon-verify(2026-11-05 真机实锤):引擎返回 ApiResponse 信封,
|
|
1133
|
-
顶层取 token 恒 None → 无 key 首提必 -32012,信封解析为必经路径。"""
|
|
1134
|
-
try:
|
|
1135
|
-
out = _http("POST", _TOKEN_PATH, {}, base=JAVA_BASE, key="", timeout=15)
|
|
1136
|
-
return _extract_anon_token(out)
|
|
1137
|
-
except ToolError:
|
|
1138
|
-
return None
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
def devkit_info(params: dict, client_info: dict | None = None) -> dict:
|
|
1142
|
-
return provenance.info_payload(client_info)
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
# 工具名 → 处理器(是否接收 client_info)
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
# ---- 两段式提交(D-token-approval-2 极简形态:插件本地 draft→commit,引擎零改动)----
|
|
1149
|
-
# 定性:最强摩擦+审计链,非人类确认硬保证(decisions 既有纠偏)。
|
|
1150
|
-
# draft 暂存 runtime.json(cap 10 环形+TTL 600s),commit 单次消费后内部复用
|
|
1151
|
-
# submit_voices 既有链——配额/幂等/归因/回显语义零新增。stage=draft/committed
|
|
1152
|
-
# 入账本:绕过两段式的直接提交在账本层面可检测(验收③)。
|
|
1153
|
-
|
|
1154
|
-
_DRAFT_KEY = "drafts"
|
|
1155
|
-
_DRAFT_CAP = 10
|
|
1156
|
-
_DRAFT_TTL = 600 # 秒;过期 commit 拒收,草稿自动作废
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
def _drafts_purge(store: dict) -> dict:
|
|
1160
|
-
"""过期草稿清除(读时惰性,无后台任务)。"""
|
|
1161
|
-
import time as _time
|
|
1162
|
-
now = _time.time()
|
|
1163
|
-
return {k: v for k, v in store.items()
|
|
1164
|
-
if v.get("expiresAt", 0) > now}
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
def _drafts_load() -> dict:
|
|
1168
|
-
"""草稿库现读 + 过期惰性清除(draft/commit 单源共用,禁双边漂移)。"""
|
|
1169
|
-
return _drafts_purge(_runtime_cfg().get(_DRAFT_KEY) or {})
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
def draft_voices(params: dict, client_info: dict | None = None) -> dict:
|
|
1173
|
-
"""两段式第一步:校验+暂存草稿+签发一次性令牌(不提交任何数据)。"""
|
|
1174
|
-
import time as _time
|
|
1175
|
-
voices_in = params.get("voices", [])
|
|
1176
|
-
invalid_tags = []
|
|
1177
|
-
clean = []
|
|
1178
|
-
|
|
1179
|
-
# 归因(D-attrib-B)前移:分类白名单按产品下发(?productId=),必须先知道
|
|
1180
|
-
# 产品才能取到该产品的分类集,否则过滤会拿到空集而静默失效。
|
|
1181
|
-
# 归因只看 content,不依赖 tags,前移不改变其它语义。
|
|
1182
|
-
_attr_items = []
|
|
1183
|
-
for i, v in enumerate(voices_in):
|
|
1184
|
-
_c = str(v.get("content", "")).strip()
|
|
1185
|
-
if _c:
|
|
1186
|
-
_attr_items.append((i, v, _c))
|
|
1187
|
-
attr = (_attribute_product(_attr_items, params, client_info)
|
|
1188
|
-
if _attr_items else {"product": None, "source": "unknown",
|
|
1189
|
-
"confidence": "low"})
|
|
1190
|
-
product = attr.get("product")
|
|
1191
|
-
allowed_tags = _allowed_tags(product)
|
|
1192
|
-
|
|
1193
|
-
for i, v in enumerate(voices_in):
|
|
1194
|
-
content = str(v.get("content", "")).strip()
|
|
1195
|
-
if not content:
|
|
1196
|
-
raise ToolError(f"第 {i + 1} 条 content 为空", code=-32602)
|
|
1197
|
-
if len(content) > 2000:
|
|
1198
|
-
raise ToolError(f"第 {i + 1} 条 content 超 2000 字({len(content)})", code=-32602)
|
|
1199
|
-
item = {"content": content}
|
|
1200
|
-
if v.get("tags"):
|
|
1201
|
-
kept, dropped = _filter_tags(v["tags"], allowed_tags)
|
|
1202
|
-
if kept:
|
|
1203
|
-
item["tags"] = kept
|
|
1204
|
-
if dropped:
|
|
1205
|
-
invalid_tags.append({"index": i, "tags": dropped})
|
|
1206
|
-
if v.get("userType"):
|
|
1207
|
-
item["userType"] = v["userType"]
|
|
1208
|
-
# D-followup-impl-2:追问补充随 draft 暂存(commit 复用 payload 原样上送),
|
|
1209
|
-
# 单源 _followup_fields 与主路径同口径
|
|
1210
|
-
item.update(_followup_fields(v))
|
|
1211
|
-
clean.append(item)
|
|
1212
|
-
if not clean:
|
|
1213
|
-
raise ToolError("voices 为必填且至少 1 条", code=-32602)
|
|
1214
|
-
_remember_attribution(attr, client_info)
|
|
1215
|
-
|
|
1216
|
-
import secrets
|
|
1217
|
-
draft_id = "draft_" + secrets.token_hex(8)
|
|
1218
|
-
token = secrets.token_hex(16)
|
|
1219
|
-
payload = {"voices": clean}
|
|
1220
|
-
if product:
|
|
1221
|
-
payload["product"] = product
|
|
1222
|
-
# 载荷 sha(防 draft→commit 间改写:commit 校验插件侧重算值一致)
|
|
1223
|
-
import hashlib
|
|
1224
|
-
payload_sha = hashlib.sha256(
|
|
1225
|
-
json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
|
|
1226
|
-
|
|
1227
|
-
store = _drafts_load()
|
|
1228
|
-
store[draft_id] = {
|
|
1229
|
-
"payload": payload, "payloadSha256": payload_sha, "tokenHash": _sha256(token),
|
|
1230
|
-
# D-resume-commit-1:token 明文随草稿落盘(runtime.json 0600,与 java_key
|
|
1231
|
-
# 同级保护)。token 的威胁模型是"防载荷改写"而非"同意凭证"——落盘不放大
|
|
1232
|
-
# 风险,换断回合可续:agent 回合中断后凭 draftId 即可恢复提交(此前
|
|
1233
|
-
# approvalToken 只存在于 draft 响应文本,回合断即丢失,只能重开草稿)
|
|
1234
|
-
"token": token,
|
|
1235
|
-
"product": product, "productSource": attr.get("source"),
|
|
1236
|
-
"productEvidence": attr.get("evidence") or [],
|
|
1237
|
-
"createdAt": _time.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
1238
|
-
"expiresAt": _time.time() + _DRAFT_TTL,
|
|
1239
|
-
}
|
|
1240
|
-
while len(store) > _DRAFT_CAP: # 环形:最旧先淘汰
|
|
1241
|
-
store.pop(next(iter(store)))
|
|
1242
|
-
_save_runtime({_DRAFT_KEY: store})
|
|
1243
|
-
|
|
1244
|
-
out = {
|
|
1245
|
-
"draftId": draft_id,
|
|
1246
|
-
"approvalToken": token,
|
|
1247
|
-
"payloadSha256": payload_sha,
|
|
1248
|
-
"expiresInSeconds": _DRAFT_TTL,
|
|
1249
|
-
"contents": [{"index": i, "content": it["content"]} for i, it in enumerate(clean)],
|
|
1250
|
-
"instruction": ("把 contents 逐条原样展示给用户核对(禁止改写概括),明确问"
|
|
1251
|
-
"「确认提交吗」。用户明确同意前禁止调用 vod_commit_voices;"
|
|
1252
|
-
"不同意则停(草稿 10 分钟后自动作废)。"),
|
|
1253
|
-
}
|
|
1254
|
-
_attach_attribution(out, attr) # 草稿阶段也让归因来源可审(commit 回执沿用)
|
|
1255
|
-
if invalid_tags:
|
|
1256
|
-
out["invalidTags"] = invalid_tags
|
|
1257
|
-
return out
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
def commit_voices(params: dict, client_info: dict | None = None) -> dict:
|
|
1261
|
-
"""两段式第二步:令牌校验→单次消费→复用 submit_voices 既有提交链。
|
|
1262
|
-
|
|
1263
|
-
D-resume-commit-1:approvalToken/payloadSha256 可省略——draftId 命中本地
|
|
1264
|
-
未过期草稿时自动恢复(断回合续提交)。显式传入仍走原校验(传了假 sha
|
|
1265
|
-
照样拒),恢复路径的完整性由签发时落盘的 sha/token 保证,语义不放宽。
|
|
1266
|
-
"""
|
|
1267
|
-
draft_id = str(params.get("draftId", ""))
|
|
1268
|
-
if not draft_id:
|
|
1269
|
-
raise ToolError("draftId 为必填(取自 vod_draft_voices 返回原样透传)", code=-32602)
|
|
1270
|
-
|
|
1271
|
-
store = _drafts_load()
|
|
1272
|
-
draft = store.get(draft_id)
|
|
1273
|
-
if draft is None:
|
|
1274
|
-
raise ToolError("草稿不存在或已过期(10 分钟 TTL),请重新 vod_draft_voices", code=-32011)
|
|
1275
|
-
token = str(params.get("approvalToken", "")) or str(draft.get("token", ""))
|
|
1276
|
-
payload_sha = str(params.get("payloadSha256", "")) or str(draft["payloadSha256"])
|
|
1277
|
-
if draft["tokenHash"] != _sha256(token):
|
|
1278
|
-
raise ToolError("审批令牌不匹配(draft 返回的 approvalToken 原样透传)", code=-32011)
|
|
1279
|
-
if draft["payloadSha256"] != payload_sha:
|
|
1280
|
-
raise ToolError("载荷校验不符(payloadSha256 与 draft 签发值不一致,禁止改写已确认内容)",
|
|
1281
|
-
code=-32011)
|
|
1282
|
-
# 单次消费:先摘除再提交——提交中途崩溃也不会二次提交(宁可丢一单重走流程)
|
|
1283
|
-
store.pop(draft_id)
|
|
1284
|
-
_save_runtime({_DRAFT_KEY: store})
|
|
1285
|
-
|
|
1286
|
-
out = submit_voices(dict(draft["payload"]), client_info,
|
|
1287
|
-
ledger_extra={"stage": "committed", "draftId": draft_id})
|
|
1288
|
-
out["twoPhase"] = True
|
|
1289
|
-
out["draftId"] = draft_id
|
|
1290
|
-
return out
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
def _sha256(s: str) -> str:
|
|
1294
|
-
import hashlib
|
|
1295
|
-
return hashlib.sha256(s.encode()).hexdigest()
|
|
1296
|
-
|
|
1297
|
-
def check_update(params: dict, client_info: dict | None = None) -> dict:
|
|
1298
|
-
from vod_mcp import update_check as uc
|
|
1299
|
-
return uc.check(params)
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
def list_skills(params: dict, client_info: dict | None = None) -> dict:
|
|
1303
|
-
from vod_mcp import skills_registry as sr
|
|
1304
|
-
try:
|
|
1305
|
-
return sr.list_skills(params)
|
|
1306
|
-
except sr.SkillError as e:
|
|
1307
|
-
raise ToolError(str(e), code=e.code)
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
def retrieve_skill(params: dict, client_info: dict | None = None) -> dict:
|
|
1311
|
-
from vod_mcp import skills_registry as sr
|
|
1312
|
-
try:
|
|
1313
|
-
return sr.retrieve_skill(params)
|
|
1314
|
-
except sr.SkillError as e:
|
|
1315
|
-
raise ToolError(str(e), code=e.code)
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
40
|
_HANDLERS = {
|
|
1319
|
-
"vod_search_products": search_products,
|
|
1320
|
-
"vod_check_update": check_update,
|
|
1321
|
-
"vod_list_skills": list_skills,
|
|
1322
|
-
"vod_retrieve_skill": retrieve_skill,
|
|
1323
|
-
"vod_submit_voices": submit_voices,
|
|
1324
|
-
"vod_list_submitted": list_submitted,
|
|
1325
|
-
"vod_devkit_info": devkit_info,
|
|
1326
|
-
"vod_auth_status": auth_status,
|
|
1327
|
-
"vod_draft_voices": draft_voices,
|
|
1328
|
-
"vod_commit_voices": commit_voices,
|
|
41
|
+
"vod_search_products": core.search_products,
|
|
42
|
+
"vod_check_update": core.check_update,
|
|
43
|
+
"vod_list_skills": knowledge.list_skills,
|
|
44
|
+
"vod_retrieve_skill": knowledge.retrieve_skill,
|
|
45
|
+
"vod_submit_voices": collect.submit_voices,
|
|
46
|
+
"vod_list_submitted": collect.list_submitted,
|
|
47
|
+
"vod_devkit_info": core.devkit_info,
|
|
48
|
+
"vod_auth_status": core.auth_status,
|
|
49
|
+
"vod_draft_voices": collect.draft_voices,
|
|
50
|
+
"vod_commit_voices": collect.commit_voices,
|
|
1329
51
|
}
|
|
1330
52
|
|
|
1331
53
|
|
|
@@ -1333,5 +55,6 @@ def dispatch(name: str, params: dict, client_info: dict | None = None) -> dict:
|
|
|
1333
55
|
handler = _HANDLERS.get(name)
|
|
1334
56
|
if handler is None:
|
|
1335
57
|
raise ToolError(f"未知工具: {name}", code=-32601)
|
|
1336
|
-
needs_host = handler in (devkit_info, submit_voices, auth_status,
|
|
58
|
+
needs_host = handler in (core.devkit_info, collect.submit_voices, core.auth_status,
|
|
59
|
+
collect.draft_voices, collect.commit_voices)
|
|
1337
60
|
return handler(params, client_info) if needs_host else handler(params)
|