vod-devkit 0.2.3 → 0.4.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.
package/vod_mcp/tools.py CHANGED
@@ -19,6 +19,30 @@ from pathlib import Path
19
19
  from vod_mcp import provenance
20
20
  from vod_mcp import DEFAULT_JAVA_BASE
21
21
 
22
+ # D-followup-impl-2:追问拒答语义词集(答"没有"类=两字段不上送)。
23
+ # 契约话术承诺了"不方便回复没有",客户端必须技术兜底——模型不守话术纪律时
24
+ # 键集合仍零漂移(test_followup_declined_or_blank_omitted 回归锁)。
25
+ _FOLLOWUP_DECLINES = frozenset({
26
+ "没有", "无", "没有。", "没了", "跳过", "不方便", "不用了", "不用",
27
+ "不补充", "算了", "没有了", "没有了。", "不方便说", "no", "none", "skip", "n/a",
28
+ })
29
+
30
+
31
+ def _followup_fields(voice: dict) -> dict:
32
+ """D-followup-impl-2 单源提取(submit 主路径与 draft 暂存共用,禁双边漂移):
33
+ 仅 trim 非空且非拒答词才含键;引擎同口径截 2000;内容永不回流 content。
34
+ followupStatus(评审八点 #3 引擎侧承载的插件上报):三态白名单归一
35
+ (strip+lower),白名单外/缺失省键——引擎侧降 NULL 不拒收,插件侧同口径双保险。"""
36
+ out = {}
37
+ for _f in ("reproSteps", "expectedBehavior"):
38
+ _val = str(voice.get(_f) or "").strip()
39
+ if _val and _val.lower() not in _FOLLOWUP_DECLINES:
40
+ out[_f] = _val[:2000]
41
+ _st = str(voice.get("followupStatus") or "").strip().lower()
42
+ if _st in ("not_asked", "declined", "answered"):
43
+ out["followupStatus"] = _st
44
+ return out
45
+
22
46
  _CONTRACT_PATH = Path(__file__).resolve().parent.parent / "contract" / "tools.schema.json"
23
47
 
24
48
 
@@ -202,6 +226,13 @@ def _install_nonce() -> str:
202
226
  if not n:
203
227
  import uuid
204
228
  n = uuid.uuid4().hex[:8]
229
+ # 首装 nonce 必须同步回写内存态 _RT(D-dev-nonce-sync,2026-11-09 真机实锤):
230
+ # _RT 仅模块导入时加载一次,_save_runtime 只落盘——不同步则同进程内每次调用
231
+ # 生成新 nonce:领令牌(设备 A)与提交(设备 B)设备绑定校验失败,重试仍
232
+ # 新 nonce(设备 C)再 401——全新安装首次提交必失败冒给用户(存量安装
233
+ # runtime.json 已有 nonce 不受影响)。同步后领令牌/提交同设备,401→领令牌
234
+ # →重试全程进程内无感。
235
+ _RT["install_nonce"] = n
205
236
  try:
206
237
  _save_runtime({"install_nonce": n})
207
238
  except Exception:
@@ -219,6 +250,15 @@ def _voice_id(source: str, content: str, nonce: str) -> str:
219
250
  return f"ext_{source}_{hashlib.sha1((content + nonce).encode('utf-8')).hexdigest()[:12]}"
220
251
 
221
252
 
253
+ def _legacy_key_hint() -> str:
254
+ """旧版残留凭据自愈提示(评审拍板项):出错时给可操作路径,不发公告靠用户撞。
255
+ 含当前插件版本与重装命令——重装会刷新 runtime/清掉旧 key 残留。"""
256
+ version = getattr(__import__("vod_mcp"), "__version__", "unknown")
257
+ return ("若为旧版安装残留凭据:更新插件(当前 v" + version + ")并重装即可清除——"
258
+ "npx vod-devkit@latest install --target <宿主> --product <产品名>;"
259
+ "或移除 VOD_JAVA_API_KEY 环境变量走匿名档")
260
+
261
+
222
262
  def _explicit_key() -> bool:
223
263
  """当前 JAVA_KEY 是否为显式配置(正式/宿主 key)而非本会话自动领取的匿名令牌。
224
264
 
@@ -232,7 +272,8 @@ def _explicit_key() -> bool:
232
272
  return bool(JAVA_KEY) and str(_RT.get("token_tier") or "") != "anonymous"
233
273
 
234
274
 
235
- def submit_voices(params: dict, client_info: dict | None = None) -> dict:
275
+ def submit_voices(params: dict, client_info: dict | None = None,
276
+ ledger_extra: dict | None = None) -> dict:
236
277
  """V16 切换:主路径=囤积端点 POST /external/voices(Bearer,批式,不触发分析);
237
278
  引擎未部署(404)自动回落老链 /external/voice/submit(提交即分析,过渡语义,
238
279
  部署后 404 分支自然失效)。
@@ -281,6 +322,9 @@ def submit_voices(params: dict, client_info: dict | None = None) -> dict:
281
322
  "title": items[min(i, len(items) - 1)][2][:40],
282
323
  "product": product, "at": _time.strftime("%Y-%m-%dT%H:%M:%S")}
283
324
  for i, (vid, tid) in enumerate(zip(vids, tids))]
325
+ if ledger_extra:
326
+ for e in entries:
327
+ e.update(ledger_extra) # 两段式:stage=committed + draftId 关联(验收③)
284
328
  _ledger_append(entries)
285
329
 
286
330
  def _legacy_submit(i, v, content):
@@ -310,6 +354,9 @@ def submit_voices(params: dict, client_info: dict | None = None) -> dict:
310
354
  ut = v.get("userType")
311
355
  if ut:
312
356
  hv["userType"] = ut
357
+ # D-followup-impl-2 追问补充透传:单源 _followup_fields(拒答词集兜底+
358
+ # 引擎同口径截 2000+禁回流 content;未追问/答"没有"=键集合零漂移)
359
+ hv.update(_followup_fields(v))
313
360
  hoard_voices.append(hv)
314
361
  body = {"voices": hoard_voices}
315
362
  if product: # 无归因不带 product(引擎 UNKNOWN 档),不本地拦截
@@ -328,8 +375,8 @@ def submit_voices(params: dict, client_info: dict | None = None) -> dict:
328
375
  #(归因错位比报错更糟,同 AIShell 错归病根)
329
376
  raise ToolError(
330
377
  f"注入的 key 被引擎拒绝(指纹 {_fingerprint(JAVA_KEY)}):"
331
- "请核对 key 是否过期/被吊销,或移除 key 走匿名档(删除 "
332
- "VOD_JAVA_API_KEY 环境变量与 runtime.json java_key)",
378
+ "请核对 key 是否过期/被吊销,或移除 key 走匿名档。"
379
+ + _legacy_key_hint(),
333
380
  code=-32012)
334
381
  # 缺 key/匿名令牌失效 → 零字段匿名令牌 → 落 runtime.json → 重试一次
335
382
  token = _fetch_anon_token()
@@ -391,7 +438,8 @@ def submit_voices(params: dict, client_info: dict | None = None) -> dict:
391
438
  # 显式 key 被拒 → fail fast(同囤积主路径口径,防静默降级)
392
439
  raise ToolError(
393
440
  f"注入的 key 被引擎拒绝(指纹 {_fingerprint(JAVA_KEY)}):"
394
- "请核对 key 是否过期/被吊销,或移除 key 走匿名档", code=-32012)
441
+ "请核对 key 是否过期/被吊销,或移除 key 走匿名档。"
442
+ + _legacy_key_hint(), code=-32012)
395
443
  # 零字段匿名令牌:缺 key/401 → 自动取令牌 → 落 runtime.json → 重试一次
396
444
  token = _fetch_anon_token()
397
445
  if token:
@@ -453,6 +501,12 @@ def probe_key(key: str | None = None, timeout: int = 8) -> dict:
453
501
  except ToolError as ex:
454
502
  code = ex.code
455
503
  if code == 401 or code == -32012:
504
+ # 匿名令牌 401 ≠ 配置错误:报"过期待重领"而非"rejected",
505
+ # 避免 runtime 残留过期匿名令牌时被误读为正式 key 失效
506
+ # (显式 key 被拒仍报 rejected——fail fast 口径不变)
507
+ if not _explicit_key():
508
+ return {"ok": False, "reason": "expired-anonymous", "fingerprint": fp,
509
+ "note": "匿名令牌已过期:下次提交自动重领,无需操作"}
456
510
  return {"ok": False, "reason": "rejected", "fingerprint": fp}
457
511
  return {"ok": None, "reason": "unreachable", "fingerprint": fp}
458
512
 
@@ -478,6 +532,10 @@ def auth_status(params: dict, client_info: dict | None = None) -> dict:
478
532
  if JAVA_KEY:
479
533
  # 主动探针(devkit auth init 真调 IAM 的廉价版):用户问"key 好没好"有确定答案
480
534
  out["keyCheck"] = probe_key()
535
+ if _explicit_key():
536
+ # 旧版残留凭据检测位(评审拍板项):显式 key 存活即在位提示自愈路径,
537
+ # 不等提交撞 401 才发现(codex 0.2.3 残留 key 挡匿名链的实锤教训)
538
+ out["legacyKeyHint"] = _legacy_key_hint()
481
539
  if not JAVA_KEY:
482
540
  out["guidance"] = _KEY_GUIDANCE
483
541
  out["tokenReady"] = "首次提交时将自动申请匿名令牌(零字段,日限额低)"
@@ -662,11 +720,140 @@ def devkit_info(params: dict, client_info: dict | None = None) -> dict:
662
720
 
663
721
 
664
722
  # 工具名 → 处理器(是否接收 client_info)
723
+
724
+
725
+ # ---- 两段式提交(D-token-approval-2 极简形态:插件本地 draft→commit,引擎零改动)----
726
+ # 定性:最强摩擦+审计链,非人类确认硬保证(decisions 既有纠偏)。
727
+ # draft 暂存 runtime.json(cap 10 环形+TTL 600s),commit 单次消费后内部复用
728
+ # submit_voices 既有链——配额/幂等/归因/回显语义零新增。stage=draft/committed
729
+ # 入账本:绕过两段式的直接提交在账本层面可检测(验收③)。
730
+
731
+ _DRAFT_KEY = "drafts"
732
+ _DRAFT_CAP = 10
733
+ _DRAFT_TTL = 600 # 秒;过期 commit 拒收,草稿自动作废
734
+
735
+
736
+ def _drafts_purge(store: dict) -> dict:
737
+ """过期草稿清除(读时惰性,无后台任务)。"""
738
+ import time as _time
739
+ now = _time.time()
740
+ return {k: v for k, v in store.items()
741
+ if v.get("expiresAt", 0) > now}
742
+
743
+
744
+ def _drafts_load() -> dict:
745
+ """草稿库现读 + 过期惰性清除(draft/commit 单源共用,禁双边漂移)。"""
746
+ return _drafts_purge(_runtime_cfg().get(_DRAFT_KEY) or {})
747
+
748
+
749
+ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
750
+ """两段式第一步:校验+暂存草稿+签发一次性令牌(不提交任何数据)。"""
751
+ import time as _time
752
+ product, ignored_runtime = _resolve_product(params)
753
+ voices_in = params.get("voices", [])
754
+ clean = []
755
+ for i, v in enumerate(voices_in):
756
+ content = str(v.get("content", "")).strip()
757
+ if not content:
758
+ raise ToolError(f"第 {i + 1} 条 content 为空", code=-32602)
759
+ if len(content) > 2000:
760
+ raise ToolError(f"第 {i + 1} 条 content 超 2000 字({len(content)})", code=-32602)
761
+ item = {"content": content}
762
+ if v.get("tags"):
763
+ item["tags"] = v["tags"]
764
+ if v.get("userType"):
765
+ item["userType"] = v["userType"]
766
+ # D-followup-impl-2:追问补充随 draft 暂存(commit 复用 payload 原样上送),
767
+ # 单源 _followup_fields 与主路径同口径
768
+ item.update(_followup_fields(v))
769
+ clean.append(item)
770
+ if not clean:
771
+ raise ToolError("voices 为必填且至少 1 条", code=-32602)
772
+
773
+ import secrets
774
+ draft_id = "draft_" + secrets.token_hex(8)
775
+ token = secrets.token_hex(16)
776
+ payload = {"voices": clean}
777
+ if product:
778
+ payload["product"] = product
779
+ # 载荷 sha(防 draft→commit 间改写:commit 校验插件侧重算值一致)
780
+ import hashlib
781
+ payload_sha = hashlib.sha256(
782
+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
783
+
784
+ store = _drafts_load()
785
+ store[draft_id] = {
786
+ "payload": payload, "payloadSha256": payload_sha, "tokenHash": _sha256(token),
787
+ # D-resume-commit-1:token 明文随草稿落盘(runtime.json 0600,与 java_key
788
+ # 同级保护)。token 的威胁模型是"防载荷改写"而非"同意凭证"——落盘不放大
789
+ # 风险,换断回合可续:agent 回合中断后凭 draftId 即可恢复提交(此前
790
+ # approvalToken 只存在于 draft 响应文本,回合断即丢失,只能重开草稿)
791
+ "token": token,
792
+ "product": product, "createdAt": _time.strftime("%Y-%m-%dT%H:%M:%S"),
793
+ "expiresAt": _time.time() + _DRAFT_TTL,
794
+ }
795
+ while len(store) > _DRAFT_CAP: # 环形:最旧先淘汰
796
+ store.pop(next(iter(store)))
797
+ _save_runtime({_DRAFT_KEY: store})
798
+
799
+ if ignored_runtime: # D-attrib-A 可观测:模型试图改归因留痕
800
+ _warn(f"draft: runtime product 被忽略(绑定权威): {ignored_runtime}")
801
+ return {
802
+ "draftId": draft_id,
803
+ "approvalToken": token,
804
+ "payloadSha256": payload_sha,
805
+ "expiresInSeconds": _DRAFT_TTL,
806
+ "contents": [{"index": i, "content": it["content"]} for i, it in enumerate(clean)],
807
+ "instruction": ("把 contents 逐条原样展示给用户核对(禁止改写概括),明确问"
808
+ "「确认提交吗」。用户明确同意前禁止调用 vod_commit_voices;"
809
+ "不同意则停(草稿 10 分钟后自动作废)。"),
810
+ }
811
+
812
+
813
+ def commit_voices(params: dict, client_info: dict | None = None) -> dict:
814
+ """两段式第二步:令牌校验→单次消费→复用 submit_voices 既有提交链。
815
+
816
+ D-resume-commit-1:approvalToken/payloadSha256 可省略——draftId 命中本地
817
+ 未过期草稿时自动恢复(断回合续提交)。显式传入仍走原校验(传了假 sha
818
+ 照样拒),恢复路径的完整性由签发时落盘的 sha/token 保证,语义不放宽。
819
+ """
820
+ draft_id = str(params.get("draftId", ""))
821
+ if not draft_id:
822
+ raise ToolError("draftId 为必填(取自 vod_draft_voices 返回原样透传)", code=-32602)
823
+
824
+ store = _drafts_load()
825
+ draft = store.get(draft_id)
826
+ if draft is None:
827
+ raise ToolError("草稿不存在或已过期(10 分钟 TTL),请重新 vod_draft_voices", code=-32011)
828
+ token = str(params.get("approvalToken", "")) or str(draft.get("token", ""))
829
+ payload_sha = str(params.get("payloadSha256", "")) or str(draft["payloadSha256"])
830
+ if draft["tokenHash"] != _sha256(token):
831
+ raise ToolError("审批令牌不匹配(draft 返回的 approvalToken 原样透传)", code=-32011)
832
+ if draft["payloadSha256"] != payload_sha:
833
+ raise ToolError("载荷校验不符(payloadSha256 与 draft 签发值不一致,禁止改写已确认内容)",
834
+ code=-32011)
835
+ # 单次消费:先摘除再提交——提交中途崩溃也不会二次提交(宁可丢一单重走流程)
836
+ store.pop(draft_id)
837
+ _save_runtime({_DRAFT_KEY: store})
838
+
839
+ out = submit_voices(dict(draft["payload"]), client_info,
840
+ ledger_extra={"stage": "committed", "draftId": draft_id})
841
+ out["twoPhase"] = True
842
+ out["draftId"] = draft_id
843
+ return out
844
+
845
+
846
+ def _sha256(s: str) -> str:
847
+ import hashlib
848
+ return hashlib.sha256(s.encode()).hexdigest()
849
+
665
850
  _HANDLERS = {
666
851
  "vod_submit_voices": submit_voices,
667
852
  "vod_list_submitted": list_submitted,
668
853
  "vod_devkit_info": devkit_info,
669
854
  "vod_auth_status": auth_status,
855
+ "vod_draft_voices": draft_voices,
856
+ "vod_commit_voices": commit_voices,
670
857
  }
671
858
 
672
859
 
@@ -674,5 +861,5 @@ def dispatch(name: str, params: dict, client_info: dict | None = None) -> dict:
674
861
  handler = _HANDLERS.get(name)
675
862
  if handler is None:
676
863
  raise ToolError(f"未知工具: {name}", code=-32601)
677
- needs_host = handler in (devkit_info, submit_voices, auth_status)
864
+ needs_host = handler in (devkit_info, submit_voices, auth_status, draft_voices, commit_voices)
678
865
  return handler(params, client_info) if needs_host else handler(params)