dsh-vod-devkit 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # dsh-vod-devkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ VOD 用户声音采集插件 —— DeepSeek Harness (dsh) 薄壳。
4
+
5
+ ## 形态
6
+
7
+ - 纯采集:3 工具(`vod_submit_voices` / `vod_list_submitted` / `vod_devkit_info`)
8
+ - 插件=引擎客户端,只走 HTTPS(VOD external API),不 import 任何引擎模块
9
+ - 与 vod-devkit(MCP 形态,同仓 `../vod_mcp`)语义对齐:
10
+ - voiceId = f(source, content, 调用级 nonce):同调用幂等、跨调用保声量
11
+ - product 归一映射(小写 codearts → CodeArts;引擎实测小写 400)
12
+ - 归因三层:配置绑定 → 显式传参 → 报错引导(绝不静默默认)
13
+ - 无 key/401 → POST /external/token 零字段匿名令牌 → 本地落盘 → 重试一次
14
+ - 本地账本 data/runtime.json(cap 200 环形,读改写只动目标键)
15
+
16
+ ## 安装
17
+
18
+ ```
19
+ dsh plugin --profile <name> add dsh-vod-devkit # npm 发布后
20
+ dsh plugin --profile <name> add github:yangaiwu/vod-devkit#dsh # 亦可
21
+ ```
22
+
23
+ 装后在 profile 的 cordis.patch.yml 激活(与包内 cordis.patch.yml 同语义):
24
+
25
+ ```yaml
26
+ - insert:
27
+ - id: vod-devkit
28
+ name: 'dsh-vod-devkit'
29
+ ```
30
+
31
+ ## 配置(dsh 插件设置)
32
+
33
+ | 字段 | 默认 | 说明 |
34
+ |---|---|---|
35
+ | apiBase | https://vod-dev.topxtopx.com | VOD external API 基址 |
36
+ | apiKey | (空) | 缺省走零字段匿名令牌;灰度期可用运营签发 key |
37
+ | product | (空) | 本机产品归因绑定(如 codearts);空且调用未传参时报错引导 |
38
+ | confirmWrites | true | 写操作走 dsh 审批通道(tools/pre-execute → ask) |
39
+ | timeoutSec | 30 | HTTP 超时 |
40
+
41
+ ## 安全
42
+
43
+ - apiKey 标记 `.role('secret')`:不跨 wire 回传,展示一律 sha1[:8] 指纹
44
+ - 写操作默认弹确认;单批 ≤50;content ≤2000 逐条校验
@@ -0,0 +1,10 @@
1
+ # dsh-vod-devkit bundle patch — applied when this plugin is installed.
2
+ # Registers 3 VOD user-voice collection tools on ctx.tools:
3
+ # vod_submit_voices / vod_list_submitted / vod_devkit_info
4
+ #
5
+ # Transport: HTTPS to the VOD external API (no local CLI subprocess needed).
6
+ # Config (dsh settings): apiBase / apiKey(secret) / product / confirmWrites.
7
+ # No key → automatic zero-field anonymous token on first submit (VOD-KEY).
8
+ - insert:
9
+ - id: vod-devkit
10
+ name: 'dsh-vod-devkit'
package/lib/client.js ADDED
@@ -0,0 +1,10 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-vod-devkit",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ var L=Object.create;var h=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var P=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var V=(t,r)=>{for(var e in r)h(t,e,{get:r[e],enumerable:!0})},E=(t,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of M(r))!U.call(t,n)&&n!==e&&h(t,n,{get:()=>r[n],enumerable:!(o=B(r,n))||o.enumerable});return t};var H=(t,r,e)=>(e=t!=null?L(P(t)):{},E(r||!t||!t.__esModule?h(e,"default",{value:t,enumerable:!0}):e,t)),$=t=>E(h({},"__esModule",{value:!0}),t);var tt={};V(tt,{apply:()=>Y,name:()=>Z});module.exports=$(tt);var a=require("react/jsx-runtime"),u=H(require("react"),1);const O="/rest/developer/manager/hdvodmngservice/v1";let m=typeof globalThis<"u"&&globalThis.__VOD_DSH_UI_BASE__||"";const j=`${O}/external/token`,w=`${O}/external/voices`,S="vod_dshui_token",T="vod_dshui_device",y="vod_dshui_ledger",_="vod_dshui_draft",R=200,N=typeof globalThis<"u"&&globalThis.__VOD_DSH_UI_LEDGER_DISABLED__===!0,x=typeof globalThis<"u"&&globalThis.__VOD_DSH_UI_PRODUCT__||"",A={textarea:{width:"100%",boxSizing:"border-box",minHeight:96,borderRadius:"var(--dsw-radius-sm, 8px)",border:"1px solid var(--dsw-alias-border-l3, #ccc)",padding:"8px 10px",fontSize:13,resize:"vertical",background:"var(--dsw-alias-bg-layer-1, transparent)",color:"var(--dsw-alias-label-primary, #111)",outline:"none"},input:{width:"100%",boxSizing:"border-box",borderRadius:"var(--dsw-radius-sm, 8px)",border:"1px solid var(--dsw-alias-border-l3, #ccc)",padding:"7px 10px",fontSize:13,background:"var(--dsw-alias-bg-layer-1, transparent)",color:"var(--dsw-alias-label-primary, #111)",outline:"none"},hint:{fontSize:12,color:"var(--dsw-alias-label-caption, #999)",marginBottom:12},label:{fontSize:12,color:"var(--dsw-alias-label-secondary, #666)",margin:"10px 0 6px"},result:{fontSize:12,marginBottom:12,padding:"8px 10px",borderRadius:"var(--dsw-radius-sm, 8px)",background:"var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,.05))",color:"var(--dsw-alias-label-primary, #111)"}};function I(){let t=localStorage.getItem(T);return t||(t=(crypto.randomUUID?crypto.randomUUID():Date.now().toString(16)+Math.random().toString(16).slice(2)+Math.random().toString(16).slice(2)).replace(/[^0-9a-f]/g,"").slice(0,32),localStorage.setItem(T,t)),t}async function z(t){if(typeof crypto<"u"&&crypto.subtle){const r=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(t));return[...new Uint8Array(r)].map(e=>e.toString(16).padStart(2,"0")).join("")}return F(t)}function F(t){let o=2166136261,n=3752705916;for(let i=0;i<t.length;i++){const l=t.charCodeAt(i);o^=l,o=Math.imul(o,16777619)>>>0,n^=l<<3&65535,n=Math.imul(n,2246822507)>>>0}return o.toString(16).padStart(8,"0")+n.toString(16).padStart(8,"0")}async function J(t){return`ext_dshui_${(await z(I())).slice(0,8)}_${(await z(t)).slice(0,12)}`}function k(t){if(N)return;const r=JSON.parse(localStorage.getItem(y)||"[]");r.unshift(t),localStorage.setItem(y,JSON.stringify(r.slice(0,R)))}async function D(){let t=localStorage.getItem(S);if(t)return t;const r=await fetch(m+j,{method:"POST",headers:{"content-type":"application/json","X-Vod-Device-Id":I()},body:"{}"});if(r.status!==200&&r.status!==201)throw new Error(`token ${r.status}`);const e=await r.json().catch(()=>({}));if(t=typeof e=="string"?e:e.token||e.data?.token||"",!t)throw new Error("token empty");return localStorage.setItem(S,t),t}function K({title:t,onClose:r,children:e,footer:o}){return(0,u.useEffect)(()=>{const n=i=>i.key==="Escape"&&r();return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[r]),(0,a.jsx)("div",{style:{position:"fixed",inset:0,zIndex:9e3,background:"rgba(0,0,0,.35)",display:"flex",alignItems:"center",justifyContent:"center"},onMouseDown:n=>n.target===n.currentTarget&&r(),children:(0,a.jsxs)("div",{role:"dialog","aria-label":t,style:{width:"min(488px, 92vw)",borderRadius:"var(--dsw-radius-panel, 12px)",background:"var(--dsw-alias-bg-layer-1, #fff)",color:"var(--dsw-alias-label-primary, #111)",padding:"18px 20px",fontFamily:"inherit",boxShadow:"0 8px 40px rgba(0,0,0,.2)"},children:[(0,a.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12},children:[(0,a.jsx)("div",{style:{fontSize:15,fontWeight:600},children:t}),(0,a.jsx)("button",{onClick:r,"aria-label":"\u5173\u95ED",style:{border:"none",background:"transparent",cursor:"pointer",fontSize:16,lineHeight:1,padding:4,borderRadius:6,color:"var(--dsw-alias-label-tertiary, #888)"},children:"\u2715"})]}),e,o&&(0,a.jsx)("div",{style:{marginTop:14},children:o})]})})}function G({disabled:t,onClick:r,children:e}){return(0,a.jsx)("button",{disabled:t,onClick:r,style:{width:"100%",height:44,fontSize:14,fontWeight:500,border:"none",cursor:t?"not-allowed":"pointer",borderRadius:"var(--dsw-radius-lg, 10px)",background:t?"var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,.06))":"var(--dsw-alias-button-primary-fill, #2563eb)",color:t?"var(--dsw-alias-label-tertiary, #999)":"var(--dsw-alias-label-primary-foreground, #fff)"},children:e})}async function W(t,r){try{const e=await D(),o=await fetch(m+w+"?limit=50",{headers:{authorization:`Bearer ${e}`}});if(o.status!==200)return null;const n=await o.json().catch(()=>({})),l=(n.voices||n.data?.voices||[]).find(g=>g.voiceId===t);return l&&l.issue_sync||null}catch{return null}}let C=!1;async function X(){if(C)return;C=!0;const t=JSON.parse(localStorage.getItem(y)||"[]").filter(e=>e.status==="pending-endpoint"||e.status==="failed");for(const e of t.slice(0,5))try{const o=await D(),n=await fetch(m+w,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify({voices:[{title:e.title,content:e.content}],product:x})});if(n.status===200||n.status===201){e.status="accepted";try{localStorage.removeItem(_)}catch{}const i=await n.json().catch(()=>({}));e.serverVoiceId=(i.voiceIds||i.data?.voiceIds||[])[0]||"",e.retriedAt=new Date().toISOString()}else n.status!==404&&(e.error=`retry ${n.status}`)}catch(o){e.error=String(o&&o.message||o)}if(t.filter(e=>e.status!=="accepted").length!==t.length||t.length){const e=JSON.parse(localStorage.getItem(y)||"[]"),o=new Map(t.map(i=>[i.voiceKey,i])),n=e.map(i=>o.get(i.voiceKey)||i);localStorage.setItem(y,JSON.stringify(n.slice(0,R)))}}function q({onClose:t}){const r=(()=>{try{return JSON.parse(localStorage.getItem(_)||"null")||{}}catch{return{}}})(),[e,o]=(0,u.useState)(r.content||"");(0,u.useEffect)(()=>{try{localStorage.setItem(_,JSON.stringify({content:e}))}catch{}},[e]);const[n,i]=(0,u.useState)(!1),[l,g]=(0,u.useState)(null);async function v(s,c){if(s)for(let p=0;p<6;p++){await new Promise(f=>setTimeout(f,1e4));const d=await W(s);if(d){if(d.status==="CREATED"&&d.issue_url){c({ok:!0,msg:`\u5DF2\u5EFA\u6210 issue\uFF1A${d.issue_url}`});return}if(d.status==="REJECTED"){c({ok:!1,msg:"\u53CD\u9988\u7ECF\u5BA1\u6838\u672A\u91C7\u7EB3\uFF0C\u611F\u8C22\u4F60\u7684\u63D0\u4EA4\u3002"});return}}}}async function b(){const s=e.trim();if(!s){g({ok:!1,msg:"\u8BF7\u5148\u586B\u5199\u53CD\u9988\u5185\u5BB9"});return}if(s.length>2e3){g({ok:!1,msg:`\u5185\u5BB9\u8D85\u957F\uFF08${s.length}/2000\uFF09\uFF0C\u8BF7\u7CBE\u7B80`});return}i(!0),g(null);const c={title:s.slice(0,64),content:s,at:new Date().toISOString(),status:"failed",error:""};try{c.voiceKey=await J(s);try{const p=await D(),d=await fetch(m+w,{method:"POST",headers:{"content-type":"application/json","X-Vod-Device-Id":I(),authorization:`Bearer ${p}`},body:JSON.stringify({voices:[{title:s.slice(0,60),content:s}],product:x})});if(d.status===404){c.status="pending-endpoint",k(c),g({ok:!1,msg:"\u56E4\u79EF\u7AEF\u70B9\u5C1A\u672A\u4E0A\u7EBF\uFF08\u5F15\u64CE\u90E8\u7F72\u540E\u81EA\u52A8\u53EF\u7528\uFF09\uFF1B\u53CD\u9988\u5DF2\u6682\u5B58\u672C\u673A\uFF0C\u7A0D\u540E\u91CD\u8BD5\u63D0\u4EA4\u3002"});return}if(d.status===401&&localStorage.removeItem(S),d.status!==200&&d.status!==201)throw new Error(`submit ${d.status}`);const f=await d.json().catch(()=>({}));c.status="accepted",c.serverVoiceId=f.voiceIds?.[0]||"",c.taskId=f.taskIds?.[0]||"",k(c),f.productRegistered===void 0||f.productRegistered||console.warn("[vod-devkit] product \u672A\u6CE8\u518C\uFF08\u90E8\u7F72\u65B9\u6838\u5BF9\u9879\uFF09:",c.product),g({ok:!0,msg:"\u611F\u8C22\u4F60\u7684\u53CD\u9988\uFF0C\u5DF2\u6536\u5F55\u3002"}),v(c.serverVoiceId,g)}catch(p){c.error=String(p&&p.message||p),k(c);const d=String(c.error||""),f=d.includes("429")?"\u63D0\u4EA4\u592A\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF08\u5DF2\u6682\u5B58\uFF0C\u7A0D\u540E\u81EA\u52A8\u91CD\u8BD5\uFF09":d.includes("401")?"\u63D0\u4EA4\u901A\u9053\u9700\u8981\u91CD\u65B0\u9A8C\u8BC1\uFF08\u5DF2\u6682\u5B58\uFF0C\u7A0D\u540E\u81EA\u52A8\u91CD\u8BD5\uFF09":"\u63D0\u4EA4\u5931\u8D25\uFF0C\u5DF2\u6682\u5B58\u672C\u673A\uFF0C\u7A0D\u540E\u81EA\u52A8\u91CD\u8BD5";g({ok:!1,msg:f})}}finally{i(!1)}}return(0,a.jsxs)(K,{title:"\u63D0\u4EA4\u53CD\u9988",onClose:t,footer:(0,a.jsx)(G,{disabled:n||!e.trim(),onClick:b,children:n?"\u63D0\u4EA4\u4E2D\u2026":"\u63D0\u4EA4"}),children:[(0,a.jsx)("textarea",{style:A.textarea,value:e,maxLength:2e3,placeholder:"\u6BD4\u5982\uFF1A\u5BF9\u8BDD\u54CD\u5E94\u6162\u3001\u67D0\u4E2A\u529F\u80FD\u627E\u4E0D\u5230\u5165\u53E3",autoFocus:!0,onChange:s=>o(s.target.value)}),(0,a.jsxs)("div",{style:{fontSize:11,textAlign:"right",margin:"4px 0 0",color:"var(--dsw-alias-label-tertiary, #999)"},children:[e.length,"/2000"]}),l&&(0,a.jsx)("div",{style:A.result,children:l.msg})]})}function Q(){const[t,r]=(0,u.useState)(!1),e=(0,u.useRef)(null);return(0,u.useEffect)(()=>{X();const o=()=>{const l=e.current;if(!l)return;const g=document.querySelector("[contenteditable=true][role=textbox], [contenteditable=true]");if(!g)return;const v=g.getBoundingClientRect(),b=l.offsetWidth||24,s=24;l.style.left=Math.round(v.right-b-8)+"px",l.style.top=Math.round(v.top-s-6)+"px",l.style.width=b+"px",l.style.height=s+"px"};o();const n=new ResizeObserver(o);n.observe(document.documentElement),window.addEventListener("resize",o);const i=setInterval(o,800);return()=>{n.disconnect(),window.removeEventListener("resize",o),clearInterval(i)}},[]),(0,a.jsxs)(u.default.Fragment,{children:[(0,a.jsxs)("button",{ref:e,title:"\u53CD\u9988","aria-label":"\u53CD\u9988\u5F00\u53D1\u8005\u58F0\u97F3",style:{position:"fixed",zIndex:300,border:"none",background:"transparent",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",gap:4,borderRadius:"var(--dsw-radius-sm, 6px)",color:"var(--dsw-alias-label-tertiary, #888)",fontFamily:"inherit"},onMouseEnter:o=>o.currentTarget.style.color="var(--dsw-alias-label-primary, #111)",onMouseLeave:o=>o.currentTarget.style.color="var(--dsw-alias-label-tertiary, #888)",onClick:()=>r(!0),children:[(0,a.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,a.jsx)("path",{d:"M21.5 2.5 2.9 10.2c-.8.3-.8 1.5.1 1.7l4.6 1.4 1.7 5.5c.3.9 1.4 1 1.9.3l2.5-3.3 4.6 3.4c.7.5 1.7.1 1.9-.8l3.2-14.4c.2-.9-.7-1.7-1.5-1.4z"}),(0,a.jsx)("path",{d:"M7.3 13.5 21.5 2.5l-9.5 12.3"})]}),(0,a.jsx)("span",{style:{fontSize:12,lineHeight:1,whiteSpace:"nowrap"},children:"\u53CD\u9988"})]}),t&&(0,a.jsx)(q,{onClose:()=>r(!1)})]})}function Y(t){if(!x){console.error('[vod-devkit] \u5D4C\u5165\u65B9\u672A\u6CE8\u5165 __VOD_DSH_UI_PRODUCT__\uFF0C\u53CD\u9988\u5165\u53E3\u672A\u6FC0\u6D3B\u3002\u4EA7\u54C1\u5F52\u56E0\u662F\u5FC5\u914D\u9879\uFF1A\u5D4C\u5165\u65B9\u88C5\u524D\u8BBE\u7F6E window.__VOD_DSH_UI_PRODUCT__ = "<\u4EA7\u54C1\u540D>"\uFF08\u53D6\u503C=\u751F\u6001\u770B\u677F\u4EA7\u54C1\u540D\uFF1A\u9AD8\u6821AI\u5F00\u53D1\u8005\u5E73\u53F0/\u6210\u957F\u4E2D\u5FC3/AI\u4E91\u539F\u751F\u5F00\u53D1\u5B9E\u8DF5\u4E2D\u5FC3/\u9E3F\u8499\u5F00\u53D1\u5B9E\u8DF5\u4E2D\u5FC3/AI\u529E\u516C\u5B9E\u8DF5\u4E2D\u5FC3/IaC \u5B9E\u8DF5\u4E2D\u5FC3/AI \u5F00\u53D1\u8005\u7A7A\u95F4/AI Agent \u96C6\u6210/AI \u5DE5\u5177\u96C6\u6210/AI \u8FD0\u884C\u73AF\u5883/\u5F00\u653E\u80FD\u529B/Skills\u95E8\u6237/GTD/VOD\uFF09');return}t.slots.inject("conversation.composer.dock",function*(){yield t.slots.register({name:"conversation.composer.dock",id:"vod-feedback",order:20},Q)})}const Z="vod-devkit-ui";
7
+ module.exports.inject = ["slots"];
8
+ return module.exports;
9
+ }
10
+ });
package/lib/index.js ADDED
@@ -0,0 +1,416 @@
1
+ /**
2
+ * dsh-vod-devkit — VOD 用户声音采集插件(dsh 薄壳)。
3
+ *
4
+ * 形态纪律(与 vod-devkit MCP 侧一致):
5
+ * - 插件=引擎的客户端,只走 HTTPS,不 import 任何引擎模块
6
+ * - 纯采集形态:submit / 本地账本查询 / 自述,共 3 工具
7
+ * - 写操作默认走 dsh 审批通道(tools/pre-execute → kind:'ask')
8
+ * - voiceId = f(source, content, 调用级nonce):同调用幂等、跨调用保声量
9
+ * - key 缺失/401 → 自动 POST /external/token 零字段令牌 → 落本地 → 重试一次
10
+ * - 本地账本(data/runtime.json,cap 200 环形)只动目标键,读改写
11
+ */
12
+ import z from '@deepseek-ai/schemastery';
13
+ import { createHash, randomUUID } from 'node:crypto';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { dirname, join } from 'node:path';
16
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
17
+
18
+ export const name = 'vod-devkit';
19
+ export const inject = ['tools'];
20
+
21
+ const PKG_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
22
+ const DATA_DIR = join(PKG_DIR, 'data');
23
+ const RUNTIME = join(DATA_DIR, 'runtime.json');
24
+ const API_PREFIX = '/rest/developer/manager/hdvodmngservice/v1';
25
+ const HOARD_PATH = `${API_PREFIX}/external/voices`; // V16 囤积端点(批量/不触发 LLM/结构化回执)
26
+ const SUBMIT_PATH = `${API_PREFIX}/external/voice/submit`; // 旧单条端点:仅 404 回落使用 // V16 已切换:主路径 HOARD_PATH(囤积),本路径仅 404 回落(见 docs/decisions.md D-dsh-4)
27
+ const TOKEN_PATH = `${API_PREFIX}/external/token`;
28
+ const LEDGER_CAP = 200;
29
+
30
+ export const Config = z.object({
31
+ apiBase: z.string().default('https://vod-dev.topxtopx.com').volatile(),
32
+ apiKey: z.string().default('').volatile().role('secret'),
33
+ product: z.string().default('').volatile(),
34
+ confirmWrites: z.boolean().default(true).volatile(),
35
+ timeoutSec: z.number().default(30).volatile(),
36
+ });
37
+
38
+ function readCfg(v, fallback) {
39
+ if (v === undefined || v === null) return fallback;
40
+ if (typeof v === 'object' && typeof v.get === 'function') {
41
+ const got = v.get();
42
+ return got === undefined || got === null ? fallback : got;
43
+ }
44
+ return v;
45
+ }
46
+
47
+ // ── 本地账本:每次文件读改写,只动目标键(防内存合并回写陈旧配置) ──
48
+ function loadRuntime() {
49
+ try { return JSON.parse(readFileSync(RUNTIME, 'utf8')); } catch { return {}; }
50
+ }
51
+ function saveRuntime(patch) {
52
+ const rt = loadRuntime();
53
+ const next = { ...rt, ...patch };
54
+ if (Array.isArray(next.submissions) && next.submissions.length > LEDGER_CAP) {
55
+ next.submissions = next.submissions.slice(-LEDGER_CAP);
56
+ }
57
+ mkdirSync(DATA_DIR, { recursive: true });
58
+ writeFileSync(RUNTIME, JSON.stringify(next, null, 2));
59
+ }
60
+ function ledgerAppend(entries) {
61
+ const rt = loadRuntime();
62
+ const subs = Array.isArray(rt.submissions) ? rt.submissions : [];
63
+ saveRuntime({ submissions: [...subs, ...entries].slice(-LEDGER_CAP) });
64
+ }
65
+
66
+ // ── HTTP ──
67
+ // ── 传输守卫(与 vod_mcp tools.py -32014 同构):Bearer key/匿名令牌不得明文过公网 ──
68
+ function transportError(base) {
69
+ if (!base) return null;
70
+ let u; try { u = new URL(base); } catch { return { error: `apiBase 非法 URL: ${base}`, code: -32014 }; }
71
+ const host = u.hostname;
72
+ const loopback = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
73
+ if (u.protocol !== 'https:' && !loopback) {
74
+ return {
75
+ error: `上游 ${u.protocol}//${host} 非 https 且非本机回环——Bearer key 明文外发被拒` +
76
+ '(插件配置 apiBase 改为 https:// 地址)',
77
+ code: -32014,
78
+ };
79
+ }
80
+ return null;
81
+ }
82
+
83
+ // VOD-DEVICE:设备锚点(纯 hex 32 位,引擎 [0-9a-f]{8,64} 校验;
84
+ // 含非 hex 字符会静默降 legacy 锚点——UI 半实锤的同类坑)
85
+ function i0Anon() { return true; } // 401 → 匿名令牌重试一次(保持原行为锚点)
86
+
87
+ function deviceNonce() {
88
+ let n = loadRuntime().device_nonce;
89
+ if (!n) {
90
+ n = (randomUUID() + randomUUID()).replace(/[^0-9a-f]/g, '').slice(0, 32);
91
+ saveRuntime({ device_nonce: n });
92
+ }
93
+ return n;
94
+ }
95
+
96
+ async function http(method, path, body, { base, key, timeoutSec, signal }) {
97
+ const guard = transportError(base);
98
+ if (guard) throw new Error(`[${guard.code}] ${guard.error}`); // backstop:守卫在工具入口已拦截,此处兜底
99
+ const ctrl = new AbortController();
100
+ const timer = setTimeout(() => ctrl.abort(), (timeoutSec || 30) * 1000);
101
+ const onOuterAbort = () => ctrl.abort();
102
+ signal?.addEventListener('abort', onOuterAbort);
103
+ try {
104
+ const res = await fetch(`${base}${path}`, {
105
+ method,
106
+ headers: {
107
+ 'content-type': 'application/json',
108
+ 'X-Vod-Device-Id': deviceNonce(),
109
+ ...(key ? { authorization: `Bearer ${key}` } : {}),
110
+ },
111
+ body: body === undefined ? undefined : JSON.stringify(body),
112
+ signal: ctrl.signal,
113
+ });
114
+ const text = await res.text();
115
+ let data = null;
116
+ try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; }
117
+ return { status: res.status, ok: res.ok, data };
118
+ } finally {
119
+ clearTimeout(timer);
120
+ signal?.removeEventListener('abort', onOuterAbort);
121
+ }
122
+ }
123
+
124
+ async function fetchAnonToken(cfg) {
125
+ const out = await http('POST', TOKEN_PATH, {}, cfg);
126
+ if (out.ok && out.data && (out.data.token || out.data.data?.token)) {
127
+ return out.data.token || out.data.data.token;
128
+ }
129
+ return null;
130
+ }
131
+
132
+ const PRODUCT_MAP = { // 引擎枚举归一(实测:小写 codearts → 400 空响应;Python 侧同款映射)
133
+ // 已知差距(M2/M3 不适用于 dsh 形态):本表硬编码,不拉 GET /external/meta——
134
+ // 引擎 VodExternalProducts 变更时需同步此表(含 kb-query-auth 合入后的 AISHELL/nameAliases)。
135
+ // 详见 docs/decisions.md D-dsh-3。
136
+ agentarts: 'AgentArts', codearts: 'CodeArts', dataarts: 'DataArts',
137
+ maas: 'MaaS', obs: 'OBS', officeclaw: 'OfficeClaw',
138
+ modelarts: 'MaaS',
139
+ };
140
+
141
+ function voiceId(source, content, nonce) {
142
+ const h = createHash('sha1').update(content + nonce).digest('hex').slice(0, 12);
143
+ return `ext_${source}_${h}`;
144
+ }
145
+
146
+ function buildParameters(specs) {
147
+ const properties = {};
148
+ const required = [];
149
+ for (const [k, spec] of Object.entries(specs)) {
150
+ properties[k] = { type: spec.type, description: spec.description || k };
151
+ if (spec.required) required.push(k);
152
+ }
153
+ const r = { type: 'object', properties, additionalProperties: false };
154
+ if (required.length) r.required = required;
155
+ return r;
156
+ }
157
+
158
+ const textResult = (obj) => obj; // execute 返回结构化对象;render 负责呈现
159
+ const renderText = (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }];
160
+
161
+ /**
162
+ * D-anon-ui(安装时配置口径):从部署配置计算要注入页面的全局变量。
163
+ * 纯函数(可单测):product 恒注入;__VOD_DSH_UI_BASE__ 仅跨域部署显式配
164
+ * uiBase 才注入(apiBase 是 server 半自用的绝对地址,浏览器同源策略下
165
+ * 不能直接给页面;UI base 默认同源相对路径,宿主代理 /rest/)。
166
+ */
167
+ export function uiGlobals(config) {
168
+ const globals = [{
169
+ kind: "global", name: "__VOD_DSH_UI_PRODUCT__",
170
+ value: readCfg(config?.product, '') || '',
171
+ }];
172
+ const uiBase = readCfg(config?.uiBase, '');
173
+ if (uiBase) {
174
+ globals.push({ kind: "global", name: "__VOD_DSH_UI_BASE__", value: uiBase });
175
+ }
176
+ // 企业数据驻留(--no-local-ledger):通知 client 半停写账本+隐藏历史入口
177
+ if (readCfg(config?.noLocalLedger, false)) {
178
+ globals.push({ kind: "global", name: "__VOD_DSH_UI_LEDGER_DISABLED__", value: true });
179
+ }
180
+ return globals;
181
+ }
182
+
183
+ export function apply(ctx, config) {
184
+ // D-anon-ui:部署配置经官方 index-inject 通道下发页面全局(对齐
185
+ // settings-account 的 __DSH_CONTACT_CONFIG__ 同款机制)。产品归因仍是
186
+ // 安装必配(T7d)——未配置=client 半 fail fast 不激活,但不再是
187
+ // "散户死插件":错误信息指向安装命令(npx vod-devkit install
188
+ // --target dsh --product <产品名>)
189
+ ctx.on("webserver/index-inject", (table) => {
190
+ for (const row of uiGlobals(config)) table.push(row);
191
+ });
192
+ const cfg = () => ({
193
+ base: (readCfg(config?.apiBase, 'https://vod-dev.topxtopx.com') || '').replace(/\/+$/, ''),
194
+ key: readCfg(config?.apiKey, '') || '',
195
+ product: readCfg(config?.product, '') || '',
196
+ confirmWrites: readCfg(config?.confirmWrites, true) !== false,
197
+ timeoutSec: readCfg(config?.timeoutSec, 30),
198
+ });
199
+
200
+ const tools = [
201
+ {
202
+ name: 'vod_submit_voices',
203
+ description: '[VOD-unique] Submit agent-product user feedback voices to VOD (write). '
204
+ + 'ON FAILURE: tell the user in plain words only (e.g. 已暂存,稍后自动重试). '
205
+ + 'NEVER expose HTTP status codes, apiKeyFingerprint, tokenTier, stack traces, '
206
+ + 'tool names (say 提交反馈, never vod_submit_voices) or mechanism words '
207
+ + '(调用/被拒/护栏/参数) to the user - they are internal diagnostics. '
208
+ + 'The agent submits on the user\'s behalf; system behavior is described as 系统/稍后自动. '
209
+ + 'OUTPUT CONTRACT: when explaining results to the user, only cover 收录状态与后续跟进. '
210
+ + 'NEVER explain internal mechanics to users: 声音来源/渠道字段、计数规则(入库/净新增)、配额、归因——这些是系统内部概念。 '
211
+ + 'Anonymous tier has NO credentials by design. ' +
212
+ 'Each voice = one user feedback (content ≤2000 chars). '
213
+ + 'content MUST be a faithful transcription of the user\'s own words - '
214
+ + 'NEVER invent sentiment (e.g. 体验不好) or fabricate content the user did not say. '
215
+ + 'A bare product name or a question is NOT feedback - ask what the user wants to report. ' +
216
+ 'Product attribution ("host-is-product", no whitelist): explicit arg → config product → ' +
217
+ 'host identity (DSH). Host-reported products pass through as-is. ' +
218
+ 'Batch ≤50. Returns voiceIds (reconciliation key) + taskIds.',
219
+ parameters: buildParameters({
220
+ voices: {
221
+ type: 'array', required: true,
222
+ description: 'Array of 1-50 voices: {content (required, ≤2000), userType (optional 企业|个人|未知)}',
223
+ },
224
+ }),
225
+ output: { schema: { type: 'object', additionalProperties: true }, render: renderText },
226
+ async execute(args, exec) {
227
+ const c = cfg();
228
+ const guard = transportError(c.base); // 传输守卫:非 https 且非回环 → 拒绝(-32014,对齐 vod_mcp)
229
+ if (guard) return textResult(guard);
230
+ const voices = Array.isArray(args.voices) ? args.voices : [];
231
+ if (!voices.length) return textResult({ error: 'voices 为空', code: -32001 });
232
+ if (voices.length > 50) return textResult({ error: '单批上限 50 条', code: -32001 });
233
+ // 归因(「宿主即产品」口径,2026-11-03 拍板·不设白名单):显式传参 > 配置绑定
234
+ // (安装时默认=宿主名)> 缺省 DSH(本插件就装在 dsh 里);白名单废除,
235
+ // 宿主自报产品原样上送(引擎宽松归一),不再 -32013 本地拦截
236
+ let product = String(c.product || '').trim(); // 部署配置权威(安装时定),无 args 覆盖
237
+ product = PRODUCT_MAP[product.toLowerCase()] || product;
238
+ const source = 'dsh';
239
+ const accepted = [], taskIds = [], rejected = [];
240
+ let key = c.key;
241
+ // V16 切换(囤积端点):批量一次 POST,title=原文截取、content=用户原话
242
+ // (新端点无 10 字下限,不做模板补齐——P1 数据完整性)。404=引擎未部署 → 回落旧单条
243
+ const hoard = [];
244
+ for (let i = 0; i < voices.length; i++) {
245
+ const v = voices[i] || {};
246
+ const content = String(v.content ?? '').trim();
247
+ if (!content) { rejected.push({ index: i, reason: 'content 为空' }); continue; }
248
+ if (content.length > 2000) { rejected.push({ index: i, reason: `content 超 2000 字(${content.length})` }); continue; }
249
+ hoard.push({ title: content.slice(0, 128), content }); // R3:title=用户原文
250
+ }
251
+ if (hoard.length) {
252
+ let out = await http('POST', HOARD_PATH, { voices: hoard, product },
253
+ { ...c, key, signal: exec?.signal });
254
+ if (out.status === 401 && i0Anon(c)) {
255
+ const token = await fetchAnonToken({ ...c, key: '', signal: exec?.signal });
256
+ if (token) {
257
+ key = token;
258
+ saveRuntime({ java_key: token, token_tier: 'anonymous' });
259
+ out = await http('POST', HOARD_PATH, { voices: hoard, product },
260
+ { ...c, key, signal: exec?.signal });
261
+ } else {
262
+ return textResult({
263
+ error: '未配置接入 key 且匿名令牌端点不可用。引导:1) 首次提交时插件自动申请零字段匿名令牌;' +
264
+ '2) 量到上限后联系 VOD 运营升级正式 key;3) 宿主平台整体对接可获宿主 key',
265
+ code: -32012,
266
+ });
267
+ }
268
+ }
269
+ if (out.status !== 404) {
270
+ if (out.ok) {
271
+ const d = out.data?.data || out.data || {};
272
+ const ids = d.voiceIds || [];
273
+ const sts = d.statuses || [];
274
+ for (let i = 0; i < hoard.length; i++) {
275
+ const vid = ids[i] || '';
276
+ if (vid && sts[i] !== 'skipped') accepted.push(vid);
277
+ else if (vid) { accepted.push(vid); } // skipped=幂等,也回执
278
+ taskIds.push(null); // 囤积语义:无即时任务
279
+ }
280
+ const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
281
+ ledgerAppend(hoard.map((h, i) => ({
282
+ voiceId: ids[i] || '', taskId: null,
283
+ title: h.title.slice(0, 40), product,
284
+ at: now, status: sts[i] === 'skipped' ? 'accepted' : 'accepted',
285
+ })));
286
+ return textResult({
287
+ accepted: accepted.length, voiceIds: accepted,
288
+ taskIds, rejected, path: 'hoarding',
289
+ ...(d.productRegistered !== undefined ? { productRegistered: d.productRegistered } : {}),
290
+ });
291
+ }
292
+ // 非 404 非 2xx → 回落旧单条(如 401 已处理;此处为兼容异常响应)
293
+ }
294
+ }
295
+ for (let i = 0; i < voices.length; i++) {
296
+ const v = voices[i] || {};
297
+ const content = String(v.content ?? '').trim();
298
+ if (!content) { rejected.push({ index: i, reason: 'content 为空' }); continue; }
299
+ if (content.length > 2000) { rejected.push({ index: i, reason: `content 超 2000 字(${content.length})` }); continue; }
300
+ const nonce = randomUUID().replace(/-/g, '').slice(0, 8); // 调用级幂等、跨调用保声量
301
+ const vid = voiceId(source, content, nonce);
302
+ const desc = content.length >= 10 ? content : `${content} [vod-devkit]`;
303
+ const body = {
304
+ voiceId: vid,
305
+ title: content.slice(0, 128), // R3:title=用户原文(分析消费),模板只允许出现在 description
306
+ description: desc,
307
+ product,
308
+ source,
309
+ ...(v.userType ? { customer: v.userType } : {}),
310
+ };
311
+ const call = () => http('POST', SUBMIT_PATH, body, { ...c, key, signal: exec?.signal });
312
+ let out = await call();
313
+ if (out.status === 401 && i === 0) {
314
+ // 零字段匿名令牌:401 → 自动取令牌 → 落本地 → 重试一次
315
+ const token = await fetchAnonToken({ ...c, key: '', signal: exec?.signal });
316
+ if (token) {
317
+ key = token;
318
+ saveRuntime({ java_key: token, token_tier: 'anonymous' });
319
+ out = await call();
320
+ } else {
321
+ return textResult({
322
+ error: '未配置接入 key 且匿名令牌端点不可用。引导:1) 首次提交时插件自动申请零字段匿名令牌;' +
323
+ '2) 量到上限后联系 VOD 运营升级正式 key;3) 宿主平台整体对接可获宿主 key',
324
+ code: -32012,
325
+ });
326
+ }
327
+ }
328
+ if (out.ok) {
329
+ accepted.push(vid);
330
+ taskIds.push(out.data?.data?.taskId ?? null);
331
+ } else {
332
+ const msg = JSON.stringify(out.data || {}).slice(0, 160);
333
+ if (msg.includes('Duplicate entry')) { accepted.push(vid); taskIds.push(null); }
334
+ else rejected.push({ index: i, reason: msg && msg !== '{}' ? msg : `HTTP ${out.status}` });
335
+ }
336
+ }
337
+ const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
338
+ ledgerAppend(accepted.map((vid, i) => ({
339
+ voiceId: vid, taskId: taskIds[i],
340
+ title: String((voices[i] || {}).content ?? '').slice(0, 40),
341
+ product, at: now,
342
+ })));
343
+ return textResult({ accepted: accepted.length, voiceIds: accepted, taskIds, rejected });
344
+ },
345
+ },
346
+ {
347
+ name: 'vod_list_submitted',
348
+ description: '[VOD-unique] Read-only: list voices submitted from THIS machine (local ledger, cap 200, newest first). ' +
349
+ 'Scope: local machine only — authoritative cross-machine query arrives with the engine-side endpoint (VOD-VOI layer 2).',
350
+ parameters: buildParameters({
351
+ limit: { type: 'number', description: '1-100, default 20, newest first' },
352
+ }),
353
+ output: { schema: { type: 'object', additionalProperties: true }, render: renderText },
354
+ async execute(args) {
355
+ const rt = loadRuntime();
356
+ const subs = Array.isArray(rt.submissions) ? rt.submissions : [];
357
+ const limit = Math.max(1, Math.min(100, Number(args.limit) || 20));
358
+ return textResult({
359
+ scope: 'local-machine',
360
+ total: subs.length,
361
+ voices: subs.slice(-limit).reverse(),
362
+ });
363
+ },
364
+ },
365
+ {
366
+ name: 'vod_devkit_info',
367
+ description: '[VOD-unique] Read-only plugin self-description: version, api endpoint (fingerprinted), auth state (fingerprinted, never plaintext), local ledger size.',
368
+ parameters: buildParameters({}),
369
+ output: { schema: { type: 'object', additionalProperties: true }, render: renderText },
370
+ async execute() {
371
+ const c = cfg();
372
+ const rt = loadRuntime();
373
+ const fp = (s) => (s ? createHash('sha1').update(s).digest('hex').slice(0, 8) : null);
374
+ // D-anon-ui:匿名档=散户默认正常态。无 key 不是"未配置"故障,
375
+ // 显式标注防模型误诊(实锤:模型曾把 null 读成"凭据没配置"端给用户)
376
+ const authMode = c.key ? 'key-configured' : (rt.token_tier ? 'anonymous-token' : 'anonymous (auto on first submit)');
377
+ return textResult({
378
+ version: '0.1.0',
379
+ host: 'dsh',
380
+ apiBase: c.base,
381
+ apiKeyFingerprint: fp(c.key),
382
+ tokenTier: rt.token_tier || null,
383
+ authMode,
384
+ authNote: c.key ? null : 'No key configured - this is the DEFAULT anonymous tier (normal), auto token on first submit. NOT a misconfiguration.',
385
+ ledgerEntries: Array.isArray(rt.submissions) ? rt.submissions.length : 0,
386
+ });
387
+ },
388
+ },
389
+ ];
390
+
391
+ for (const t of tools) ctx.tools.register(t);
392
+
393
+ // 写操作确认:dsh 审批通道(web 端弹确认框),拒绝则不执行
394
+ if (typeof ctx.on === 'function') {
395
+ try {
396
+ ctx.on('tools/pre-execute', (exec, next) => {
397
+ if (exec.name !== 'vod_submit_voices') return next();
398
+ if (!cfg().confirmWrites) return next();
399
+ return {
400
+ kind: 'ask',
401
+ reason: `vod-write:${exec.name}`,
402
+ displayReason: {
403
+ en: 'Submit this user feedback voice to VOD?',
404
+ zh: '向 VOD 提交这条用户反馈声音?',
405
+ },
406
+ };
407
+ });
408
+ } catch (err) {
409
+ console.warn(`[dsh-vod-devkit] pre-execute registration failed: ${String(err)}`);
410
+ }
411
+ }
412
+
413
+ console.log(`[dsh-vod-devkit] Registered ${tools.length} tools, apiBase=${cfg().base}` +
414
+ (cfg().key ? ', key=set' : ', key=none (auto anonymous-token on first submit)') +
415
+ (cfg().product ? `, product=${cfg().product}` : ', product=unset (must be set or passed per call)'));
416
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "dsh-vod-devkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "VOD user-voice collection tools for DeepSeek Harness (dsh). Thin shell over the VOD external HTTP API — mirrors vod-devkit (MCP) collect semantics.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "files": [
8
+ "lib/**/*.js",
9
+ "cordis.patch.yml",
10
+ "README.md"
11
+ ],
12
+ "license": "MIT",
13
+ "dsh": {
14
+ "bundle": {
15
+ "patch": "./cordis.patch.yml"
16
+ },
17
+ "client": {
18
+ "platform": "web",
19
+ "inject": [
20
+ "@deepseek-ai/dsh-client-ui-chat"
21
+ ]
22
+ }
23
+ },
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "peerDependencies": {
28
+ "@deepseek-ai/cordis": ">=4.0.0",
29
+ "@deepseek-ai/dsh-tools": ">=0.0.1-0",
30
+ "@deepseek-ai/schemastery": ">=3.18.0"
31
+ },
32
+ "keywords": [
33
+ "dsh",
34
+ "deepseek-harness",
35
+ "dsh-plugin",
36
+ "vod",
37
+ "feedback"
38
+ ],
39
+ "devDependencies": {
40
+ "esbuild": "^0.28.2",
41
+ "react": "^19.3.1"
42
+ },
43
+ "exports": {
44
+ ".": "./lib/index.js",
45
+ "./client": "./lib/client.js"
46
+ },
47
+ "scripts": {
48
+ "build-client": "esbuild src/client.jsx --jsx=automatic --format=cjs --minify --outfile=/tmp/client-cjs.js && python3 scripts/wrap_client.py"
49
+ }
50
+ }