vod-devkit 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/QUICKSTART.md +1 -1
  3. package/README.en.md +190 -56
  4. package/README.md +210 -56
  5. package/bin/vod-devkit +502 -460
  6. package/contract/tools.schema.json +114 -7
  7. package/integrations/codeartsdoer/host.json +11 -0
  8. package/integrations/codex/host.json +20 -0
  9. package/integrations/dsh/host.json +15 -0
  10. package/integrations/hermes/host.json +20 -0
  11. package/integrations/opencode/command/vod-doctor.md +10 -0
  12. package/integrations/opencode/host.json +28 -0
  13. package/package.json +13 -10
  14. package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
  15. package/plugins/vod-devkit/build-info.json +3 -3
  16. package/plugins/vod-devkit/skills/vod-core/SKILL.md +43 -15
  17. package/plugins/vod-devkit/skills/vod-core/references/acceptance-criteria.md +9 -0
  18. package/plugins/vod-devkit/skills/vod-core/references/verification-method.md +29 -0
  19. package/plugins/vod-devkit/skills/vod-feedback-collect/SKILL.md +57 -11
  20. package/plugins/vod-devkit/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  21. package/plugins/vod-devkit/skills/vod-feedback-collect/references/verification-method.md +31 -0
  22. package/plugins/vod-devkit/skills/vod-problem-classification-rules/SKILL.md +3 -1
  23. package/plugins/vod-devkit/skills/vod-scoring-rules/SKILL.md +22 -1
  24. package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
  25. package/plugins/vod-devkit/vod_mcp/attribution.py +378 -0
  26. package/plugins/vod-devkit/vod_mcp/config_forms.py +154 -0
  27. package/plugins/vod-devkit/vod_mcp/guardrails.py +25 -0
  28. package/plugins/vod-devkit/vod_mcp/host_adapters/__init__.py +26 -0
  29. package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +73 -0
  30. package/plugins/vod-devkit/vod_mcp/host_adapters/codearts.py +57 -0
  31. package/plugins/vod-devkit/vod_mcp/host_adapters/codex.py +209 -0
  32. package/plugins/vod-devkit/vod_mcp/host_adapters/dsh.py +176 -0
  33. package/plugins/vod-devkit/vod_mcp/host_adapters/generic.py +132 -0
  34. package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +76 -0
  35. package/plugins/vod-devkit/vod_mcp/host_adapters/opencode.py +52 -0
  36. package/plugins/vod-devkit/vod_mcp/hosts.py +100 -0
  37. package/plugins/vod-devkit/vod_mcp/packs.py +19 -3
  38. package/plugins/vod-devkit/vod_mcp/payload.py +174 -0
  39. package/plugins/vod-devkit/vod_mcp/remote_app.py +100 -0
  40. package/plugins/vod-devkit/vod_mcp/server.py +43 -16
  41. package/plugins/vod-devkit/vod_mcp/skills_registry.py +124 -0
  42. package/plugins/vod-devkit/vod_mcp/tools.py +455 -55
  43. package/plugins/vod-devkit/vod_mcp/transport_remote.py +289 -0
  44. package/plugins/vod-devkit/vod_mcp/update_check.py +133 -0
  45. package/skills/vod-core/SKILL.md +43 -15
  46. package/skills/vod-core/references/acceptance-criteria.md +9 -0
  47. package/skills/vod-core/references/verification-method.md +29 -0
  48. package/skills/vod-feedback-collect/SKILL.md +57 -11
  49. package/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  50. package/skills/vod-feedback-collect/references/verification-method.md +31 -0
  51. package/skills/vod-problem-classification-rules/SKILL.md +3 -1
  52. package/skills/vod-scoring-rules/SKILL.md +22 -1
  53. package/vod_mcp/__init__.py +1 -1
  54. package/vod_mcp/attribution.py +378 -0
  55. package/vod_mcp/config_forms.py +154 -0
  56. package/vod_mcp/guardrails.py +25 -0
  57. package/vod_mcp/host_adapters/__init__.py +26 -0
  58. package/vod_mcp/host_adapters/__pycache__/__init__.cpython-314.pyc +0 -0
  59. package/vod_mcp/host_adapters/__pycache__/base.cpython-314.pyc +0 -0
  60. package/vod_mcp/host_adapters/__pycache__/codearts.cpython-314.pyc +0 -0
  61. package/vod_mcp/host_adapters/__pycache__/codex.cpython-314.pyc +0 -0
  62. package/vod_mcp/host_adapters/__pycache__/dsh.cpython-314.pyc +0 -0
  63. package/vod_mcp/host_adapters/__pycache__/generic.cpython-314.pyc +0 -0
  64. package/vod_mcp/host_adapters/__pycache__/hermes.cpython-314.pyc +0 -0
  65. package/vod_mcp/host_adapters/__pycache__/opencode.cpython-314.pyc +0 -0
  66. package/vod_mcp/host_adapters/base.py +73 -0
  67. package/vod_mcp/host_adapters/codearts.py +57 -0
  68. package/vod_mcp/host_adapters/codex.py +209 -0
  69. package/vod_mcp/host_adapters/dsh.py +176 -0
  70. package/vod_mcp/host_adapters/generic.py +132 -0
  71. package/vod_mcp/host_adapters/hermes.py +76 -0
  72. package/vod_mcp/host_adapters/opencode.py +52 -0
  73. package/vod_mcp/hosts.py +100 -0
  74. package/vod_mcp/packs.py +19 -3
  75. package/vod_mcp/payload.py +174 -0
  76. package/vod_mcp/remote_app.py +100 -0
  77. package/vod_mcp/server.py +43 -16
  78. package/vod_mcp/skills_registry.py +124 -0
  79. package/vod_mcp/tools.py +455 -55
  80. package/vod_mcp/transport_remote.py +289 -0
  81. package/vod_mcp/update_check.py +133 -0
@@ -9,6 +9,7 @@ ExternalApiKeyFilter Bearer)。
9
9
  POST …/external/voice/submit(现有接口,提交即分析)
10
10
  POST …/external/token(VOD-KEY,零字段匿名令牌)
11
11
  """
12
+ import contextvars
12
13
  import json
13
14
  import os
14
15
  import stat
@@ -16,9 +17,26 @@ import urllib.request
16
17
  import urllib.error
17
18
  from pathlib import Path
18
19
 
20
+ from vod_mcp import attribution as _attrib
19
21
  from vod_mcp import provenance
20
22
  from vod_mcp import DEFAULT_JAVA_BASE
21
23
 
24
+ # ── 服务面(HTTP 传输)上下文 ────────────────────────────────────────────
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
+
22
40
  # D-followup-impl-2:追问拒答语义词集(答"没有"类=两字段不上送)。
23
41
  # 契约话术承诺了"不方便回复没有",客户端必须技术兜底——模型不守话术纪律时
24
42
  # 键集合仍零漂移(test_followup_declined_or_blank_omitted 回归锁)。
@@ -76,28 +94,41 @@ _META_SNAPSHOT = {"products": ["agentarts", "codearts", "dataarts", "maas", "obs
76
94
 
77
95
 
78
96
  def _load_meta(force: bool = False) -> dict:
79
- """可漂移值(product 白名单等)动态取:缓存 TTL 24h,
80
- 引擎端点不可达时回退快照并标 stale。真源=引擎 submit 校验常量。
97
+ """可漂移值动态取:缓存 TTL 24h,引擎端点不可达时回退快照并标 stale。
98
+ 真源=引擎 submit 校验常量。
99
+
81
100
  T7i:productCatalog=[{id,name}](t_vod_product 运营预置,meta 组装)——
82
- 提交产品归因按平台主键 id 的解析真源;老引擎无该键=catalog 空。"""
101
+ 提交产品归因按平台主键 id 的解析真源;老引擎无该键=catalog 空。
102
+
103
+ **2026-11-12 引擎契约收紧**:
104
+ · `nameAliases` / `aliases` 已由引擎删除 → 本函数不再读取;别名能力改由
105
+ attribution 的规则派生 + BRAND_ALIASES 提供。
106
+ · `problemTypes` 改为按产品下发(`?productId=`):**无参请求不含该键**。
107
+ 分类白名单必须用 `_allowed_tags(product_id)` 按产品取,见下。
108
+ """
83
109
  import time
84
110
  cache = _RT.get("meta_cache") or {}
85
111
  now = time.time()
86
112
  if not force and cache.get("data") and now - cache.get("fetchedAt", 0) < _META_TTL:
87
113
  return {"products": cache["data"].get("products", _META_SNAPSHOT["products"]),
88
114
  "catalog": cache["data"].get("productCatalog") or [],
115
+ "dictVersion": cache["data"].get("dictVersion"),
89
116
  "stale": False, "source": "cache"}
90
117
  try:
91
- out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=JAVA_KEY, timeout=10)
118
+ out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
92
119
  data = out.get("data") or {}
93
120
  if isinstance(data.get("products"), list) and data["products"]:
94
121
  _save_runtime({"meta_cache": {"fetchedAt": int(now), "data": data}})
95
122
  return {"products": data["products"],
96
123
  "catalog": data.get("productCatalog") or [],
124
+ "dictVersion": data.get("dictVersion"),
97
125
  "stale": False, "source": "meta"}
98
126
  except ToolError:
99
127
  pass
128
+ # 快照不含分类白名单:_allowed_tags 取不到产品分类时 allowed 为空=不校验
129
+ # (宁可放行也不误杀采集)
100
130
  return {"products": _META_SNAPSHOT["products"], "catalog": [],
131
+ "dictVersion": None,
101
132
  "stale": True, "source": "snapshot"}
102
133
 
103
134
 
@@ -175,35 +206,250 @@ _PRODUCT_MAP = {
175
206
  }
176
207
 
177
208
 
178
- def _resolve_product(params: dict) -> tuple[str | None, str | None]:
179
- """归因(D-attrib-A:2026-11-06 负责人拍板,方案 A 收紧):
180
- 归因只由 install 绑定(runtime.json product)决定——运行期显式传参
181
- 仅当与绑定一致(忽略大小写)才采信;不一致=宿主模型自报,一律忽略
182
- 回退绑定值(实锤:hermes 会话模型传 product="hermes" 覆盖 CodeArts
183
- 绑定,[HERMES] 未注册错归)。无绑定 → None(引擎 UNKNOWN 档兜底)。
184
- 返回 (product, ignored_runtime_product)。
185
- T7i(方案 A,2026-11-05 拍板):产品归因主键化——
186
- ①纯数字串=平台主键 id,原样透传(引擎 selectById 精确命中)
187
- ②名字→meta productCatalog 按名解析出平台 id 后提交(对账主键化,
188
- 归一化/改名漂移不进提交链路);_PRODUCT_MAP 先归一短码再查目录
189
- ③目录无此名/目录不可用→规范名原样上送(引擎 name 兼容通道,
190
- 命中同样补落 product_id)——不静默丢提交。"""
191
- binding = str(_RT.get("product") or "").strip()
192
- raw = str(params.get("product") or "").strip()
193
- ignored = None
194
- if raw and (not binding or raw.lower() != binding.lower()):
195
- ignored = raw # 运行期自报≠绑定(或无绑定)→ 忽略留痕,不采信
196
- raw = ""
197
- product = raw or binding or None
198
- if not product:
199
- return None, ignored
200
- if product.isdigit():
201
- return product, ignored
202
- name = _PRODUCT_MAP.get(product.lower(), product)
203
- for item in (_load_meta().get("catalog") or []):
204
- if str(item.get("name") or "").lower() == name.lower():
205
- return str(item.get("id")), ignored
206
- return name, ignored
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
+ if not cands: # 别名没命中:退回名字子串(用户可能打错/只说一半)
271
+ q = query.lower()
272
+ for item in catalog:
273
+ name = str(item.get("name") or "")
274
+ if q and (q in name.lower() or name.lower() in q):
275
+ cands.append({"id": str(item.get("id")), "name": name, "score": 0.5})
276
+ if not cands: # 完全无关联词:给名录前 N 个当"可选项"(问用户用)
277
+ for item in catalog[:limit]:
278
+ cands.append({"id": str(item.get("id")), "name": str(item.get("name") or ""),
279
+ "score": 0.0})
280
+ cands.sort(key=lambda c: (c["score"], len(c["name"])), reverse=True)
281
+ return {"candidates": cands[:limit], "total": len(catalog)}
282
+
283
+
284
+ def _attribute_product(items: list, params: dict, client_info: dict | None = None) -> dict:
285
+ """归因(D-product-ask-1,2026-11-11 负责人拍板:不许裸 UNKNOWN,缺产品先问)。
286
+
287
+ 优先级(按拍板口径,不是"原话永远第一"):
288
+ ① 用户明确回答/确认(params.product,仅问过用户后由模型填)
289
+ ② 原话唯一且高置信提及(多产品/歧义=低置信,转去问)
290
+ ③ 会话记忆(30 分钟滑动,进程内;跨会话不继承)
291
+ ④ 安装先验
292
+ ⑤ host_default:仅当用户明确说"不知道/随便"(params.productNotSpecified)
293
+ 都拿不到 → 返回 source=unknown + confidence=low,由调用方抛可执行错误要求追问。
294
+ """
295
+ text = "\n".join(content for _i, _v, content in items)
296
+ meta = _load_meta()
297
+ answer = str(params.get("product") or "").strip()
298
+ mem = _memory_get(client_info)
299
+ binding = str(_RT.get("product") or "").strip() or None
300
+
301
+ if answer:
302
+ rid = _attrib.resolve_id(answer, meta)
303
+ hit = [c for c in (meta.get("catalog") or [])
304
+ if str(c.get("id")) == str(rid)
305
+ or str(c.get("name") or "").lower() == answer.lower()]
306
+ if not hit and not (meta.get("catalog") or []):
307
+ # 名录不可用(离线/快照/老引擎):没有校验依据,不能假装能核。
308
+ # 按用户回答原样上报,标 low(引擎侧仍会按表解析,未命中落未知池)。
309
+ return {"product": answer, "productName": answer, "source": "user_answer",
310
+ "confidence": "low", "rawText": answer,
311
+ "evidence": [{"reason": "catalog-unavailable", "rawText": answer}],
312
+ "ignored": None}
313
+ if not hit:
314
+ # 用户说了名录里没有的产品("智果"/"XYZ"/打错):**不拿原名硬提交**,
315
+ # 也不要自己猜最像的——把候选交回去,让模型按名录再问一次。
316
+ cands = search_products({"query": answer, "limit": 5})["candidates"]
317
+ return {"product": None, "productName": None, "source": "unknown",
318
+ "confidence": "low", "rawText": answer, "unmatched_answer": answer,
319
+ "candidates": cands,
320
+ "evidence": [{"reason": "unmatched-answer", "rawText": answer}],
321
+ "ignored": None}
322
+ name = hit[0].get("name")
323
+ return {"product": str(hit[0].get("id")), "productName": name,
324
+ "source": "user_answer", "confidence": "high", "rawText": answer,
325
+ "evidence": [{"product": name, "alias": "用户回答", "snippet": answer}],
326
+ "ignored": None}
327
+
328
+ result = _attrib.attribute(text, meta,
329
+ memory={k: v for k, v in mem.items()
330
+ if k in ("product", "productName", "alias",
331
+ "snippet", "at")},
332
+ binding=binding)
333
+ result["rawText"] = None
334
+ result["ignored"] = None
335
+ if result["source"] == "user_input":
336
+ result["confidence"] = "high"
337
+ return result
338
+ if result["source"] == "memory" and mem.get("product") and not mem.get("not_specified"):
339
+ result["confidence"] = "medium"
340
+ return result
341
+ if result["source"] == "install_binding":
342
+ result["confidence"] = "medium"
343
+ return result
344
+
345
+ not_specified = bool(params.get("productNotSpecified")) or bool(mem.get("not_specified"))
346
+ if not_specified:
347
+ # 用户明确说不知道:**不做任何猜测**(不按宿主产品兜底——那也是一次推断,
348
+ # 且产品会进引擎幂等域,错归代价比丢一条高)。交给调用方提示用户"缺产品不提交"。
349
+ pass
350
+ ev = list(result.get("evidence") or [])
351
+ if not_specified:
352
+ ev = [{"reason": "user-not-specified"}] + ev
353
+ return {"product": None, "productName": None, "source": "unknown",
354
+ "not_specified": not_specified,
355
+ "confidence": "low", "rawText": None,
356
+ "evidence": (ev or [{"reason": "no-evidence"}]),
357
+ "ignored": None}
358
+
359
+
360
+ def _require_product_or_ask(attr: dict, items: list) -> None:
361
+ """缺产品且用户没说不知道 → 可执行错误:先问一次(D-product-ask-1)。
362
+
363
+ 错误里带候选(来自原话关键词),模型照着问一句就能补齐;不是"参考文档"。
364
+ """
365
+ if attr.get("product"):
366
+ return
367
+ if attr.get("unmatched_answer"):
368
+ cands = attr.get("candidates") or []
369
+ hint = "、".join(f"{c['name']}({c['id']})" for c in cands) or "(名录为空)"
370
+ raise ToolError(
371
+ f"用户说的产品「{attr['rawText']}」不在产品名录里,不能按它提交。"
372
+ f"请按名录再确认一次是哪一个:{hint};用户仍说不出来就说明这条先不提交。",
373
+ code=_UNRESOLVED_CODE)
374
+ if attr.get("not_specified"):
375
+ raise ToolError(
376
+ "用户没有提供产品,这条反馈**不能提交**:请告诉用户「没有产品归属的反馈我不提交,"
377
+ "因为不知道要转给哪个产品团队」,并请他补充是哪个产品;他仍不想说就说明这条先不提交。"
378
+ f"可选候选:{'、'.join(c['name'] + '(' + str(c['id']) + ')' for c in search_products({'query': '\n'.join(x[2] for x in items), 'limit': 5})['candidates'])}",
379
+ code=_UNRESOLVED_CODE)
380
+ if os.environ.get("VOD_ALLOW_UNKNOWN_PRODUCT") == "1":
381
+ # 旧客户端兼容(业界口径:可选字段 + 明确默认值,不做破坏性变更):
382
+ # 缺 product 的老客户端不让它直接失败,回执标 legacy_default/low,可追溯。
383
+ attr["source"] = "legacy_default"
384
+ attr["confidence"] = "low"
385
+ return
386
+ text = "\n".join(c for _i, _v, c in items)
387
+ cands = search_products({"query": text, "limit": 5})["candidates"]
388
+ hint = "、".join(f"{c['name']}({c['id']})" for c in cands) or "(名录未命中,可问用户直接说产品名)"
389
+ raise ToolError(
390
+ "这条反馈还没确定是哪个产品:请先问用户一次『这条是哪个产品的反馈?』,"
391
+ "把回答填进 product(产品名或 ID);用户明确说不知道/随便时,传 productNotSpecified=true。"
392
+ f"候选:{hint}", code=_UNRESOLVED_CODE)
393
+
394
+
395
+ def _attach_attribution(result: dict, attr: dict) -> None:
396
+ """回执留痕(D-product-ask-1):来源 + 置信 + 原始回答 + 证据。
397
+
398
+ productSource 枚举:user_input | user_answer | memory | install_binding |
399
+ host_default(后者恒 confidence=low,必须可人工修正)。
400
+ """
401
+ result["productSource"] = attr.get("source") or "unknown"
402
+ result["productConfidence"] = attr.get("confidence") or "low"
403
+ if attr.get("productName"):
404
+ result["productName"] = attr["productName"]
405
+ if attr.get("product") is not None:
406
+ result["productId"] = str(attr["product"])
407
+ if attr.get("rawText"):
408
+ result["productRawText"] = attr["rawText"]
409
+ if attr.get("evidence"):
410
+ result["productEvidence"] = attr["evidence"]
411
+
412
+
413
+ def _merge_ledger(extra: dict | None, attr: dict) -> dict:
414
+ """账本条目带上归因来源与证据:错归可回溯到用户原话(S99)。"""
415
+ out = dict(extra or {})
416
+ out["productSource"] = attr.get("source") or "unknown"
417
+ if attr.get("evidence"):
418
+ out["productEvidence"] = attr["evidence"]
419
+ return out
420
+
421
+
422
+ _ATTR_HISTORY_CAP = 10
423
+
424
+
425
+ def _remember_attribution(result: dict, client_info: dict | None = None) -> None:
426
+ """写记忆:只接受「字面证据唯一命中」,歧义/无证据/记忆本身不写(S100)。
427
+
428
+ 覆盖时留快照(D-attrib-B 追加,评审意见采纳项):旧条目进
429
+ attribution_history(cap 10,带 replacedAt),事后能回答「当时为什么归
430
+ 到 A 而不是 B」——单条记忆被覆盖后判据不可追是排障黑洞。
431
+ """
432
+ # 会话记忆(D-product-ask-1):只记「有证据/用户明确回答/用户说不知道」三种
433
+ src = result.get("source")
434
+ if src in ("user_input", "user_answer"):
435
+ _memory_put(client_info, product=result.get("product"),
436
+ productName=result.get("productName"),
437
+ alias=(result.get("evidence") or [{}])[0].get("alias"))
438
+ elif src == "host_default":
439
+ _memory_put(client_info, not_specified=True,
440
+ product=result.get("product"), productName=result.get("productName"))
441
+ mem = _attrib.remember_if_evidenced(result)
442
+ if not mem:
443
+ return
444
+ prev = _RT.get("attribution_memory") or {}
445
+ if prev and prev.get("product"):
446
+ hist = list(_RT.get("attribution_history") or [])
447
+ hist.append({**prev, "replacedAt": mem["at"]})
448
+ hist = hist[-_ATTR_HISTORY_CAP:]
449
+ _save_runtime({"attribution_history": hist})
450
+ _RT["attribution_history"] = hist # 进程内同步:否则同会话读不到新记忆
451
+ _save_runtime({"attribution_memory": mem})
452
+ _RT["attribution_memory"] = mem
207
453
 
208
454
 
209
455
  _SUBMIT_HOARDING = "/rest/developer/manager/hdvodmngservice/v1/external/voices"
@@ -304,7 +550,7 @@ def _flush_pending(product):
304
550
  if product:
305
551
  body["product"] = product
306
552
  try:
307
- out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
553
+ out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
308
554
  ids = (out or {}).get("voiceIds") or ((out or {}).get("data") or {}).get("voiceIds")
309
555
  if ids is None:
310
556
  failed += 1
@@ -323,6 +569,67 @@ def _flush_pending(product):
323
569
 
324
570
 
325
571
 
572
+ def _allowed_tags(product_id=None) -> set:
573
+ """分类白名单(引擎 meta.problemTypes,单一真源)。
574
+
575
+ 2026-11-12 引擎契约变更:problemTypes 不再随无参 meta 下发(那是"全部分类"
576
+ 的假全集),改为 `GET /external/meta?productId=<id>` 按产品下发——真源是
577
+ t_vod_problem_category 按 product_id 分组,不同产品的分类集不同。
578
+
579
+ 取不到(无 product_id / 老引擎 / 快照降级 / 该产品无分类)→ 空集=不知道
580
+ 白名单 → 不过滤:宁可放行也不误杀采集。
581
+ """
582
+ pid = str(product_id or "").strip()
583
+ if not pid or not pid.isdigit():
584
+ return set()
585
+ import time
586
+ cache = _RT.get("ptype_cache") or {}
587
+ now = time.time()
588
+ if now - float(cache.get("at") or 0) < _META_TTL and pid in (cache.get("by") or {}):
589
+ return set(cache["by"][pid] or [])
590
+ by = dict(cache.get("by") or {})
591
+ try:
592
+ path = f"{_META_PATH}?productId={pid}"
593
+ out = _http("GET", path, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
594
+ data = out.get("data") or {}
595
+ types = [str(t) for t in (data.get("problemTypes") or []) if str(t).strip()]
596
+ by[pid] = types
597
+ cache = {"at": int(now), "by": by}
598
+ _save_runtime({"ptype_cache": cache})
599
+ _RT["ptype_cache"] = cache # 同进程后续调用要能命中,否则每次提交都外呼
600
+ return set(types)
601
+ except Exception:
602
+ # 任何取不到(网络/超时/引擎异常)= 不知道值域 → 不过滤,绝不阻断提交
603
+ return set(by.get(pid) or [])
604
+
605
+
606
+ _PROBLEM_TYPE_PREFIX = "problem_type:"
607
+
608
+
609
+ def _filter_tags(tags, allowed: set) -> tuple:
610
+ """tags 白名单过滤 → (kept, dropped)。
611
+
612
+ 引擎约定(ExternalVoicesServiceImpl.extractProblemType):分类标注写
613
+ `problem_type:<值>`,值域=meta.problemTypes(六类)。其它语义的 tag 不参与
614
+ 分类校验、原样保留;只有 problem_type 的值会被白名单过滤——脏值丢弃不拒收
615
+ 声音(对标 vod-skill 的 check_classification:分类必须存在于知识库)。
616
+ """
617
+ kept, dropped = [], []
618
+ for t in tags or []:
619
+ s = str(t).strip()
620
+ if not s:
621
+ continue
622
+ if allowed and s.startswith(_PROBLEM_TYPE_PREFIX):
623
+ val = s[len(_PROBLEM_TYPE_PREFIX):].strip()
624
+ if val not in allowed:
625
+ dropped.append(s)
626
+ continue
627
+ s = _PROBLEM_TYPE_PREFIX + val # 归一(去多余空白)
628
+ if s not in kept:
629
+ kept.append(s)
630
+ return kept, dropped
631
+
632
+
326
633
  def _collect_voice_items(params: dict) -> tuple[list, list]:
327
634
  """校验段:content 非空+≤2000 字(契约 maxLength,防超大 payload)。
328
635
  返回 (items[(index, voice, content)], rejected 明细)。"""
@@ -413,12 +720,15 @@ def submit_voices(params: dict, client_info: dict | None = None,
413
720
  """
414
721
  import uuid
415
722
  host = (client_info or {}).get("name") or "unknown-host"
416
- product, ignored_runtime = _resolve_product(params)
417
723
  global JAVA_KEY
418
724
  accepted, voice_ids, task_ids = 0, [], []
419
725
  items, rejected = _collect_voice_items(params)
420
726
  if not items:
421
727
  return {"accepted": 0, "voiceIds": [], "taskIds": [], "rejected": rejected}
728
+ # 归因(D-attrib-B):证据来自用户原话,模型自报不参战
729
+ # 归因(D-product-ask-1):身份/鉴权优先于产品追问,产品校验放在下面 key 守卫之后
730
+ attr = _attribute_product(items, params, client_info)
731
+ product = attr["product"]
422
732
 
423
733
  def _legacy_submit(i, v, content):
424
734
  """过渡回落:老链单条提交(提交即分析语义,仅 404 触发)。"""
@@ -434,28 +744,60 @@ def submit_voices(params: dict, client_info: dict | None = None,
434
744
  }
435
745
  if product:
436
746
  body["product"] = product
437
- out = _http("POST", _EXISTING_SUBMIT, body, base=JAVA_BASE, key=JAVA_KEY)
747
+ out = _http("POST", _EXISTING_SUBMIT, body, base=JAVA_BASE, key=_eff_key())
438
748
  return vid, (out.get("data") or {}).get("taskId")
439
749
 
750
+ # 服务面(HTTP):身份只能来自请求头。缺 key 时 fail fast——不先打引擎再
751
+ # 靠 401 兜底(那会多一次无意义外呼,且引擎若宽容 200 就绕过了守卫)。
752
+ if _SERVER_FACE.get() and not _eff_key():
753
+ raise ToolError(
754
+ "服务面(HTTP 传输)不代签身份:请在本请求带上 Authorization: Bearer "
755
+ "<VOD key>(插件只搬运身份,不产生身份;落库与配额都在服务端)",
756
+ code=-32012)
757
+
758
+ # 缺产品且用户没说不知道 → 可执行错误(先问一次),不许裸提交 UNKNOWN
759
+ _require_product_or_ask(attr, items)
440
760
  # ---- 主路径:囤积端点批式提交 ----
441
- body = {"voices": [_hoard_voice(v, content) for _, v, content in items]}
761
+ # 分类白名单按产品取(引擎 ?productId= 下发);product 非数字 id 时取不到→不过滤
762
+ allowed_tags = _allowed_tags(product)
763
+ hoard, invalid_tags = [], []
764
+ for i, v, content in items:
765
+ hv = _hoard_voice(v, content)
766
+ if hv.get("tags"):
767
+ kept, dropped = _filter_tags(hv["tags"], allowed_tags)
768
+ if kept:
769
+ hv["tags"] = kept
770
+ else:
771
+ hv.pop("tags", None)
772
+ if dropped:
773
+ invalid_tags.append({"index": i, "tags": dropped})
774
+ hoard.append(hv)
775
+ body = {"voices": hoard}
442
776
  if product: # 无归因不带 product(引擎 UNKNOWN 档),不本地拦截
443
777
  body["product"] = product
444
778
  out = None
445
779
  fallback = False
446
780
  try:
447
- out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
781
+ out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
448
782
  except ToolError as ex:
449
783
  if ex.code == 404:
450
784
  fallback = True # 囤积端点未部署 → 落到下方 legacy 回落
451
- elif not JAVA_KEY or ex.code == -32012:
785
+ elif not _eff_key() or ex.code == -32012:
786
+ if _SERVER_FACE.get():
787
+ # 服务面(HTTP):不代签身份。匿名令牌按设备锚点签发,一进程
788
+ # 一锚点会把配额/声量/归因全搅在一起(服务端多用户形态的
789
+ # 已拍板口径:formal/host key + 按请求透传)。
790
+ raise ToolError(
791
+ "服务面(HTTP 传输)不代签身份:请在本请求带上 "
792
+ "Authorization: Bearer <VOD key>,或改用 stdio 形态的匿名链",
793
+ code=-32012)
452
794
  if _explicit_key():
453
- _raise_explicit_key_rejected(JAVA_KEY)
795
+ _raise_explicit_key_rejected(_eff_key())
454
796
  # 缺 key/匿名令牌失效 → 零字段匿名令牌 → 落 runtime.json → 重试一次
455
797
  token = _acquire_anon_token_or_raise()
456
798
  JAVA_KEY = token
457
799
  _save_runtime({"java_key": token, "token_tier": "anonymous"})
458
- out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
800
+ out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
459
801
  else:
460
802
  raise # 网络/413 等如实上抛
461
803
  if not fallback:
@@ -481,13 +823,14 @@ def submit_voices(params: dict, client_info: dict | None = None,
481
823
  "analysis": "deferred", # 囤积语义明示(V6 运营批量消费)
482
824
  "path": "hoarding",
483
825
  "echo": _echo_plan(items, voice_ids)}
826
+ if invalid_tags: # 分类白名单外值被丢弃(不拒收声音,只丢 tag)
827
+ result["invalidTags"] = invalid_tags
484
828
  if out.get("productRegistered") is not None:
485
829
  result["productRegistered"] = out.get("productRegistered")
486
- # D-attrib-A 可观测:模型试图改归因留痕,不静默吞
487
- result["productSource"] = "install_binding"
488
- if ignored_runtime:
489
- result["ignoredRuntimeProduct"] = ignored_runtime
490
- _ledger_submit(items, voice_ids, task_ids, product, ledger_extra)
830
+ _attach_attribution(result, attr) # 来源+证据留痕(S99)
831
+ _remember_attribution(attr, client_info) # 会话记忆 + 审计(S95/S100)
832
+ _ledger_submit(items, voice_ids, task_ids, product,
833
+ _merge_ledger(ledger_extra, attr))
491
834
  result["pendingFlush"] = _flush_pending(product)
492
835
  return result
493
836
  # ---- 过渡回落:老链单条提交(仅囤积端点 404 触发) ----
@@ -503,9 +846,13 @@ def submit_voices(params: dict, client_info: dict | None = None,
503
846
  accepted += 1
504
847
  voice_ids.append(vid)
505
848
  task_ids.append(None)
506
- elif (not JAVA_KEY or e.code == -32012) and not voice_ids:
849
+ elif (not _eff_key() or e.code == -32012) and not voice_ids:
850
+ if _SERVER_FACE.get():
851
+ rejected.append({"index": i, "reason":
852
+ "服务面(HTTP 传输)不代签身份:请带 Authorization: Bearer <VOD key>"})
853
+ continue
507
854
  if _explicit_key():
508
- _raise_explicit_key_rejected(JAVA_KEY)
855
+ _raise_explicit_key_rejected(_eff_key())
509
856
  # 零字段匿名令牌:缺 key/401 → 自动取令牌 → 落 runtime.json → 重试一次
510
857
  token = _acquire_anon_token_or_raise()
511
858
  JAVA_KEY = token
@@ -520,7 +867,11 @@ def submit_voices(params: dict, client_info: dict | None = None,
520
867
  "taskIds": task_ids, "rejected": rejected,
521
868
  "path": "legacy-fallback",
522
869
  "echo": _echo_plan(items, voice_ids)}
523
- _ledger_submit(items, voice_ids, task_ids, product, ledger_extra)
870
+ _attach_attribution(result, attr)
871
+ if accepted:
872
+ _remember_attribution(attr, client_info)
873
+ _ledger_submit(items, voice_ids, task_ids, product,
874
+ _merge_ledger(ledger_extra, attr))
524
875
  result["pendingFlush"] = _flush_pending(product)
525
876
  return result
526
877
 
@@ -807,9 +1158,24 @@ def _drafts_load() -> dict:
807
1158
  def draft_voices(params: dict, client_info: dict | None = None) -> dict:
808
1159
  """两段式第一步:校验+暂存草稿+签发一次性令牌(不提交任何数据)。"""
809
1160
  import time as _time
810
- product, ignored_runtime = _resolve_product(params)
811
1161
  voices_in = params.get("voices", [])
1162
+ invalid_tags = []
812
1163
  clean = []
1164
+
1165
+ # 归因(D-attrib-B)前移:分类白名单按产品下发(?productId=),必须先知道
1166
+ # 产品才能取到该产品的分类集,否则过滤会拿到空集而静默失效。
1167
+ # 归因只看 content,不依赖 tags,前移不改变其它语义。
1168
+ _attr_items = []
1169
+ for i, v in enumerate(voices_in):
1170
+ _c = str(v.get("content", "")).strip()
1171
+ if _c:
1172
+ _attr_items.append((i, v, _c))
1173
+ attr = (_attribute_product(_attr_items, params, client_info)
1174
+ if _attr_items else {"product": None, "source": "unknown",
1175
+ "confidence": "low"})
1176
+ product = attr.get("product")
1177
+ allowed_tags = _allowed_tags(product)
1178
+
813
1179
  for i, v in enumerate(voices_in):
814
1180
  content = str(v.get("content", "")).strip()
815
1181
  if not content:
@@ -818,7 +1184,11 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
818
1184
  raise ToolError(f"第 {i + 1} 条 content 超 2000 字({len(content)})", code=-32602)
819
1185
  item = {"content": content}
820
1186
  if v.get("tags"):
821
- item["tags"] = v["tags"]
1187
+ kept, dropped = _filter_tags(v["tags"], allowed_tags)
1188
+ if kept:
1189
+ item["tags"] = kept
1190
+ if dropped:
1191
+ invalid_tags.append({"index": i, "tags": dropped})
822
1192
  if v.get("userType"):
823
1193
  item["userType"] = v["userType"]
824
1194
  # D-followup-impl-2:追问补充随 draft 暂存(commit 复用 payload 原样上送),
@@ -827,6 +1197,7 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
827
1197
  clean.append(item)
828
1198
  if not clean:
829
1199
  raise ToolError("voices 为必填且至少 1 条", code=-32602)
1200
+ _remember_attribution(attr, client_info)
830
1201
 
831
1202
  import secrets
832
1203
  draft_id = "draft_" + secrets.token_hex(8)
@@ -847,16 +1218,16 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
847
1218
  # 风险,换断回合可续:agent 回合中断后凭 draftId 即可恢复提交(此前
848
1219
  # approvalToken 只存在于 draft 响应文本,回合断即丢失,只能重开草稿)
849
1220
  "token": token,
850
- "product": product, "createdAt": _time.strftime("%Y-%m-%dT%H:%M:%S"),
1221
+ "product": product, "productSource": attr.get("source"),
1222
+ "productEvidence": attr.get("evidence") or [],
1223
+ "createdAt": _time.strftime("%Y-%m-%dT%H:%M:%S"),
851
1224
  "expiresAt": _time.time() + _DRAFT_TTL,
852
1225
  }
853
1226
  while len(store) > _DRAFT_CAP: # 环形:最旧先淘汰
854
1227
  store.pop(next(iter(store)))
855
1228
  _save_runtime({_DRAFT_KEY: store})
856
1229
 
857
- if ignored_runtime: # D-attrib-A 可观测:模型试图改归因留痕
858
- _warn(f"draft: runtime product 被忽略(绑定权威): {ignored_runtime}")
859
- return {
1230
+ out = {
860
1231
  "draftId": draft_id,
861
1232
  "approvalToken": token,
862
1233
  "payloadSha256": payload_sha,
@@ -866,6 +1237,10 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
866
1237
  "「确认提交吗」。用户明确同意前禁止调用 vod_commit_voices;"
867
1238
  "不同意则停(草稿 10 分钟后自动作废)。"),
868
1239
  }
1240
+ _attach_attribution(out, attr) # 草稿阶段也让归因来源可审(commit 回执沿用)
1241
+ if invalid_tags:
1242
+ out["invalidTags"] = invalid_tags
1243
+ return out
869
1244
 
870
1245
 
871
1246
  def commit_voices(params: dict, client_info: dict | None = None) -> dict:
@@ -905,7 +1280,32 @@ def _sha256(s: str) -> str:
905
1280
  import hashlib
906
1281
  return hashlib.sha256(s.encode()).hexdigest()
907
1282
 
1283
+ def check_update(params: dict, client_info: dict | None = None) -> dict:
1284
+ from vod_mcp import update_check as uc
1285
+ return uc.check(params)
1286
+
1287
+
1288
+ def list_skills(params: dict, client_info: dict | None = None) -> dict:
1289
+ from vod_mcp import skills_registry as sr
1290
+ try:
1291
+ return sr.list_skills(params)
1292
+ except sr.SkillError as e:
1293
+ raise ToolError(str(e), code=e.code)
1294
+
1295
+
1296
+ def retrieve_skill(params: dict, client_info: dict | None = None) -> dict:
1297
+ from vod_mcp import skills_registry as sr
1298
+ try:
1299
+ return sr.retrieve_skill(params)
1300
+ except sr.SkillError as e:
1301
+ raise ToolError(str(e), code=e.code)
1302
+
1303
+
908
1304
  _HANDLERS = {
1305
+ "vod_search_products": search_products,
1306
+ "vod_check_update": check_update,
1307
+ "vod_list_skills": list_skills,
1308
+ "vod_retrieve_skill": retrieve_skill,
909
1309
  "vod_submit_voices": submit_voices,
910
1310
  "vod_list_submitted": list_submitted,
911
1311
  "vod_devkit_info": devkit_info,