agentworkshop 0.12.0 → 0.13.0
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/.output/nitro.json +1 -1
- package/.output/public/_nuxt/builds/latest.json +1 -1
- package/.output/public/_nuxt/builds/meta/2f96705b-cf57-4bde-87a4-1b818b268f0f.json +1 -0
- package/.output/server/chunks/_/nitro.mjs +1102 -1088
- package/.output/server/package.json +1 -1
- package/README-zh.md +18 -6
- package/README.md +20 -6
- package/config.yml +1 -1
- package/docs/cli.en.md +1 -1
- package/docs/cli.md +1 -1
- package/docs/plugin-idd-rag-contract.md +87 -0
- package/docs/plugins.en.md +2 -2
- package/docs/plugins.md +2 -2
- package/docs/sdk.en.md +1 -1
- package/docs/sdk.md +1 -1
- package/package.json +2 -1
- package/scripts/onboarding/sim-twin.mjs +27 -15
- package/server/plugins-builtin/diag-bridge/host/deposit.mjs +232 -0
- package/server/plugins-builtin/diag-bridge/host/diagnosis.mjs +121 -38
- package/server/plugins-builtin/diag-bridge/host/external-v1.mjs +213 -0
- package/server/plugins-builtin/diag-bridge/host/helpers.mjs +4 -2
- package/server/plugins-builtin/diag-bridge/host/intents.mjs +65 -62
- package/server/plugins-builtin/diag-bridge/host/plugin.mjs +351 -82
- package/server/plugins-builtin/diag-bridge/host/receipt.mjs +83 -0
- package/server/plugins-builtin/diag-bridge/host/sweep.mjs +70 -91
- package/server/plugins-builtin/diag-bridge/i18n.json +4 -0
- package/server/plugins-builtin/rag-bridge/i18n.json +18 -0
- package/server/plugins-builtin/rag-bridge/index.mjs +556 -68
- package/server/services/workshop/agents/industrial/optimization-tools.ts +12 -1
- package/server/services/workshop/tools/policy.ts +16 -1
- package/.output/public/_nuxt/builds/meta/577f464e-672a-4c4e-a3c8-dc8c1b38930d.json +0 -1
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WS-3:诊断完成 → RAG 文档库(aw-docs)一键入库 + 检索自查。
|
|
3
|
+
*
|
|
4
|
+
* 机制(计划裁定):diag-bridge **直连 rag web 层 HTTP**,跨插件不直引代码,
|
|
5
|
+
* 只共享配置与契约:
|
|
6
|
+
* - web_url/base_url/token 读 `plugins.rag-bridge.*`(系统配置全局命名空间);
|
|
7
|
+
* - 文档库名读 `plugins.rag-bridge.docs_kb`(缺省 aw-docs);
|
|
8
|
+
* - 索引走 rag backend `POST /api/v1/search/index-document`(单文档向量+BM25 增量);
|
|
9
|
+
* - 自查走 web `POST /api/search/two-stage`,可见性窗口 ≤3×5s 重试。
|
|
10
|
+
* 负路径:报告正文为空/取不到 → 可读失败,**不落半截文档**。
|
|
11
|
+
*/
|
|
12
|
+
import { baseOf, jget, short } from './helpers.mjs'
|
|
13
|
+
import { mapV1Error, normalizeResult, v1Result } from './external-v1.mjs'
|
|
14
|
+
|
|
15
|
+
const DEFAULT_RAG_WEB = 'http://127.0.0.1:6789'
|
|
16
|
+
const DEFAULT_RAG_BASE = 'http://127.0.0.1:8770'
|
|
17
|
+
const DEFAULT_DOCS_KB = 'aw-docs'
|
|
18
|
+
|
|
19
|
+
const trimSlash = s => String(s ?? '').replace(/\/+$/, '')
|
|
20
|
+
|
|
21
|
+
export function ragEndpointsOf(ctx) {
|
|
22
|
+
const get = k => ctx.config?.get?.(k)
|
|
23
|
+
const web = trimSlash(String(get('plugins.rag-bridge.web_url') || get('plugins.diag-bridge.deposit_rag_web') || DEFAULT_RAG_WEB))
|
|
24
|
+
const base = trimSlash(String(get('plugins.rag-bridge.base_url') || get('plugins.diag-bridge.deposit_rag_base') || DEFAULT_RAG_BASE))
|
|
25
|
+
const token = String(get('plugins.rag-bridge.token') || get('plugins.diag-bridge.deposit_rag_token') || '').trim()
|
|
26
|
+
const kb = String(get('plugins.rag-bridge.docs_kb') || DEFAULT_DOCS_KB).trim() || DEFAULT_DOCS_KB
|
|
27
|
+
return { web, base, token, kb }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function headersOf(token) {
|
|
31
|
+
return token ? { 'authorization': `Bearer ${token}`, 'x-kb-token': token } : {}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** rag 请求:返回 {ok,status,body,error}(不强制 success 断言,调用方按端点语义判断) */
|
|
35
|
+
async function ragReq(ctx, method, url, body, token, timeoutMs = 20000) {
|
|
36
|
+
const opts = { timeoutMs, headers: headersOf(token) }
|
|
37
|
+
try {
|
|
38
|
+
let res
|
|
39
|
+
if (method === 'GET') res = await ctx.http.get(url, opts)
|
|
40
|
+
else if (method === 'PATCH') {
|
|
41
|
+
if (typeof ctx.http.patch !== 'function') return { ok: false, status: 0, error: '宿主不支持 PATCH' }
|
|
42
|
+
res = await ctx.http.patch(url, body ?? {}, opts)
|
|
43
|
+
}
|
|
44
|
+
else res = await ctx.http.post(url, body ?? {}, opts)
|
|
45
|
+
const json = await res.json().catch(() => null)
|
|
46
|
+
if (!res.ok) return { ok: false, status: res.status, body: json, error: `HTTP ${res.status} ${short(json)}` }
|
|
47
|
+
return { ok: true, status: res.status, body: json }
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
return { ok: false, status: 0, error: String(err?.message ?? err) }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 报告正文获取:优先 v1 内联,其次 report_md_url(JSON content),最后 legacy workspace 报告 */
|
|
55
|
+
async function fetchReportText(ctx, { base, contract, meta, runId, normalized }) {
|
|
56
|
+
if (normalized?.reportMd) return normalized.reportMd
|
|
57
|
+
// v1/legacy 通用:files.report_md_url 指向 /api/files/workspace/report/<ws>(JSON {data:{content}})
|
|
58
|
+
if (normalized?.reportUrl) {
|
|
59
|
+
try {
|
|
60
|
+
const r = await jget(ctx, `${base}${normalized.reportUrl}`, 15000)
|
|
61
|
+
const content = String(r?.data?.content ?? '')
|
|
62
|
+
if (content.trim()) return content
|
|
63
|
+
}
|
|
64
|
+
catch { /* 落到 legacy workspace 查找 */ }
|
|
65
|
+
}
|
|
66
|
+
if (contract !== 'v1') {
|
|
67
|
+
try {
|
|
68
|
+
const ws = (await jget(ctx, `${base}/api/files/workspace`, 8000)).data ?? []
|
|
69
|
+
const names = Array.isArray(ws) ? ws : []
|
|
70
|
+
// 目录命名不统一:<ts>_<scene> / <ts>_<scene>_<runId>;scene 与目录可能 -/_ 混用。
|
|
71
|
+
// 归一化仅保留 [a-z0-9],再按 runId → scene → reportPath 目录名 逐级匹配。
|
|
72
|
+
const norm = s => String(s ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '')
|
|
73
|
+
const reportDir = String(normalized?.reportPath ?? '').replace(/\\/g, '/').split('/').slice(-2, -1)[0] ?? ''
|
|
74
|
+
const sceneNorm = norm(meta?.scene)
|
|
75
|
+
const dirNorm = norm(reportDir)
|
|
76
|
+
const hit = names.find(e => String(e?.name ?? '').includes(runId))
|
|
77
|
+
?? (sceneNorm ? names.find(e => norm(e?.name).includes(sceneNorm)) : null)
|
|
78
|
+
?? (dirNorm ? names.find(e => norm(e?.name).includes(dirNorm)) : null)
|
|
79
|
+
if (hit?.name) {
|
|
80
|
+
const rep = (await jget(ctx, `${base}/api/files/workspace/report/${encodeURIComponent(hit.name)}`, 15000)).data
|
|
81
|
+
return String(rep?.content ?? '')
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch { /* 返回空串由调用方报可读失败 */ }
|
|
85
|
+
}
|
|
86
|
+
return ''
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 文件名净化(Windows 非法字符 → '-') */
|
|
90
|
+
function safeFileName(raw) {
|
|
91
|
+
const unsafe = '<>:"/\\|?*'
|
|
92
|
+
return Array.from(String(raw))
|
|
93
|
+
.map(ch => (ch.charCodeAt(0) < 32 || unsafe.includes(ch) ? '-' : ch))
|
|
94
|
+
.join('')
|
|
95
|
+
.replace(/\s+/g, ' ')
|
|
96
|
+
.trim()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 入库一条已完成的诊断到 rag 文档库,并做检索自查。
|
|
101
|
+
* 返回 { ok, docPath, kbName, hits, verified, error }。
|
|
102
|
+
*/
|
|
103
|
+
export async function depositRunToRag(ctx, { runId, meta, kb, title }) {
|
|
104
|
+
const base = baseOf(ctx)
|
|
105
|
+
if (!base) return { ok: false, error: 'diag.base_url 非法(仅允许 http/https 且 host 为 127.0.0.1/localhost)。' }
|
|
106
|
+
const contract = String(meta?.contract ?? 'legacy')
|
|
107
|
+
|
|
108
|
+
// ① 取终态结果(两个契约分支都会赋值或提前返回)
|
|
109
|
+
let normalized
|
|
110
|
+
let status
|
|
111
|
+
if (contract === 'v1') {
|
|
112
|
+
const q = await v1Result(ctx, meta?.taskId || runId, 15000)
|
|
113
|
+
if (!q.ok) return { ok: false, error: `取诊断结果失败:${mapV1Error(q, { base })}` }
|
|
114
|
+
const data = q.body?.data ?? {}
|
|
115
|
+
status = String(data.status ?? '')
|
|
116
|
+
if (status !== 'completed') return { ok: false, error: `诊断尚未完成(status=${status || 'unknown'}),暂不能入库;先 diag_status 确认。` }
|
|
117
|
+
normalized = normalizeResult(data)
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
try {
|
|
121
|
+
const st = (await jget(ctx, `${base}/api/diagnosis/tasks/${encodeURIComponent(runId)}`, 8000)).data ?? {}
|
|
122
|
+
status = String(st.status ?? '')
|
|
123
|
+
if (status !== 'completed') return { ok: false, error: `诊断尚未完成(status=${status || 'unknown'}),暂不能入库;先 diag_status 确认。` }
|
|
124
|
+
normalized = normalizeResult(st)
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
return { ok: false, error: `取诊断结果失败:${String(err?.message ?? err)}` }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const reportMd = await fetchReportText(ctx, { base, contract, meta, runId, normalized })
|
|
132
|
+
if (!reportMd.trim()) {
|
|
133
|
+
return { ok: false, error: '报告正文为空或无法取得(既无内联 report_md,也无法通过 report URL/workspace 读取);未创建任何文档。请确认 run 状态为 completed 且报告工件存在。' }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ② 目标库解析
|
|
137
|
+
const { web, base: ragBase, token, kb: defaultKb } = ragEndpointsOf(ctx)
|
|
138
|
+
const kbName = String(kb || defaultKb).trim() || DEFAULT_DOCS_KB
|
|
139
|
+
const cat = await ragReq(ctx, 'GET', `${web}/api/kb/catalog`, undefined, token, 10000)
|
|
140
|
+
if (!cat.ok) return { ok: false, error: `RAG 目录不可达:${cat.error}(检查 plugins.rag-bridge.web_url/token 与 rag web 服务)` }
|
|
141
|
+
const kbs = Array.isArray(cat.body?.knowledgeBases) ? cat.body.knowledgeBases : []
|
|
142
|
+
let hit = kbs.find(k => k?.name === kbName)
|
|
143
|
+
if (!hit) {
|
|
144
|
+
// 文档库按需自愈(与 rag-bridge ensureKB 同语义):建库后再解析
|
|
145
|
+
const created = await ragReq(ctx, 'POST', `${web}/api/kb/create`, { name: kbName, description: 'AgentWorkShop 文档库(诊断报告/规范/协议)' }, token, 20000)
|
|
146
|
+
if (!created.ok) return { ok: false, error: `目标知识库「${kbName}」不存在且创建失败:${created.error}` }
|
|
147
|
+
const again = await ragReq(ctx, 'GET', `${web}/api/kb/catalog`, undefined, token, 10000)
|
|
148
|
+
hit = (again.body?.knowledgeBases ?? []).find(k => k?.name === kbName)
|
|
149
|
+
if (!hit?.kbId) return { ok: false, error: `知识库「${kbName}」创建后仍无法在目录中解析` }
|
|
150
|
+
}
|
|
151
|
+
const kbId = String(hit.kbId)
|
|
152
|
+
const kbPath = String(hit.path ?? kbName).replace(/\\/g, '/')
|
|
153
|
+
const kbSlug = kbPath.split('/').pop() || kbName
|
|
154
|
+
|
|
155
|
+
// ③ 文档名(幂等键):<line|scene>_<intent>_<runId>
|
|
156
|
+
const intent = String(meta?.intent ?? 'deep-diagnosis')
|
|
157
|
+
const stem = safeFileName(title || `${meta?.line || 'offline'}_${intent}_${runId}`)
|
|
158
|
+
const fileName = /\.[A-Za-z0-9]+$/.test(stem) ? stem : `${stem}.md`
|
|
159
|
+
const description = `诊断报告自动入库:产线=${meta?.line ?? '?'},意图=${intent},run=${runId},评分=${normalized?.score ?? '-'},结论=${normalized?.verdict ?? '-'}`
|
|
160
|
+
|
|
161
|
+
// ④ 幂等预查(服务端 create 对重名是自动改名,不是 409)
|
|
162
|
+
const list = await ragReq(ctx, 'GET', `${web}/api/kb/documents?kbId=${encodeURIComponent(kbId)}`, undefined, token, 15000)
|
|
163
|
+
const findSame = body => (Array.isArray(body?.documents) ? body.documents : [])
|
|
164
|
+
.find(d => String(d?.name ?? '').toLowerCase() === fileName.toLowerCase())
|
|
165
|
+
let docPath
|
|
166
|
+
let docId
|
|
167
|
+
const existing = list.ok ? findSame(list.body) : null
|
|
168
|
+
if (existing?.path) {
|
|
169
|
+
docPath = String(existing.path).replace(/\\/g, '/')
|
|
170
|
+
docId = String(existing.id ?? '')
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
const created = await ragReq(ctx, 'POST', `${web}/api/kb/documents/create`, { kbId, name: fileName, content: reportMd, description }, token, 30000)
|
|
174
|
+
if (!created.ok) return { ok: false, error: `文档创建失败:${created.error}` }
|
|
175
|
+
docPath = String(created.body?.document?.path ?? '').replace(/\\/g, '/')
|
|
176
|
+
docId = String(created.body?.document?.id ?? '')
|
|
177
|
+
if (!docPath) return { ok: false, error: `创建响应缺少 document.path:${short(created.body)}` }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ⑤ 单文档索引(向量+图谱+BM25 增量;rag backend)
|
|
181
|
+
let indexState = 'ok'
|
|
182
|
+
const idx = await ragReq(ctx, 'POST', `${ragBase}/api/v1/search/index-document`,
|
|
183
|
+
docId ? { doc_id: docId, doc_name: fileName, description } : { kb_id: kbId, doc_path: docPath, doc_name: fileName, description, content: reportMd },
|
|
184
|
+
token, 30000)
|
|
185
|
+
if (!idx.ok) indexState = `failed(${idx.error})`
|
|
186
|
+
|
|
187
|
+
// ⑥ 标签(尽力)
|
|
188
|
+
const tags = ['diag', intent, String(meta?.line ?? 'offline'), runId].filter(Boolean).slice(0, 16)
|
|
189
|
+
const tagRes = await ragReq(ctx, 'PATCH', `${web}/api/kb/documents/tags`, { kbId, docPath, tags }, token, 15000)
|
|
190
|
+
|
|
191
|
+
// ⑦ 检索自查(两段检索为主;可见性窗口 ≤3×5s)
|
|
192
|
+
const query = title || `${meta?.line ?? ''} ${intent} ${runId}`.trim()
|
|
193
|
+
let hits = 0
|
|
194
|
+
let verified = false
|
|
195
|
+
let searchMode = 'two-stage'
|
|
196
|
+
for (let i = 0; i < 3 && !verified; i++) {
|
|
197
|
+
if (i > 0) await new Promise(resolve => ctx.timer.setTimeout(resolve, 5000))
|
|
198
|
+
const ts = await ragReq(ctx, 'POST', `${web}/api/search/two-stage`, { query, kb_id: kbId, stage2_top_k: 5 }, token, 15000)
|
|
199
|
+
if (ts.ok && ts.body?.success === true) {
|
|
200
|
+
const results = Array.isArray(ts.body?.stage2?.results) ? ts.body.stage2.results : []
|
|
201
|
+
hits = results.length
|
|
202
|
+
verified = results.some(r => String(r?.doc_path ?? '').replace(/\\/g, '/') === docPath)
|
|
203
|
+
continue
|
|
204
|
+
}
|
|
205
|
+
// 两段检索不可用 → 关键词兜底(仅元数据)
|
|
206
|
+
searchMode = 'keyword-degraded'
|
|
207
|
+
const kw = await ragReq(ctx, 'GET', `${web}/api/kb/search?query=${encodeURIComponent(query)}&top_k=10`, undefined, token, 10000)
|
|
208
|
+
const khits = Array.isArray(kw.body?.hits) ? kw.body.hits : []
|
|
209
|
+
hits = khits.length
|
|
210
|
+
verified = khits.some(h => String(h?.path ?? '').replace(/\\/g, '/') === docPath)
|
|
211
|
+
break
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
ok: true,
|
|
216
|
+
docPath,
|
|
217
|
+
docId,
|
|
218
|
+
kbName,
|
|
219
|
+
kbId,
|
|
220
|
+
kbSlug,
|
|
221
|
+
hits,
|
|
222
|
+
verified,
|
|
223
|
+
searchMode,
|
|
224
|
+
indexState,
|
|
225
|
+
tagsState: tagRes.ok ? 'ok' : `failed(${tagRes.error})`,
|
|
226
|
+
reportChars: reportMd.length,
|
|
227
|
+
score: normalized?.score ?? null,
|
|
228
|
+
verdict: normalized?.verdict ?? null,
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export { DEFAULT_DOCS_KB, DEFAULT_RAG_WEB, safeFileName }
|
|
@@ -1,24 +1,42 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 启动一次诊断(建运行记录 / 调
|
|
3
|
-
* (
|
|
2
|
+
* 启动一次诊断(契约定轨 → 建运行记录 / 调 IDD / 落 KV)
|
|
3
|
+
* WS-2:主契约迁移 external v1(auto 提交前探测定轨,legacy 显式回退);
|
|
4
|
+
* run meta 持久化 contract + task_id + run_id,轮询/状态/回执全链同契约。
|
|
4
5
|
*/
|
|
5
6
|
import { baseOf, harnessOf, jpost, maxMinutesOf, maxTurnsOf, runKey, runningOfLine, short } from './helpers.mjs'
|
|
6
7
|
import { snapshotCore } from './snapshot.mjs'
|
|
7
8
|
import { startingLines } from './constants.mjs'
|
|
8
9
|
import { defaultQuestionFor, resolveBridgeIntent } from './intents.mjs'
|
|
10
|
+
import { getCapabilities, mapV1Error, preflightCapabilities, resolveContract, v1Request } from './external-v1.mjs'
|
|
9
11
|
|
|
10
|
-
export async function startDiagnosis(ctx, {
|
|
12
|
+
export async function startDiagnosis(ctx, {
|
|
13
|
+
line, lineScope, fromMs, toMs, question, scene, source, dataPath, dataPaths,
|
|
14
|
+
harness, agentId, channelId, analysisIntent, model, permissionMode,
|
|
15
|
+
ontologyMode, ontologyScene, ontologySource, preprocessingMode, reportLanguage,
|
|
16
|
+
}) {
|
|
11
17
|
const base = baseOf(ctx)
|
|
12
18
|
if (!base) return { ok: false, error: 'diag.base_url 非法(仅允许 http/https 且 host 为 127.0.0.1/localhost)。' }
|
|
13
19
|
const intent = resolveBridgeIntent(analysisIntent)
|
|
14
20
|
if (analysisIntent && String(analysisIntent).trim() && !intent) {
|
|
15
|
-
return { ok: false, error: `未知分析意图: ${String(analysisIntent)}(支持 deep-diagnosis/stability-report/quick-screen/doe-analysis/experience-mining/optimizer-campaign)` }
|
|
21
|
+
return { ok: false, error: `未知分析意图: ${String(analysisIntent)}(支持 deep-diagnosis/stability-report/quick-screen/doe-analysis/experience-mining/optimizer-campaign/improvement-advisory)` }
|
|
16
22
|
}
|
|
17
23
|
if (startingLines.has(line)) return { ok: false, error: `产线 ${line} 已有诊断正在启动,请稍后再试。` }
|
|
18
24
|
const existing = runningOfLine(ctx, line)
|
|
19
25
|
if (existing) return { ok: false, error: `产线 ${line} 已有运行中的诊断(run_id=${existing.id}),请稍后用 diag_status 查询。` }
|
|
20
26
|
startingLines.add(line)
|
|
21
27
|
try {
|
|
28
|
+
// ① 契约定轨(提交前;v1 /analyze 无幂等键,禁止"失败后回退"式重提交)
|
|
29
|
+
const track = await resolveContract(ctx)
|
|
30
|
+
if (!track.contract) return { ok: false, error: track.error }
|
|
31
|
+
const contract = track.contract
|
|
32
|
+
|
|
33
|
+
// ② v1 能力预检(软拒绝:intent/引擎不在 capabilities 清单 → 提交前可读拒绝)
|
|
34
|
+
if (contract === 'v1') {
|
|
35
|
+
const cap = await getCapabilities(ctx)
|
|
36
|
+
const reject = preflightCapabilities(cap, { intent, harness: harness || harnessOf(ctx) })
|
|
37
|
+
if (reject) return { ok: false, error: reject }
|
|
38
|
+
}
|
|
39
|
+
|
|
22
40
|
let snap = { ok: true, csvPath: '', rows: 0, nodes: 0 }
|
|
23
41
|
if (!dataPath && !(Array.isArray(dataPaths) && dataPaths.length > 0)) {
|
|
24
42
|
snap = await snapshotCore(ctx, line, fromMs, toMs)
|
|
@@ -27,46 +45,116 @@ export async function startDiagnosis(ctx, { line, fromMs, toMs, question, scene,
|
|
|
27
45
|
// 按情景注入业务提示词:调用方显式 question 优先,否则用意图目录的模板(分析语义在此,执行解耦在 IDD)
|
|
28
46
|
const q = question || defaultQuestionFor(intent, { line, fromMs, toMs })
|
|
29
47
|
const sceneName = scene || `${line}_diag`
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
48
|
+
const engine = harness || harnessOf(ctx)
|
|
49
|
+
const notes = []
|
|
50
|
+
|
|
51
|
+
let runId
|
|
52
|
+
let taskId = ''
|
|
53
|
+
let initialStatus = 'running'
|
|
54
|
+
let name = ''
|
|
55
|
+
|
|
56
|
+
if (contract === 'v1') {
|
|
57
|
+
// v1 提交:202 {task_id, run_id, status, links}(无 success 字段,按 HTTP 状态码分支)
|
|
58
|
+
const payload = Array.isArray(dataPaths) && dataPaths.length > 0
|
|
59
|
+
? { dataPaths }
|
|
60
|
+
: { dataPath: dataPath || snap.csvPath }
|
|
61
|
+
const body = {
|
|
62
|
+
...payload,
|
|
63
|
+
analysisIntent: intent,
|
|
64
|
+
harness: engine,
|
|
65
|
+
sceneName,
|
|
66
|
+
question: q,
|
|
67
|
+
reportLanguage: String(reportLanguage || 'zh'),
|
|
68
|
+
wait: false,
|
|
69
|
+
...(ontologyMode ? { ontologyMode: String(ontologyMode) } : {}),
|
|
70
|
+
...(ontologyScene ? { ontologyScene: String(ontologyScene) } : {}),
|
|
71
|
+
...(ontologySource ? { ontologySource: String(ontologySource) } : {}),
|
|
72
|
+
...(preprocessingMode ? { preprocessingMode: String(preprocessingMode) } : {}),
|
|
73
|
+
maxTurns: maxTurnsOf(ctx),
|
|
74
|
+
timeoutMinutes: maxMinutesOf(ctx),
|
|
75
|
+
}
|
|
76
|
+
if (model || permissionMode) notes.push('external v1 无 model/permissionMode 字段,本次已忽略(按 IDD 默认执行)')
|
|
77
|
+
const started = await v1Request(ctx, 'POST', '/analyze', body, 20000)
|
|
78
|
+
if (!started.ok) {
|
|
79
|
+
return { ok: false, error: `发起分析失败:${mapV1Error(started, { base })}` }
|
|
80
|
+
}
|
|
81
|
+
const data = started.body?.data ?? {}
|
|
82
|
+
taskId = String(data.task_id ?? '')
|
|
83
|
+
runId = String(data.run_id ?? taskId)
|
|
84
|
+
name = String(data.name ?? '')
|
|
85
|
+
const ackStatus = String(data.status ?? '').toLowerCase()
|
|
86
|
+
if (!taskId || !runId) return { ok: false, error: `v1 analyze 响应缺少 task_id/run_id: ${short(started.body)}` }
|
|
87
|
+
if (['failed', 'interrupted', 'expired'].includes(ackStatus)) {
|
|
88
|
+
return { ok: false, error: `诊断任务已受理但立即 ${ackStatus}(run_id=${runId}):${data.error ?? 'IDD 未返回原因'}` }
|
|
89
|
+
}
|
|
90
|
+
initialStatus = ['queued', 'running', 'accepted', 'awaiting_input'].includes(ackStatus) ? ackStatus : 'running'
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
// legacy 提交(/api/diagnosis/tasks):接收即返 task_id,诊断在 IDD 后台执行
|
|
94
|
+
const payload = Array.isArray(dataPaths) && dataPaths.length > 0
|
|
95
|
+
? { dataPaths }
|
|
96
|
+
: { dataPath: dataPath || snap.csvPath }
|
|
97
|
+
const started = await jpost(ctx, `${base}/api/diagnosis/tasks`, {
|
|
98
|
+
...payload,
|
|
99
|
+
sceneName,
|
|
100
|
+
userQuestion: q,
|
|
101
|
+
harness: engine, // 缺省落 claude 引擎会因无 key 失败,必须显式(系统配置 → kv → omp)
|
|
102
|
+
...(intent && intent !== 'deep-diagnosis' ? { analysisIntent: intent } : {}),
|
|
103
|
+
...(model ? { model: String(model) } : {}),
|
|
104
|
+
...(permissionMode ? { permissionMode: String(permissionMode) } : {}),
|
|
105
|
+
...(reportLanguage ? { reportLanguage: String(reportLanguage) } : { reportLanguage: 'zh' }),
|
|
106
|
+
...(ontologyMode ? { ontologyMode: String(ontologyMode) } : {}),
|
|
107
|
+
...(ontologyScene ? { ontologyScene: String(ontologyScene) } : {}),
|
|
108
|
+
...(ontologySource ? { ontologySource: String(ontologySource) } : {}),
|
|
109
|
+
...(preprocessingMode ? { preprocessingMode: String(preprocessingMode) } : {}),
|
|
110
|
+
enhancement: 'off',
|
|
111
|
+
maxTurns: maxTurnsOf(ctx),
|
|
112
|
+
timeoutMinutes: maxMinutesOf(ctx),
|
|
113
|
+
})
|
|
114
|
+
runId = String(started.data?.task_id ?? started.data?.runId ?? '')
|
|
115
|
+
taskId = runId
|
|
116
|
+
name = String(started.data?.name ?? '')
|
|
117
|
+
if (!runId) return { ok: false, error: `tasks 响应缺少 data.task_id: ${short(started)}` }
|
|
118
|
+
// 采用 IDD ack 的真实初始态:队列满时是 queued,触发失败时是 failed。
|
|
119
|
+
const ackStatus = String(started.data?.status ?? '').toLowerCase()
|
|
120
|
+
if (ackStatus === 'failed') {
|
|
121
|
+
return { ok: false, error: `诊断任务已受理但立即失败(run_id=${runId}):${started.data?.error ?? started.data?.result?.error ?? 'IDD 未返回原因'}` }
|
|
122
|
+
}
|
|
123
|
+
initialStatus = ['queued', 'running'].includes(ackStatus) ? ackStatus : 'running'
|
|
57
124
|
}
|
|
58
|
-
|
|
125
|
+
|
|
59
126
|
ctx.kv.set(runKey(runId), {
|
|
60
127
|
line, fromMs, toMs, question: q, scene: sceneName,
|
|
128
|
+
// 授权作用域(区别于 line 锁键):显式传入的产线才参与可读面校验;
|
|
129
|
+
// 纯离线数据集为 ''(不按产线拒,读取面已由数据集归属/导出约束)。
|
|
130
|
+
lineScope: String(lineScope ?? line ?? ''),
|
|
61
131
|
intent: intent || 'deep-diagnosis',
|
|
62
132
|
status: initialStatus, createdAt: Date.now(), source,
|
|
63
133
|
csvPath: snap.csvPath,
|
|
64
134
|
files: Array.isArray(dataPaths) ? dataPaths.length : 0,
|
|
65
135
|
name,
|
|
136
|
+
// 契约路由字段:轮询/状态/回执/report 全链同契约(跨 sweep 与工具面)
|
|
137
|
+
contract,
|
|
138
|
+
taskId,
|
|
139
|
+
runId,
|
|
66
140
|
// 归因:发起 Agent 完成后的结果回执靠它寻址(平台通告面 deliver)
|
|
67
141
|
agentId: agentId || '', channelId: channelId || '',
|
|
68
142
|
})
|
|
69
|
-
return {
|
|
143
|
+
return {
|
|
144
|
+
ok: true,
|
|
145
|
+
runId,
|
|
146
|
+
taskId,
|
|
147
|
+
contract,
|
|
148
|
+
name,
|
|
149
|
+
status: initialStatus,
|
|
150
|
+
csvPath: snap.csvPath,
|
|
151
|
+
rows: snap.rows,
|
|
152
|
+
nodes: snap.nodes,
|
|
153
|
+
files: Array.isArray(dataPaths) ? dataPaths.length : 0,
|
|
154
|
+
intent: intent || 'deep-diagnosis',
|
|
155
|
+
question: q,
|
|
156
|
+
notes,
|
|
157
|
+
}
|
|
70
158
|
}
|
|
71
159
|
catch (err) {
|
|
72
160
|
return { ok: false, error: `发起诊断失败: ${err?.message ?? err}` }
|
|
@@ -75,8 +163,3 @@ export async function startDiagnosis(ctx, { line, fromMs, toMs, question, scene,
|
|
|
75
163
|
startingLines.delete(line)
|
|
76
164
|
}
|
|
77
165
|
}
|
|
78
|
-
|
|
79
|
-
// ── 轮询器:15s 扫描 kv 中 running 的 run → 更新状态 ──────────────────────
|
|
80
|
-
// v2.1:入库不再由本插件自动执行(web documents/create 旧两步管线已移除)。
|
|
81
|
-
// 完成后的协调契约:Channel 空闲时用 diag_status 查询 → 拿到 诊断总结+报告 md
|
|
82
|
-
// 路径 → 由 Agent 调用 rag-bridge 的 kb_agent(mode=async) 把报告入库知识库。
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IDD external v1 契约层(WS-2)。
|
|
3
|
+
*
|
|
4
|
+
* - 契约定轨:显式 settings `contract` ∈ auto|v1|legacy;auto 时**提交前**探测
|
|
5
|
+
* `GET /capabilities` 并缓存(5min,按 base+token 指纹)——不是"失败后回退",
|
|
6
|
+
* 因为 v1 /analyze 无幂等键,202 后重提交有双跑风险。
|
|
7
|
+
* - 请求层:不复用 jget/jpost 的 success 断言 —— v1 202 信封无 success 字段;
|
|
8
|
+
* 一律按 HTTP 状态码分支,错误码统一映射为中文可读指引(手册 §9)。
|
|
9
|
+
* - 结果归一:v1 task/result → 既有内部形状(score/verdict/summary/reportPath/...),
|
|
10
|
+
* 下游(回执/结果库/面板)零形状断裂。
|
|
11
|
+
*/
|
|
12
|
+
import { authHeadersOf, baseOf, diagTokenOf } from './helpers.mjs'
|
|
13
|
+
|
|
14
|
+
export const V1_PREFIX = '/api/external/v1'
|
|
15
|
+
export const CONTRACT_TTL_MS = 5 * 60_000
|
|
16
|
+
|
|
17
|
+
/** 契约开关(系统配置优先,kv 兜底;auto=探测) */
|
|
18
|
+
export function contractModeOf(ctx) {
|
|
19
|
+
const v = String(ctx.config?.get?.('plugins.diag-bridge.contract') || ctx.kv.get('diag.contract') || 'auto').trim().toLowerCase()
|
|
20
|
+
return ['v1', 'legacy', 'auto'].includes(v) ? v : 'auto'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 等待人工介入(run=awaiting_input)的老化上限(分钟;到期转 expired 并提示) */
|
|
24
|
+
export function awaitingMaxMinutesOf(ctx) {
|
|
25
|
+
const n = Number(ctx.config?.get?.('plugins.diag-bridge.awaiting_max_minutes')) || Number(ctx.kv.get('diag.awaiting_max_minutes')) || 30
|
|
26
|
+
return Math.min(24 * 60, Math.max(1, Math.round(n)))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 缓存指纹:base_url + token 变化必须使探测缓存失效 */
|
|
30
|
+
function probeKeyOf(ctx) {
|
|
31
|
+
const base = baseOf(ctx) ?? ''
|
|
32
|
+
const token = diagTokenOf(ctx)
|
|
33
|
+
let h = 0
|
|
34
|
+
for (let i = 0; i < token.length; i += 1) h = (h * 31 + token.charCodeAt(i)) | 0
|
|
35
|
+
return `diag.contract_probe:${base}:${h}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* v1 请求:返回 { ok, status, body } 或 { ok:false, status, body, error }。
|
|
40
|
+
* 不使用 success 断言(202 无 success;部分端点成功信封只有 data/status)。
|
|
41
|
+
*/
|
|
42
|
+
export async function v1Request(ctx, method, path, body, timeoutMs = 10000) {
|
|
43
|
+
const base = baseOf(ctx)
|
|
44
|
+
if (!base) return { ok: false, status: 0, error: 'base_url 非法(仅允许 http/https 且 host 为 127.0.0.1/localhost)' }
|
|
45
|
+
const url = `${base}${V1_PREFIX}${path}`
|
|
46
|
+
const opts = { timeoutMs, headers: authHeadersOf(ctx) }
|
|
47
|
+
try {
|
|
48
|
+
const res = method === 'GET'
|
|
49
|
+
? await ctx.http.get(url, opts)
|
|
50
|
+
: await ctx.http.post(url, body ?? {}, opts)
|
|
51
|
+
const json = await res.json().catch(() => null)
|
|
52
|
+
if (!res.ok) {
|
|
53
|
+
return { ok: false, status: res.status, body: json, error: `HTTP ${res.status}${json?.code ? ` ${json.code}` : ''}${json?.error ? `:${json.error}` : ''}` }
|
|
54
|
+
}
|
|
55
|
+
return { ok: true, status: res.status, body: json }
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
return { ok: false, status: 0, error: String(err?.message ?? err) }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** capabilities(缓存 5min;force=true 强制刷新) */
|
|
63
|
+
export async function getCapabilities(ctx, { force = false } = {}) {
|
|
64
|
+
const key = probeKeyOf(ctx)
|
|
65
|
+
if (!force) {
|
|
66
|
+
const cached = ctx.kv.get(key)
|
|
67
|
+
if (cached) {
|
|
68
|
+
try {
|
|
69
|
+
const p = JSON.parse(cached)
|
|
70
|
+
if (Date.now() - p.at < CONTRACT_TTL_MS && p.capabilities) return { ok: true, cached: true, data: p.capabilities }
|
|
71
|
+
}
|
|
72
|
+
catch { /* 缓存损坏则重探 */ }
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const r = await v1Request(ctx, 'GET', '/capabilities', undefined, 5000)
|
|
76
|
+
if (r.ok && r.body?.success === true && r.body?.data) {
|
|
77
|
+
try {
|
|
78
|
+
ctx.kv.set(key, JSON.stringify({ at: Date.now(), capabilities: r.body.data }))
|
|
79
|
+
}
|
|
80
|
+
catch { /* kv 不可写不影响主流程 */ }
|
|
81
|
+
return { ok: true, data: r.body.data }
|
|
82
|
+
}
|
|
83
|
+
// HTTP 200 但不是 v1 能力信封(常见于反向代理 catch-all/旧后端兜底)→ 标记 shape,
|
|
84
|
+
// 由 resolveContract 按 legacy 处理(而不是把"200"误当 v1 能力)。
|
|
85
|
+
const shape = Boolean(r.ok) && !(r.body?.success === true && r.body?.data)
|
|
86
|
+
return { ok: false, status: r.status ?? 0, shape, error: r.error ?? (shape ? 'capabilities 响应形状不符(非 v1 信封)' : 'capabilities 不可达') }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 契约定轨。返回 { contract:'v1'|'legacy', mode, cached? } 或 { contract:null, error }。
|
|
91
|
+
* 铁律:401/403 与 5xx 不钉 legacy(token/服务故障时 legacy 同样不可用,静默回退会掩盖问题)。
|
|
92
|
+
*/
|
|
93
|
+
export async function resolveContract(ctx, { force = false } = {}) {
|
|
94
|
+
const mode = contractModeOf(ctx)
|
|
95
|
+
if (mode === 'v1' || mode === 'legacy') return { contract: mode, mode, pinned: true }
|
|
96
|
+
const cap = await getCapabilities(ctx, { force })
|
|
97
|
+
if (cap.ok) return { contract: 'v1', mode, cached: Boolean(cap.cached) }
|
|
98
|
+
const status = Number(cap.status ?? 0)
|
|
99
|
+
if (status === 404 || status === 400) return { contract: 'legacy', mode }
|
|
100
|
+
if (status === 0) return { contract: 'legacy', mode } // 老后端/不可达:legacy 路径会给出更具体的网络错误
|
|
101
|
+
if (cap.shape) return { contract: 'legacy', mode } // 200 非 v1 信封(代理兜底/旧后端)
|
|
102
|
+
if (status === 401 || status === 403) {
|
|
103
|
+
return {
|
|
104
|
+
contract: null,
|
|
105
|
+
mode,
|
|
106
|
+
error: `IDD Token 无效或过期(HTTP ${status}):请到 系统设置→运行配置→插件 更新「诊断 API Token」(idd_ 前缀持久 Token)。契约定轨不会回退 legacy —— token 错误时两条路径都不可用。`,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { contract: null, mode, error: `capabilities 探测失败(HTTP ${status},${cap.error});服务可能暂时不可用,请稍后重试或将 contract 显式设为 v1/legacy。` }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** v1 任务状态(GET /tasks/:id;/tasks 接受 task_id 或 run_id) */
|
|
113
|
+
export function v1Task(ctx, id, timeoutMs = 8000) {
|
|
114
|
+
return v1Request(ctx, 'GET', `/tasks/${encodeURIComponent(id)}`, undefined, timeoutMs)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** v1 终态结果(GET /tasks/:id/result;运行中 409 EXTERNAL_TASK_RUNNING) */
|
|
118
|
+
export function v1Result(ctx, id, timeoutMs = 15000) {
|
|
119
|
+
return v1Request(ctx, 'GET', `/tasks/${encodeURIComponent(id)}/result`, undefined, timeoutMs)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** v1 续聊(POST /chat) */
|
|
123
|
+
export function v1Chat(ctx, runId, message, timeoutMs = 20000) {
|
|
124
|
+
return v1Request(ctx, 'POST', '/chat', { run_id: runId, message }, timeoutMs)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** v1 停止(POST /analyze/:runId/stop) */
|
|
128
|
+
export function v1Stop(ctx, runId, timeoutMs = 15000) {
|
|
129
|
+
return v1Request(ctx, 'POST', `/analyze/${encodeURIComponent(runId)}/stop`, {}, timeoutMs)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 手册 §9 错误码 → 中文可读 + 处方 */
|
|
133
|
+
export function mapV1Error(r, { base = '' } = {}) {
|
|
134
|
+
const code = String(r?.body?.code ?? '')
|
|
135
|
+
const status = Number(r?.status ?? 0)
|
|
136
|
+
const raw = String(r?.body?.error ?? r?.error ?? '')
|
|
137
|
+
if (/^AUTH_/.test(code) || status === 401 || status === 403) {
|
|
138
|
+
return `IDD Token 无效/过期(${code || `HTTP ${status}`}):在 系统设置→运行配置→插件 更新「诊断 API Token」(idd_ 持久 Token),保存即热生效。`
|
|
139
|
+
}
|
|
140
|
+
if (code === 'EXTERNAL_INTENT_UNKNOWN') {
|
|
141
|
+
const supported = Array.isArray(r?.body?.supported) ? r.body.supported.join('/') : 'deep-diagnosis/stability-report/quick-screen/doe-analysis/experience-mining/optimizer-campaign/improvement-advisory'
|
|
142
|
+
return `未知分析意图(${raw})。支持:${supported}。`
|
|
143
|
+
}
|
|
144
|
+
if (code === 'HARNESS_UNKNOWN') {
|
|
145
|
+
return `诊断引擎名不存在(${raw})。可用引擎以 GET /api/external/v1/capabilities 的 harnesses 为准(当前推荐 omp)。`
|
|
146
|
+
}
|
|
147
|
+
if (code === 'HARNESS_UNAVAILABLE') {
|
|
148
|
+
return `诊断引擎不可用(${raw})。该引擎未安装或健康探测失败;换用 capabilities 中 runs_capable=true 的引擎(如 omp),或先在 IDD 侧修复引擎环境。`
|
|
149
|
+
}
|
|
150
|
+
if (code === 'EXTERNAL_DATA_REQUIRED') {
|
|
151
|
+
return '缺少数据来源:line(平台快照)/data_path(诊断服务内文件)/export_id(daq_export 数据集)至少给一个。'
|
|
152
|
+
}
|
|
153
|
+
if (code === 'DATA_NOT_FOUND') return `数据路径不存在(${raw}):确认 data_path 相对 data/ 或 workspace 白名单;export 数据集请先用 daq_export 导出。`
|
|
154
|
+
if (code === 'PATH_TRAVERSAL') return `数据路径越界被拒(${raw}):只允许 data/ 或 workspace 白名单内的路径。`
|
|
155
|
+
if (code === 'INTENT_UNSUPPORTED_ON_HARNESS') return `该引擎不支持此分析意图(${raw});换引擎或换意图(capabilities 的 supported_intents 为准)。`
|
|
156
|
+
if (code === 'PREPROCESSING_MODE_UNSUPPORTED_INTENT') return 'preprocessing_mode 仅 stability-report 支持;其它意图请去掉该参数。'
|
|
157
|
+
if (code === 'ONTOLOGY_UNSUPPORTED_INTENT') return 'ontology 字段仅 deep-diagnosis/stability-report/quick-screen/doe-analysis 支持;其它意图请去掉。'
|
|
158
|
+
if (code === 'RUN_NOT_IDLE') {
|
|
159
|
+
return `该 run 正在运行,不能续聊(RUN_NOT_IDLE):先 diag_stop 停止,或等终态后再 diag_chat。`
|
|
160
|
+
}
|
|
161
|
+
if (code === 'RUN_TERMINAL') return `该 run 已结束(${raw}),无需再 stop;如需追问用 diag_chat(终态 run 可续聊)。`
|
|
162
|
+
if (code === 'EXTERNAL_TASK_RUNNING') return `任务仍在运行(HTTP 409):先把任务跑到终态再取结果;进度用 diag_status 查询。`
|
|
163
|
+
if (code === 'RUN_NOT_FOUND') return `run 不存在(${raw}):可能已被 IDD 清理或服务重启丢失;用 diag_status 查本地记录。`
|
|
164
|
+
if (code === 'RESULT_FORBIDDEN') return '结果不属于当前 Token 属主;换创建它的账号 Token 或由 IDD 管理员操作。'
|
|
165
|
+
if (status === 404) return `任务/资源不存在(HTTP 404):可能已过期(2h)或 IDD 重启丢失;重新 diag_run 或 diag_status 查本地记录。`
|
|
166
|
+
if (status >= 500) return `IDD 服务端错误(HTTP ${status}):${raw || '请查看 IDD 日志'};稍后重试。`
|
|
167
|
+
if (status === 0) return `诊断服务不可达${base ? `(${base})` : ''}:${raw || '检查 base_url、IDD 服务状态与网络'}。`
|
|
168
|
+
return raw || `请求失败(HTTP ${status || '?'})`
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* v1 / legacy 结果 → 内部统一形状。
|
|
173
|
+
* data 可为:task entry(refreshTask)、tasks/:id/result 信封(data.result/files)、
|
|
174
|
+
* legacy tasks/:id 的 data(result 内嵌)。
|
|
175
|
+
*/
|
|
176
|
+
export function normalizeResult(data) {
|
|
177
|
+
const result = data?.result ?? {}
|
|
178
|
+
const files = data?.files ?? result?.files ?? null
|
|
179
|
+
return {
|
|
180
|
+
score: result.score ?? null,
|
|
181
|
+
verdict: result.verdict ?? null,
|
|
182
|
+
summary: String(result.summary ?? ''),
|
|
183
|
+
reportPath: files?.report_md_path ?? result.report_md_path ?? null,
|
|
184
|
+
reportUrl: files?.report_md_url ?? result.report_md_url ?? null,
|
|
185
|
+
reportMd: typeof result.report_md === 'string' && result.report_md.length ? result.report_md : null,
|
|
186
|
+
html: Array.isArray(files?.html) ? files.html : [],
|
|
187
|
+
files,
|
|
188
|
+
error: result.error ?? data?.error ?? null,
|
|
189
|
+
artifacts: result.artifacts ?? null,
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 能力预检(软拒绝):intent/harness 不在 capabilities 清单时给出可读原因 */
|
|
194
|
+
export function preflightCapabilities(cap, { intent, harness }) {
|
|
195
|
+
if (!cap?.ok || !cap.data) return null // 探测失败不阻断提交(服务端仍会校验)
|
|
196
|
+
const intents = (Array.isArray(cap.data.intents) ? cap.data.intents : []).map(i => i?.intent).filter(Boolean)
|
|
197
|
+
if (intent && intents.length && !intents.includes(intent)) {
|
|
198
|
+
return `未知分析意图「${intent}」。支持:${intents.join('/')}。`
|
|
199
|
+
}
|
|
200
|
+
const list = Array.isArray(cap.data.harnesses) ? cap.data.harnesses : []
|
|
201
|
+
const hit = list.find(h => String(h?.id ?? '').toLowerCase() === String(harness ?? '').toLowerCase())
|
|
202
|
+
if (!hit) {
|
|
203
|
+
const ids = list.map(h => h?.id).filter(Boolean)
|
|
204
|
+
return `诊断引擎「${harness}」不在 capabilities 清单。可用:${ids.join('/') || '(空)'}。`
|
|
205
|
+
}
|
|
206
|
+
if (hit.runs_capable === false) {
|
|
207
|
+
return `诊断引擎「${harness}」不具备 runs 能力(可执行分析),提交必失败。请换用 runs_capable=true 的引擎(如 omp)。`
|
|
208
|
+
}
|
|
209
|
+
if (intent && Array.isArray(hit.supported_intents) && !hit.supported_intents.includes(intent)) {
|
|
210
|
+
return `引擎「${harness}」不支持分析意图「${intent}」。该引擎支持:${hit.supported_intents.join('/')}。`
|
|
211
|
+
}
|
|
212
|
+
return null
|
|
213
|
+
}
|