argo-search 2.16.0 → 2.18.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 (126) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.es.md +15 -5
  3. package/README.ja.md +15 -5
  4. package/README.ko.md +15 -5
  5. package/README.md +16 -6
  6. package/README.zh.md +16 -6
  7. package/SKILL.md +12 -11
  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 +121 -18
  13. package/backends/engine_registry.yaml +23 -0
  14. package/backends/env_passthrough.txt +2 -0
  15. package/backends/quota_profiles.json +20 -0
  16. package/bin/argo +78 -12
  17. package/docs/CHANGELOG.md +35 -1
  18. package/docs/COMMIT_STANDARD.md +12 -2
  19. package/docs/ENGINE_CATALOG.md +36 -33
  20. package/docs/RELEASE_NOTES_v2.17.0.md +66 -0
  21. package/docs/RELEASE_NOTES_v2.18.0.md +87 -0
  22. package/docs/RELEASING.md +2 -2
  23. package/engines/specs/crossref.yaml +2 -0
  24. package/engines/specs/hackernews.yaml +2 -0
  25. package/engines/specs/helve.yaml +49 -0
  26. package/engines/specs/hf_papers.yaml +2 -0
  27. package/engines/specs/openalex.yaml +9 -2
  28. package/engines/specs/twitter_cli.yaml +17 -0
  29. package/engines/specs/twitter_syndication.yaml +2 -3
  30. package/package.json +3 -1
  31. package/packages/dsh-plugin/README.md +5 -2
  32. package/packages/dsh-plugin/cordis.patch.yml +4 -1
  33. package/packages/dsh-plugin/dsh/client.js +57 -63
  34. package/packages/dsh-plugin/dsh/diagnostics.js +25 -4
  35. package/packages/dsh-plugin/dsh/index.js +109 -21
  36. package/packages/dsh-plugin/dsh/native-tools.mjs +10 -0
  37. package/packages/dsh-plugin/dsh/route-guard.js +95 -0
  38. package/packages/dsh-plugin/dsh/runner.js +49 -6
  39. package/packages/dsh-plugin/dsh/wide-research.js +20 -18
  40. package/packages/dsh-plugin/dsh/workbench-client.js +119 -20
  41. package/packages/dsh-plugin/dsh/workbench-io.js +182 -0
  42. package/packages/dsh-plugin/dsh/workbench-search.js +445 -0
  43. package/packages/dsh-plugin/dsh/workbench-suggestions.js +387 -75
  44. package/packages/dsh-plugin/dsh/workbench.js +277 -497
  45. package/packages/dsh-plugin/package.json +4 -3
  46. package/packages/dsh-plugin/scripts/sync-local.mjs +4 -2
  47. package/packages/dsh-plugin/scripts/sync-local.sh +4 -2
  48. package/packages/dsh-plugin/test/client.test.js +26 -0
  49. package/packages/dsh-plugin/test/diagnostics.test.js +5 -2
  50. package/packages/dsh-plugin/test/index.test.js +150 -1
  51. package/packages/dsh-plugin/test/workbench-concurrency.test.js +96 -0
  52. package/packages/dsh-plugin/test/workbench.test.js +422 -9
  53. package/scripts/adaptive.py +13 -11
  54. package/scripts/affected_tests.py +324 -0
  55. package/scripts/badcase_ledger.py +93 -2
  56. package/scripts/browser_auth.py +178 -4
  57. package/scripts/cache.py +68 -69
  58. package/scripts/check_commit_report.py +59 -9
  59. package/scripts/chrome_cdp.py +71 -0
  60. package/scripts/circuit_breaker.py +77 -12
  61. package/scripts/cli_io.py +8 -3
  62. package/scripts/config_cache.py +4 -3
  63. package/scripts/daemon.py +9 -2
  64. package/scripts/engine_add.py +45 -0
  65. package/scripts/engine_dispatch.py +27 -47
  66. package/scripts/engine_failure.py +33 -0
  67. package/scripts/engine_families.py +1 -0
  68. package/scripts/engine_fingerprint.py +114 -0
  69. package/scripts/engine_health.py +130 -0
  70. package/scripts/engine_states.py +54 -4
  71. package/scripts/engines.py +2 -0
  72. package/scripts/engines_base.py +19 -44
  73. package/scripts/engines_builders_intl.py +20 -94
  74. package/scripts/engines_builders_search.py +19 -8
  75. package/scripts/engines_builders_tech.py +16 -16
  76. package/scripts/engines_fields.py +23 -0
  77. package/scripts/engines_twitter_cli.py +182 -0
  78. package/scripts/evidence_grounding.py +182 -0
  79. package/scripts/fetch_browser.py +25 -10
  80. package/scripts/fetch_cli_output.py +75 -0
  81. package/scripts/fetch_dispatch.py +248 -0
  82. package/scripts/fetch_quality.py +11 -0
  83. package/scripts/fetch_v3.py +48 -114
  84. package/scripts/gate_manifest_check.py +75 -0
  85. package/scripts/gen_readme_art.py +264 -0
  86. package/scripts/intent_router.py +224 -0
  87. package/scripts/mcp_compact.py +3 -0
  88. package/scripts/mcp_handlers.py +24 -4
  89. package/scripts/mcp_tools.py +2 -0
  90. package/scripts/mcp_transport.py +24 -5
  91. package/scripts/mcp_warm.py +15 -11
  92. package/scripts/numeric_verify.py +9 -0
  93. package/scripts/output_transparency.py +10 -0
  94. package/scripts/pre-commit +65 -8
  95. package/scripts/query_operators.py +229 -1
  96. package/scripts/quota.py +19 -37
  97. package/scripts/release.py +16 -1
  98. package/scripts/release_check.py +1 -2
  99. package/scripts/research_gates.py +85 -1
  100. package/scripts/research_notes.py +52 -5
  101. package/scripts/retry_policy.py +17 -3
  102. package/scripts/route_combo.py +21 -4
  103. package/scripts/search.py +29 -29
  104. package/scripts/search_cli.py +104 -8
  105. package/scripts/search_output.py +4 -1
  106. package/scripts/social_research.py +8 -6
  107. package/scripts/source_discovery.py +611 -0
  108. package/scripts/sync_backends.py +45 -0
  109. package/scripts/time_utils.py +28 -0
  110. package/scripts/twitter_single_read.py +107 -0
  111. package/scripts/x_keyword_route.py +138 -0
  112. package/scripts/x_search.py +24 -33
  113. package/scripts/zhihu_answer_body.py +96 -0
  114. package/scripts/zhihu_answer_fetch.py +66 -0
  115. package/scripts/zhihu_answer_lookup.py +138 -0
  116. package/sub-skills/ego-search/README.md +9 -0
  117. package/sub-skills/ego-search/scripts/ego_search.py +182 -15
  118. package/sub-skills/ego-search/scripts/pacing.py +291 -0
  119. package/sub-skills/ego-search/scripts/quality.py +262 -6
  120. package/sub-skills/ego-search/scripts/runtime.py +7 -1
  121. package/sub-skills/ego-search/scripts/site_profiles.py +157 -0
  122. package/sub-skills/ego-search/scripts/webbridge_adapter.py +7 -1
  123. package/sub-skills/local-seek/SKILL.md +3 -1
  124. package/sub-skills/local-seek/scripts/seek.py +80 -109
  125. package/sub-skills/local-seek/scripts/seek_git.py +65 -0
  126. package/sub-skills/local-seek/scripts/seek_inspect.py +242 -0
@@ -6,50 +6,71 @@
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
+ inspectLocalFile,
23
+ MODES,
24
+ MODE_LABELS,
25
+ resolveLocalSearchPath,
26
+ runClarifyIfShort,
27
+ runEvidenceScoring,
28
+ saveNoteStudy,
29
+ streamLlmAnswer,
30
+ } from './workbench-search.js'
31
+ import {
32
+ buildSuggestions,
33
+ createHotspotRefresher,
34
+ loadHotspotStore,
35
+ updateRefreshTime,
36
+ } from './workbench-suggestions.js'
37
+ import { checkLoopbackAndOrigin, resolveAuthStatusWithBgVerify } from './route-guard.js'
38
+ import {
39
+ acquireStateFileLock,
40
+ breakerFilePath,
41
+ loadWatches,
42
+ mergedLaunchdPath,
43
+ mutateWatches,
44
+ readStaticAssetCached,
45
+ releaseStateFileLock,
46
+ resolveArgoBin,
47
+ runArgoCli,
48
+ WATCH_STORE_FILE,
49
+ } from './workbench-io.js'
50
+
51
+ // 供既有测试与外部调用方沿旧入口取用(真源在 workbench-search.js)
52
+ export { buildSearchCliArgs, summarizeTrackRuns } from './workbench-search.js'
18
53
 
19
54
  const HERE = dirname(fileURLToPath(import.meta.url))
20
- const ARGO_BIN = join(HERE, '..', '..', '..', 'bin', 'argo')
21
55
  const CLIENT_FILE = join(HERE, 'workbench-client.js')
22
56
  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
57
 
26
58
  const CACHE_TTL_MS = 5 * 60 * 1000
27
59
  const MAX_CACHE_ENTRIES = 32
28
60
  const MAX_DIAGNOSTICS = 20
29
61
  const MAX_WATCHES = 20
30
62
 
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
63
  function sendJson(res, status, data) {
52
64
  if (res.writableEnded) return
65
+ if (res.headersSent) {
66
+ // SSE 头已 flush 后再 setHeader 会抛 ERR_HTTP_HEADERS_SENT(2026-11-18
67
+ // 实跑复现:followup 传 cards:[null] 在 flushHeaders 后抛 TypeError,
68
+ // 落到这里二次抛 → 响应悬挂 + 异常逃出 async handler)。改发 SSE
69
+ // failure 事件收尾,让客户端与连接都能干净结束。
70
+ sendSse(res, 'failure', data)
71
+ if (!res.writableEnded) res.end()
72
+ return
73
+ }
53
74
  res.statusCode = status
54
75
  res.setHeader('Content-Type', 'application/json; charset=utf-8')
55
76
  res.setHeader('Cache-Control', 'no-store')
@@ -61,19 +82,6 @@ function sendSse(res, event, data) {
61
82
  res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
62
83
  }
63
84
 
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
85
  async function readJsonBody(req, maxBytes = 256 * 1024) {
78
86
  const chunks = []
79
87
  let size = 0
@@ -86,86 +94,6 @@ async function readJsonBody(req, maxBytes = 256 * 1024) {
86
94
  return raw ? JSON.parse(raw) : {}
87
95
  }
88
96
 
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
97
  function readEgoSearchStatus() {
170
98
  const statePath = process.env.EGO_SEARCH_STATE || join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'ego-search.json')
171
99
  try {
@@ -178,7 +106,7 @@ function readEgoSearchStatus() {
178
106
 
179
107
  function readBreakerSummary() {
180
108
  try {
181
- const raw = JSON.parse(readFileSync(BREAKER_FILE, 'utf8'))
109
+ const raw = JSON.parse(readFileSync(breakerFilePath(), 'utf8'))
182
110
  const engines = raw?.engines && typeof raw.engines === 'object' ? raw.engines : {}
183
111
  const tripped = []
184
112
  let total = 0
@@ -201,324 +129,25 @@ function readBreakerSummary() {
201
129
  }
202
130
  }
203
131
 
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) {
132
+ export function createWorkbenchHandler(ctx, config, getCredentials, options = {}) {
133
+ const authVerifyCache = new Map()
134
+ const authVerifyInflight = new Set()
516
135
  const cache = new Map()
517
136
  const inflight = new Map()
518
137
  const diagnostics = []
519
138
  let watches = loadWatches()
520
139
  let watchBusy = false
521
140
 
141
+ // 热榜触发端(inflight 复用 + 全失败 1h 退避)实现在 workbench-suggestions.js
142
+ const hotspotRefresher = createHotspotRefresher({
143
+ buildRunner: async () => {
144
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
145
+ return (cliArgs) => runArgoCli(cliArgs, { env, timeoutMs: 12000 })
146
+ },
147
+ })
148
+ const triggerDailyHotspotRefresh = hotspotRefresher.trigger
149
+ const hotspotRetryDue = hotspotRefresher.retryDue
150
+
522
151
  const executeWatch = async (watch) => {
523
152
  const started = Date.now()
524
153
  const credentials = typeof getCredentials === 'function' ? getCredentials() : undefined
@@ -534,11 +163,10 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
534
163
  role: 'user',
535
164
  content: [{ type: 'text', text: `定时追踪任务:${watch.query}\n\n最新检索证据:\n\n${evidence}\n\n请用简明结构概括最新动态,并在句末标注 [1]、[2] 引用编号。` }],
536
165
  }],
537
- maxTokens: 1800,
538
166
  signal: AbortSignal.timeout(35000),
539
167
  onDelta: () => {},
540
168
  })
541
- summary = llmRes.text || buildFallbackSummary(watch.query, watch.mode, cards)
169
+ summary = llmRes.text || buildFallbackSummary(watch.query, watch.mode, cards, llmRes)
542
170
  } else {
543
171
  summary = buildFallbackSummary(watch.query, watch.mode, cards)
544
172
  }
@@ -554,17 +182,34 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
554
182
  watch.nextRunAt = new Date(Date.now() + watch.intervalMinutes * 60000).toISOString()
555
183
  watch.lastStatus = `error: ${String(err?.message ?? err)}`
556
184
  }
557
- saveWatches(watches)
185
+ // 按 id upsert 合并写:磁盘是唯一真源,另一宿主对其他 watch 的增删改不被抹掉
186
+ // (旧 saveWatches(watches) 全量覆盖写,2026-11-21 审计 P1)
187
+ const updated = mutateWatches((list) => {
188
+ const idx = list.findIndex(w => w.id === watch.id)
189
+ if (idx >= 0) list[idx] = watch
190
+ else list.unshift(watch)
191
+ return list
192
+ })
193
+ if (Array.isArray(updated)) watches = updated
558
194
  return watch
559
195
  }
560
196
 
561
197
  const timer = setInterval(async () => {
198
+ if (!hotspotRefresher.isBusy() && hotspotRetryDue(loadHotspotStore())) {
199
+ triggerDailyHotspotRefresh()
200
+ }
562
201
  if (watchBusy) return
202
+ // 每 tick 重读磁盘:另一宿主刚增删的 watch 立即可见,不靠 60s 前的内存快照
203
+ watches = loadWatches()
563
204
  const now = Date.now()
564
205
  const due = watches.find(w => w.enabled !== false && (!w.nextRunAt || Date.parse(w.nextRunAt) <= now))
565
206
  if (!due) return
207
+ // 跨宿主执行互斥:单锁串行化全部 watch 执行(最坏 ~80s << 5min stale 阈值),
208
+ // 抢不到说明另一宿主在跑,本轮让路——被让路的 watch 下轮仍 due 会重试
209
+ const execLock = acquireStateFileLock(`${WATCH_STORE_FILE}.exec.lock`)
210
+ if (!execLock) return
566
211
  watchBusy = true
567
- try { await executeWatch(due) } finally { watchBusy = false }
212
+ try { await executeWatch(due) } finally { watchBusy = false; releaseStateFileLock(execLock) }
568
213
  }, 60 * 1000)
569
214
  timer.unref?.()
570
215
 
@@ -597,7 +242,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
597
242
  const path = url.pathname
598
243
 
599
244
  if (path === '/argo/workbench-client.js' && req.method === 'GET') {
600
- const source = readFileSync(CLIENT_FILE, 'utf8')
245
+ const source = readStaticAssetCached(CLIENT_FILE)
601
246
  res.statusCode = 200
602
247
  res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
603
248
  res.setHeader('Cache-Control', 'no-store')
@@ -606,7 +251,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
606
251
  }
607
252
 
608
253
  if (path === '/argo/workbench-md.js' && req.method === 'GET') {
609
- const source = readFileSync(MD_FILE, 'utf8')
254
+ const source = readStaticAssetCached(MD_FILE)
610
255
  res.statusCode = 200
611
256
  res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
612
257
  res.setHeader('Cache-Control', 'no-store')
@@ -614,13 +259,30 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
614
259
  return
615
260
  }
616
261
 
262
+ if (path.startsWith('/argo/api/') && !checkLoopbackAndOrigin(ctx, req)) {
263
+ sendJson(res, 403, { error: 'forbidden_origin' })
264
+ return
265
+ }
266
+
267
+ if (path === '/argo/api/auth-status' && req.method === 'GET') {
268
+ const runCli = options.runAuthCli || (async (cliArgs) => {
269
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
270
+ return runArgoCli(cliArgs, { env, timeoutMs: 8000 })
271
+ })
272
+ const items = await resolveAuthStatusWithBgVerify({
273
+ runCli, verifyCache: authVerifyCache, inflight: authVerifyInflight,
274
+ allowVerify: url.searchParams.get('verify') !== '0',
275
+ })
276
+ sendJson(res, 200, { ok: true, profiles: items })
277
+ return
278
+ }
279
+
617
280
  if (path === '/argo/api/watches' && req.method === 'GET') {
618
281
  sendJson(res, 200, { ok: true, items: watches })
619
282
  return
620
283
  }
621
284
 
622
285
  if (path === '/argo/api/watches' && req.method === 'POST') {
623
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
624
286
  const body = await readJsonBody(req)
625
287
  const query = String(body.query || '').trim()
626
288
  const mode = MODES.has(body.mode) ? body.mode : 'general'
@@ -641,40 +303,95 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
641
303
  lastSummary: '',
642
304
  lastCards: [],
643
305
  }
644
- watches.unshift(item)
645
- if (watches.length > MAX_WATCHES) watches.length = MAX_WATCHES
646
- saveWatches(watches)
306
+ const updatedList = mutateWatches((list) => {
307
+ list.unshift(item)
308
+ if (list.length > MAX_WATCHES) list.length = MAX_WATCHES
309
+ return list
310
+ })
311
+ if (!Array.isArray(updatedList)) { sendJson(res, 409, { error: 'watch_busy' }); return }
312
+ watches = updatedList
647
313
  sendJson(res, 200, { ok: true, item, items: watches })
648
314
  return
649
315
  }
650
316
 
651
317
  if (path === '/argo/api/watches/run' && req.method === 'POST') {
652
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
653
318
  const body = await readJsonBody(req)
319
+ watches = loadWatches()
654
320
  const target = watches.find(w => w.id === body.id)
655
321
  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 })
322
+ if (watchBusy) { sendJson(res, 409, { error: 'watch_busy' }); return }
323
+ // 与定时器同锁:手动触发与另一宿主的执行互斥
324
+ const execLock = acquireStateFileLock(`${WATCH_STORE_FILE}.exec.lock`)
325
+ if (!execLock) { sendJson(res, 409, { error: 'watch_busy' }); return }
326
+ watchBusy = true
327
+ try {
328
+ const updated = await executeWatch(target)
329
+ sendJson(res, 200, { ok: true, item: updated, items: watches })
330
+ } finally {
331
+ watchBusy = false
332
+ releaseStateFileLock(execLock)
333
+ }
658
334
  return
659
335
  }
660
336
 
661
337
  if (path === '/argo/api/watches' && req.method === 'DELETE') {
662
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
663
338
  const id = url.searchParams.get('id') || ''
664
- watches = watches.filter(w => w.id !== id)
665
- saveWatches(watches)
339
+ const updatedList = mutateWatches((list) => list.filter(w => w.id !== id))
340
+ if (!Array.isArray(updatedList)) { sendJson(res, 409, { error: 'watch_busy' }); return }
341
+ watches = updatedList
666
342
  sendJson(res, 200, { ok: true, items: watches })
667
343
  return
668
344
  }
669
345
 
346
+ if (path === '/argo/api/local-inspect' && req.method === 'POST') {
347
+ const body = await readJsonBody(req)
348
+ const filePath = String(body.path || body.filePath || '').trim()
349
+ if (!filePath) { sendJson(res, 400, { error: 'missing_path' }); return }
350
+ try {
351
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
352
+ const out = await inspectLocalFile(env, {
353
+ filePath,
354
+ allowedRoot: resolveLocalSearchPath(config),
355
+ symbol: body.symbol || '',
356
+ lines: body.lines || '',
357
+ runner: options.runInspectCli || runArgoCli,
358
+ })
359
+ const status = out?.error === 'path_outside_root' ? 403 : (out?.ok === false ? 400 : 200)
360
+ sendJson(res, status, out)
361
+ } catch (err) {
362
+ sendJson(res, 500, { ok: false, error: String(err?.message ?? err) })
363
+ }
364
+ return
365
+ }
366
+
367
+ if (path === '/argo/api/note-study' && req.method === 'POST') {
368
+ const body = await readJsonBody(req)
369
+ const payload = body.payload || (body.results || body.url ? body : null)
370
+ if (!payload) { sendJson(res, 400, { error: 'missing_payload' }); return }
371
+ try {
372
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
373
+ const out = await saveNoteStudy(env, {
374
+ payload,
375
+ title: body.title || '',
376
+ runner: options.runNoteCli || runArgoCli,
377
+ })
378
+ sendJson(res, 200, { ok: true, ...out })
379
+ } catch (err) {
380
+ sendJson(res, 500, { ok: false, error: String(err?.message ?? err) })
381
+ }
382
+ return
383
+ }
384
+
670
385
  if (path === '/argo/api/health' && req.method === 'GET') {
671
386
  const hasLlm = Boolean(ctx.get?.('llm') && ctx.get?.('agentDefaultModel')?.currentSelection?.()?.model)
387
+ const hs = loadHotspotStore()
672
388
  sendJson(res, 200, {
673
389
  ok: true,
674
390
  modes: Object.entries(MODE_LABELS).map(([id, label]) => ({ id, label })),
675
391
  hasLlm,
676
392
  egoSearch: readEgoSearchStatus(),
677
393
  breaker: readBreakerSummary(),
394
+ hotspotSchedule: { refreshTime: hs.refreshTime, lastRefreshedAt: hs.lastRefreshedAt },
678
395
  })
679
396
  return
680
397
  }
@@ -683,16 +400,51 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
683
400
  const reqMode = MODES.has(url.searchParams.get('mode')) ? url.searchParams.get('mode') : 'general'
684
401
  const lang = url.searchParams.get('lang') || 'zh'
685
402
  const shuffle = url.searchParams.get('shuffle') === '1'
686
- sendJson(res, 200, buildSuggestions(reqMode, lang, shuffle))
403
+ const store = loadHotspotStore()
404
+ if (hotspotRetryDue(store)) triggerDailyHotspotRefresh()
405
+ // 本机模式建议词与 callLocalSeek 同源同路径
406
+ sendJson(res, 200, buildSuggestions(reqMode, lang, shuffle, {
407
+ watches,
408
+ hotspotStore: store,
409
+ cwd: resolveLocalSearchPath(config),
410
+ }))
411
+ return
412
+ }
413
+
414
+ if (path === '/argo/api/suggestions/config' && req.method === 'POST') {
415
+ const body = await readJsonBody(req)
416
+ let store = loadHotspotStore()
417
+ if (body.refreshTime !== undefined) {
418
+ const updated = updateRefreshTime(body.refreshTime)
419
+ if (!updated) { sendJson(res, 400, { error: 'invalid_refresh_time' }); return }
420
+ store = updated
421
+ }
422
+ if (body.refreshNow === true) {
423
+ store = await triggerDailyHotspotRefresh()
424
+ }
425
+ sendJson(res, 200, {
426
+ ok: true,
427
+ refreshTime: store.refreshTime,
428
+ lastRefreshedAt: store.lastRefreshedAt,
429
+ hotspotCount: (store.zh?.length || 0) + (store.en?.length || 0),
430
+ refreshing: hotspotRefresher.isBusy(),
431
+ // 锁被另一宿主占时如实回传 skipped,前端提示「另一宿主刷新中」,
432
+ // 不再拿旧时间戳冒充刚刷过(2026-11-21 审计:假成功边界)
433
+ skipped: store.skipped || null,
434
+ })
687
435
  return
688
436
  }
689
437
 
690
438
  if (path === '/argo/api/ego-search' && req.method === 'POST') {
691
- if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
692
439
  const body = await readJsonBody(req)
693
440
  const action = body.enabled ? 'enable' : 'disable'
694
441
  await new Promise((resolve) => {
695
- execFile('argo', ['ego-search', action], { timeout: 8000 }, () => resolve())
442
+ execFile(
443
+ resolveArgoBin({ PATH: mergedLaunchdPath() }),
444
+ ['ego-search', action],
445
+ { timeout: 8000, env: { ...process.env, PATH: mergedLaunchdPath() } },
446
+ () => resolve(),
447
+ )
696
448
  })
697
449
  sendJson(res, 200, { ok: true, egoSearch: readEgoSearchStatus() })
698
450
  return
@@ -704,10 +456,6 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
704
456
  }
705
457
 
706
458
  if (path === '/argo/api/stream' && req.method === 'GET') {
707
- if (!checkSameOrigin(ctx, req)) {
708
- sendJson(res, 403, { error: 'forbidden_origin' })
709
- return
710
- }
711
459
  const query = (url.searchParams.get('q') || '').trim()
712
460
  const rawMode = (url.searchParams.get('mode') || 'general').trim()
713
461
  const mode = MODES.has(rawMode) ? rawMode : 'general'
@@ -748,21 +496,26 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
748
496
 
749
497
  let cards
750
498
  let payload
499
+ let trackStats
751
500
  let cached = !refresh ? getCached(cacheKey) : null
752
501
  if (cached) {
753
502
  cards = cached.cards
754
503
  payload = cached.payload
504
+ trackStats = cached.trackStats
755
505
  } else {
756
506
  let pending = !refresh ? inflight.get(cacheKey) : null
757
507
  if (!pending) {
758
- pending = callArgoSearch(config, env, query, mode, refresh, ac.signal, researchTracks)
508
+ // 共享去重任务使用独立 signal,防止客户端 A 断连误杀同 key 并发等待的客户端 B
509
+ const searchSignal = refresh ? ac.signal : new AbortController().signal
510
+ pending = callArgoSearch(config, env, query, mode, refresh, searchSignal, researchTracks)
759
511
  .finally(() => inflight.delete(cacheKey))
760
512
  if (!refresh) inflight.set(cacheKey, pending)
761
513
  }
762
514
  const resData = await pending
763
515
  cards = resData.cards
764
516
  payload = resData.payload
765
- if (cards.length > 0) setCached(cacheKey, { cards, payload })
517
+ trackStats = resData.trackStats
518
+ if (cards.length > 0) setCached(cacheKey, { cards, payload, trackStats })
766
519
  }
767
520
 
768
521
  if (ac.signal.aborted) return
@@ -781,6 +534,8 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
781
534
  cards,
782
535
  funnel: payload?.funnel || null,
783
536
  engines: [...new Set(cards.map(c => c.source))],
537
+ intentResolution: payload?.intent_resolution || null,
538
+ warnings: Array.isArray(payload?.warnings) ? payload.warnings : [],
784
539
  })
785
540
  if (ac.signal.aborted) return
786
541
 
@@ -795,7 +550,6 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
795
550
  const llmRes = await streamLlmAnswer(ctx, {
796
551
  system,
797
552
  messages: [{ role: 'user', content: [{ type: 'text', text: userPrompt }] }],
798
- maxTokens: mode === 'research' ? 6000 : 3500,
799
553
  signal: ac.signal,
800
554
  onDelta: (delta) => sendSse(res, 'answer', { delta }),
801
555
  })
@@ -808,7 +562,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
808
562
  message: `默认模型(${llmRes.model || 'unknown'})暂不可用:${llmRes.message || llmRes.reason},已自动切换为多源聚合直出视图`,
809
563
  })
810
564
  }
811
- finalText = buildFallbackSummary(query, mode, cards)
565
+ finalText = buildFallbackSummary(query, mode, cards, llmRes)
812
566
  sendSse(res, 'answer', { delta: finalText })
813
567
  } else if (!llmRes.ok && llmRes.reason !== 'aborted') {
814
568
  sendSse(res, 'answer-status', {
@@ -820,11 +574,24 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
820
574
  const citations = extractCitations(finalText, cards)
821
575
  sendSse(res, 'citations', citations)
822
576
  if (mode === 'research') {
577
+ const total = (researchTracks || []).length
578
+ // 真实 track 成败统计进门禁;旧缓存条目无 trackStats 时按结果有无推断,
579
+ // 不再恒注入 completedTracks/failedTracks: 0 的假章(2026-11-21 审计)
580
+ const stats = trackStats || {
581
+ total,
582
+ completed: cards.length > 0 ? total : 0,
583
+ failed: 0,
584
+ }
823
585
  const gate = evaluateGates({
824
586
  answer: finalText,
825
587
  sources: cards.map(c => ({ url: c.url, title: c.title, domain: c.domain })),
826
588
  tracks: researchTracks || [],
827
589
  warnings: [],
590
+ stats: {
591
+ sourceCount: cards.length,
592
+ completedTracks: stats.completed,
593
+ failedTracks: stats.failed,
594
+ },
828
595
  })
829
596
  sendSse(res, 'gate', gate)
830
597
  }
@@ -865,14 +632,16 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
865
632
  }
866
633
 
867
634
  if (path === '/argo/api/followup' && req.method === 'POST') {
868
- if (!checkSameOrigin(ctx, req)) {
869
- sendJson(res, 403, { error: 'forbidden_origin' })
870
- return
871
- }
872
635
  const body = await readJsonBody(req)
873
636
  const question = String(body.question || '').trim()
874
- const cards = Array.isArray(body.cards) ? body.cards : []
875
- const history = Array.isArray(body.history) ? body.history : []
637
+ // 元素级过滤:null/非对象条目会在 buildEvidenceContext 与 history
638
+ // 映射处抛 TypeError(2026-11-18 实跑复现 cards:[null] 崩溃链)
639
+ const cards = Array.isArray(body.cards)
640
+ ? body.cards.filter(c => c && typeof c === 'object')
641
+ : []
642
+ const history = Array.isArray(body.history)
643
+ ? body.history.filter(h => h && typeof h === 'object')
644
+ : []
876
645
  const mode = MODES.has(body.mode) ? body.mode : 'general'
877
646
 
878
647
  if (!question) {
@@ -887,38 +656,49 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
887
656
  res.flushHeaders?.()
888
657
 
889
658
  const ac = new AbortController()
890
- req.on('close', () => ac.abort())
659
+ const onClose = () => { if (!res.writableEnded) ac.abort() }
660
+ if (typeof res.on === 'function') res.on('close', onClose)
661
+ else if (typeof req.on === 'function') req.on('close', onClose)
891
662
 
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
- ]
663
+ try {
664
+ const evidence = buildEvidenceContext(cards)
665
+ const messages = [
666
+ {
667
+ role: 'user',
668
+ content: [{ type: 'text', text: `原始问题:${body.query || ''}\n\n已检索证据:\n${evidence}` }],
669
+ },
670
+ ...history.slice(-6).map(item => ({
671
+ role: item.role === 'assistant' ? 'assistant' : 'user',
672
+ content: [{ type: 'text', text: String(item.text || '') }],
673
+ })),
674
+ {
675
+ role: 'user',
676
+ content: [{ type: 'text', text: `基于上述已检索证据继续追问:${question}\n请继续使用 [1]、[2] 引用编号;若当前证据未覆盖,请明确说明。` }],
677
+ },
678
+ ]
907
679
 
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
- })
680
+ const llmRes = await streamLlmAnswer(ctx, {
681
+ system: buildSystemPrompt(mode),
682
+ messages,
683
+ signal: ac.signal,
684
+ onDelta: (delta) => sendSse(res, 'answer', { delta }),
685
+ })
915
686
 
916
- if (!llmRes.ok && llmRes.reason === 'no_model') {
917
- sendSse(res, 'answer', { delta: '当前宿主未配置默认模型,无法进行多轮追问推理。' })
687
+ if (!llmRes.ok && !llmRes.text) {
688
+ const msg = llmRes.reason === 'no_model'
689
+ ? '当前宿主未配置默认模型,无法进行多轮追问推理。'
690
+ : `默认模型(${llmRes.model || 'unknown'})调用未完成:${llmRes.message || llmRes.reason}`
691
+ sendSse(res, 'answer', { delta: msg })
692
+ }
693
+ sendSse(res, 'citations', extractCitations(llmRes.text || '', cards))
694
+ sendSse(res, 'done', { ok: llmRes.ok })
695
+ } catch (err) {
696
+ if (!ac.signal.aborted) {
697
+ sendSse(res, 'failure', { message: String(err?.message ?? err) })
698
+ }
699
+ } finally {
700
+ if (!res.writableEnded) res.end()
918
701
  }
919
- sendSse(res, 'citations', extractCitations(llmRes.text || '', cards))
920
- sendSse(res, 'done', { ok: llmRes.ok })
921
- if (!res.writableEnded) res.end()
922
702
  return
923
703
  }
924
704
 
@@ -931,7 +711,7 @@ export function createWorkbenchHandler(ctx, config, getCredentials) {
931
711
  return workbenchHandler
932
712
  }
933
713
 
934
- export function registerArgoWorkbench(ctx, config, getCredentials) {
714
+ export function registerArgoWorkbench(ctx, config, getCredentials, options = {}) {
935
715
  const attach = (targetCtx) => {
936
716
  let webServer
937
717
  try {
@@ -940,7 +720,7 @@ export function registerArgoWorkbench(ctx, config, getCredentials) {
940
720
  return undefined
941
721
  }
942
722
  if (!webServer || typeof webServer.register !== 'function') return undefined
943
- const handler = createWorkbenchHandler(targetCtx, config, getCredentials)
723
+ const handler = createWorkbenchHandler(targetCtx, config, getCredentials, options)
944
724
  const off = webServer.register({ kind: 'prefix', path: '/argo', handler })
945
725
  return () => {
946
726
  handler.dispose?.()