argo-search 2.16.0 → 2.17.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.
Files changed (86) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.es.md +9 -4
  3. package/README.ja.md +9 -4
  4. package/README.ko.md +9 -4
  5. package/README.md +9 -4
  6. package/README.zh.md +9 -4
  7. package/SKILL.md +1 -1
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +3 -3
  10. package/assets/readme/hero.template.svg +121 -0
  11. package/assets/readme/proof-routes.svg +17 -16
  12. package/backends/domain_profiles.json +115 -18
  13. package/backends/engine_registry.yaml +11 -0
  14. package/backends/env_passthrough.txt +2 -0
  15. package/backends/quota_profiles.json +10 -0
  16. package/docs/CHANGELOG.md +17 -1
  17. package/docs/COMMIT_STANDARD.md +10 -0
  18. package/docs/ENGINE_CATALOG.md +32 -30
  19. package/docs/RELEASE_NOTES_v2.17.0.md +64 -0
  20. package/docs/RELEASING.md +1 -1
  21. package/engines/specs/crossref.yaml +2 -0
  22. package/engines/specs/hackernews.yaml +2 -0
  23. package/engines/specs/helve.yaml +49 -0
  24. package/engines/specs/hf_papers.yaml +2 -0
  25. package/engines/specs/openalex.yaml +9 -2
  26. package/package.json +2 -1
  27. package/packages/dsh-plugin/README.md +5 -2
  28. package/packages/dsh-plugin/cordis.patch.yml +4 -1
  29. package/packages/dsh-plugin/dsh/client.js +57 -63
  30. package/packages/dsh-plugin/dsh/diagnostics.js +25 -4
  31. package/packages/dsh-plugin/dsh/index.js +109 -21
  32. package/packages/dsh-plugin/dsh/route-guard.js +95 -0
  33. package/packages/dsh-plugin/dsh/runner.js +49 -6
  34. package/packages/dsh-plugin/dsh/wide-research.js +20 -18
  35. package/packages/dsh-plugin/dsh/workbench-client.js +119 -20
  36. package/packages/dsh-plugin/dsh/workbench-io.js +163 -0
  37. package/packages/dsh-plugin/dsh/workbench-search.js +385 -0
  38. package/packages/dsh-plugin/dsh/workbench-suggestions.js +387 -75
  39. package/packages/dsh-plugin/dsh/workbench.js +234 -497
  40. package/packages/dsh-plugin/package.json +4 -3
  41. package/packages/dsh-plugin/scripts/sync-local.mjs +4 -2
  42. package/packages/dsh-plugin/scripts/sync-local.sh +4 -2
  43. package/packages/dsh-plugin/test/client.test.js +26 -0
  44. package/packages/dsh-plugin/test/diagnostics.test.js +5 -2
  45. package/packages/dsh-plugin/test/index.test.js +150 -1
  46. package/packages/dsh-plugin/test/workbench-concurrency.test.js +98 -0
  47. package/packages/dsh-plugin/test/workbench.test.js +337 -9
  48. package/scripts/adaptive.py +13 -11
  49. package/scripts/browser_auth.py +178 -4
  50. package/scripts/cache.py +68 -69
  51. package/scripts/check_commit_report.py +46 -0
  52. package/scripts/chrome_cdp.py +71 -0
  53. package/scripts/circuit_breaker.py +77 -12
  54. package/scripts/config_cache.py +4 -3
  55. package/scripts/daemon.py +9 -2
  56. package/scripts/engine_add.py +45 -0
  57. package/scripts/engine_dispatch.py +27 -47
  58. package/scripts/engine_failure.py +33 -0
  59. package/scripts/engine_fingerprint.py +114 -0
  60. package/scripts/engine_health.py +130 -0
  61. package/scripts/engine_states.py +50 -0
  62. package/scripts/engines_base.py +7 -16
  63. package/scripts/engines_builders_search.py +19 -8
  64. package/scripts/engines_builders_tech.py +16 -16
  65. package/scripts/engines_fields.py +23 -0
  66. package/scripts/evidence_grounding.py +182 -0
  67. package/scripts/fetch_browser.py +25 -10
  68. package/scripts/gate_manifest_check.py +75 -0
  69. package/scripts/gen_readme_art.py +264 -0
  70. package/scripts/mcp_transport.py +24 -5
  71. package/scripts/numeric_verify.py +9 -0
  72. package/scripts/pre-commit +57 -8
  73. package/scripts/query_operators.py +229 -1
  74. package/scripts/quota.py +19 -37
  75. package/scripts/release.py +16 -1
  76. package/scripts/research_gates.py +85 -1
  77. package/scripts/route_combo.py +13 -1
  78. package/scripts/source_discovery.py +611 -0
  79. package/scripts/sync_backends.py +45 -0
  80. package/sub-skills/ego-search/README.md +9 -0
  81. package/sub-skills/ego-search/scripts/ego_search.py +182 -15
  82. package/sub-skills/ego-search/scripts/pacing.py +291 -0
  83. package/sub-skills/ego-search/scripts/quality.py +262 -6
  84. package/sub-skills/ego-search/scripts/runtime.py +7 -1
  85. package/sub-skills/ego-search/scripts/site_profiles.py +157 -0
  86. package/sub-skills/ego-search/scripts/webbridge_adapter.py +7 -1
@@ -6,50 +6,69 @@
6
6
  * 搜索分析工作台(5 种专题模式 + 左答右证 SSE + 原文核验 + 多轮追问)。
7
7
  */
8
8
 
9
- import { execFile, spawn } from 'node:child_process'
10
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
9
+ import { execFile } from 'node:child_process'
10
+ import { readFileSync } from 'node:fs'
11
11
  import { homedir } from 'node:os'
12
12
  import { dirname, join } from 'node:path'
13
13
  import { fileURLToPath } from 'node:url'
14
- import { DEFAULTS, stripBoundary } from './runner.js'
15
14
  import { resolveArgoEnv } from './specs.js'
16
- import { boundedMap, buildCrossLingualTracks, evaluateGates } from './wide-research.js'
17
- import { buildSuggestions } from './workbench-suggestions.js'
15
+ import { buildCrossLingualTracks, evaluateGates } from './wide-research.js'
16
+ import {
17
+ buildEvidenceContext,
18
+ buildFallbackSummary,
19
+ buildSystemPrompt,
20
+ callArgoSearch,
21
+ extractCitations,
22
+ MODES,
23
+ MODE_LABELS,
24
+ resolveLocalSearchPath,
25
+ runClarifyIfShort,
26
+ runEvidenceScoring,
27
+ streamLlmAnswer,
28
+ } from './workbench-search.js'
29
+ import {
30
+ buildSuggestions,
31
+ createHotspotRefresher,
32
+ loadHotspotStore,
33
+ updateRefreshTime,
34
+ } from './workbench-suggestions.js'
35
+ import { checkLoopbackAndOrigin, resolveAuthStatusWithBgVerify } from './route-guard.js'
36
+ import {
37
+ acquireStateFileLock,
38
+ breakerFilePath,
39
+ loadWatches,
40
+ mergedLaunchdPath,
41
+ mutateWatches,
42
+ readStaticAssetCached,
43
+ releaseStateFileLock,
44
+ resolveArgoBin,
45
+ runArgoCli,
46
+ WATCH_STORE_FILE,
47
+ } from './workbench-io.js'
48
+
49
+ // 供既有测试与外部调用方沿旧入口取用(真源在 workbench-search.js)
50
+ export { buildSearchCliArgs, summarizeTrackRuns } from './workbench-search.js'
18
51
 
19
52
  const HERE = dirname(fileURLToPath(import.meta.url))
20
- const ARGO_BIN = join(HERE, '..', '..', '..', 'bin', 'argo')
21
53
  const CLIENT_FILE = join(HERE, 'workbench-client.js')
22
54
  const MD_FILE = join(HERE, 'workbench-md.js')
23
- const WATCH_STORE_FILE = join(homedir(), '.config', 'argo', 'workbench-watches.json')
24
- const BREAKER_FILE = join(homedir(), '.cache', 'unified-search', 'circuit_breaker.json')
25
55
 
26
56
  const CACHE_TTL_MS = 5 * 60 * 1000
27
57
  const MAX_CACHE_ENTRIES = 32
28
58
  const MAX_DIAGNOSTICS = 20
29
59
  const MAX_WATCHES = 20
30
60
 
31
- const CITATION_RULE = [
32
- '严格基于提供的检索证据回答,所有事实判断、数据与观点必须在句末使用方括号编号引用,例如 [1] 或 [2][3]。',
33
- '严禁编造未出现在证据中的数字、链接或来源;如果证据不足或存在冲突,直接指出并并列呈现不同来源。',
34
- '使用清晰的中文 Markdown 结构(小标题、要点列表或对比表格),先给核心结论,再展开细节。',
35
- ].join('\n')
36
-
37
- const MODE_SPECS = {
38
- general: { label: '全网搜索', searchArgs: { max_results: 12, verify: 2, depth: 'balanced' }, prompt: '当前模式为「全网搜索」:先用 2 到 3 句话给出直接结论,再用清晰小标题展开关键依据与延伸信息。' },
39
- hotspot: { label: '热点分析', searchArgs: { max_results: 14, sort: 'newest', since: '14d', depth: 'balanced', verify: 2 }, socialSupplement: true, prompt: '当前模式为「热点分析」:按「一、核心结论与现状」「二、事件脉络」「三、核心争议与各方立场」「四、影响与后续关注点」组织输出。' },
40
- verify: { label: '真假核验', searchArgs: { max_results: 12, verify: 5, depth: 'deep', mode: 'deep' }, prompt: '当前模式为「真假核验」:按「一、核验结论(明确给出可信度判断:可信 / 存疑 / 失实 / 证据不足)」「二、关键证据链(优先引用已核验正文)」「三、冲突点与核验边界」组织输出。' },
41
- research: { label: '深度研究', searchArgs: { max_results: 16, verify: 5, depth: 'deep', mode: 'deep' }, prompt: '当前模式为「深度研究」:按「一、执行摘要」「二、多维拆解与关键发现」「三、数据与案例支撑」「四、风险、局限与待验证项」组织详尽研究报告。' },
42
- compare: { label: '选型对比', searchArgs: { max_results: 14, verify: 3, depth: 'balanced' }, prompt: '当前模式为「选型对比」:按「一、选型结论与推荐」「二、核心维度对比表(Markdown 表格)」「三、各自优缺点与适用人群」「四、替代方案与踩坑提示」组织输出。' },
43
- academic: { label: '学术文献', searchArgs: { max_results: 14, domain: 'academic', depth: 'deep', mode: 'deep', verify: 3 }, prompt: '当前模式为「学术文献」:按「一、核心研究结论与共识」「二、代表性论文与方法拆解」「三、实验证据与关键数据」「四、局限性与延伸方向」组织输出。' },
44
- plugin: { label: '插件评测', searchArgs: { max_results: 14, domain: 'dsh_plugin_search', verify: 3, depth: 'balanced' }, socialSupplement: true, prompt: '当前模式为「插件评测」:按「一、是否值得安装(结论)」「二、核心能力与亮点」「三、社区真实反馈与局限」「四、替代方案与安装配置注意」组织输出。' },
45
- local: { label: '本机检索', searchArgs: { max_results: 16 }, prompt: '当前模式为「本机检索」:基于本机文件与代码命中证据回答,标明文件路径、行号与上下文关联,禁止编造未命中的本地文件。' },
46
- }
47
-
48
- const MODES = new Set(Object.keys(MODE_SPECS))
49
- const MODE_LABELS = Object.fromEntries(Object.entries(MODE_SPECS).map(([k, v]) => [k, v.label]))
50
-
51
61
  function sendJson(res, status, data) {
52
62
  if (res.writableEnded) return
63
+ if (res.headersSent) {
64
+ // SSE 头已 flush 后再 setHeader 会抛 ERR_HTTP_HEADERS_SENT(2026-11-18
65
+ // 实跑复现:followup 传 cards:[null] 在 flushHeaders 后抛 TypeError,
66
+ // 落到这里二次抛 → 响应悬挂 + 异常逃出 async handler)。改发 SSE
67
+ // failure 事件收尾,让客户端与连接都能干净结束。
68
+ sendSse(res, 'failure', data)
69
+ if (!res.writableEnded) res.end()
70
+ return
71
+ }
53
72
  res.statusCode = status
54
73
  res.setHeader('Content-Type', 'application/json; charset=utf-8')
55
74
  res.setHeader('Cache-Control', 'no-store')
@@ -61,19 +80,6 @@ function sendSse(res, event, data) {
61
80
  res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
62
81
  }
63
82
 
64
- function checkSameOrigin(ctx, req) {
65
- const origin = req.headers?.origin
66
- if (!origin) return true
67
- try {
68
- const expected = ctx.webServer?.getOrigin?.()
69
- if (expected && origin === expected) return true
70
- const parsed = new URL(origin)
71
- return parsed.hostname === '127.0.0.1' || parsed.hostname === 'localhost' || parsed.hostname === '::1'
72
- } catch {
73
- return false
74
- }
75
- }
76
-
77
83
  async function readJsonBody(req, maxBytes = 256 * 1024) {
78
84
  const chunks = []
79
85
  let size = 0
@@ -86,86 +92,6 @@ async function readJsonBody(req, maxBytes = 256 * 1024) {
86
92
  return raw ? JSON.parse(raw) : {}
87
93
  }
88
94
 
89
- function extractDomain(url) {
90
- try {
91
- return new URL(url).hostname.replace(/^www\./i, '')
92
- } catch {
93
- return ''
94
- }
95
- }
96
-
97
- function normalizeCandidates(payload) {
98
- const rawList = Array.isArray(payload?.results) ? payload.results : []
99
- const seen = new Set()
100
- const cards = []
101
- for (const item of rawList) {
102
- if (!item || typeof item.url !== 'string' || !item.url.startsWith('http')) continue
103
- const key = item.url.trim()
104
- if (seen.has(key)) continue
105
- seen.add(key)
106
- const index = cards.length + 1
107
- const title = stripBoundary(item.title) || key
108
- const snippet = stripBoundary(item.snippet || item.content || '') || ''
109
- const verifiedText = stripBoundary(item.verified_excerpt || item.fetched_excerpt || '') || ''
110
- const source = item.engine || item.source || item.provider || 'web'
111
- cards.push({
112
- id: `c${index}`,
113
- index,
114
- title,
115
- url: key,
116
- domain: extractDomain(key),
117
- source,
118
- snippet,
119
- verifiedText,
120
- verified: Boolean(item.verified || verifiedText),
121
- credibility: typeof item.credibility_fast === 'number'
122
- ? item.credibility_fast
123
- : (typeof item.credibility === 'number' ? item.credibility : null),
124
- publishedAt: item.published_at || item.publishedAt || item.date || '',
125
- })
126
- if (cards.length >= 16) break
127
- }
128
- return cards
129
- }
130
-
131
- function buildSystemPrompt(mode) {
132
- const spec = MODE_SPECS[mode] || MODE_SPECS.general
133
- return `${CITATION_RULE}\n${spec.prompt}`
134
- }
135
-
136
- function normalizeLocalCards(payload) {
137
- const rawList = Array.isArray(payload?.matches)
138
- ? payload.matches
139
- : (Array.isArray(payload?.results) ? payload.results : [])
140
- const seen = new Set()
141
- const cards = []
142
- for (const item of rawList) {
143
- const filePath = String(item?.path || item?.file || item?.url || '').trim()
144
- if (!filePath) continue
145
- const line = item?.line ? `:${item.line}` : ''
146
- const dedupKey = `${filePath}${line}`
147
- if (seen.has(dedupKey)) continue
148
- seen.add(dedupKey)
149
- const index = cards.length + 1
150
- const snippet = stripBoundary(item?.snippet || item?.text || item?.preview || (Array.isArray(item?.lines) ? item.lines.join('\n') : '')) || ''
151
- cards.push({
152
- id: `c${index}`,
153
- index,
154
- title: `${filePath.split('/').slice(-2).join('/')}${line}`,
155
- url: filePath.startsWith('file://') ? filePath : `file://${filePath}`,
156
- domain: 'local-seek',
157
- source: 'local-seek',
158
- snippet,
159
- verifiedText: '',
160
- verified: true,
161
- credibility: 1,
162
- publishedAt: item?.mtime || '',
163
- })
164
- if (cards.length >= 16) break
165
- }
166
- return cards
167
- }
168
-
169
95
  function readEgoSearchStatus() {
170
96
  const statePath = process.env.EGO_SEARCH_STATE || join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'ego-search.json')
171
97
  try {
@@ -178,7 +104,7 @@ function readEgoSearchStatus() {
178
104
 
179
105
  function readBreakerSummary() {
180
106
  try {
181
- const raw = JSON.parse(readFileSync(BREAKER_FILE, 'utf8'))
107
+ const raw = JSON.parse(readFileSync(breakerFilePath(), 'utf8'))
182
108
  const engines = raw?.engines && typeof raw.engines === 'object' ? raw.engines : {}
183
109
  const tripped = []
184
110
  let total = 0
@@ -201,324 +127,25 @@ function readBreakerSummary() {
201
127
  }
202
128
  }
203
129
 
204
- function buildEvidenceContext(cards, maxChars = 14000) {
205
- const lines = []
206
- let used = 0
207
- for (const c of cards) {
208
- const body = c.verifiedText || c.snippet || '(无摘要)'
209
- const block = [
210
- `[${c.index}] 标题:${c.title}`,
211
- `来源:${c.source} (${c.domain})${c.publishedAt ? ` · 时间:${c.publishedAt}` : ''}${c.verified ? ' · [已核验正文]' : ''}`,
212
- `链接:${c.url}`,
213
- `内容:${body.slice(0, 900)}`,
214
- ].join('\n')
215
- if (used + block.length > maxChars) break
216
- lines.push(block)
217
- used += block.length
218
- }
219
- return lines.join('\n\n')
220
- }
221
-
222
- function buildFallbackSummary(query, mode, cards) {
223
- const label = MODE_LABELS[mode] || '全网综合'
224
- if (cards.length === 0) {
225
- return `### 未检索到相关结果\n\n针对「${query}」在 **${label}** 模式下未命中有效网页结果,建议精简关键词或点击右上角「强制刷新」重试。`
226
- }
227
- const rows = cards.slice(0, 8).map((c) => {
228
- const text = (c.verifiedText || c.snippet || '').slice(0, 180).replace(/\n+/g, ' ')
229
- return `- **${c.title}** [${c.index}](${c.domain || c.source})\n ${text || '点击右侧卡片查看原文'}`
230
- })
231
- return `### ${label} · 聚合检索结果(零模型直出模式)\n\n当前宿主未配置可用默认模型,已为你整理最相关的 ${cards.length} 条多源证据,可直接在右侧核对原文:\n\n${rows.join('\n\n')}`
232
- }
233
-
234
- async function runArgoCli(args, { env = {}, stdin = null, timeoutMs = 30000, signal = null } = {}) {
235
- const extraPath = ['/opt/homebrew/bin', '/usr/local/bin', join(homedir(), '.local', 'bin')].join(':')
236
- const basePath = env.PATH || process.env.PATH || ''
237
- const mergedPath = basePath ? `${extraPath}:${basePath}` : extraPath
238
- return new Promise((resolve, reject) => {
239
- if (signal?.aborted) { reject(new Error('aborted')); return }
240
- const child = spawn(ARGO_BIN, args, {
241
- env: { ...process.env, ...env, PATH: mergedPath },
242
- stdio: ['pipe', 'pipe', 'pipe'],
243
- })
244
- const out = []
245
- const err = []
246
- const timer = setTimeout(() => {
247
- child.kill('SIGTERM')
248
- reject(new Error(`argo ${args[0] || ''} timeout (${timeoutMs}ms)`))
249
- }, timeoutMs)
250
- const onAbort = () => {
251
- clearTimeout(timer)
252
- child.kill('SIGTERM')
253
- reject(new Error('aborted'))
254
- }
255
- signal?.addEventListener('abort', onAbort, { once: true })
256
- child.stdout.on('data', d => out.push(d))
257
- child.stderr.on('data', d => err.push(d))
258
- child.on('error', (e) => {
259
- clearTimeout(timer)
260
- signal?.removeEventListener('abort', onAbort)
261
- reject(e)
262
- })
263
- child.on('close', (code) => {
264
- clearTimeout(timer)
265
- signal?.removeEventListener('abort', onAbort)
266
- const text = Buffer.concat(out).toString('utf8').trim()
267
- if (code !== 0 && !text) {
268
- reject(new Error(Buffer.concat(err).toString('utf8').trim() || `argo exit ${code}`))
269
- return
270
- }
271
- try {
272
- resolve(JSON.parse(text || '{}'))
273
- } catch {
274
- reject(new Error(`invalid json from argo ${args[0] || ''}`))
275
- }
276
- })
277
- if (stdin !== null && stdin !== undefined) {
278
- child.stdin.end(typeof stdin === 'string' ? stdin : JSON.stringify(stdin))
279
- } else {
280
- child.stdin.end()
281
- }
282
- })
283
- }
284
-
285
- function buildSearchCliArgs(query, mode, refresh = false, overrides = {}) {
286
- const spec = MODE_SPECS[mode] || MODE_SPECS.general
287
- const merged = { ...spec.searchArgs, ...overrides }
288
- const args = ['search', query, '--json', '--envelope']
289
- if (merged.max_results) args.push('-n', String(merged.max_results))
290
- if (merged.depth) args.push('--depth', String(merged.depth))
291
- if (merged.mode) args.push('--mode', String(merged.mode))
292
- if (merged.domain) args.push('--domain', String(merged.domain))
293
- if (merged.since) args.push('--since', String(merged.since))
294
- if (merged.sort) args.push('--sort', String(merged.sort))
295
- if (merged.verify) args.push('--verify', String(merged.verify))
296
- if (refresh) args.push('--no-cache')
297
- return args
298
- }
299
-
300
- function mergeDedupCards(lists, maxCards = 16) {
301
- const seen = new Set()
302
- const merged = []
303
- for (const list of lists) {
304
- for (const card of list || []) {
305
- if (!card?.url || seen.has(card.url)) continue
306
- seen.add(card.url)
307
- merged.push({ ...card, id: `c${merged.length + 1}`, index: merged.length + 1 })
308
- if (merged.length >= maxCards) return merged
309
- }
310
- }
311
- return merged
312
- }
313
-
314
- async function callLocalSeek(config, env, query, maxResults = 16, signal) {
315
- const searchPath = config?.localSearchPath || process.env.ARGO_LOCAL_SEARCH_PATH || join(homedir(), 'Documents')
316
- try {
317
- const payload = await runArgoCli(
318
- ['seek', query, '--path', searchPath, '--json', '--max', String(Math.min(20, Math.max(1, maxResults)))],
319
- { env, timeoutMs: 15000, signal },
320
- )
321
- return { payload, cards: normalizeLocalCards(payload) }
322
- } catch (err) {
323
- return { payload: { errors: [String(err?.message ?? err)] }, cards: [] }
324
- }
325
- }
326
-
327
- async function callArgoSearch(config, env, query, mode, refresh, signal, tracks = null) {
328
- if (mode === 'local') {
329
- return callLocalSeek(config, env, query, MODE_SPECS.local.searchArgs.max_results, signal)
330
- }
331
-
332
- const timeoutMs = mode === 'research'
333
- ? Math.max(config.searchTimeoutMs ?? 60000, 90000)
334
- : (config.searchTimeoutMs ?? DEFAULTS.searchTimeoutMs)
335
-
336
- if (mode === 'research' && Array.isArray(tracks) && tracks.length > 1) {
337
- const trackRuns = await boundedMap(tracks, 3, async (track) => {
338
- const cliArgs = buildSearchCliArgs(track.question || query, 'research', refresh, { max_results: 10, verify: 3 })
339
- const payload = await runArgoCli(cliArgs, { env, timeoutMs, signal }).catch(() => ({}))
340
- return { payload, cards: normalizeCandidates(payload) }
341
- })
342
- return {
343
- payload: trackRuns[0]?.payload || {},
344
- cards: mergeDedupCards(trackRuns.map(r => r.cards), 16),
345
- }
346
- }
347
-
348
- const primaryTask = runArgoCli(buildSearchCliArgs(query, mode, refresh), { env, timeoutMs, signal })
349
- .then(payload => ({ payload, cards: normalizeCandidates(payload) }))
350
-
351
- // 热点分析与插件评测并行补充社区/社交域召回,避免单靠网页引擎错过一手讨论
352
- const socialTask = MODE_SPECS[mode]?.socialSupplement
353
- ? runArgoCli(buildSearchCliArgs(query, 'general', refresh, { domain: 'social', max_results: 6, verify: 0 }), { env, timeoutMs: Math.min(timeoutMs, 15000), signal })
354
- .then(payload => normalizeCandidates(payload))
355
- .catch(() => [])
356
- : Promise.resolve([])
357
-
358
- const [primary, socialCards] = await Promise.all([primaryTask, socialTask])
359
- let combined = mergeDedupCards([primary.cards, socialCards], 16)
360
-
361
- if (mode === 'plugin' && combined.length < 6) {
362
- const fallbackPayload = await runArgoCli(
363
- buildSearchCliArgs(`${query} 评测 替代`, 'general', refresh, { verify: 2 }),
364
- { env, timeoutMs, signal },
365
- ).catch(() => ({}))
366
- combined = mergeDedupCards([combined, normalizeCandidates(fallbackPayload)], 16)
367
- }
368
-
369
- return { payload: primary.payload, cards: combined }
370
- }
371
-
372
- async function runClarifyIfShort(query, mode, env, signal) {
373
- if (mode === 'local' || query.length > 18) return null
374
- try {
375
- const data = await runArgoCli(['clarify', query, '--json'], { env, timeoutMs: 3000, signal })
376
- if (!data || (!data.ambiguities?.length && !data.routing?.explanation)) return null
377
- return {
378
- ambiguities: data.ambiguities || [],
379
- explanation: data.routing?.explanation || '',
380
- recommendedStrategy: data.recommended_strategy || '',
381
- }
382
- } catch {
383
- return null
384
- }
385
- }
386
-
387
- async function runEvidenceScoring(query, cards, env, signal) {
388
- if (!cards.length) return { cards, evidenceSummary: null }
389
- try {
390
- const payload = await runArgoCli(
391
- ['evidence', query],
392
- {
393
- env,
394
- stdin: {
395
- results: cards.map(c => ({
396
- title: c.title,
397
- url: c.url,
398
- source: c.source,
399
- snippet: c.verifiedText || c.snippet,
400
- published_at: c.publishedAt,
401
- })),
402
- },
403
- timeoutMs: 5000,
404
- signal,
405
- },
406
- )
407
- const scored = Array.isArray(payload?.results) ? payload.results : []
408
- const enriched = cards.map((c, idx) => {
409
- const ev = scored[idx]?.credibility
410
- if (!ev) return c
411
- return {
412
- ...c,
413
- credibility: typeof ev.final === 'number' ? ev.final : c.credibility,
414
- authorityTier: ev.authority?.tier || null,
415
- authorityReason: ev.authority?.reason || '',
416
- }
417
- })
418
- return {
419
- cards: enriched,
420
- evidenceSummary: {
421
- crossValidation: payload?.cross_validation || null,
422
- summary: payload?.summary || null,
423
- },
424
- }
425
- } catch {
426
- return { cards, evidenceSummary: null }
427
- }
428
- }
429
-
430
- async function streamLlmAnswer(ctx, { system, messages, maxTokens, signal, onDelta }) {
431
- const llm = ctx.get?.('llm')
432
- const modelService = ctx.get?.('agentDefaultModel')
433
- if (!llm || !modelService) return { ok: false, reason: 'no_model' }
434
-
435
- let selection
436
- try {
437
- selection = modelService.currentSelection?.()
438
- } catch {
439
- selection = null
440
- }
441
- if (!selection?.provider || !selection?.model) {
442
- return { ok: false, reason: 'no_model' }
443
- }
444
-
445
- let text = ''
446
- let usage = null
447
- let finish = null
448
- try {
449
- const stream = llm.stream({
450
- provider: selection.provider,
451
- model: selection.model,
452
- maxTokens,
453
- signal,
454
- system,
455
- messages,
456
- })
457
- for await (const chunk of stream) {
458
- if (signal?.aborted) break
459
- if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') {
460
- text += chunk.text
461
- onDelta(chunk.text)
462
- } else if (chunk?.type === 'usage') {
463
- usage = chunk.usage
464
- } else if (chunk?.type === 'finish') {
465
- finish = chunk.reason
466
- } else if (chunk?.type === 'error') {
467
- const msg = chunk.error?.message || chunk.message || 'model stream error'
468
- return { ok: false, reason: 'error', message: String(msg), text, model: `${selection.provider}/${selection.model}` }
469
- }
470
- }
471
- if (finish && finish.kind !== 'stop') {
472
- const msg = finish.failure?.message || finish.failure?.code || `finish=${finish.kind}`
473
- console.warn(`[argo-workbench] llm finish=${finish.kind} model=${selection.provider}/${selection.model} msg=${msg}`)
474
- return { ok: false, reason: finish.kind, message: String(msg), text, usage, finish, model: `${selection.provider}/${selection.model}` }
475
- }
476
- return { ok: true, text, usage, finish, model: `${selection.provider}/${selection.model}` }
477
- } catch (err) {
478
- return { ok: false, reason: err?.name === 'AbortError' ? 'aborted' : 'error', message: String(err?.message ?? err), text }
479
- }
480
- }
481
-
482
- function extractCitations(text, cards) {
483
- const used = new Set()
484
- const re = /\[(\d+)\]/g
485
- let m
486
- while ((m = re.exec(text)) !== null) {
487
- const n = Number(m[1])
488
- if (n >= 1 && n <= cards.length) used.add(n)
489
- }
490
- return {
491
- citedIndices: [...used].sort((a, b) => a - b),
492
- totalCards: cards.length,
493
- }
494
- }
495
-
496
- function loadWatches() {
497
- try {
498
- const raw = readFileSync(WATCH_STORE_FILE, 'utf8')
499
- const parsed = JSON.parse(raw)
500
- return Array.isArray(parsed) ? parsed : []
501
- } catch {
502
- return []
503
- }
504
- }
505
-
506
- function saveWatches(items) {
507
- try {
508
- mkdirSync(dirname(WATCH_STORE_FILE), { recursive: true })
509
- const tmp = `${WATCH_STORE_FILE}.tmp.${process.pid}`
510
- writeFileSync(tmp, JSON.stringify(items, null, 2), 'utf8')
511
- renameSync(tmp, WATCH_STORE_FILE)
512
- } catch { /* ignore */ }
513
- }
514
-
515
- export function createWorkbenchHandler(ctx, config, getCredentials) {
130
+ export function createWorkbenchHandler(ctx, config, getCredentials, options = {}) {
131
+ const authVerifyCache = new Map()
132
+ const authVerifyInflight = new Set()
516
133
  const cache = new Map()
517
134
  const inflight = new Map()
518
135
  const diagnostics = []
519
136
  let watches = loadWatches()
520
137
  let watchBusy = false
521
138
 
139
+ // 热榜触发端(inflight 复用 + 全失败 1h 退避)实现在 workbench-suggestions.js
140
+ const hotspotRefresher = createHotspotRefresher({
141
+ buildRunner: async () => {
142
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
143
+ return (cliArgs) => runArgoCli(cliArgs, { env, timeoutMs: 12000 })
144
+ },
145
+ })
146
+ const triggerDailyHotspotRefresh = hotspotRefresher.trigger
147
+ const hotspotRetryDue = hotspotRefresher.retryDue
148
+
522
149
  const executeWatch = async (watch) => {
523
150
  const started = Date.now()
524
151
  const credentials = typeof getCredentials === 'function' ? getCredentials() : undefined
@@ -534,11 +161,10 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
534
161
  role: 'user',
535
162
  content: [{ type: 'text', text: `定时追踪任务:${watch.query}\n\n最新检索证据:\n\n${evidence}\n\n请用简明结构概括最新动态,并在句末标注 [1]、[2] 引用编号。` }],
536
163
  }],
537
- maxTokens: 1800,
538
164
  signal: AbortSignal.timeout(35000),
539
165
  onDelta: () => {},
540
166
  })
541
- summary = llmRes.text || buildFallbackSummary(watch.query, watch.mode, cards)
167
+ summary = llmRes.text || buildFallbackSummary(watch.query, watch.mode, cards, llmRes)
542
168
  } else {
543
169
  summary = buildFallbackSummary(watch.query, watch.mode, cards)
544
170
  }
@@ -554,17 +180,34 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
554
180
  watch.nextRunAt = new Date(Date.now() + watch.intervalMinutes * 60000).toISOString()
555
181
  watch.lastStatus = `error: ${String(err?.message ?? err)}`
556
182
  }
557
- saveWatches(watches)
183
+ // 按 id upsert 合并写:磁盘是唯一真源,另一宿主对其他 watch 的增删改不被抹掉
184
+ // (旧 saveWatches(watches) 全量覆盖写,2026-11-21 审计 P1)
185
+ const updated = mutateWatches((list) => {
186
+ const idx = list.findIndex(w => w.id === watch.id)
187
+ if (idx >= 0) list[idx] = watch
188
+ else list.unshift(watch)
189
+ return list
190
+ })
191
+ if (Array.isArray(updated)) watches = updated
558
192
  return watch
559
193
  }
560
194
 
561
195
  const timer = setInterval(async () => {
196
+ if (!hotspotRefresher.isBusy() && hotspotRetryDue(loadHotspotStore())) {
197
+ triggerDailyHotspotRefresh()
198
+ }
562
199
  if (watchBusy) return
200
+ // 每 tick 重读磁盘:另一宿主刚增删的 watch 立即可见,不靠 60s 前的内存快照
201
+ watches = loadWatches()
563
202
  const now = Date.now()
564
203
  const due = watches.find(w => w.enabled !== false && (!w.nextRunAt || Date.parse(w.nextRunAt) <= now))
565
204
  if (!due) return
205
+ // 跨宿主执行互斥:单锁串行化全部 watch 执行(最坏 ~80s << 5min stale 阈值),
206
+ // 抢不到说明另一宿主在跑,本轮让路——被让路的 watch 下轮仍 due 会重试
207
+ const execLock = acquireStateFileLock(`${WATCH_STORE_FILE}.exec.lock`)
208
+ if (!execLock) return
566
209
  watchBusy = true
567
- try { await executeWatch(due) } finally { watchBusy = false }
210
+ try { await executeWatch(due) } finally { watchBusy = false; releaseStateFileLock(execLock) }
568
211
  }, 60 * 1000)
569
212
  timer.unref?.()
570
213
 
@@ -597,7 +240,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
597
240
  const path = url.pathname
598
241
 
599
242
  if (path === '/argo/workbench-client.js' && req.method === 'GET') {
600
- const source = readFileSync(CLIENT_FILE, 'utf8')
243
+ const source = readStaticAssetCached(CLIENT_FILE)
601
244
  res.statusCode = 200
602
245
  res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
603
246
  res.setHeader('Cache-Control', 'no-store')
@@ -606,7 +249,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
606
249
  }
607
250
 
608
251
  if (path === '/argo/workbench-md.js' && req.method === 'GET') {
609
- const source = readFileSync(MD_FILE, 'utf8')
252
+ const source = readStaticAssetCached(MD_FILE)
610
253
  res.statusCode = 200
611
254
  res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
612
255
  res.setHeader('Cache-Control', 'no-store')
@@ -614,13 +257,30 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
614
257
  return
615
258
  }
616
259
 
260
+ if (path.startsWith('/argo/api/') && !checkLoopbackAndOrigin(ctx, req)) {
261
+ sendJson(res, 403, { error: 'forbidden_origin' })
262
+ return
263
+ }
264
+
265
+ if (path === '/argo/api/auth-status' && req.method === 'GET') {
266
+ const runCli = options.runAuthCli || (async (cliArgs) => {
267
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
268
+ return runArgoCli(cliArgs, { env, timeoutMs: 8000 })
269
+ })
270
+ const items = await resolveAuthStatusWithBgVerify({
271
+ runCli, verifyCache: authVerifyCache, inflight: authVerifyInflight,
272
+ allowVerify: url.searchParams.get('verify') !== '0',
273
+ })
274
+ sendJson(res, 200, { ok: true, profiles: items })
275
+ return
276
+ }
277
+
617
278
  if (path === '/argo/api/watches' && req.method === 'GET') {
618
279
  sendJson(res, 200, { ok: true, items: watches })
619
280
  return
620
281
  }
621
282
 
622
283
  if (path === '/argo/api/watches' && req.method === 'POST') {
623
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
624
284
  const body = await readJsonBody(req)
625
285
  const query = String(body.query || '').trim()
626
286
  const mode = MODES.has(body.mode) ? body.mode : 'general'
@@ -641,40 +301,56 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
641
301
  lastSummary: '',
642
302
  lastCards: [],
643
303
  }
644
- watches.unshift(item)
645
- if (watches.length > MAX_WATCHES) watches.length = MAX_WATCHES
646
- saveWatches(watches)
304
+ const updatedList = mutateWatches((list) => {
305
+ list.unshift(item)
306
+ if (list.length > MAX_WATCHES) list.length = MAX_WATCHES
307
+ return list
308
+ })
309
+ if (!Array.isArray(updatedList)) { sendJson(res, 409, { error: 'watch_busy' }); return }
310
+ watches = updatedList
647
311
  sendJson(res, 200, { ok: true, item, items: watches })
648
312
  return
649
313
  }
650
314
 
651
315
  if (path === '/argo/api/watches/run' && req.method === 'POST') {
652
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
653
316
  const body = await readJsonBody(req)
317
+ watches = loadWatches()
654
318
  const target = watches.find(w => w.id === body.id)
655
319
  if (!target) { sendJson(res, 404, { error: 'watch_not_found' }); return }
656
- const updated = await executeWatch(target)
657
- sendJson(res, 200, { ok: true, item: updated, items: watches })
320
+ if (watchBusy) { sendJson(res, 409, { error: 'watch_busy' }); return }
321
+ // 与定时器同锁:手动触发与另一宿主的执行互斥
322
+ const execLock = acquireStateFileLock(`${WATCH_STORE_FILE}.exec.lock`)
323
+ if (!execLock) { sendJson(res, 409, { error: 'watch_busy' }); return }
324
+ watchBusy = true
325
+ try {
326
+ const updated = await executeWatch(target)
327
+ sendJson(res, 200, { ok: true, item: updated, items: watches })
328
+ } finally {
329
+ watchBusy = false
330
+ releaseStateFileLock(execLock)
331
+ }
658
332
  return
659
333
  }
660
334
 
661
335
  if (path === '/argo/api/watches' && req.method === 'DELETE') {
662
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
663
336
  const id = url.searchParams.get('id') || ''
664
- watches = watches.filter(w => w.id !== id)
665
- saveWatches(watches)
337
+ const updatedList = mutateWatches((list) => list.filter(w => w.id !== id))
338
+ if (!Array.isArray(updatedList)) { sendJson(res, 409, { error: 'watch_busy' }); return }
339
+ watches = updatedList
666
340
  sendJson(res, 200, { ok: true, items: watches })
667
341
  return
668
342
  }
669
343
 
670
344
  if (path === '/argo/api/health' && req.method === 'GET') {
671
345
  const hasLlm = Boolean(ctx.get?.('llm') && ctx.get?.('agentDefaultModel')?.currentSelection?.()?.model)
346
+ const hs = loadHotspotStore()
672
347
  sendJson(res, 200, {
673
348
  ok: true,
674
349
  modes: Object.entries(MODE_LABELS).map(([id, label]) => ({ id, label })),
675
350
  hasLlm,
676
351
  egoSearch: readEgoSearchStatus(),
677
352
  breaker: readBreakerSummary(),
353
+ hotspotSchedule: { refreshTime: hs.refreshTime, lastRefreshedAt: hs.lastRefreshedAt },
678
354
  })
679
355
  return
680
356
  }
@@ -683,16 +359,51 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
683
359
  const reqMode = MODES.has(url.searchParams.get('mode')) ? url.searchParams.get('mode') : 'general'
684
360
  const lang = url.searchParams.get('lang') || 'zh'
685
361
  const shuffle = url.searchParams.get('shuffle') === '1'
686
- sendJson(res, 200, buildSuggestions(reqMode, lang, shuffle))
362
+ const store = loadHotspotStore()
363
+ if (hotspotRetryDue(store)) triggerDailyHotspotRefresh()
364
+ // 本机模式建议词与 callLocalSeek 同源同路径
365
+ sendJson(res, 200, buildSuggestions(reqMode, lang, shuffle, {
366
+ watches,
367
+ hotspotStore: store,
368
+ cwd: resolveLocalSearchPath(config),
369
+ }))
370
+ return
371
+ }
372
+
373
+ if (path === '/argo/api/suggestions/config' && req.method === 'POST') {
374
+ const body = await readJsonBody(req)
375
+ let store = loadHotspotStore()
376
+ if (body.refreshTime !== undefined) {
377
+ const updated = updateRefreshTime(body.refreshTime)
378
+ if (!updated) { sendJson(res, 400, { error: 'invalid_refresh_time' }); return }
379
+ store = updated
380
+ }
381
+ if (body.refreshNow === true) {
382
+ store = await triggerDailyHotspotRefresh()
383
+ }
384
+ sendJson(res, 200, {
385
+ ok: true,
386
+ refreshTime: store.refreshTime,
387
+ lastRefreshedAt: store.lastRefreshedAt,
388
+ hotspotCount: (store.zh?.length || 0) + (store.en?.length || 0),
389
+ refreshing: hotspotRefresher.isBusy(),
390
+ // 锁被另一宿主占时如实回传 skipped,前端提示「另一宿主刷新中」,
391
+ // 不再拿旧时间戳冒充刚刷过(2026-11-21 审计:假成功边界)
392
+ skipped: store.skipped || null,
393
+ })
687
394
  return
688
395
  }
689
396
 
690
397
  if (path === '/argo/api/ego-search' && req.method === 'POST') {
691
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
692
398
  const body = await readJsonBody(req)
693
399
  const action = body.enabled ? 'enable' : 'disable'
694
400
  await new Promise((resolve) => {
695
- execFile('argo', ['ego-search', action], { timeout: 8000 }, () => resolve())
401
+ execFile(
402
+ resolveArgoBin({ PATH: mergedLaunchdPath() }),
403
+ ['ego-search', action],
404
+ { timeout: 8000, env: { ...process.env, PATH: mergedLaunchdPath() } },
405
+ () => resolve(),
406
+ )
696
407
  })
697
408
  sendJson(res, 200, { ok: true, egoSearch: readEgoSearchStatus() })
698
409
  return
@@ -704,10 +415,6 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
704
415
  }
705
416
 
706
417
  if (path === '/argo/api/stream' && req.method === 'GET') {
707
- if (!checkSameOrigin(ctx, req)) {
708
- sendJson(res, 403, { error: 'forbidden_origin' })
709
- return
710
- }
711
418
  const query = (url.searchParams.get('q') || '').trim()
712
419
  const rawMode = (url.searchParams.get('mode') || 'general').trim()
713
420
  const mode = MODES.has(rawMode) ? rawMode : 'general'
@@ -748,21 +455,26 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
748
455
 
749
456
  let cards
750
457
  let payload
458
+ let trackStats
751
459
  let cached = !refresh ? getCached(cacheKey) : null
752
460
  if (cached) {
753
461
  cards = cached.cards
754
462
  payload = cached.payload
463
+ trackStats = cached.trackStats
755
464
  } else {
756
465
  let pending = !refresh ? inflight.get(cacheKey) : null
757
466
  if (!pending) {
758
- pending = callArgoSearch(config, env, query, mode, refresh, ac.signal, researchTracks)
467
+ // 共享去重任务使用独立 signal,防止客户端 A 断连误杀同 key 并发等待的客户端 B
468
+ const searchSignal = refresh ? ac.signal : new AbortController().signal
469
+ pending = callArgoSearch(config, env, query, mode, refresh, searchSignal, researchTracks)
759
470
  .finally(() => inflight.delete(cacheKey))
760
471
  if (!refresh) inflight.set(cacheKey, pending)
761
472
  }
762
473
  const resData = await pending
763
474
  cards = resData.cards
764
475
  payload = resData.payload
765
- if (cards.length > 0) setCached(cacheKey, { cards, payload })
476
+ trackStats = resData.trackStats
477
+ if (cards.length > 0) setCached(cacheKey, { cards, payload, trackStats })
766
478
  }
767
479
 
768
480
  if (ac.signal.aborted) return
@@ -795,7 +507,6 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
795
507
  const llmRes = await streamLlmAnswer(ctx, {
796
508
  system,
797
509
  messages: [{ role: 'user', content: [{ type: 'text', text: userPrompt }] }],
798
- maxTokens: mode === 'research' ? 6000 : 3500,
799
510
  signal: ac.signal,
800
511
  onDelta: (delta) => sendSse(res, 'answer', { delta }),
801
512
  })
@@ -808,7 +519,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
808
519
  message: `默认模型(${llmRes.model || 'unknown'})暂不可用:${llmRes.message || llmRes.reason},已自动切换为多源聚合直出视图`,
809
520
  })
810
521
  }
811
- finalText = buildFallbackSummary(query, mode, cards)
522
+ finalText = buildFallbackSummary(query, mode, cards, llmRes)
812
523
  sendSse(res, 'answer', { delta: finalText })
813
524
  } else if (!llmRes.ok && llmRes.reason !== 'aborted') {
814
525
  sendSse(res, 'answer-status', {
@@ -820,11 +531,24 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
820
531
  const citations = extractCitations(finalText, cards)
821
532
  sendSse(res, 'citations', citations)
822
533
  if (mode === 'research') {
534
+ const total = (researchTracks || []).length
535
+ // 真实 track 成败统计进门禁;旧缓存条目无 trackStats 时按结果有无推断,
536
+ // 不再恒注入 completedTracks/failedTracks: 0 的假章(2026-11-21 审计)
537
+ const stats = trackStats || {
538
+ total,
539
+ completed: cards.length > 0 ? total : 0,
540
+ failed: 0,
541
+ }
823
542
  const gate = evaluateGates({
824
543
  answer: finalText,
825
544
  sources: cards.map(c => ({ url: c.url, title: c.title, domain: c.domain })),
826
545
  tracks: researchTracks || [],
827
546
  warnings: [],
547
+ stats: {
548
+ sourceCount: cards.length,
549
+ completedTracks: stats.completed,
550
+ failedTracks: stats.failed,
551
+ },
828
552
  })
829
553
  sendSse(res, 'gate', gate)
830
554
  }
@@ -865,14 +589,16 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
865
589
  }
866
590
 
867
591
  if (path === '/argo/api/followup' && req.method === 'POST') {
868
- if (!checkSameOrigin(ctx, req)) {
869
- sendJson(res, 403, { error: 'forbidden_origin' })
870
- return
871
- }
872
592
  const body = await readJsonBody(req)
873
593
  const question = String(body.question || '').trim()
874
- const cards = Array.isArray(body.cards) ? body.cards : []
875
- const history = Array.isArray(body.history) ? body.history : []
594
+ // 元素级过滤:null/非对象条目会在 buildEvidenceContext 与 history
595
+ // 映射处抛 TypeError(2026-11-18 实跑复现 cards:[null] 崩溃链)
596
+ const cards = Array.isArray(body.cards)
597
+ ? body.cards.filter(c => c && typeof c === 'object')
598
+ : []
599
+ const history = Array.isArray(body.history)
600
+ ? body.history.filter(h => h && typeof h === 'object')
601
+ : []
876
602
  const mode = MODES.has(body.mode) ? body.mode : 'general'
877
603
 
878
604
  if (!question) {
@@ -887,38 +613,49 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
887
613
  res.flushHeaders?.()
888
614
 
889
615
  const ac = new AbortController()
890
- req.on('close', () => ac.abort())
616
+ const onClose = () => { if (!res.writableEnded) ac.abort() }
617
+ if (typeof res.on === 'function') res.on('close', onClose)
618
+ else if (typeof req.on === 'function') req.on('close', onClose)
891
619
 
892
- const evidence = buildEvidenceContext(cards)
893
- const messages = [
894
- {
895
- role: 'user',
896
- content: [{ type: 'text', text: `原始问题:${body.query || ''}\n\n已检索证据:\n${evidence}` }],
897
- },
898
- ...history.slice(-6).map(item => ({
899
- role: item.role === 'assistant' ? 'assistant' : 'user',
900
- content: [{ type: 'text', text: String(item.text || '') }],
901
- })),
902
- {
903
- role: 'user',
904
- content: [{ type: 'text', text: `基于上述已检索证据继续追问:${question}\n请继续使用 [1]、[2] 引用编号;若当前证据未覆盖,请明确说明。` }],
905
- },
906
- ]
620
+ try {
621
+ const evidence = buildEvidenceContext(cards)
622
+ const messages = [
623
+ {
624
+ role: 'user',
625
+ content: [{ type: 'text', text: `原始问题:${body.query || ''}\n\n已检索证据:\n${evidence}` }],
626
+ },
627
+ ...history.slice(-6).map(item => ({
628
+ role: item.role === 'assistant' ? 'assistant' : 'user',
629
+ content: [{ type: 'text', text: String(item.text || '') }],
630
+ })),
631
+ {
632
+ role: 'user',
633
+ content: [{ type: 'text', text: `基于上述已检索证据继续追问:${question}\n请继续使用 [1]、[2] 引用编号;若当前证据未覆盖,请明确说明。` }],
634
+ },
635
+ ]
907
636
 
908
- const llmRes = await streamLlmAnswer(ctx, {
909
- system: buildSystemPrompt(mode),
910
- messages,
911
- maxTokens: 2500,
912
- signal: ac.signal,
913
- onDelta: (delta) => sendSse(res, 'answer', { delta }),
914
- })
637
+ const llmRes = await streamLlmAnswer(ctx, {
638
+ system: buildSystemPrompt(mode),
639
+ messages,
640
+ signal: ac.signal,
641
+ onDelta: (delta) => sendSse(res, 'answer', { delta }),
642
+ })
915
643
 
916
- if (!llmRes.ok && llmRes.reason === 'no_model') {
917
- sendSse(res, 'answer', { delta: '当前宿主未配置默认模型,无法进行多轮追问推理。' })
644
+ if (!llmRes.ok && !llmRes.text) {
645
+ const msg = llmRes.reason === 'no_model'
646
+ ? '当前宿主未配置默认模型,无法进行多轮追问推理。'
647
+ : `默认模型(${llmRes.model || 'unknown'})调用未完成:${llmRes.message || llmRes.reason}`
648
+ sendSse(res, 'answer', { delta: msg })
649
+ }
650
+ sendSse(res, 'citations', extractCitations(llmRes.text || '', cards))
651
+ sendSse(res, 'done', { ok: llmRes.ok })
652
+ } catch (err) {
653
+ if (!ac.signal.aborted) {
654
+ sendSse(res, 'failure', { message: String(err?.message ?? err) })
655
+ }
656
+ } finally {
657
+ if (!res.writableEnded) res.end()
918
658
  }
919
- sendSse(res, 'citations', extractCitations(llmRes.text || '', cards))
920
- sendSse(res, 'done', { ok: llmRes.ok })
921
- if (!res.writableEnded) res.end()
922
659
  return
923
660
  }
924
661
 
@@ -931,7 +668,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
931
668
  return workbenchHandler
932
669
  }
933
670
 
934
- export function registerArgoWorkbench(ctx, config, getCredentials) {
671
+ export function registerArgoWorkbench(ctx, config, getCredentials, options = {}) {
935
672
  const attach = (targetCtx) => {
936
673
  let webServer
937
674
  try {
@@ -940,7 +677,7 @@ export function registerArgoWorkbench(ctx, config, getCredentials) {
940
677
  return undefined
941
678
  }
942
679
  if (!webServer || typeof webServer.register !== 'function') return undefined
943
- const handler = createWorkbenchHandler(targetCtx, config, getCredentials)
680
+ const handler = createWorkbenchHandler(targetCtx, config, getCredentials, options)
944
681
  const off = webServer.register({ kind: 'prefix', path: '/argo', handler })
945
682
  return () => {
946
683
  handler.dispose?.()