argo-search 2.14.1 → 2.16.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 (245) hide show
  1. package/AGENTS.md +8 -6
  2. package/README.es.md +57 -813
  3. package/README.ja.md +56 -814
  4. package/README.ko.md +56 -812
  5. package/README.md +160 -754
  6. package/README.zh.md +152 -872
  7. package/SKILL.md +22 -23
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +23 -23
  10. package/backends/concept_vectors.bin +0 -0
  11. package/backends/domain_profiles.json +149 -6
  12. package/backends/engine_concept_vectors.json +1525 -1525
  13. package/backends/engine_registry.yaml +139 -30
  14. package/backends/quota_profiles.json +83 -3
  15. package/bin/argo +33 -17
  16. package/config.yaml +189 -33
  17. package/docs/ADDING_NEW_ENGINE.md +10 -0
  18. package/docs/ARGO_INTRO.md +1 -1
  19. package/docs/CHANGELOG.md +38 -0
  20. package/docs/ENGINE_CATALOG.md +102 -89
  21. package/docs/MCP_SETUP.md +10 -1
  22. package/docs/RELEASE_NOTES_v2.14.1.md +4 -4
  23. package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
  24. package/docs/RELEASE_NOTES_v2.16.0.md +58 -0
  25. package/docs/RELEASING.md +1 -1
  26. package/engines/specs/ai_labs.yaml +89 -0
  27. package/engines/specs/archive_org.yaml +1 -1
  28. package/engines/specs/bilibili_hot.yaml +11 -1
  29. package/engines/specs/brave.yaml +3 -3
  30. package/engines/specs/carbon_intensity.yaml +1 -1
  31. package/engines/specs/cisa_alerts.yaml +40 -0
  32. package/engines/specs/cn_ai_news.yaml +10 -8
  33. package/engines/specs/crates.yaml +1 -1
  34. package/engines/specs/crossref.yaml +4 -2
  35. package/engines/specs/crt_sh.yaml +1 -1
  36. package/engines/specs/dblp.yaml +1 -1
  37. package/engines/specs/devto.yaml +1 -1
  38. package/engines/specs/digup.yaml +11 -6
  39. package/engines/specs/docker_hub.yaml +1 -1
  40. package/engines/specs/douyin_hot.yaml +11 -1
  41. package/engines/specs/dw_news.yaml +4 -2
  42. package/engines/specs/eng_blogs.yaml +63 -0
  43. package/engines/specs/europeana.yaml +3 -4
  44. package/engines/specs/europepmc.yaml +1 -1
  45. package/engines/specs/felo.yaml +3 -3
  46. package/engines/specs/firecrawl.yaml +3 -0
  47. package/engines/specs/fourget.yaml +5 -2
  48. package/engines/specs/france24.yaml +6 -4
  49. package/engines/specs/fxtwitter.yaml +30 -7
  50. package/engines/specs/gbfs_nyc.yaml +1 -1
  51. package/engines/specs/gleif.yaml +1 -1
  52. package/engines/specs/gov_regulations.yaml +1 -1
  53. package/engines/specs/grepapp_mcp.yaml +62 -0
  54. package/engines/specs/guardian_rss.yaml +6 -4
  55. package/engines/specs/hf_datasets.yaml +1 -1
  56. package/engines/specs/huggingface.yaml +1 -1
  57. package/engines/specs/itotii.yaml +13 -1
  58. package/engines/specs/keenable.yaml +7 -1
  59. package/engines/specs/linux_do.yaml +63 -0
  60. package/engines/specs/lobsters.yaml +41 -0
  61. package/engines/specs/local_crossref.yaml +3 -1
  62. package/engines/specs/local_github.yaml +1 -1
  63. package/engines/specs/local_npm.yaml +6 -0
  64. package/engines/specs/local_openstreetmap.yaml +1 -1
  65. package/engines/specs/local_seek.yaml +6 -0
  66. package/engines/specs/maven.yaml +1 -1
  67. package/engines/specs/mdn.yaml +1 -1
  68. package/engines/specs/musicbrainz.yaml +1 -1
  69. package/engines/specs/nasa_images.yaml +1 -1
  70. package/engines/specs/nhtsa_vpic.yaml +6 -3
  71. package/engines/specs/npm.yaml +1 -1
  72. package/engines/specs/nuget.yaml +1 -1
  73. package/engines/specs/nvd.yaml +1 -1
  74. package/engines/specs/open_meteo.yaml +1 -1
  75. package/engines/specs/openalex.yaml +4 -2
  76. package/engines/specs/openreview.yaml +1 -1
  77. package/engines/specs/polymarket.yaml +1 -1
  78. package/engines/specs/redskill.yaml +2 -0
  79. package/engines/specs/searxng.yaml +4 -2
  80. package/engines/specs/sec_edgar.yaml +9 -4
  81. package/engines/specs/steam.yaml +1 -1
  82. package/engines/specs/tinyfish.yaml +2 -0
  83. package/engines/specs/tinyfish_news.yaml +2 -0
  84. package/engines/specs/tinyfish_paper.yaml +2 -0
  85. package/engines/specs/toutiao_hot.yaml +11 -1
  86. package/engines/specs/train.yaml +3 -0
  87. package/engines/specs/twitter.yaml +4 -0
  88. package/engines/specs/unpaywall.yaml +6 -0
  89. package/engines/specs/vam.yaml +17 -3
  90. package/engines/specs/weibo_hot.yaml +11 -1
  91. package/engines/specs/wikidata.yaml +1 -1
  92. package/engines/specs/wikipedia.yaml +1 -1
  93. package/engines/specs/wolframalpha.yaml +3 -3
  94. package/engines/specs/xiaohongshu.yaml +2 -0
  95. package/engines/specs/zhihu.yaml +3 -18
  96. package/engines/specs/zhihu_hot_app.yaml +1 -1
  97. package/engines/specs/zhihu_kb.yaml +18 -0
  98. package/engines/specs/zhihu_questions.yaml +19 -0
  99. package/package.json +4 -2
  100. package/packages/dsh-plugin/README.md +9 -14
  101. package/packages/dsh-plugin/dsh/client.js +481 -1037
  102. package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
  103. package/packages/dsh-plugin/dsh/index.js +6 -0
  104. package/packages/dsh-plugin/dsh/runner.js +3 -1
  105. package/packages/dsh-plugin/dsh/workbench-client.js +796 -0
  106. package/packages/dsh-plugin/dsh/workbench-md.js +386 -0
  107. package/packages/dsh-plugin/dsh/workbench-suggestions.js +148 -0
  108. package/packages/dsh-plugin/dsh/workbench.js +966 -0
  109. package/packages/dsh-plugin/icon.svg +23 -0
  110. package/packages/dsh-plugin/package.json +10 -3
  111. package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
  112. package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
  113. package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
  114. package/packages/dsh-plugin/test/size-gate.test.js +2 -9
  115. package/packages/dsh-plugin/test/workbench.test.js +92 -0
  116. package/scripts/adaptive.py +7 -1
  117. package/scripts/archive_run.py +112 -53
  118. package/scripts/argo_paths.py +42 -5
  119. package/scripts/badcase_ledger.py +117 -9
  120. package/scripts/build_concept_table.py +112 -55
  121. package/scripts/cache.py +6 -2
  122. package/scripts/caliber_isolation.py +60 -23
  123. package/scripts/circuit_breaker.py +72 -11
  124. package/scripts/cli_io.py +20 -2
  125. package/scripts/config_cache.py +44 -1
  126. package/scripts/daemon.py +151 -51
  127. package/scripts/dormant_ledger.py +23 -9
  128. package/scripts/engine_dispatch.py +8 -5
  129. package/scripts/engine_env.py +191 -1
  130. package/scripts/engine_families.py +50 -7
  131. package/scripts/engine_states.py +3 -50
  132. package/scripts/engine_validate.py +13 -45
  133. package/scripts/engines.py +15 -31
  134. package/scripts/engines_base.py +66 -61
  135. package/scripts/engines_builders.py +0 -15
  136. package/scripts/engines_builders_archive.py +4 -3
  137. package/scripts/engines_builders_batch10.py +346 -100
  138. package/scripts/engines_builders_batch11.py +4 -76
  139. package/scripts/engines_builders_batch13.py +4 -3
  140. package/scripts/engines_builders_batch14.py +2 -1
  141. package/scripts/engines_builders_batch15.py +2 -1
  142. package/scripts/engines_builders_batch9.py +16 -25
  143. package/scripts/engines_builders_cn.py +7 -201
  144. package/scripts/engines_builders_data.py +12 -11
  145. package/scripts/engines_builders_data_macro.py +5 -4
  146. package/scripts/engines_builders_dsh.py +2 -1
  147. package/scripts/engines_builders_feeds.py +76 -11
  148. package/scripts/engines_builders_finance.py +2 -1
  149. package/scripts/engines_builders_intl.py +18 -117
  150. package/scripts/engines_builders_media.py +59 -12
  151. package/scripts/engines_builders_pixiv.py +2 -16
  152. package/scripts/engines_builders_science.py +8 -7
  153. package/scripts/engines_builders_search.py +7 -14
  154. package/scripts/engines_builders_skill.py +2 -1
  155. package/scripts/engines_builders_tech.py +8 -17
  156. package/scripts/engines_builders_weather.py +241 -0
  157. package/scripts/engines_fields.py +91 -0
  158. package/scripts/engines_http.py +184 -0
  159. package/scripts/engines_mcp.py +405 -0
  160. package/scripts/engines_parsers.py +13 -369
  161. package/scripts/engines_schema_drift.py +260 -0
  162. package/scripts/evidence.py +13 -0
  163. package/scripts/evidence_loop.py +19 -4
  164. package/scripts/extend_route_labels.py +6 -0
  165. package/scripts/fetch_jina.py +98 -0
  166. package/scripts/fetch_jsrun.py +15 -11
  167. package/scripts/fetch_v3.py +79 -120
  168. package/scripts/fulltext_store.py +42 -1
  169. package/scripts/fxtwitter_api.py +8 -7
  170. package/scripts/gen_engine_catalog.py +2 -2
  171. package/scripts/general_pool.py +15 -4
  172. package/scripts/health_check.py +1 -1
  173. package/scripts/image_vision/vision_probe +0 -0
  174. package/scripts/install.sh +2 -0
  175. package/scripts/link_source.py +65 -24
  176. package/scripts/local_seek_adapter.py +57 -17
  177. package/scripts/matrix_search_eval.py +8 -10
  178. package/scripts/mcp_handlers.py +53 -31
  179. package/scripts/mcp_handlers_surface.py +6 -18
  180. package/scripts/mcp_transport.py +10 -5
  181. package/scripts/min_version_scan.py +7 -3
  182. package/scripts/network_aware.py +7 -13
  183. package/scripts/numeric_verify.py +3 -2
  184. package/scripts/output_transparency.py +3 -0
  185. package/scripts/pre-commit +45 -43
  186. package/scripts/query_understanding.py +30 -6
  187. package/scripts/quota.py +36 -30
  188. package/scripts/rank_signals.py +9 -0
  189. package/scripts/recompute.py +15 -5
  190. package/scripts/recovery.py +38 -29
  191. package/scripts/recovery_runner.py +29 -10
  192. package/scripts/redskill/redskill_engine.py +2 -1
  193. package/scripts/release.py +14 -26
  194. package/scripts/release_check.py +5 -25
  195. package/scripts/replay_eval.py +2 -2
  196. package/scripts/research_cli.py +40 -0
  197. package/scripts/research_notes.py +368 -0
  198. package/scripts/route.py +40 -70
  199. package/scripts/route_audit.py +259 -0
  200. package/scripts/route_combo.py +21 -6
  201. package/scripts/route_domains.py +150 -23
  202. package/scripts/route_lang.py +20 -7
  203. package/scripts/route_log.py +26 -9
  204. package/scripts/route_policy.py +85 -6
  205. package/scripts/route_telemetry_export.py +199 -0
  206. package/scripts/rrf_classic.py +5 -22
  207. package/scripts/search.py +2 -1
  208. package/scripts/search_attribution.py +53 -10
  209. package/scripts/search_entry.py +32 -1
  210. package/scripts/search_output.py +23 -11
  211. package/scripts/search_pipeline.py +15 -3
  212. package/scripts/search_rank.py +21 -11
  213. package/scripts/semantic_evidence.py +394 -178
  214. package/scripts/serp_guard.py +13 -1
  215. package/scripts/settings_page.py +4 -3
  216. package/scripts/single_flight.py +1 -1
  217. package/scripts/social_engines/hackernews_engine.py +2 -1
  218. package/scripts/social_engines/reddit_engine.py +2 -1
  219. package/scripts/social_engines/xiaohongshu_engine.py +2 -1
  220. package/scripts/social_engines/zhihu_engine.py +252 -43
  221. package/scripts/sogou_weixin_browser.py +5 -6
  222. package/scripts/source_audit.py +44 -9
  223. package/scripts/source_ledger.py +2 -15
  224. package/scripts/source_selection.py +45 -20
  225. package/scripts/straggler_policy.py +1 -2
  226. package/scripts/sync_backends.py +17 -0
  227. package/scripts/tfidf_router.py +23 -11
  228. package/scripts/time_utils.py +54 -1
  229. package/scripts/train.py +68 -2
  230. package/scripts/usage_log.py +50 -10
  231. package/scripts/watch.py +3 -3
  232. package/scripts/zhihu_quota.py +2 -1
  233. package/sub-skills/argo-wide-research/SKILL.md +70 -0
  234. package/sub-skills/ego-search/{SKILL.md → README.md} +15 -47
  235. package/sub-skills/ego-search/scripts/ego_search.py +13 -4
  236. package/sub-skills/js-run/{SKILL.md → README.md} +3 -20
  237. package/sub-skills/local-search/{SKILL.md → README.md} +3 -8
  238. package/sub-skills/local-search/engine_registry.py +32 -7
  239. package/sub-skills/local-seek/SKILL.md +20 -22
  240. package/sub-skills/local-seek/scripts/seek_fts.py +58 -3
  241. package/scripts/caliber_dedupe.py +0 -66
  242. package/scripts/engines_builders_batch16.py +0 -13
  243. package/scripts/health_probe.py +0 -253
  244. package/scripts/social_engines/twitter_engine.py +0 -514
  245. package/scripts/sync_installs.py +0 -29
@@ -0,0 +1,966 @@
1
+ /*
2
+ * @taxueseek/argo-dsh — 搜索分析工作台 Host 端(webServer + SSE + 宿主 LLM)
3
+ *
4
+ * 独立于 Agent 工具链(nativeTools / web seam / wide_research):
5
+ * 仅在宿主提供 webServer 时挂载 `/argo/*` 路由,为普通用户提供类网页版
6
+ * 搜索分析工作台(5 种专题模式 + 左答右证 SSE + 原文核验 + 多轮追问)。
7
+ */
8
+
9
+ import { execFile, spawn } from 'node:child_process'
10
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
11
+ import { homedir } from 'node:os'
12
+ import { dirname, join } from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { DEFAULTS, stripBoundary } from './runner.js'
15
+ import { resolveArgoEnv } from './specs.js'
16
+ import { boundedMap, buildCrossLingualTracks, evaluateGates } from './wide-research.js'
17
+ import { buildSuggestions } from './workbench-suggestions.js'
18
+
19
+ const HERE = dirname(fileURLToPath(import.meta.url))
20
+ const ARGO_BIN = join(HERE, '..', '..', '..', 'bin', 'argo')
21
+ const CLIENT_FILE = join(HERE, 'workbench-client.js')
22
+ 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
+
26
+ const CACHE_TTL_MS = 5 * 60 * 1000
27
+ const MAX_CACHE_ENTRIES = 32
28
+ const MAX_DIAGNOSTICS = 20
29
+ const MAX_WATCHES = 20
30
+
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
+ function sendJson(res, status, data) {
52
+ if (res.writableEnded) return
53
+ res.statusCode = status
54
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
55
+ res.setHeader('Cache-Control', 'no-store')
56
+ res.end(JSON.stringify(data))
57
+ }
58
+
59
+ function sendSse(res, event, data) {
60
+ if (res.writableEnded || res.destroyed) return
61
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
62
+ }
63
+
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
+ async function readJsonBody(req, maxBytes = 256 * 1024) {
78
+ const chunks = []
79
+ let size = 0
80
+ for await (const chunk of req) {
81
+ size += chunk.length
82
+ if (size > maxBytes) throw new Error('request body too large')
83
+ chunks.push(chunk)
84
+ }
85
+ const raw = Buffer.concat(chunks).toString('utf8').trim()
86
+ return raw ? JSON.parse(raw) : {}
87
+ }
88
+
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
+ function readEgoSearchStatus() {
170
+ const statePath = process.env.EGO_SEARCH_STATE || join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'ego-search.json')
171
+ try {
172
+ const parsed = JSON.parse(readFileSync(statePath, 'utf8'))
173
+ return { enabled: Boolean(parsed?.enabled), enabledAt: parsed?.enabled_at || null }
174
+ } catch {
175
+ return { enabled: false, enabledAt: null }
176
+ }
177
+ }
178
+
179
+ function readBreakerSummary() {
180
+ try {
181
+ const raw = JSON.parse(readFileSync(BREAKER_FILE, 'utf8'))
182
+ const engines = raw?.engines && typeof raw.engines === 'object' ? raw.engines : {}
183
+ const tripped = []
184
+ let total = 0
185
+ for (const [name, info] of Object.entries(engines)) {
186
+ if (!info || typeof info !== 'object') continue
187
+ total += 1
188
+ if (info.state && info.state !== 'closed') {
189
+ tripped.push({
190
+ engine: name,
191
+ state: info.state,
192
+ opens: info.opens || 0,
193
+ lastError: String(info.last_error || '').slice(0, 60),
194
+ })
195
+ }
196
+ }
197
+ tripped.sort((a, b) => (b.opens || 0) - (a.opens || 0))
198
+ return { total, nonClosedCount: tripped.length, topTripped: tripped.slice(0, 8) }
199
+ } catch {
200
+ return { total: 0, nonClosedCount: 0, topTripped: [] }
201
+ }
202
+ }
203
+
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) {
516
+ const cache = new Map()
517
+ const inflight = new Map()
518
+ const diagnostics = []
519
+ let watches = loadWatches()
520
+ let watchBusy = false
521
+
522
+ const executeWatch = async (watch) => {
523
+ const started = Date.now()
524
+ const credentials = typeof getCredentials === 'function' ? getCredentials() : undefined
525
+ try {
526
+ const env = await resolveArgoEnv(config, { credentials }).catch(() => ({}))
527
+ const { cards } = await callArgoSearch(config, env, watch.query, watch.mode, true, AbortSignal.timeout(45000))
528
+ let summary = ''
529
+ if (cards.length > 0) {
530
+ const evidence = buildEvidenceContext(cards, 9000)
531
+ const llmRes = await streamLlmAnswer(ctx, {
532
+ system: buildSystemPrompt(watch.mode),
533
+ messages: [{
534
+ role: 'user',
535
+ content: [{ type: 'text', text: `定时追踪任务:${watch.query}\n\n最新检索证据:\n\n${evidence}\n\n请用简明结构概括最新动态,并在句末标注 [1]、[2] 引用编号。` }],
536
+ }],
537
+ maxTokens: 1800,
538
+ signal: AbortSignal.timeout(35000),
539
+ onDelta: () => {},
540
+ })
541
+ summary = llmRes.text || buildFallbackSummary(watch.query, watch.mode, cards)
542
+ } else {
543
+ summary = buildFallbackSummary(watch.query, watch.mode, cards)
544
+ }
545
+ watch.lastRunAt = new Date().toISOString()
546
+ watch.nextRunAt = new Date(Date.now() + watch.intervalMinutes * 60000).toISOString()
547
+ watch.lastStatus = 'ok'
548
+ watch.lastCardCount = cards.length
549
+ watch.lastSummary = summary
550
+ watch.lastCards = cards.slice(0, 10)
551
+ watch.lastDurationMs = Date.now() - started
552
+ } catch (err) {
553
+ watch.lastRunAt = new Date().toISOString()
554
+ watch.nextRunAt = new Date(Date.now() + watch.intervalMinutes * 60000).toISOString()
555
+ watch.lastStatus = `error: ${String(err?.message ?? err)}`
556
+ }
557
+ saveWatches(watches)
558
+ return watch
559
+ }
560
+
561
+ const timer = setInterval(async () => {
562
+ if (watchBusy) return
563
+ const now = Date.now()
564
+ const due = watches.find(w => w.enabled !== false && (!w.nextRunAt || Date.parse(w.nextRunAt) <= now))
565
+ if (!due) return
566
+ watchBusy = true
567
+ try { await executeWatch(due) } finally { watchBusy = false }
568
+ }, 60 * 1000)
569
+ timer.unref?.()
570
+
571
+ const recordDiag = (entry) => {
572
+ diagnostics.unshift({ ...entry, ts: new Date().toISOString() })
573
+ if (diagnostics.length > MAX_DIAGNOSTICS) diagnostics.length = MAX_DIAGNOSTICS
574
+ }
575
+
576
+ const getCached = (key) => {
577
+ const hit = cache.get(key)
578
+ if (!hit) return null
579
+ if (Date.now() - hit.ts > CACHE_TTL_MS) {
580
+ cache.delete(key)
581
+ return null
582
+ }
583
+ return hit
584
+ }
585
+
586
+ const setCached = (key, value) => {
587
+ if (cache.size >= MAX_CACHE_ENTRIES) {
588
+ const oldest = cache.keys().next().value
589
+ if (oldest) cache.delete(oldest)
590
+ }
591
+ cache.set(key, { ...value, ts: Date.now() })
592
+ }
593
+
594
+ const workbenchHandler = async (req, res) => {
595
+ try {
596
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
597
+ const path = url.pathname
598
+
599
+ if (path === '/argo/workbench-client.js' && req.method === 'GET') {
600
+ const source = readFileSync(CLIENT_FILE, 'utf8')
601
+ res.statusCode = 200
602
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
603
+ res.setHeader('Cache-Control', 'no-store')
604
+ res.end(source)
605
+ return
606
+ }
607
+
608
+ if (path === '/argo/workbench-md.js' && req.method === 'GET') {
609
+ const source = readFileSync(MD_FILE, 'utf8')
610
+ res.statusCode = 200
611
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
612
+ res.setHeader('Cache-Control', 'no-store')
613
+ res.end(source)
614
+ return
615
+ }
616
+
617
+ if (path === '/argo/api/watches' && req.method === 'GET') {
618
+ sendJson(res, 200, { ok: true, items: watches })
619
+ return
620
+ }
621
+
622
+ if (path === '/argo/api/watches' && req.method === 'POST') {
623
+ if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
624
+ const body = await readJsonBody(req)
625
+ const query = String(body.query || '').trim()
626
+ const mode = MODES.has(body.mode) ? body.mode : 'general'
627
+ const intervalMinutes = Math.max(60, Math.min(43200, Number(body.intervalMinutes) || 1440))
628
+ if (!query) { sendJson(res, 400, { error: 'missing_query' }); return }
629
+ const item = {
630
+ id: `w_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`,
631
+ query,
632
+ mode,
633
+ modeLabel: MODE_LABELS[mode] || mode,
634
+ intervalMinutes,
635
+ enabled: true,
636
+ createdAt: new Date().toISOString(),
637
+ nextRunAt: new Date(Date.now() + intervalMinutes * 60000).toISOString(),
638
+ lastRunAt: null,
639
+ lastStatus: 'pending',
640
+ lastCardCount: 0,
641
+ lastSummary: '',
642
+ lastCards: [],
643
+ }
644
+ watches.unshift(item)
645
+ if (watches.length > MAX_WATCHES) watches.length = MAX_WATCHES
646
+ saveWatches(watches)
647
+ sendJson(res, 200, { ok: true, item, items: watches })
648
+ return
649
+ }
650
+
651
+ if (path === '/argo/api/watches/run' && req.method === 'POST') {
652
+ if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
653
+ const body = await readJsonBody(req)
654
+ const target = watches.find(w => w.id === body.id)
655
+ 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 })
658
+ return
659
+ }
660
+
661
+ if (path === '/argo/api/watches' && req.method === 'DELETE') {
662
+ if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
663
+ const id = url.searchParams.get('id') || ''
664
+ watches = watches.filter(w => w.id !== id)
665
+ saveWatches(watches)
666
+ sendJson(res, 200, { ok: true, items: watches })
667
+ return
668
+ }
669
+
670
+ if (path === '/argo/api/health' && req.method === 'GET') {
671
+ const hasLlm = Boolean(ctx.get?.('llm') && ctx.get?.('agentDefaultModel')?.currentSelection?.()?.model)
672
+ sendJson(res, 200, {
673
+ ok: true,
674
+ modes: Object.entries(MODE_LABELS).map(([id, label]) => ({ id, label })),
675
+ hasLlm,
676
+ egoSearch: readEgoSearchStatus(),
677
+ breaker: readBreakerSummary(),
678
+ })
679
+ return
680
+ }
681
+
682
+ if (path === '/argo/api/suggestions' && req.method === 'GET') {
683
+ const reqMode = MODES.has(url.searchParams.get('mode')) ? url.searchParams.get('mode') : 'general'
684
+ const lang = url.searchParams.get('lang') || 'zh'
685
+ const shuffle = url.searchParams.get('shuffle') === '1'
686
+ sendJson(res, 200, buildSuggestions(reqMode, lang, shuffle))
687
+ return
688
+ }
689
+
690
+ if (path === '/argo/api/ego-search' && req.method === 'POST') {
691
+ if (!checkSameOrigin(ctx, req)) { sendJson(res, 403, { error: 'forbidden_origin' }); return }
692
+ const body = await readJsonBody(req)
693
+ const action = body.enabled ? 'enable' : 'disable'
694
+ await new Promise((resolve) => {
695
+ execFile('argo', ['ego-search', action], { timeout: 8000 }, () => resolve())
696
+ })
697
+ sendJson(res, 200, { ok: true, egoSearch: readEgoSearchStatus() })
698
+ return
699
+ }
700
+
701
+ if (path === '/argo/api/diagnostics' && req.method === 'GET') {
702
+ sendJson(res, 200, { ok: true, items: diagnostics })
703
+ return
704
+ }
705
+
706
+ if (path === '/argo/api/stream' && req.method === 'GET') {
707
+ if (!checkSameOrigin(ctx, req)) {
708
+ sendJson(res, 403, { error: 'forbidden_origin' })
709
+ return
710
+ }
711
+ const query = (url.searchParams.get('q') || '').trim()
712
+ const rawMode = (url.searchParams.get('mode') || 'general').trim()
713
+ const mode = MODES.has(rawMode) ? rawMode : 'general'
714
+ const refresh = url.searchParams.get('refresh') === '1'
715
+
716
+ if (!query) {
717
+ sendJson(res, 400, { error: 'missing_query' })
718
+ return
719
+ }
720
+
721
+ res.statusCode = 200
722
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
723
+ res.setHeader('Cache-Control', 'no-cache, no-transform')
724
+ res.setHeader('Connection', 'keep-alive')
725
+ res.flushHeaders?.()
726
+
727
+ const ac = new AbortController()
728
+ req.on('close', () => ac.abort())
729
+
730
+ const startedAt = Date.now()
731
+ const cacheKey = `${mode}::${query.toLowerCase()}`
732
+
733
+ try {
734
+ sendSse(res, 'status', { stage: 'searching', message: `正在通过 Argo 多源检索(${MODE_LABELS[mode]})…` })
735
+ const researchTracks = mode === 'research' ? buildCrossLingualTracks(query, 3) : null
736
+ sendSse(res, 'plan', {
737
+ query,
738
+ mode,
739
+ modeLabel: MODE_LABELS[mode],
740
+ tracks: researchTracks
741
+ ? researchTracks.map(t => t.title)
742
+ : (mode === 'local' ? ['本机 FTS/rg 索引检索'] : ['智能路由检索', '证据梳理与引用']),
743
+ })
744
+
745
+ const credentials = typeof getCredentials === 'function' ? getCredentials() : undefined
746
+ const env = await resolveArgoEnv(config, { credentials }).catch(() => ({}))
747
+ const clarifyPromise = runClarifyIfShort(query, mode, env, ac.signal)
748
+
749
+ let cards
750
+ let payload
751
+ let cached = !refresh ? getCached(cacheKey) : null
752
+ if (cached) {
753
+ cards = cached.cards
754
+ payload = cached.payload
755
+ } else {
756
+ let pending = !refresh ? inflight.get(cacheKey) : null
757
+ if (!pending) {
758
+ pending = callArgoSearch(config, env, query, mode, refresh, ac.signal, researchTracks)
759
+ .finally(() => inflight.delete(cacheKey))
760
+ if (!refresh) inflight.set(cacheKey, pending)
761
+ }
762
+ const resData = await pending
763
+ cards = resData.cards
764
+ payload = resData.payload
765
+ if (cards.length > 0) setCached(cacheKey, { cards, payload })
766
+ }
767
+
768
+ if (ac.signal.aborted) return
769
+
770
+ const clarify = await clarifyPromise
771
+ if (clarify) sendSse(res, 'clarify', clarify)
772
+
773
+ if (mode !== 'local' && cards.length > 0) {
774
+ sendSse(res, 'status', { stage: 'verifying', message: '正在计算证据可信度与交叉验证…' })
775
+ const scored = await runEvidenceScoring(query, cards, env, ac.signal)
776
+ cards = scored.cards
777
+ if (scored.evidenceSummary) sendSse(res, 'evidence', scored.evidenceSummary)
778
+ }
779
+
780
+ sendSse(res, 'cards', {
781
+ cards,
782
+ funnel: payload?.funnel || null,
783
+ engines: [...new Set(cards.map(c => c.source))],
784
+ })
785
+ if (ac.signal.aborted) return
786
+
787
+ sendSse(res, 'status', { stage: 'synthesizing', message: '正在结合检索证据生成结构化分析…' })
788
+
789
+ const system = buildSystemPrompt(mode)
790
+ const evidence = buildEvidenceContext(cards)
791
+ const userPrompt = cards.length > 0
792
+ ? `问题:${query}\n\n以下是检索到的多源证据:\n\n${evidence}\n\n请严格依据上述证据回答,并在句末标注 [1]、[2] 等引用编号。`
793
+ : `问题:${query}\n\n当前未检索到外部网页结果,请如实说明并给出可行的关键词调整建议。`
794
+
795
+ const llmRes = await streamLlmAnswer(ctx, {
796
+ system,
797
+ messages: [{ role: 'user', content: [{ type: 'text', text: userPrompt }] }],
798
+ maxTokens: mode === 'research' ? 6000 : 3500,
799
+ signal: ac.signal,
800
+ onDelta: (delta) => sendSse(res, 'answer', { delta }),
801
+ })
802
+
803
+ let finalText = llmRes.text || ''
804
+ if (!llmRes.ok && finalText === '') {
805
+ if (llmRes.reason !== 'no_model') {
806
+ sendSse(res, 'answer-status', {
807
+ status: 'fallback',
808
+ message: `默认模型(${llmRes.model || 'unknown'})暂不可用:${llmRes.message || llmRes.reason},已自动切换为多源聚合直出视图`,
809
+ })
810
+ }
811
+ finalText = buildFallbackSummary(query, mode, cards)
812
+ sendSse(res, 'answer', { delta: finalText })
813
+ } else if (!llmRes.ok && llmRes.reason !== 'aborted') {
814
+ sendSse(res, 'answer-status', {
815
+ status: 'interrupted',
816
+ message: llmRes.message || '模型输出中断,已保留已生成内容',
817
+ })
818
+ }
819
+
820
+ const citations = extractCitations(finalText, cards)
821
+ sendSse(res, 'citations', citations)
822
+ if (mode === 'research') {
823
+ const gate = evaluateGates({
824
+ answer: finalText,
825
+ sources: cards.map(c => ({ url: c.url, title: c.title, domain: c.domain })),
826
+ tracks: researchTracks || [],
827
+ warnings: [],
828
+ })
829
+ sendSse(res, 'gate', gate)
830
+ }
831
+ sendSse(res, 'done', {
832
+ durationMs: Date.now() - startedAt,
833
+ cardCount: cards.length,
834
+ verifiedCount: cards.filter(c => c.verified).length,
835
+ model: llmRes.model || 'none',
836
+ usage: llmRes.usage || null,
837
+ })
838
+
839
+ recordDiag({
840
+ query,
841
+ mode,
842
+ durationMs: Date.now() - startedAt,
843
+ cardCount: cards.length,
844
+ verifiedCount: cards.filter(c => c.verified).length,
845
+ citedCount: citations.citedIndices.length,
846
+ status: llmRes.ok ? 'ok' : (llmRes.reason || 'fallback'),
847
+ usage: llmRes.usage || null,
848
+ })
849
+ } catch (err) {
850
+ if (!ac.signal.aborted) {
851
+ sendSse(res, 'failure', { message: String(err?.message ?? err) })
852
+ recordDiag({
853
+ query,
854
+ mode,
855
+ durationMs: Date.now() - startedAt,
856
+ cardCount: 0,
857
+ status: 'error',
858
+ error: String(err?.message ?? err),
859
+ })
860
+ }
861
+ } finally {
862
+ if (!res.writableEnded) res.end()
863
+ }
864
+ return
865
+ }
866
+
867
+ if (path === '/argo/api/followup' && req.method === 'POST') {
868
+ if (!checkSameOrigin(ctx, req)) {
869
+ sendJson(res, 403, { error: 'forbidden_origin' })
870
+ return
871
+ }
872
+ const body = await readJsonBody(req)
873
+ const question = String(body.question || '').trim()
874
+ const cards = Array.isArray(body.cards) ? body.cards : []
875
+ const history = Array.isArray(body.history) ? body.history : []
876
+ const mode = MODES.has(body.mode) ? body.mode : 'general'
877
+
878
+ if (!question) {
879
+ sendJson(res, 400, { error: 'missing_question' })
880
+ return
881
+ }
882
+
883
+ res.statusCode = 200
884
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
885
+ res.setHeader('Cache-Control', 'no-cache, no-transform')
886
+ res.setHeader('Connection', 'keep-alive')
887
+ res.flushHeaders?.()
888
+
889
+ const ac = new AbortController()
890
+ req.on('close', () => ac.abort())
891
+
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
+ ]
907
+
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
+ })
915
+
916
+ if (!llmRes.ok && llmRes.reason === 'no_model') {
917
+ sendSse(res, 'answer', { delta: '当前宿主未配置默认模型,无法进行多轮追问推理。' })
918
+ }
919
+ sendSse(res, 'citations', extractCitations(llmRes.text || '', cards))
920
+ sendSse(res, 'done', { ok: llmRes.ok })
921
+ if (!res.writableEnded) res.end()
922
+ return
923
+ }
924
+
925
+ sendJson(res, 404, { error: 'not_found', path })
926
+ } catch (err) {
927
+ sendJson(res, 500, { error: 'internal_error', message: String(err?.message ?? err) })
928
+ }
929
+ }
930
+ workbenchHandler.dispose = () => clearInterval(timer)
931
+ return workbenchHandler
932
+ }
933
+
934
+ export function registerArgoWorkbench(ctx, config, getCredentials) {
935
+ const attach = (targetCtx) => {
936
+ let webServer
937
+ try {
938
+ webServer = targetCtx?.get?.('webServer') ?? targetCtx?.webServer
939
+ } catch {
940
+ return undefined
941
+ }
942
+ if (!webServer || typeof webServer.register !== 'function') return undefined
943
+ const handler = createWorkbenchHandler(targetCtx, config, getCredentials)
944
+ const off = webServer.register({ kind: 'prefix', path: '/argo', handler })
945
+ return () => {
946
+ handler.dispose?.()
947
+ if (typeof off === 'function') off()
948
+ }
949
+ }
950
+
951
+ if (typeof ctx?.inject === 'function') {
952
+ try {
953
+ ctx.inject(['webServer'], (subCtx) => {
954
+ const off = attach(subCtx)
955
+ if (off && typeof subCtx.effect === 'function') subCtx.effect(() => off)
956
+ })
957
+ return undefined
958
+ } catch {
959
+ /* 测试环境或无 webServer 时静默跳过 */
960
+ }
961
+ }
962
+
963
+ const direct = attach(ctx)
964
+ if (direct && typeof ctx?.effect === 'function') ctx.effect(() => direct)
965
+ return direct
966
+ }