vod-devkit 0.2.0 → 0.2.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/CHANGELOG.md +4 -0
- package/contract/tools.schema.json +1 -1
- package/package.json +15 -2
- package/plugins/.agents/plugins/marketplace.json +19 -0
- package/plugins/vod-devkit/.codex-plugin/plugin.json +27 -0
- package/plugins/vod-devkit/.mcp.json +10 -0
- package/plugins/vod-devkit/build-info.json +6 -0
- package/plugins/vod-devkit/skills/vod-feedback-collect/SKILL.md +145 -0
- package/plugins/vod-devkit/vod_mcp/__init__.py +11 -0
- package/plugins/vod-devkit/vod_mcp/packs.py +30 -0
- package/plugins/vod-devkit/vod_mcp/policy.py +98 -0
- package/plugins/vod-devkit/vod_mcp/provenance.py +43 -0
- package/plugins/vod-devkit/vod_mcp/runtime.example.json +6 -0
- package/plugins/vod-devkit/vod_mcp/server.py +105 -0
- package/plugins/vod-devkit/vod_mcp/tools.py +639 -0
- package/vod_mcp/__init__.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -116,3 +116,7 @@
|
|
|
116
116
|
- 599478b feat(D-codex-agents-1): codex 技能层载体落地——codex 无 skill 机制,采集质量方法论(触发三条件/content🔒字段分级/推断≠编造禁例/预检三项/不追问/回执话术/职责边界)此前在 codex 上裸奔(工具描述只装硬约束)。install --target codex 随装幂等写入 ~/.codex/AGENTS.md 技能紧凑块(标记剥离幂等,用户自有内容保留)。工具描述同步修口径冲突:删除'用户明确要求其他产品可显式传参覆盖'(违背 S1 同源原则——用户自报产品一律不采信不覆盖,照部署产品提交正文原样)。tags 语义注释(problem_type:云声三分类入标题前缀,非 n01 六类)。新增 AGENTS.md 幂等/内容保留测试锁;72 用例绿
|
|
117
117
|
- acfcc4d fix(D-product-id-2 收口): submit_voices 描述补归因话术并前置——codex 等 MCP-only 宿主不加载 skill,模型唯一约束源是工具描述;原描述零归因话术导致用户提单时被反问'什么产品'(T7d 后已废除的旧职责话机复活)。话术前置防宿主描述截断;外部对表建议采纳:约束三层(工具描述/参数描述/非required 结构)+AGENTS.md 仅冗余;其 .codex-plugin/capability_directories 体系与本机 codex CLI v0.166 实测机制不符未采纳(待证据)。71 用例绿;codex 真机行为验证:提单不带 product 不再反问、直接安装绑定归因提交落库
|
|
118
118
|
|
|
119
|
+
|
|
120
|
+
## v0.2.1(2026-11-05)
|
|
121
|
+
|
|
122
|
+
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
3
|
"title": "vod-devkit MCP 工具契约(唯一事实源)",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.1",
|
|
5
5
|
"tools": {
|
|
6
6
|
"vod_submit_voices": {
|
|
7
7
|
"description": "提交用户反馈。product 归因由安装绑定自动完成(install --product 必配且经产品名录硬校验),调用时无需用户提供、禁止向用户询问\"提交到什么产品\";用户自报的目标产品一律不采信不覆盖(照部署产品提交,提到什么产品随正文原样传达)。批式提交对接囤积端点 POST /external/voices(不触发分析,voiceId 由引擎计算回执下发;引擎未部署 404 自动回落老链)。tags=采集层三分类(problem_type:值)。缺 key 时自动获取零字段匿名令牌。禁止向用户解释内部机制(声音来源/渠道字段/计数规则/配额/归因)。",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vod-devkit",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "VOD 用户声音采集插件——MCP server + 技能 + 声明式护栏,把 agent 产品的用户反馈安全送进 VOD 平台",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -23,7 +23,20 @@
|
|
|
23
23
|
"vod_mcp/packs.py",
|
|
24
24
|
"vod_mcp/policy.py",
|
|
25
25
|
"vod_mcp/provenance.py",
|
|
26
|
-
"vod_mcp/runtime.example.json"
|
|
26
|
+
"vod_mcp/runtime.example.json",
|
|
27
|
+
"vod_mcp/__init__.py",
|
|
28
|
+
"vod_mcp/server.py",
|
|
29
|
+
"vod_mcp/tools.py",
|
|
30
|
+
"vod_mcp/packs.py",
|
|
31
|
+
"vod_mcp/policy.py",
|
|
32
|
+
"vod_mcp/provenance.py",
|
|
33
|
+
"vod_mcp/runtime.example.json",
|
|
34
|
+
"plugins/vod-devkit/.codex-plugin/plugin.json",
|
|
35
|
+
"plugins/vod-devkit/.mcp.json",
|
|
36
|
+
"plugins/vod-devkit/build-info.json",
|
|
37
|
+
"plugins/vod-devkit/vod_mcp",
|
|
38
|
+
"plugins/vod-devkit/skills",
|
|
39
|
+
"plugins/.agents/plugins/marketplace.json"
|
|
27
40
|
],
|
|
28
41
|
"keywords": [
|
|
29
42
|
"mcp",
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vod-local",
|
|
3
|
+
"plugins": [
|
|
4
|
+
{
|
|
5
|
+
"name": "vod-devkit",
|
|
6
|
+
"source": {
|
|
7
|
+
"source": "local",
|
|
8
|
+
"path": "./vod-devkit"
|
|
9
|
+
},
|
|
10
|
+
"policy": {
|
|
11
|
+
"installation": "AVAILABLE",
|
|
12
|
+
"authentication": "ON_INSTALL",
|
|
13
|
+
"products": [
|
|
14
|
+
"CODEX"
|
|
15
|
+
]
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
]
|
|
19
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vod-devkit",
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "VOD user-feedback collection: structured voice capture and submission to the VOD hoarding endpoint.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"feedback",
|
|
7
|
+
"vod",
|
|
8
|
+
"voice",
|
|
9
|
+
"collection"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"interface": {
|
|
13
|
+
"displayName": "VOD DevKit",
|
|
14
|
+
"shortDescription": "Collect user feedback voices into VOD (product-bound attribution, safe defaults).",
|
|
15
|
+
"category": "Developer Tools",
|
|
16
|
+
"capabilities": [
|
|
17
|
+
"Read",
|
|
18
|
+
"Interactive"
|
|
19
|
+
],
|
|
20
|
+
"defaultPrompt": [
|
|
21
|
+
"我想反馈一个产品问题",
|
|
22
|
+
"帮我把这条意见提交给产品团队"
|
|
23
|
+
]
|
|
24
|
+
},
|
|
25
|
+
"skills": "./skills/",
|
|
26
|
+
"mcpServers": "./.mcp.json"
|
|
27
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vod-feedback-collect
|
|
3
|
+
description: Use when 用户表达对本产品的反馈、不满、建议或明确要求提交反馈(慢/错/卡/希望支持/记下来反馈给产品团队)。采集-确认-提交-回执一条线;产品归由安装绑定自动完成,不问用户
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# VOD 用户反馈采集
|
|
7
|
+
|
|
8
|
+
闭环:用户反馈 → agent 识别 → 用户确认 → 入库(不触发分析)→ 运营择机
|
|
9
|
+
批量分析 → 报告/看板 → 产品改进。
|
|
10
|
+
|
|
11
|
+
## 触发识别
|
|
12
|
+
|
|
13
|
+
**本技能是什么(一句话)**:把用户对本产品的反馈整理为一条声音、
|
|
14
|
+
经用户同意后提交到 VOD、把回执用人话告诉用户。模型在此过程中
|
|
15
|
+
只做三件事:**识别反馈意图、忠实转写用户原话、征得提交同意**。
|
|
16
|
+
决定权在用户:说什么、何时提交,都由用户定;模型不补写、不判断、
|
|
17
|
+
不发散(细则见下方各条禁令——它们是这三件事的实施边界,不是职责本身)。
|
|
18
|
+
|
|
19
|
+
**触发条件(满足任一即加载本技能)**:
|
|
20
|
+
1. 用户表达对本产品的否定或建议——关键词如:慢、报错、不好用、
|
|
21
|
+
希望支持、建议增加、为什么不能、体验差;
|
|
22
|
+
2. 用户明确要求提交反馈——"记下来"、"反馈给产品团队"、"提交这条";
|
|
23
|
+
3. 连续两轮抱怨同一问题。
|
|
24
|
+
不满足时本技能不激活(产品问答、闲聊、操作指导等交回宿主通用能力)。
|
|
25
|
+
|
|
26
|
+
**字段处理分级(借鉴 gitcode-issue-creator,先于一切)**:
|
|
27
|
+
| 字段 | 处理 | 规则 |
|
|
28
|
+
|------|------|------|
|
|
29
|
+
| content | 🔒 原样保留 | 用户原话忠实转写,只做脱敏(密钥替换);禁止改写、扩展、补充情感结论(如"体验不好")或任何用户没说的内容 |
|
|
30
|
+
| title | 🧠 推断摘要 | 从用户表述提炼核心问题(引擎自动截前 64 字,无需手拼) |
|
|
31
|
+
| 分类 | 🧠 推断 | 从内容判断三分类之一;判断不了不选(引擎重判兜底) |
|
|
32
|
+
|
|
33
|
+
**推断 ≠ 编造(关键辨析)**:
|
|
34
|
+
- ✅ 推断:用户说"AIShell 补全经常卡住" → content 原样保留,分类=产品缺陷(从"经常卡住"提取重组)
|
|
35
|
+
- ❌ 编造:用户只说了"AIShell" → 写成"AIShell 产品体验不好"(用户没说体验不好——情感结论是编造,实锤事故)
|
|
36
|
+
- ✅ 推断:用户说"希望支持扫码授权" → 分类=功能建议
|
|
37
|
+
- ❌ 编造:用户问"AIShell 是什么"(提问不是反馈)→ 不采集,需澄清
|
|
38
|
+
|
|
39
|
+
**调用前强制预检(不过不许调用)**:
|
|
40
|
+
检查 1: content 是否等于用户原话?(≠ → 改回原话)
|
|
41
|
+
检查 2: 用户的话是否构成一条反馈(有具体对象/现象)?裸产品名、
|
|
42
|
+
纯提问、闲聊 → 停止采集,先澄清用户想说什么
|
|
43
|
+
检查 3: 分类是否与内容相符?(不符 → 重新推断)
|
|
44
|
+
|
|
45
|
+
**不追问原则**:内容太泛时引导一次("说下具体现象?"),用户不补
|
|
46
|
+
就按原话提交或放弃——禁止反复追问,禁止替用户脑补现象细节。
|
|
47
|
+
|
|
48
|
+
**职责边界(先于一切)**:本技能只做一件事=采集-确认-提交-回执。
|
|
49
|
+
产品问答("AIShell 是什么")、产品对比、内部机制解释(归因/白名单/
|
|
50
|
+
配额)一律**不在职责内**:不读仓库文档作答、不展开、不主动科普——
|
|
51
|
+
一句"这不在反馈功能范围内"即可,或交回宿主通用能力处理。
|
|
52
|
+
模型发散=把内部实现端给用户(实锤:'AIShell 是归因产品名之一'+
|
|
53
|
+
白名单/文档行号整套端出去)。
|
|
54
|
+
|
|
55
|
+
用户表达针对**本产品(宿主 agent 产品)**的体验反馈,特征:
|
|
56
|
+
- 抱怨/问题:慢、错、卡、缺失功能、交互别扭
|
|
57
|
+
- 建议/期望:希望支持、要是能…就好了、建议增加
|
|
58
|
+
- 区分边界:用户抱怨的是**宿主产品**才走本技能;用户在讨论第三方
|
|
59
|
+
事物(某网站、某文档)不采集;用户要求提交"工单"类诉求时可询问
|
|
60
|
+
是否愿意同步收录为产品反馈(只确认收录意愿,不问产品归属)
|
|
61
|
+
|
|
62
|
+
## 采集流程
|
|
63
|
+
|
|
64
|
+
0. 产品归因(安装时已配置,不问用户):产品=安装/部署时绑定的
|
|
65
|
+
宿主产品(install --product / dsh profile config),工具与引擎
|
|
66
|
+
自动赋值——**禁止向用户追问"哪个产品"**(用户不知道也不该知道
|
|
67
|
+
采集侧的归因配置)。**用户自报的目标产品一律不采信、不覆盖**
|
|
68
|
+
(S1 同源原则:话术可以把反馈投到任意产品=污染别人产品数据)。
|
|
69
|
+
用户说"这是给 XX 的反馈"→ 照常按部署产品提交,内容原样保留
|
|
70
|
+
(提到什么产品随正文传达);不要确认、不要改归因
|
|
71
|
+
1. 识别到反馈意图 → 先口头确认收录意愿("要把这条反馈提交给产品
|
|
72
|
+
团队吗?")
|
|
73
|
+
2. 用户同意 → 结构化为声音(不篡改原意):
|
|
74
|
+
- content:用户反馈内容(尽量保留用户原话措辞,可轻度去噪)
|
|
75
|
+
- userType:可判断时填(企业/个人),不确定不填
|
|
76
|
+
- tags:明显的主题词(性能/功能/易用性),最多 3 个
|
|
77
|
+
3. 调用 vod_submit_voices(必须用户已确认,confirmed=true)——
|
|
78
|
+
**一次一批**,攒多条一起交也行,但每批都要用户点头
|
|
79
|
+
4. 拿到回执 → 对用户说人话:"已收录,产品团队会看到这条反馈"——
|
|
80
|
+
**voiceId 不展示给终端用户**(编号噪音),仅供 agent 对账用;
|
|
81
|
+
用户追问"提交了吗"时 agent 用 voiceId/taskId 核对后回答状态
|
|
82
|
+
|
|
83
|
+
## 纪律
|
|
84
|
+
|
|
85
|
+
0. 回执纪律(F2,成功与失败路径同口径):给用户的话=人话
|
|
86
|
+
(成功=已收录/产品团队会看到;失败=提交失败,反馈已暂存本机,
|
|
87
|
+
稍后会自动重试)。**失败时禁止向用户复述内部诊断字段**——HTTP
|
|
88
|
+
状态码、apiKeyFingerprint、tokenTier、堆栈等属于 agent 内部排障
|
|
89
|
+
信息,用户看不到也不需要看;匿名档用户没有"凭据"概念,"凭据未
|
|
90
|
+
配置"对他们是无效信息。voiceId/taskId 是对账主键,在 agent 内部
|
|
91
|
+
使用,不出现在用户可见文案里。
|
|
92
|
+
**工具名与机制词同理不外露**:对用户永远说"提交反馈",禁止出现
|
|
93
|
+
vod_submit_voices 等工具名,禁止"调用/被拒/护栏/参数/配额"等
|
|
94
|
+
机制词(实锤:"vod_submit_voices 被我调用后你拒绝了它"——用户
|
|
95
|
+
看不懂谁调用了什么、自己为什么成了拒绝者)。主语纪律:动作主体
|
|
96
|
+
是"我"(agent 替用户提交),系统行为统一说"系统/稍后自动",不
|
|
97
|
+
把内部裁决说成用户的行为
|
|
98
|
+
1. 逐次确认:每批提交前用户点头一次,不打包沉默提交(护栏强制,
|
|
99
|
+
confirmed=false 会被拒)
|
|
100
|
+
2. 来源标记由插件自动注入(宿主身份),不手填——防伪造
|
|
101
|
+
3. content 是用户原话,agent 不加自己的评价/总结进 content
|
|
102
|
+
4. 不提交用户身份信息(姓名/账号/工号)——内容里的凭据类内容
|
|
103
|
+
会被 deny 护栏拦截
|
|
104
|
+
5. voiceId 是回执主键,用户追问"提交了吗"用编号对账,不凭记忆
|
|
105
|
+
6. 单批上限 50 条,超限分批
|
|
106
|
+
|
|
107
|
+
## 对齐 VOD-Project 采集标准(2026-11-04 二轮修订,待一次真实用户观测后定稿)
|
|
108
|
+
|
|
109
|
+
学习源=VOD-Project skills/bbs-suggestion + vod-sync/SKILL.md(深读):
|
|
110
|
+
|
|
111
|
+
### content 模板(替代自由拼装,四节加粗标签)
|
|
112
|
+
```
|
|
113
|
+
用户原话(不加标签,保留措辞)
|
|
114
|
+
|
|
115
|
+
**使用场景:**
|
|
116
|
+
(agent 推断,不允许空——空=拒提交,逼推断)
|
|
117
|
+
|
|
118
|
+
**当前影响:**(可选)
|
|
119
|
+
|
|
120
|
+
**期望能力:**
|
|
121
|
+
|
|
122
|
+
**声音来源:**
|
|
123
|
+
(agent 会话平台:cli/飞书/企业微信…——运行时从宿主会话上下文
|
|
124
|
+
获取,禁止硬编码默认值;对齐 detect_channel 纪律)
|
|
125
|
+
```
|
|
126
|
+
- 有对话上下文时:最近 5 轮用户消息格式化为 `> 用户:原话` 引用块
|
|
127
|
+
置顶(过滤触发词、与 content 重复的最后一条去掉)
|
|
128
|
+
|
|
129
|
+
### 分类(采集层三分类,不越层)
|
|
130
|
+
- 给用户的选项=功能建议/用户体验/产品缺陷(云声表单标准);
|
|
131
|
+
六类是引擎 n01 分析层内部枚举,agent 侧不使用、不自造第四个枚举
|
|
132
|
+
- 落 tags=["problem_type:<三分类值>"],引擎以【类型名】标题前缀正式
|
|
133
|
+
入库,n01 照常重判——两层并存,agent 不许宣称"分类即定案"
|
|
134
|
+
|
|
135
|
+
### 路由纪律
|
|
136
|
+
- 用户说"反馈/报告问题/提 issue"→引擎 ISYNC 审核队列路径(本技能
|
|
137
|
+
提交即入队,运营复审后建 issue),agent 不直接建 GitCode issue
|
|
138
|
+
- 用户明确"提建议"且要求直上渠道时才提及云声链(bbs-suggestion 为
|
|
139
|
+
VOD-Project 内部资产,外部 agent 不分发)
|
|
140
|
+
|
|
141
|
+
### 自检清单(提交前逐条过,不过不提交)
|
|
142
|
+
- [ ] content 含四节模板且使用场景/期望能力非空?
|
|
143
|
+
- [ ] 声音来源=真实会话平台(非硬编码)?
|
|
144
|
+
- [ ] 分类(若有)是三分类枚举值?
|
|
145
|
+
- [ ] 未把 agent 自己的评价混进用户原话?
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""vod-devkit:VOD 分析能力的 MCP 插件薄壳。
|
|
2
|
+
|
|
3
|
+
铁律(见 docs/design.md):
|
|
4
|
+
1. 只允许经 HTTP 调 workflow/api.py,禁止 import 引擎内部模块
|
|
5
|
+
2. 外部无 DB 直连路径(护栏 deny 兜底)
|
|
6
|
+
3. 任务 ID 是唯一对账主键,写类工具返回一律携带
|
|
7
|
+
"""
|
|
8
|
+
__version__ = "0.2.1"
|
|
9
|
+
# 默认上游:VOD 测试环境。外部用户本机无 VOD,回环默认值=装完即坏;
|
|
10
|
+
# 生产地址定型后只改这一处(tools.py 与 bin/vod-devkit 共用本常量)。
|
|
11
|
+
DEFAULT_JAVA_BASE = "https://vod-dev.topxtopx.com"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""packs 裁剪:VOD_PACKS=core,workflow,kb(逗号分隔,默认全装)。
|
|
2
|
+
|
|
3
|
+
core 常驻(vod_devkit_info + vod-core 技能);未启用的 pack 工具不注册。
|
|
4
|
+
"""
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
ALL_PACKS = ("core", "collect", "knowledge")
|
|
8
|
+
|
|
9
|
+
PACK_TOOLS = {
|
|
10
|
+
"core": ["vod_devkit_info", "vod_auth_status"],
|
|
11
|
+
"collect": ["vod_submit_voices", "vod_list_submitted"],
|
|
12
|
+
"knowledge": [], # 纯技能包:3 个领域规则技能,零工具零依赖
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def enabled_packs() -> tuple:
|
|
17
|
+
raw = os.environ.get("VOD_PACKS", "").strip()
|
|
18
|
+
if not raw:
|
|
19
|
+
return ALL_PACKS
|
|
20
|
+
packs = tuple(p.strip() for p in raw.split(",") if p.strip() in ALL_PACKS)
|
|
21
|
+
if "core" not in packs:
|
|
22
|
+
packs = ("core",) + packs
|
|
23
|
+
return packs
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def enabled_tools() -> list:
|
|
27
|
+
tools = []
|
|
28
|
+
for pack in enabled_packs():
|
|
29
|
+
tools.extend(PACK_TOOLS[pack])
|
|
30
|
+
return tools
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""声明式护栏:safety/policy.json 规则执行(deny/confirm)。
|
|
2
|
+
|
|
3
|
+
规则匹配分两类:
|
|
4
|
+
- 工具参数规则(match.tool 指定):在 tools/call 前置检查
|
|
5
|
+
- 文本规则(match.field=text):供 hook 层与工具参数串一起检查
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
_POLICY_PATH = Path(__file__).resolve().parent.parent / "safety" / "policy.json"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_policy() -> dict:
|
|
15
|
+
with open(_POLICY_PATH, encoding="utf-8") as f:
|
|
16
|
+
return json.load(f)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _resolve_ref(policy: dict, value):
|
|
20
|
+
"""match 里 'maxVoicesPerTask' 这类引用政策顶层的值。"""
|
|
21
|
+
if isinstance(value, str) and value in policy:
|
|
22
|
+
return policy[value]
|
|
23
|
+
return value
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _match_tool_rule(rule: dict, tool: str, params: dict) -> bool:
|
|
27
|
+
m = rule["match"]
|
|
28
|
+
if m.get("tool") != tool:
|
|
29
|
+
return False
|
|
30
|
+
p = m.get("param")
|
|
31
|
+
if p is None:
|
|
32
|
+
return True
|
|
33
|
+
actual = params.get(p)
|
|
34
|
+
if actual is None and "equals" in m and m["equals"] is False:
|
|
35
|
+
actual = False # 缺省视为未确认
|
|
36
|
+
if "equals" in m:
|
|
37
|
+
return actual == m["equals"]
|
|
38
|
+
if "gt" in m:
|
|
39
|
+
limit = _resolve_ref(load_policy(), m["gt"])
|
|
40
|
+
try:
|
|
41
|
+
if isinstance(actual, list):
|
|
42
|
+
return len(actual) > int(limit)
|
|
43
|
+
return actual is not None and int(actual) > int(limit)
|
|
44
|
+
except (TypeError, ValueError):
|
|
45
|
+
return False
|
|
46
|
+
if "notIn" in m:
|
|
47
|
+
whitelist = _resolve_ref(load_policy(), m["notIn"])
|
|
48
|
+
if not isinstance(whitelist, (list, tuple)):
|
|
49
|
+
return False
|
|
50
|
+
return actual not in whitelist
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def check_tool_call(policy: dict, tool: str, params: dict) -> list:
|
|
55
|
+
"""返回命中的规则列表(空=放行)。deny 命中=拒绝;confirm 命中=要求确认。"""
|
|
56
|
+
hits = []
|
|
57
|
+
for rule in policy.get("rules", []):
|
|
58
|
+
if "tool" in rule.get("match", {}):
|
|
59
|
+
if _match_tool_rule(rule, tool, params):
|
|
60
|
+
hits.append(rule)
|
|
61
|
+
return hits
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def guard_scope(params: dict) -> dict:
|
|
65
|
+
"""文本规则的扫描面(E4 修复):剔除用户内容字段——拦"凭据读取意图"
|
|
66
|
+
不误杀"反馈内容里引用凭据"。voices[].content 与 data 是用户原话,
|
|
67
|
+
不进文本规则;scene/tags/query/product 等结构性字段仍扫描。"""
|
|
68
|
+
scope = {}
|
|
69
|
+
for k, v in (params or {}).items():
|
|
70
|
+
if k in ("data",): # run_analysis 的声音数据=用户原话
|
|
71
|
+
scope[k] = "<%d records>" % len(v) if isinstance(v, list) else "..."
|
|
72
|
+
elif k == "voices": # 采集的反馈内容=用户原话,仅扫非 content 字段
|
|
73
|
+
scope[k] = [{kk: vv for kk, vv in (item or {}).items() if kk != "content"}
|
|
74
|
+
for item in v] if isinstance(v, list) else v
|
|
75
|
+
else:
|
|
76
|
+
scope[k] = v
|
|
77
|
+
return scope
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def check_text(policy: dict, text: str) -> list:
|
|
81
|
+
"""文本类 deny 规则(DB 直连/凭据模式),供 hook 与参数串调用。"""
|
|
82
|
+
hits = []
|
|
83
|
+
for rule in policy.get("rules", []):
|
|
84
|
+
m = rule.get("match", {})
|
|
85
|
+
if m.get("field") == "text":
|
|
86
|
+
if re.search(m["regex"], text or ""):
|
|
87
|
+
hits.append(rule)
|
|
88
|
+
return hits
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def decide(hits: list) -> tuple:
|
|
92
|
+
"""(verdict, message);verdict ∈ {allow, confirm, deny}。"""
|
|
93
|
+
if not hits:
|
|
94
|
+
return "allow", ""
|
|
95
|
+
denies = [r for r in hits if r["severity"] == "deny"]
|
|
96
|
+
if denies:
|
|
97
|
+
return "deny", denies[0]["message"]
|
|
98
|
+
return "confirm", hits[0]["message"]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""溯源与宿主身份:build-info.json(构建烧录)+ 握手 clientInfo + install-manifest。"""
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
_ROOT = Path(__file__).resolve().parent.parent
|
|
6
|
+
_BUILD_INFO = _ROOT / "build-info.json"
|
|
7
|
+
_MANIFEST = _ROOT / "install-manifest.json"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def read_build_info() -> dict:
|
|
11
|
+
if _BUILD_INFO.exists():
|
|
12
|
+
with open(_BUILD_INFO, encoding="utf-8") as f:
|
|
13
|
+
return json.load(f)
|
|
14
|
+
return {"version": "dev", "commitSha": None, "builtAt": None, "sourceRemote": None}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def read_manifest() -> dict:
|
|
18
|
+
if _MANIFEST.exists():
|
|
19
|
+
with open(_MANIFEST, encoding="utf-8") as f:
|
|
20
|
+
return json.load(f)
|
|
21
|
+
return {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def host_identity() -> dict:
|
|
25
|
+
"""安装清单的 target + 握手 clientInfo(由 server.py 注入 _HOST)。"""
|
|
26
|
+
return read_manifest().get("target") or {}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def info_payload(client_info: dict | None = None) -> dict:
|
|
30
|
+
bi = read_build_info()
|
|
31
|
+
mf = read_manifest()
|
|
32
|
+
host = client_info or mf.get("clientInfo") or {}
|
|
33
|
+
return {
|
|
34
|
+
"version": bi.get("version"),
|
|
35
|
+
"commitSha": bi.get("commitSha"),
|
|
36
|
+
"packs": sorted(__import__("vod_mcp.packs", fromlist=["enabled_packs"]).enabled_packs()),
|
|
37
|
+
"hostClient": host,
|
|
38
|
+
"manifestSummary": {
|
|
39
|
+
"target": mf.get("target"),
|
|
40
|
+
"installedAt": mf.get("installedAt"),
|
|
41
|
+
"source": mf.get("source"),
|
|
42
|
+
},
|
|
43
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""MCP stdio server(JSON-RPC 2.0,行分隔)。
|
|
2
|
+
|
|
3
|
+
依赖:Python 3.10+,零第三方依赖(内网友好)。
|
|
4
|
+
握手记录 clientInfo(宿主感知);工具调用前过声明式护栏。
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
# 自举包路径(对任意 MCP 宿主成立:不依赖宿主透传 PYTHONPATH——
|
|
12
|
+
# Hermes 等宿主出于安全过滤环境变量,stdio 子进程只继承白名单)
|
|
13
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
14
|
+
|
|
15
|
+
from vod_mcp import packs, policy as policy_mod, tools # noqa: E402
|
|
16
|
+
|
|
17
|
+
_PROTOCOL_VERSION = "2025-06-18"
|
|
18
|
+
_client_info = {}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _result(req_id, result):
|
|
22
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _error(req_id, code, message):
|
|
26
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def handle(message: dict) -> dict | None:
|
|
30
|
+
method = message.get("method", "")
|
|
31
|
+
req_id = message.get("id")
|
|
32
|
+
if method == "initialize":
|
|
33
|
+
global _client_info
|
|
34
|
+
_client_info = (message.get("params") or {}).get("clientInfo") or {}
|
|
35
|
+
return _result(req_id, {
|
|
36
|
+
"protocolVersion": _PROTOCOL_VERSION,
|
|
37
|
+
"capabilities": {"tools": {}},
|
|
38
|
+
"serverInfo": {
|
|
39
|
+
"name": "vod-devkit",
|
|
40
|
+
"version": tools.load_contract()["version"],
|
|
41
|
+
},
|
|
42
|
+
})
|
|
43
|
+
if method == "notifications/initialized":
|
|
44
|
+
return None # 通知无响应
|
|
45
|
+
if method == "ping":
|
|
46
|
+
return _result(req_id, {})
|
|
47
|
+
if method == "tools/list":
|
|
48
|
+
return _result(req_id, {"tools": tools.tool_specs(packs.enabled_tools())})
|
|
49
|
+
if method == "tools/call":
|
|
50
|
+
params = message.get("params") or {}
|
|
51
|
+
name = params.get("name") or ""
|
|
52
|
+
args = params.get("arguments") or {}
|
|
53
|
+
pol = policy_mod.load_policy()
|
|
54
|
+
verdict, msg = policy_mod.decide(
|
|
55
|
+
policy_mod.check_tool_call(pol, name, args) if name else [])
|
|
56
|
+
if verdict == "deny":
|
|
57
|
+
return _error(req_id, -32010, f"[guard:deny] {msg}")
|
|
58
|
+
if verdict == "confirm":
|
|
59
|
+
return _error(req_id, -32011, f"[guard:confirm] {msg}")
|
|
60
|
+
text_hits = policy_mod.check_text(
|
|
61
|
+
pol, json.dumps(policy_mod.guard_scope(args), ensure_ascii=False))
|
|
62
|
+
if text_hits:
|
|
63
|
+
return _error(req_id, -32010,
|
|
64
|
+
f"[guard:deny] {policy_mod.decide(text_hits)[1]}")
|
|
65
|
+
try:
|
|
66
|
+
out = tools.dispatch(name, args, _client_info)
|
|
67
|
+
return _result(req_id, {
|
|
68
|
+
"content": [{"type": "text", "text": json.dumps(out, ensure_ascii=False)}],
|
|
69
|
+
"structuredContent": out,
|
|
70
|
+
"isError": False,
|
|
71
|
+
})
|
|
72
|
+
except tools.ToolError as e:
|
|
73
|
+
return _error(req_id, e.code, str(e))
|
|
74
|
+
if req_id is not None:
|
|
75
|
+
return _error(req_id, -32601, f"未知方法: {method}")
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def main():
|
|
80
|
+
# 启动自诊(排障:写 /tmp,宿主过滤环境变量时可观察实际 env)
|
|
81
|
+
try:
|
|
82
|
+
tools._ensure_first_boot() # D-key-guard-3①:首启标记+构建机残留清理(preset 兜底)
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
tools._log(f"started pid={os.getpid()} argv={sys.argv} "
|
|
86
|
+
f"VOD_PACKS={os.environ.get('VOD_PACKS')!r} "
|
|
87
|
+
f"distribution={tools._distribution()} "
|
|
88
|
+
f"cwd={os.getcwd()}")
|
|
89
|
+
for line in sys.stdin:
|
|
90
|
+
line = line.strip()
|
|
91
|
+
if not line:
|
|
92
|
+
continue
|
|
93
|
+
try:
|
|
94
|
+
message = json.loads(line)
|
|
95
|
+
except json.JSONDecodeError:
|
|
96
|
+
resp = _error(None, -32700, "解析错误")
|
|
97
|
+
else:
|
|
98
|
+
resp = handle(message)
|
|
99
|
+
if resp is not None:
|
|
100
|
+
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
|
|
101
|
+
sys.stdout.flush()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
if __name__ == "__main__":
|
|
105
|
+
main()
|
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
"""工具实现:唯一事实源=contract/tools.schema.json;单上游(纯采集插件)。
|
|
2
|
+
|
|
3
|
+
方案 A 收敛(2026-11-03 拍板):插件只做用户声音采集,运营能力归
|
|
4
|
+
vod-system 前端(既有工作台)。workflow 三工具与 kb_search 已删除
|
|
5
|
+
(git 历史可查;删除依据=零真实使用+受众耦合,负复杂度决策)。
|
|
6
|
+
|
|
7
|
+
唯一上游:Java backend(VOD_JAVA_API_BASE + VOD_JAVA_API_KEY,
|
|
8
|
+
ExternalApiKeyFilter Bearer)。
|
|
9
|
+
POST …/external/voice/submit(现有接口,提交即分析)
|
|
10
|
+
POST …/external/token(VOD-KEY,零字段匿名令牌)
|
|
11
|
+
"""
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import stat
|
|
15
|
+
import urllib.request
|
|
16
|
+
import urllib.error
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from vod_mcp import provenance
|
|
20
|
+
from vod_mcp import DEFAULT_JAVA_BASE
|
|
21
|
+
|
|
22
|
+
_CONTRACT_PATH = Path(__file__).resolve().parent.parent / "contract" / "tools.schema.json"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _runtime_path() -> Path:
|
|
26
|
+
return Path(__file__).resolve().parent / "runtime.json"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _runtime_cfg() -> dict:
|
|
30
|
+
# 路径单源:一律走 _runtime_path()(曾与 _save_runtime 双写路径,
|
|
31
|
+
# 注入/重定位场景读写分叉——测试实锤的真缺陷)
|
|
32
|
+
p = _runtime_path()
|
|
33
|
+
if p.exists():
|
|
34
|
+
try:
|
|
35
|
+
return json.loads(p.read_text(encoding="utf-8"))
|
|
36
|
+
except Exception:
|
|
37
|
+
return {}
|
|
38
|
+
return {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# 上游配置:env 优先,runtime.json 兜底——不依赖宿主 env 透传
|
|
42
|
+
# (实测部分 MCP 宿主对子进程 env 过滤/丢失,如 Hermes 多 --env 只存活一个)
|
|
43
|
+
_RT = _runtime_cfg()
|
|
44
|
+
JAVA_BASE = os.environ.get("VOD_JAVA_API_BASE") or _RT.get("java_base") or DEFAULT_JAVA_BASE
|
|
45
|
+
JAVA_KEY = os.environ.get("VOD_JAVA_API_KEY", "") or _RT.get("java_key", "") # ExternalApiKeyFilter Bearer
|
|
46
|
+
|
|
47
|
+
_META_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/meta"
|
|
48
|
+
_META_TTL = 24 * 3600
|
|
49
|
+
# 快照兜底(引擎 meta 端点未上线/不可达时用;stale 语义见 _load_meta)
|
|
50
|
+
_META_SNAPSHOT = {"products": ["agentarts", "codearts", "dataarts", "maas", "obs",
|
|
51
|
+
"officeclaw", "modelarts"]}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _load_meta(force: bool = False) -> dict:
|
|
55
|
+
"""可漂移值(product 白名单等)动态取:缓存 TTL 24h,
|
|
56
|
+
引擎端点不可达时回退快照并标 stale。真源=引擎 submit 校验常量。
|
|
57
|
+
T7i:productCatalog=[{id,name}](t_vod_product 运营预置,meta 组装)——
|
|
58
|
+
提交产品归因按平台主键 id 的解析真源;老引擎无该键=catalog 空。"""
|
|
59
|
+
import time
|
|
60
|
+
cache = _RT.get("meta_cache") or {}
|
|
61
|
+
now = time.time()
|
|
62
|
+
if not force and cache.get("data") and now - cache.get("fetchedAt", 0) < _META_TTL:
|
|
63
|
+
return {"products": cache["data"].get("products", _META_SNAPSHOT["products"]),
|
|
64
|
+
"catalog": cache["data"].get("productCatalog") or [],
|
|
65
|
+
"stale": False, "source": "cache"}
|
|
66
|
+
try:
|
|
67
|
+
out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=JAVA_KEY, timeout=10)
|
|
68
|
+
data = out.get("data") or {}
|
|
69
|
+
if isinstance(data.get("products"), list) and data["products"]:
|
|
70
|
+
_save_runtime({"meta_cache": {"fetchedAt": int(now), "data": data}})
|
|
71
|
+
return {"products": data["products"],
|
|
72
|
+
"catalog": data.get("productCatalog") or [],
|
|
73
|
+
"stale": False, "source": "meta"}
|
|
74
|
+
except ToolError:
|
|
75
|
+
pass
|
|
76
|
+
return {"products": _META_SNAPSHOT["products"], "catalog": [],
|
|
77
|
+
"stale": True, "source": "snapshot"}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ToolError(Exception):
|
|
81
|
+
def __init__(self, message: str, code: int = -32000):
|
|
82
|
+
super().__init__(message)
|
|
83
|
+
self.code = code
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def load_contract() -> dict:
|
|
87
|
+
with open(_CONTRACT_PATH, encoding="utf-8") as f:
|
|
88
|
+
return json.load(f)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def tool_specs(only: list) -> list:
|
|
92
|
+
"""按 packs 启用清单生成 tools/list 的 MCP 工具描述。"""
|
|
93
|
+
contract = load_contract()
|
|
94
|
+
specs = []
|
|
95
|
+
for name, spec in contract["tools"].items():
|
|
96
|
+
if name not in only:
|
|
97
|
+
continue
|
|
98
|
+
specs.append({
|
|
99
|
+
"name": name,
|
|
100
|
+
"description": spec["description"],
|
|
101
|
+
"inputSchema": spec["input"],
|
|
102
|
+
})
|
|
103
|
+
return specs
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _http(method: str, path: str, body: dict | None = None,
|
|
107
|
+
base: str | None = None, key: str | None = None, timeout: int = 30) -> dict:
|
|
108
|
+
"""统一出口:一律携带 Authorization Bearer(E1 修复:认证头缺失)。
|
|
109
|
+
|
|
110
|
+
base/key 缺省在调用时解析模块级配置(不能用函数默认值——定义时即冻结,
|
|
111
|
+
环境变更/测试 monkeypatch 均无法生效)。
|
|
112
|
+
"""
|
|
113
|
+
base = base if base is not None else JAVA_BASE
|
|
114
|
+
key = key if key is not None else JAVA_KEY
|
|
115
|
+
# 传输协议守卫:非本机回环一律要求 https(Bearer 不得明文过公网)
|
|
116
|
+
_host = base.split("//", 1)[-1].split("/", 1)[0].split(":")[0]
|
|
117
|
+
if not base.startswith("https://") and _host not in ("127.0.0.1", "localhost", "::1"):
|
|
118
|
+
raise ToolError(
|
|
119
|
+
f"上游 {base} 非 https 且非本机回环——Bearer key 明文外发被拒"
|
|
120
|
+
"(配置 VOD_JAVA_API_BASE 为 https:// 地址)", code=-32014)
|
|
121
|
+
url = base.rstrip("/") + path
|
|
122
|
+
_log(f"http {method} {url} key={'yes' if key else 'no'}")
|
|
123
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
124
|
+
headers = {"Content-Type": "application/json",
|
|
125
|
+
# VOD-DEVICE:设备锚点(install_nonce=首启自生成常驻,零新增状态)——
|
|
126
|
+
# 引擎据此建每设备独立锚点(NAT/产品分发不再收敛);服务端缺失回落 legacy
|
|
127
|
+
"X-Vod-Device-Id": _install_nonce()}
|
|
128
|
+
if key:
|
|
129
|
+
headers["Authorization"] = f"Bearer {key}"
|
|
130
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
131
|
+
try:
|
|
132
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
133
|
+
return json.loads(resp.read().decode())
|
|
134
|
+
except urllib.error.HTTPError as e:
|
|
135
|
+
detail = e.read().decode()[:200]
|
|
136
|
+
if e.code == 401:
|
|
137
|
+
raise ToolError(
|
|
138
|
+
f"鉴权失败({base}):检查 VOD_JAVA_API_KEY 配置",
|
|
139
|
+
code=-32012) from e
|
|
140
|
+
raise ToolError(f"上游返回 {e.code}: {detail}", code=e.code) from e
|
|
141
|
+
except urllib.error.URLError as e:
|
|
142
|
+
raise ToolError(f"上游不可达({base}): {e.reason}", code=-32001) from e
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# 引擎 submit 校验白名单(ExternalVoiceServiceImpl.VALID_PRODUCTS 实测:
|
|
146
|
+
# CODEARTS/AGENTARTS/OFFICECLAW/DATAARTS/MAAS/OBS + 别名归一 MODELARTS→MAAS)
|
|
147
|
+
_PRODUCT_MAP = {
|
|
148
|
+
"agentarts": "AgentArts", "codearts": "CodeArts", "dataarts": "DataArts",
|
|
149
|
+
"maas": "MaaS", "obs": "OBS", "officeclaw": "OfficeClaw",
|
|
150
|
+
"modelarts": "MaaS", # 引擎别名归一实测
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _resolve_product(params: dict) -> str | None:
|
|
155
|
+
"""归因(「宿主即产品」口径,2026-11-03 拍板·不设白名单):
|
|
156
|
+
①调用方显式传参 ②安装绑定(runtime.json product——安装器默认写入宿主名,
|
|
157
|
+
hermes/opencode/codex 装在哪就归哪)③都没有 → 返回 None(body 不带
|
|
158
|
+
product,引擎落 UNKNOWN 档人工归因解析,V19)——不再 -32013 本地拦截。
|
|
159
|
+
T7i(方案 A,2026-11-05 拍板):产品归因主键化——
|
|
160
|
+
①纯数字串=平台主键 id,原样透传(引擎 selectById 精确命中)
|
|
161
|
+
②名字→meta productCatalog 按名解析出平台 id 后提交(对账主键化,
|
|
162
|
+
归一化/改名漂移不进提交链路);_PRODUCT_MAP 先归一短码再查目录
|
|
163
|
+
③目录无此名/目录不可用→规范名原样上送(引擎 name 兼容通道,
|
|
164
|
+
命中同样补落 product_id)——不静默丢提交。"""
|
|
165
|
+
raw = str(params.get("product") or _RT.get("product") or "").strip()
|
|
166
|
+
if not raw:
|
|
167
|
+
return None
|
|
168
|
+
if raw.isdigit():
|
|
169
|
+
return raw
|
|
170
|
+
name = _PRODUCT_MAP.get(raw.lower(), raw)
|
|
171
|
+
for item in (_load_meta().get("catalog") or []):
|
|
172
|
+
if str(item.get("name") or "").lower() == name.lower():
|
|
173
|
+
return str(item.get("id"))
|
|
174
|
+
return name
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
_SUBMIT_HOARDING = "/rest/developer/manager/hdvodmngservice/v1/external/voices"
|
|
178
|
+
_EXISTING_SUBMIT = "/rest/developer/manager/hdvodmngservice/v1/external/voice/submit" # 过渡期 404 回落
|
|
179
|
+
_TOKEN_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/token"
|
|
180
|
+
|
|
181
|
+
# 结构化引导(devkit error-table 模式:步骤=可执行动作,不是"参考文档")
|
|
182
|
+
_KEY_GUIDANCE = [
|
|
183
|
+
{"order": 1, "action": "auto-token", "label": "首次提交时插件自动申请零字段匿名令牌(默认路径,无需注册)"},
|
|
184
|
+
{"order": 2, "action": "upgrade", "label": "提交量达上限后升级正式 key:联系 VOD 运营(低信任档→正式档)"},
|
|
185
|
+
{"order": 3, "action": "host", "label": "宿主平台整体对接可获宿主 key:由宿主运维持有(高信任档)"},
|
|
186
|
+
]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _install_nonce() -> str:
|
|
190
|
+
"""per-install 8 位 hex:runtime.json 首次生成常驻——legacy 共用 key 场景下
|
|
191
|
+
source 命名空间 per-machine 化,杜绝不同用户提交同款内容被确定性
|
|
192
|
+
voiceId 合并成一条(跨用户吞声量,切换补丁前置修复)。"""
|
|
193
|
+
n = _RT.get("install_nonce")
|
|
194
|
+
if not n:
|
|
195
|
+
import uuid
|
|
196
|
+
n = uuid.uuid4().hex[:8]
|
|
197
|
+
try:
|
|
198
|
+
_save_runtime({"install_nonce": n})
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
return str(n)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _voice_id(source: str, content: str, nonce: str) -> str:
|
|
205
|
+
"""voiceId = f(source, content, 调用级nonce)。
|
|
206
|
+
|
|
207
|
+
R1 修正(声量保真):跨调用不去重——不同用户提交同款反馈必须各占
|
|
208
|
+
一行(声量是分析核心信号);同调用内重试复用同 nonce 保幂等。
|
|
209
|
+
"""
|
|
210
|
+
import hashlib
|
|
211
|
+
return f"ext_{source}_{hashlib.sha1((content + nonce).encode('utf-8')).hexdigest()[:12]}"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _explicit_key() -> bool:
|
|
215
|
+
"""当前 JAVA_KEY 是否为显式配置(正式/宿主 key)而非本会话自动领取的匿名令牌。
|
|
216
|
+
|
|
217
|
+
判据:环境变量显式注入(权威,env 优先级最高的既有口径)或
|
|
218
|
+
token_tier != "anonymous"。匿名令牌过期/被吊销时 401 应走重领链;
|
|
219
|
+
显式 key 被 401 拒绝时必须 fail fast(静默降级匿名=配置错误被吞=归因错位,
|
|
220
|
+
「注入 appkey」场景的锚定承诺会变成假的)。
|
|
221
|
+
"""
|
|
222
|
+
if bool(os.environ.get("VOD_JAVA_API_KEY")):
|
|
223
|
+
return True
|
|
224
|
+
return bool(JAVA_KEY) and str(_RT.get("token_tier") or "") != "anonymous"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def submit_voices(params: dict, client_info: dict | None = None) -> dict:
|
|
228
|
+
"""V16 切换:主路径=囤积端点 POST /external/voices(Bearer,批式,不触发分析);
|
|
229
|
+
引擎未部署(404)自动回落老链 /external/voice/submit(提交即分析,过渡语义,
|
|
230
|
+
部署后 404 分支自然失效)。
|
|
231
|
+
|
|
232
|
+
- voiceId:囤积链由引擎确定性计算(per-token/per-install 命名空间),回执
|
|
233
|
+
voiceIds 为权威对账键;回落老链仍用客户端 nonce id(R1 声量保真)
|
|
234
|
+
- title=用户原文截断;tags=采集层三分类(problem_type:)正式入库通道
|
|
235
|
+
- source:key 持有者被引擎锚定为 host_name;legacy 共用 key 场景带
|
|
236
|
+
per-install nonce 后缀(杜绝跨用户共享命名空间吞声量)
|
|
237
|
+
"""
|
|
238
|
+
import uuid
|
|
239
|
+
host = (client_info or {}).get("name") or "unknown-host"
|
|
240
|
+
product = _resolve_product(params)
|
|
241
|
+
accepted, voice_ids, task_ids, rejected = 0, [], [], []
|
|
242
|
+
global JAVA_KEY
|
|
243
|
+
voices_in = params.get("voices", [])
|
|
244
|
+
items = [] # (index, voice_map, content)
|
|
245
|
+
for i, v in enumerate(voices_in):
|
|
246
|
+
content = str(v.get("content", "")).strip()
|
|
247
|
+
if not content:
|
|
248
|
+
rejected.append({"index": i, "reason": "content 为空"})
|
|
249
|
+
continue
|
|
250
|
+
if len(content) > 2000: # 契约 maxLength 2000:内容边界(防超大 payload)
|
|
251
|
+
rejected.append({"index": i, "reason": f"content 超 2000 字({len(content)})"})
|
|
252
|
+
continue
|
|
253
|
+
items.append((i, v, content))
|
|
254
|
+
if not items:
|
|
255
|
+
return {"accepted": 0, "voiceIds": [], "taskIds": [], "rejected": rejected}
|
|
256
|
+
|
|
257
|
+
def _ledger(vids, tids):
|
|
258
|
+
import time as _time
|
|
259
|
+
entries = [{"voiceId": vid, "taskId": tid,
|
|
260
|
+
"title": items[min(i, len(items) - 1)][2][:40],
|
|
261
|
+
"product": product, "at": _time.strftime("%Y-%m-%dT%H:%M:%S")}
|
|
262
|
+
for i, (vid, tid) in enumerate(zip(vids, tids))]
|
|
263
|
+
_ledger_append(entries)
|
|
264
|
+
|
|
265
|
+
def _legacy_submit(i, v, content):
|
|
266
|
+
"""过渡回落:老链单条提交(提交即分析语义,仅 404 触发)。"""
|
|
267
|
+
nonce = uuid.uuid4().hex[:8] # 调用级:重试复用,跨调用不重复
|
|
268
|
+
vid = _voice_id(host, content, nonce)
|
|
269
|
+
desc = content if len(content) >= 10 else f"{content} [vod-devkit]"
|
|
270
|
+
body = {
|
|
271
|
+
"voiceId": vid,
|
|
272
|
+
"title": content[:128],
|
|
273
|
+
"description": desc,
|
|
274
|
+
"source": f"{host}-{_install_nonce()}", # per-install 命名空间(legacy 吞声量修复)
|
|
275
|
+
"customer": v.get("userType"),
|
|
276
|
+
}
|
|
277
|
+
if product:
|
|
278
|
+
body["product"] = product
|
|
279
|
+
out = _http("POST", _EXISTING_SUBMIT, body, base=JAVA_BASE, key=JAVA_KEY)
|
|
280
|
+
return vid, (out.get("data") or {}).get("taskId")
|
|
281
|
+
|
|
282
|
+
# ---- 主路径:囤积端点批式提交 ----
|
|
283
|
+
hoard_voices = []
|
|
284
|
+
for i, v, content in items:
|
|
285
|
+
hv = {"title": content[:60], "content": content}
|
|
286
|
+
tags = v.get("tags") # 采集层三分类(problem_type:值)→【类型名】标题前缀正式入库
|
|
287
|
+
if tags:
|
|
288
|
+
hv["tags"] = tags
|
|
289
|
+
ut = v.get("userType")
|
|
290
|
+
if ut:
|
|
291
|
+
hv["userType"] = ut
|
|
292
|
+
hoard_voices.append(hv)
|
|
293
|
+
body = {"voices": hoard_voices}
|
|
294
|
+
if product: # 无归因不带 product(引擎 UNKNOWN 档),不本地拦截
|
|
295
|
+
body["product"] = product
|
|
296
|
+
out = None
|
|
297
|
+
fallback = False
|
|
298
|
+
try:
|
|
299
|
+
out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
|
|
300
|
+
except ToolError as ex:
|
|
301
|
+
if ex.code == 404:
|
|
302
|
+
fallback = True # 囤积端点未部署 → 落到下方 legacy 回落
|
|
303
|
+
elif not JAVA_KEY or ex.code == -32012:
|
|
304
|
+
if _explicit_key():
|
|
305
|
+
# 显式 key(安装注入/正式档)被引擎 401 拒绝 → fail fast:
|
|
306
|
+
# 不取匿名令牌、不覆盖配置——静默降级匿名档=配置错误被吞
|
|
307
|
+
#(归因错位比报错更糟,同 AIShell 错归病根)
|
|
308
|
+
raise ToolError(
|
|
309
|
+
f"注入的 key 被引擎拒绝(指纹 {_fingerprint(JAVA_KEY)}):"
|
|
310
|
+
"请核对 key 是否过期/被吊销,或移除 key 走匿名档(删除 "
|
|
311
|
+
"VOD_JAVA_API_KEY 环境变量与 runtime.json java_key)",
|
|
312
|
+
code=-32012)
|
|
313
|
+
# 缺 key/匿名令牌失效 → 零字段匿名令牌 → 落 runtime.json → 重试一次
|
|
314
|
+
token = _fetch_anon_token()
|
|
315
|
+
if not token:
|
|
316
|
+
raise ToolError(
|
|
317
|
+
"未配置接入 key 且匿名令牌端点不可用。引导:" +
|
|
318
|
+
";".join(g["label"] for g in _KEY_GUIDANCE), code=-32012)
|
|
319
|
+
JAVA_KEY = token
|
|
320
|
+
_save_runtime({"java_key": token, "token_tier": "anonymous"})
|
|
321
|
+
out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
|
|
322
|
+
else:
|
|
323
|
+
raise # 网络/413 等如实上抛
|
|
324
|
+
if not fallback:
|
|
325
|
+
server_ids = (out.get("voiceIds") or out.get("data", {}).get("voiceIds")
|
|
326
|
+
or [])
|
|
327
|
+
accepted = len(server_ids) or len(hoard_voices)
|
|
328
|
+
voice_ids.extend(server_ids if server_ids else [""] * len(hoard_voices))
|
|
329
|
+
task_ids.extend([None] * len(hoard_voices)) # 囤积语义:无即时任务
|
|
330
|
+
result = {"accepted": accepted, "voiceIds": voice_ids,
|
|
331
|
+
"taskIds": task_ids, "rejected": rejected,
|
|
332
|
+
"analysis": "deferred", # 囤积语义明示(V6 运营批量消费)
|
|
333
|
+
"path": "hoarding"}
|
|
334
|
+
if out.get("productRegistered") is not None:
|
|
335
|
+
result["productRegistered"] = out.get("productRegistered")
|
|
336
|
+
_ledger(voice_ids, task_ids)
|
|
337
|
+
return result
|
|
338
|
+
# ---- 过渡回落:老链单条提交(仅囤积端点 404 触发) ----
|
|
339
|
+
for i, v, content in items:
|
|
340
|
+
try:
|
|
341
|
+
vid, tid = _legacy_submit(i, v, content)
|
|
342
|
+
accepted += 1
|
|
343
|
+
voice_ids.append(vid)
|
|
344
|
+
task_ids.append(tid)
|
|
345
|
+
except ToolError as e:
|
|
346
|
+
msg = str(e)
|
|
347
|
+
if "Duplicate entry" in msg: # 极端重放场景:DB 唯一键兜底
|
|
348
|
+
accepted += 1
|
|
349
|
+
voice_ids.append(vid)
|
|
350
|
+
task_ids.append(None)
|
|
351
|
+
elif (not JAVA_KEY or e.code == -32012) and not voice_ids:
|
|
352
|
+
if _explicit_key():
|
|
353
|
+
# 显式 key 被拒 → fail fast(同囤积主路径口径,防静默降级)
|
|
354
|
+
raise ToolError(
|
|
355
|
+
f"注入的 key 被引擎拒绝(指纹 {_fingerprint(JAVA_KEY)}):"
|
|
356
|
+
"请核对 key 是否过期/被吊销,或移除 key 走匿名档", code=-32012)
|
|
357
|
+
# 零字段匿名令牌:缺 key/401 → 自动取令牌 → 落 runtime.json → 重试一次
|
|
358
|
+
token = _fetch_anon_token()
|
|
359
|
+
if token:
|
|
360
|
+
JAVA_KEY = token
|
|
361
|
+
_save_runtime({"java_key": token, "token_tier": "anonymous"})
|
|
362
|
+
vid, tid = _legacy_submit(i, v, content)
|
|
363
|
+
accepted += 1
|
|
364
|
+
voice_ids.append(vid)
|
|
365
|
+
task_ids.append(tid)
|
|
366
|
+
else:
|
|
367
|
+
raise ToolError(
|
|
368
|
+
"未配置接入 key 且匿名令牌端点不可用。引导:" +
|
|
369
|
+
";".join(g["label"] for g in _KEY_GUIDANCE), code=-32012)
|
|
370
|
+
else:
|
|
371
|
+
rejected.append({"index": i, "reason": msg[:120]})
|
|
372
|
+
result = {"accepted": accepted, "voiceIds": voice_ids,
|
|
373
|
+
"taskIds": task_ids, "rejected": rejected,
|
|
374
|
+
"path": "legacy-fallback"}
|
|
375
|
+
_ledger(voice_ids, task_ids)
|
|
376
|
+
return result
|
|
377
|
+
|
|
378
|
+
# 本地账本落账(层级①查询的源)
|
|
379
|
+
import time as _time
|
|
380
|
+
_contents = [str(v.get("content", ""))[:40]
|
|
381
|
+
for v in params.get("voices", []) if str(v.get("content", "")).strip()]
|
|
382
|
+
ledger_entries = [
|
|
383
|
+
{"voiceId": vid, "taskId": tid,
|
|
384
|
+
"title": (_contents[i] if i < len(_contents) else ""),
|
|
385
|
+
"product": product, "at": _time.strftime("%Y-%m-%dT%H:%M:%S")}
|
|
386
|
+
for i, (vid, tid) in enumerate(zip(voice_ids, task_ids))
|
|
387
|
+
]
|
|
388
|
+
_ledger_append(ledger_entries)
|
|
389
|
+
return {"accepted": accepted, "voiceIds": voice_ids,
|
|
390
|
+
"taskIds": task_ids, "rejected": rejected}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _fingerprint(key: str) -> str | None:
|
|
394
|
+
import hashlib
|
|
395
|
+
return hashlib.sha1(key.encode()).hexdigest()[:8] if key else None
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def probe_key(key: str | None = None, timeout: int = 8) -> dict:
|
|
399
|
+
"""key 有效性探针:带 key 调只读端点 GET /external/meta(Filter 网内)。
|
|
400
|
+
|
|
401
|
+
判定语义(引擎是唯一权威,本地零判定):
|
|
402
|
+
- 200 → {"ok": True}:key 有效且在网内
|
|
403
|
+
- 401/-32012 → {"ok": False, "reason": "rejected"}:引擎判无效(过期/吊销/不存在)
|
|
404
|
+
- 其他错误(网络不可达/超时/5xx)→ {"ok": None, "reason": "unreachable"}:
|
|
405
|
+
不判定——网络问题不是 key 问题,报"无法验证"而非"无效"
|
|
406
|
+
"""
|
|
407
|
+
key = key if key is not None else JAVA_KEY
|
|
408
|
+
fp = _fingerprint(key)
|
|
409
|
+
if not key:
|
|
410
|
+
return {"ok": None, "reason": "no-key", "fingerprint": None}
|
|
411
|
+
try:
|
|
412
|
+
_http("GET", _META_PATH, None, key=key, timeout=timeout)
|
|
413
|
+
return {"ok": True, "reason": "verified", "fingerprint": fp}
|
|
414
|
+
except ToolError as ex:
|
|
415
|
+
code = ex.code
|
|
416
|
+
if code == 401 or code == -32012:
|
|
417
|
+
return {"ok": False, "reason": "rejected", "fingerprint": fp}
|
|
418
|
+
return {"ok": None, "reason": "unreachable", "fingerprint": fp}
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
_META_PATH = "/rest/developer/manager/hdvodmngservice/v1/external/meta"
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _key_state() -> dict:
|
|
425
|
+
return {"configured": bool(JAVA_KEY), "fingerprint": _fingerprint(JAVA_KEY),
|
|
426
|
+
"base": JAVA_BASE,
|
|
427
|
+
"note": "已配置" if JAVA_KEY else "未配置(首次提交自动取匿名令牌)"}
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def auth_status(params: dict, client_info: dict | None = None) -> dict:
|
|
431
|
+
"""认证自检:指纹化输出(明文永不出现),无 key 也跑并给引导。"""
|
|
432
|
+
out = {
|
|
433
|
+
"javaKey": _key_state(),
|
|
434
|
+
"packs": sorted(__import__("vod_mcp.packs", fromlist=["enabled_packs"]).enabled_packs()),
|
|
435
|
+
}
|
|
436
|
+
meta = _load_meta()
|
|
437
|
+
out["meta"] = {"source": meta["source"], "stale": meta["stale"],
|
|
438
|
+
"productCount": len(meta["products"])}
|
|
439
|
+
if JAVA_KEY:
|
|
440
|
+
# 主动探针(devkit auth init 真调 IAM 的廉价版):用户问"key 好没好"有确定答案
|
|
441
|
+
out["keyCheck"] = probe_key()
|
|
442
|
+
if not JAVA_KEY:
|
|
443
|
+
out["guidance"] = _KEY_GUIDANCE
|
|
444
|
+
out["tokenReady"] = "首次提交时将自动申请匿名令牌(零字段,日限额低)"
|
|
445
|
+
return out
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
_LEDGER_KEY = "submissions"
|
|
449
|
+
_LEDGER_CAP = 200
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _ledger_append(entries: list) -> None:
|
|
453
|
+
"""本地提交账本(层级①):本机提交记录,供 vod_list_submitted 对账。
|
|
454
|
+
cap 200 条(环形截断,防 runtime.json 膨胀)。
|
|
455
|
+
实现纪律:每次从文件读改写、只动 submissions 键——不从内存 _RT
|
|
456
|
+
合并(陈旧配置会整体回写,覆盖其他键,且把无关配置泄入调用方)。
|
|
457
|
+
D-key-guard-3④:local_ledger=false(企业数据驻留要求)→ 账本关闭,
|
|
458
|
+
vod_list_submitted 随之不可用——留痕是可选项不是义务。"""
|
|
459
|
+
if not entries:
|
|
460
|
+
return
|
|
461
|
+
fresh = _runtime_cfg()
|
|
462
|
+
if fresh.get("local_ledger") is False:
|
|
463
|
+
return
|
|
464
|
+
ledger = (fresh.get(_LEDGER_KEY) or [])[-_LEDGER_CAP:]
|
|
465
|
+
ledger.extend(entries)
|
|
466
|
+
_save_runtime({_LEDGER_KEY: ledger[-_LEDGER_CAP:]})
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def list_submitted(params: dict, client_info: dict | None = None) -> dict:
|
|
470
|
+
"""查询本机已提交的声音(只读,采集者对账闭环)。
|
|
471
|
+
引擎级跨机查询随 VOD-VOI 列表端点;终端用户自助查询维持 P2(签名回执)。"""
|
|
472
|
+
limit = params.get("limit", 20)
|
|
473
|
+
try:
|
|
474
|
+
limit = max(1, min(int(limit), 100))
|
|
475
|
+
except (TypeError, ValueError):
|
|
476
|
+
limit = 20
|
|
477
|
+
ledger = _runtime_cfg().get(_LEDGER_KEY) or [] # 文件现读(进程内账本可能刚更新)
|
|
478
|
+
return {"total": len(ledger),
|
|
479
|
+
"submissions": ledger[-limit:][::-1], # 最新在前
|
|
480
|
+
"scope": "本机提交记录(换机/重装不保留;引擎级查询随 VOD-VOI)"}
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
_RUNTIME_STATE_KEYS = ("java_key", "token_tier", "install_nonce", "submissions",
|
|
484
|
+
"meta_cache")
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _distribution() -> str:
|
|
488
|
+
"""分发形态位(D-key-guard-3):install --distribution preset 写入 manifest。
|
|
489
|
+
devkit=自装自管;preset=产品随 agent 分发(客户机首启重生成运行时状态)。"""
|
|
490
|
+
p = Path(__file__).resolve().parent.parent / "install-manifest.json"
|
|
491
|
+
if not p.exists():
|
|
492
|
+
return "devkit"
|
|
493
|
+
try:
|
|
494
|
+
return json.loads(p.read_text(encoding="utf-8")).get("distribution", "devkit")
|
|
495
|
+
except Exception:
|
|
496
|
+
return "devkit"
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _ensure_first_boot(rt_path: Path | None = None) -> dict:
|
|
500
|
+
"""首启标记 + 构建机残留清理(D-key-guard-3①,preset 形态兜底)。
|
|
501
|
+
|
|
502
|
+
主防线是打包排除(分发产物不含 runtime.json);本函数兜底打包者漏排:
|
|
503
|
+
preset 形态 + runtime.json 存在但无 firstBootAt + 携带运行时状态
|
|
504
|
+
(key/nonce/账本/缓存)→ 判构建机残留 → 自动清空这些状态(保留
|
|
505
|
+
product/java_base 等装机配置)+ 重新生成 per-install nonce + 告警。
|
|
506
|
+
处置用自动重生成而非拒绝启动:残留状态全是本机可再生数据,
|
|
507
|
+
自动清零伤害半径为零,拒启会把误判放大成全功能瘫痪。
|
|
508
|
+
firstBootAt 首启写入,此后不再触发(防误伤正常运行中的安装)。"""
|
|
509
|
+
p = rt_path or _runtime_path()
|
|
510
|
+
if not p.exists():
|
|
511
|
+
return {"action": "none"}
|
|
512
|
+
try:
|
|
513
|
+
cfg = json.loads(p.read_text(encoding="utf-8"))
|
|
514
|
+
except Exception:
|
|
515
|
+
return {"action": "none"}
|
|
516
|
+
if cfg.get("firstBootAt"):
|
|
517
|
+
_warn_if_cloned(cfg, p)
|
|
518
|
+
return {"action": "none"}
|
|
519
|
+
residual = [k for k in _RUNTIME_STATE_KEYS if cfg.get(k)]
|
|
520
|
+
import time as _t
|
|
521
|
+
if _distribution() == "preset" and residual:
|
|
522
|
+
# 残留清理=整体重建(合并删不掉旧键),但保留装机配置(product/java_base 等)
|
|
523
|
+
_save_runtime({**{k: v for k, v in cfg.items() if k not in _RUNTIME_STATE_KEYS},
|
|
524
|
+
"firstBootAt": _t.strftime("%Y-%m-%dT%H:%M:%S")},
|
|
525
|
+
replace=True)
|
|
526
|
+
_warn(f"检测到构建机残留状态({','.join(residual)})已自动清空重生成——"
|
|
527
|
+
"分发产物应只含代码与配置,不含安装结果(D-key-guard-3①)")
|
|
528
|
+
return {"action": "cleaned", "removed": residual}
|
|
529
|
+
_save_runtime({"firstBootAt": _t.strftime("%Y-%m-%dT%H:%M:%S")})
|
|
530
|
+
return {"action": "stamped"}
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _warn_if_cloned(cfg: dict, p: Path) -> None:
|
|
534
|
+
"""preset 克隆镜像检测(D-key-guard-3①延伸,仅告警不阻断):
|
|
535
|
+
firstBootAt 距今显著超过本机 uptime(>1h 容差)→ 本机状态大概率来自
|
|
536
|
+
母机镜像克隆——所有克隆机共享同一 device 锚点/账本,声量与配额会收敛。
|
|
537
|
+
判据:firstBootAt 的"年龄" > uptime+容差 ⇒ 首启发生在"这台机器"存在之前。"""
|
|
538
|
+
import time as _t
|
|
539
|
+
try:
|
|
540
|
+
if _distribution() != "preset":
|
|
541
|
+
return
|
|
542
|
+
boot = _t.mktime(_t.strptime(cfg["firstBootAt"], "%Y-%m-%dT%H:%M:%S"))
|
|
543
|
+
uptime_s = float(open("/proc/uptime").read().split()[0])
|
|
544
|
+
if _t.time() - boot > uptime_s + 3600:
|
|
545
|
+
_warn("疑似镜像克隆机:firstBootAt 早于本机 uptime——克隆分发未清 "
|
|
546
|
+
"runtime.json,所有克隆机共享同一设备锚点/账本。请在镜像冻结前 "
|
|
547
|
+
"uninstall 或删除 runtime.json(装机 checklist ②)")
|
|
548
|
+
except Exception:
|
|
549
|
+
pass
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _save_runtime(update: dict, replace: bool = False) -> None:
|
|
553
|
+
p = _runtime_path()
|
|
554
|
+
cfg = {}
|
|
555
|
+
if p.exists() and not replace:
|
|
556
|
+
try:
|
|
557
|
+
cfg = json.loads(p.read_text(encoding="utf-8"))
|
|
558
|
+
except Exception:
|
|
559
|
+
cfg = {}
|
|
560
|
+
cfg.update(update)
|
|
561
|
+
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
562
|
+
# S1 式写后验(借 huaweicloud-devkit ensurePrivateMode 模式):写完 chmod 0600
|
|
563
|
+
# 并 stat 回验——不假设 chmod 按文档工作(WSL/drvfs 会静默忽略 chmod),
|
|
564
|
+
# 验的是效果不是动作;runtime.json 含 java_key 明文,权限失效必须告警
|
|
565
|
+
try:
|
|
566
|
+
os.chmod(p, 0o600)
|
|
567
|
+
mode = stat.S_IMODE(os.stat(p).st_mode)
|
|
568
|
+
if mode != 0o600:
|
|
569
|
+
_warn(f"runtime.json 权限异常({oct(mode)},期望 0600)——"
|
|
570
|
+
"key 可能被同机其他用户读取,请检查文件系统(WSL 挂载盘建议移回 Linux 原生盘)")
|
|
571
|
+
except OSError as e:
|
|
572
|
+
_warn(f"runtime.json 权限校验失败:{e}")
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _log(line: str, path: str = "/tmp/vod_mcp_server.log") -> None:
|
|
576
|
+
"""统一日志出口,1MB 截断轮转
|
|
577
|
+
(D-key-guard-3⑤:客户机长期运行防无限增长;截断保留尾部近期日志)。"""
|
|
578
|
+
try:
|
|
579
|
+
p = path
|
|
580
|
+
if os.path.exists(p) and os.path.getsize(p) > 1024 * 1024:
|
|
581
|
+
with open(p, "r", encoding="utf-8", errors="replace") as f:
|
|
582
|
+
tail = f.read()[-200 * 1024:]
|
|
583
|
+
os.replace(p, p + ".old")
|
|
584
|
+
with open(p, "w", encoding="utf-8") as f:
|
|
585
|
+
f.write("== truncated ==\n" + tail)
|
|
586
|
+
with open(p, "a", encoding="utf-8") as f:
|
|
587
|
+
f.write(line.rstrip("\n") + "\n")
|
|
588
|
+
except Exception:
|
|
589
|
+
pass
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _warn(msg: str) -> None:
|
|
593
|
+
"""告警出口:server 日志(排障真源),失败静默——不阻断业务主链。"""
|
|
594
|
+
_log(f"warn {msg}")
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _extract_anon_token(out: object) -> str | None:
|
|
598
|
+
"""从令牌端点响应提取 token(真源契约:引擎 ApiResponse 信封
|
|
599
|
+
{"code":200,"data":{"token":...}};顶层扁平 {"token":...} 兼容历史形态)。"""
|
|
600
|
+
if not isinstance(out, dict):
|
|
601
|
+
return None
|
|
602
|
+
data = out.get("data")
|
|
603
|
+
token = data.get("token") if isinstance(data, dict) else None
|
|
604
|
+
if not token:
|
|
605
|
+
token = out.get("token")
|
|
606
|
+
return token if isinstance(token, str) and token else None
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _fetch_anon_token() -> str | None:
|
|
610
|
+
"""零字段匿名令牌(T7b 定稿):渠道由引擎囤积入库侧固定赋值 vod-agent
|
|
611
|
+
(链路即渠道,客户端不自报)——本端保持空 body(方案 C 原样)。
|
|
612
|
+
D-anon-verify(2026-11-05 真机实锤):引擎返回 ApiResponse 信封,
|
|
613
|
+
顶层取 token 恒 None → 无 key 首提必 -32012,信封解析为必经路径。"""
|
|
614
|
+
try:
|
|
615
|
+
out = _http("POST", _TOKEN_PATH, {}, base=JAVA_BASE, key="", timeout=15)
|
|
616
|
+
return _extract_anon_token(out)
|
|
617
|
+
except ToolError:
|
|
618
|
+
return None
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def devkit_info(params: dict, client_info: dict | None = None) -> dict:
|
|
622
|
+
return provenance.info_payload(client_info)
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
# 工具名 → 处理器(是否接收 client_info)
|
|
626
|
+
_HANDLERS = {
|
|
627
|
+
"vod_submit_voices": submit_voices,
|
|
628
|
+
"vod_list_submitted": list_submitted,
|
|
629
|
+
"vod_devkit_info": devkit_info,
|
|
630
|
+
"vod_auth_status": auth_status,
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def dispatch(name: str, params: dict, client_info: dict | None = None) -> dict:
|
|
635
|
+
handler = _HANDLERS.get(name)
|
|
636
|
+
if handler is None:
|
|
637
|
+
raise ToolError(f"未知工具: {name}", code=-32601)
|
|
638
|
+
needs_host = handler in (devkit_info, submit_voices, auth_status)
|
|
639
|
+
return handler(params, client_info) if needs_host else handler(params)
|
package/vod_mcp/__init__.py
CHANGED