argo-search 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.es.md +32 -5
  3. package/README.ja.md +32 -5
  4. package/README.ko.md +32 -5
  5. package/README.md +73 -19
  6. package/README.zh.md +73 -19
  7. package/SKILL.md +7 -7
  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 +222 -24
  13. package/backends/engine_registry.yaml +26 -2
  14. package/backends/env_passthrough.txt +2 -0
  15. package/backends/quota_profiles.json +23 -3
  16. package/bin/argo +3 -0
  17. package/config.yaml +16 -0
  18. package/docs/CHANGELOG.md +31 -0
  19. package/docs/COMMIT_STANDARD.md +10 -0
  20. package/docs/ENGINE_CATALOG.md +40 -37
  21. package/docs/MCP_SETUP.md +9 -0
  22. package/docs/RELEASE_NOTES_v2.16.0.md +58 -0
  23. package/docs/RELEASE_NOTES_v2.17.0.md +64 -0
  24. package/docs/RELEASING.md +1 -1
  25. package/engines/specs/archive_org.yaml +1 -1
  26. package/engines/specs/carbon_intensity.yaml +1 -1
  27. package/engines/specs/crates.yaml +1 -1
  28. package/engines/specs/crossref.yaml +6 -2
  29. package/engines/specs/crt_sh.yaml +1 -1
  30. package/engines/specs/dblp.yaml +1 -1
  31. package/engines/specs/devto.yaml +1 -1
  32. package/engines/specs/docker_hub.yaml +1 -1
  33. package/engines/specs/europepmc.yaml +1 -1
  34. package/engines/specs/fxtwitter.yaml +1 -1
  35. package/engines/specs/gbfs_nyc.yaml +1 -1
  36. package/engines/specs/gleif.yaml +1 -1
  37. package/engines/specs/gov_regulations.yaml +1 -1
  38. package/engines/specs/hackernews.yaml +2 -0
  39. package/engines/specs/helve.yaml +49 -0
  40. package/engines/specs/hf_datasets.yaml +1 -1
  41. package/engines/specs/hf_papers.yaml +2 -0
  42. package/engines/specs/huggingface.yaml +1 -1
  43. package/engines/specs/keenable.yaml +7 -1
  44. package/engines/specs/linux_do.yaml +63 -0
  45. package/engines/specs/local_crossref.yaml +3 -1
  46. package/engines/specs/local_github.yaml +1 -1
  47. package/engines/specs/local_npm.yaml +6 -0
  48. package/engines/specs/local_openstreetmap.yaml +1 -1
  49. package/engines/specs/maven.yaml +1 -1
  50. package/engines/specs/mdn.yaml +1 -1
  51. package/engines/specs/musicbrainz.yaml +1 -1
  52. package/engines/specs/nasa_images.yaml +1 -1
  53. package/engines/specs/nhtsa_vpic.yaml +6 -3
  54. package/engines/specs/npm.yaml +1 -1
  55. package/engines/specs/nuget.yaml +1 -1
  56. package/engines/specs/nvd.yaml +1 -1
  57. package/engines/specs/openalex.yaml +13 -4
  58. package/engines/specs/openreview.yaml +1 -1
  59. package/engines/specs/polymarket.yaml +1 -1
  60. package/engines/specs/sec_edgar.yaml +1 -1
  61. package/engines/specs/steam.yaml +1 -1
  62. package/engines/specs/vam.yaml +1 -1
  63. package/engines/specs/wikidata.yaml +1 -1
  64. package/engines/specs/wikipedia.yaml +1 -1
  65. package/engines/specs/zhihu_hot_app.yaml +1 -1
  66. package/package.json +3 -1
  67. package/packages/dsh-plugin/README.md +5 -2
  68. package/packages/dsh-plugin/cordis.patch.yml +4 -1
  69. package/packages/dsh-plugin/dsh/client.js +69 -74
  70. package/packages/dsh-plugin/dsh/diagnostics.js +25 -4
  71. package/packages/dsh-plugin/dsh/index.js +115 -21
  72. package/packages/dsh-plugin/dsh/route-guard.js +95 -0
  73. package/packages/dsh-plugin/dsh/runner.js +50 -7
  74. package/packages/dsh-plugin/dsh/wide-research.js +20 -18
  75. package/packages/dsh-plugin/dsh/workbench-client.js +895 -0
  76. package/packages/dsh-plugin/dsh/workbench-io.js +163 -0
  77. package/packages/dsh-plugin/dsh/workbench-md.js +386 -0
  78. package/packages/dsh-plugin/dsh/workbench-search.js +385 -0
  79. package/packages/dsh-plugin/dsh/workbench-suggestions.js +460 -0
  80. package/packages/dsh-plugin/dsh/workbench.js +703 -0
  81. package/packages/dsh-plugin/icon.svg +23 -0
  82. package/packages/dsh-plugin/package.json +6 -3
  83. package/packages/dsh-plugin/scripts/sync-local.mjs +4 -2
  84. package/packages/dsh-plugin/scripts/sync-local.sh +4 -2
  85. package/packages/dsh-plugin/test/client.test.js +26 -0
  86. package/packages/dsh-plugin/test/diagnostics.test.js +5 -2
  87. package/packages/dsh-plugin/test/index.test.js +150 -1
  88. package/packages/dsh-plugin/test/workbench-concurrency.test.js +98 -0
  89. package/packages/dsh-plugin/test/workbench.test.js +420 -0
  90. package/scripts/adaptive.py +13 -11
  91. package/scripts/argo_paths.py +2 -2
  92. package/scripts/badcase_ledger.py +9 -0
  93. package/scripts/browser_auth.py +178 -4
  94. package/scripts/cache.py +69 -70
  95. package/scripts/check_commit_report.py +46 -0
  96. package/scripts/chrome_cdp.py +71 -0
  97. package/scripts/circuit_breaker.py +91 -13
  98. package/scripts/config_cache.py +23 -10
  99. package/scripts/daemon.py +14 -2
  100. package/scripts/engine_add.py +45 -0
  101. package/scripts/engine_dispatch.py +32 -49
  102. package/scripts/engine_env.py +13 -4
  103. package/scripts/engine_failure.py +33 -0
  104. package/scripts/engine_fingerprint.py +114 -0
  105. package/scripts/engine_health.py +130 -0
  106. package/scripts/engine_states.py +50 -0
  107. package/scripts/engines_base.py +31 -19
  108. package/scripts/engines_builders_archive.py +4 -3
  109. package/scripts/engines_builders_batch11.py +2 -1
  110. package/scripts/engines_builders_batch13.py +4 -3
  111. package/scripts/engines_builders_batch14.py +2 -1
  112. package/scripts/engines_builders_batch15.py +2 -1
  113. package/scripts/engines_builders_batch9.py +2 -2
  114. package/scripts/engines_builders_cn.py +7 -7
  115. package/scripts/engines_builders_data.py +12 -11
  116. package/scripts/engines_builders_data_macro.py +5 -4
  117. package/scripts/engines_builders_dsh.py +2 -1
  118. package/scripts/engines_builders_feeds.py +34 -19
  119. package/scripts/engines_builders_finance.py +2 -1
  120. package/scripts/engines_builders_intl.py +3 -2
  121. package/scripts/engines_builders_media.py +59 -12
  122. package/scripts/engines_builders_science.py +8 -7
  123. package/scripts/engines_builders_search.py +19 -8
  124. package/scripts/engines_builders_skill.py +2 -1
  125. package/scripts/engines_builders_tech.py +19 -19
  126. package/scripts/engines_builders_weather.py +9 -4
  127. package/scripts/engines_fields.py +23 -0
  128. package/scripts/engines_http.py +50 -1
  129. package/scripts/engines_mcp.py +28 -6
  130. package/scripts/evidence_grounding.py +182 -0
  131. package/scripts/evidence_loop.py +15 -1
  132. package/scripts/extend_route_labels.py +6 -0
  133. package/scripts/fetch_browser.py +25 -10
  134. package/scripts/fetch_jina.py +98 -0
  135. package/scripts/fetch_v3.py +52 -93
  136. package/scripts/gate_manifest_check.py +75 -0
  137. package/scripts/gen_readme_art.py +264 -0
  138. package/scripts/image_vision/vision_probe +0 -0
  139. package/scripts/install.sh +2 -0
  140. package/scripts/matrix_search_eval.py +8 -10
  141. package/scripts/mcp_transport.py +33 -9
  142. package/scripts/numeric_verify.py +12 -2
  143. package/scripts/output_transparency.py +3 -0
  144. package/scripts/pre-commit +57 -8
  145. package/scripts/query_operators.py +229 -1
  146. package/scripts/quota.py +46 -63
  147. package/scripts/recovery.py +19 -16
  148. package/scripts/recovery_runner.py +29 -10
  149. package/scripts/redskill/redskill_engine.py +2 -1
  150. package/scripts/release.py +16 -1
  151. package/scripts/research_gates.py +85 -1
  152. package/scripts/route.py +8 -0
  153. package/scripts/route_combo.py +24 -3
  154. package/scripts/route_policy.py +1 -1
  155. package/scripts/search_attribution.py +20 -0
  156. package/scripts/search_entry.py +27 -0
  157. package/scripts/search_output.py +18 -7
  158. package/scripts/search_pipeline.py +3 -3
  159. package/scripts/semantic_evidence.py +20 -11
  160. package/scripts/serp_guard.py +13 -1
  161. package/scripts/settings_page.py +1 -0
  162. package/scripts/single_flight.py +1 -1
  163. package/scripts/social_engines/hackernews_engine.py +2 -1
  164. package/scripts/social_engines/reddit_engine.py +2 -1
  165. package/scripts/social_engines/zhihu_engine.py +2 -1
  166. package/scripts/source_audit.py +42 -7
  167. package/scripts/source_discovery.py +611 -0
  168. package/scripts/sync_backends.py +45 -0
  169. package/scripts/usage_log.py +24 -9
  170. package/scripts/watch.py +3 -3
  171. package/scripts/zhihu_quota.py +2 -1
  172. package/sub-skills/argo-wide-research/SKILL.md +7 -5
  173. package/sub-skills/ego-search/{SKILL.md → README.md} +24 -47
  174. package/sub-skills/ego-search/scripts/ego_search.py +195 -19
  175. package/sub-skills/ego-search/scripts/pacing.py +291 -0
  176. package/sub-skills/ego-search/scripts/quality.py +262 -6
  177. package/sub-skills/ego-search/scripts/runtime.py +7 -1
  178. package/sub-skills/ego-search/scripts/site_profiles.py +157 -0
  179. package/sub-skills/ego-search/scripts/webbridge_adapter.py +7 -1
  180. package/sub-skills/js-run/{SKILL.md → README.md} +3 -20
  181. package/sub-skills/local-search/{SKILL.md → README.md} +3 -8
  182. package/sub-skills/local-search/engine_registry.py +32 -7
  183. package/sub-skills/local-seek/SKILL.md +20 -22
@@ -0,0 +1,703 @@
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 } from 'node:child_process'
10
+ import { readFileSync } from 'node:fs'
11
+ import { homedir } from 'node:os'
12
+ import { dirname, join } from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { resolveArgoEnv } from './specs.js'
15
+ import { buildCrossLingualTracks, evaluateGates } from './wide-research.js'
16
+ import {
17
+ buildEvidenceContext,
18
+ buildFallbackSummary,
19
+ buildSystemPrompt,
20
+ callArgoSearch,
21
+ extractCitations,
22
+ MODES,
23
+ MODE_LABELS,
24
+ resolveLocalSearchPath,
25
+ runClarifyIfShort,
26
+ runEvidenceScoring,
27
+ streamLlmAnswer,
28
+ } from './workbench-search.js'
29
+ import {
30
+ buildSuggestions,
31
+ createHotspotRefresher,
32
+ loadHotspotStore,
33
+ updateRefreshTime,
34
+ } from './workbench-suggestions.js'
35
+ import { checkLoopbackAndOrigin, resolveAuthStatusWithBgVerify } from './route-guard.js'
36
+ import {
37
+ acquireStateFileLock,
38
+ breakerFilePath,
39
+ loadWatches,
40
+ mergedLaunchdPath,
41
+ mutateWatches,
42
+ readStaticAssetCached,
43
+ releaseStateFileLock,
44
+ resolveArgoBin,
45
+ runArgoCli,
46
+ WATCH_STORE_FILE,
47
+ } from './workbench-io.js'
48
+
49
+ // 供既有测试与外部调用方沿旧入口取用(真源在 workbench-search.js)
50
+ export { buildSearchCliArgs, summarizeTrackRuns } from './workbench-search.js'
51
+
52
+ const HERE = dirname(fileURLToPath(import.meta.url))
53
+ const CLIENT_FILE = join(HERE, 'workbench-client.js')
54
+ const MD_FILE = join(HERE, 'workbench-md.js')
55
+
56
+ const CACHE_TTL_MS = 5 * 60 * 1000
57
+ const MAX_CACHE_ENTRIES = 32
58
+ const MAX_DIAGNOSTICS = 20
59
+ const MAX_WATCHES = 20
60
+
61
+ function sendJson(res, status, data) {
62
+ if (res.writableEnded) return
63
+ if (res.headersSent) {
64
+ // SSE 头已 flush 后再 setHeader 会抛 ERR_HTTP_HEADERS_SENT(2026-11-18
65
+ // 实跑复现:followup 传 cards:[null] 在 flushHeaders 后抛 TypeError,
66
+ // 落到这里二次抛 → 响应悬挂 + 异常逃出 async handler)。改发 SSE
67
+ // failure 事件收尾,让客户端与连接都能干净结束。
68
+ sendSse(res, 'failure', data)
69
+ if (!res.writableEnded) res.end()
70
+ return
71
+ }
72
+ res.statusCode = status
73
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
74
+ res.setHeader('Cache-Control', 'no-store')
75
+ res.end(JSON.stringify(data))
76
+ }
77
+
78
+ function sendSse(res, event, data) {
79
+ if (res.writableEnded || res.destroyed) return
80
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
81
+ }
82
+
83
+ async function readJsonBody(req, maxBytes = 256 * 1024) {
84
+ const chunks = []
85
+ let size = 0
86
+ for await (const chunk of req) {
87
+ size += chunk.length
88
+ if (size > maxBytes) throw new Error('request body too large')
89
+ chunks.push(chunk)
90
+ }
91
+ const raw = Buffer.concat(chunks).toString('utf8').trim()
92
+ return raw ? JSON.parse(raw) : {}
93
+ }
94
+
95
+ function readEgoSearchStatus() {
96
+ const statePath = process.env.EGO_SEARCH_STATE || join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'ego-search.json')
97
+ try {
98
+ const parsed = JSON.parse(readFileSync(statePath, 'utf8'))
99
+ return { enabled: Boolean(parsed?.enabled), enabledAt: parsed?.enabled_at || null }
100
+ } catch {
101
+ return { enabled: false, enabledAt: null }
102
+ }
103
+ }
104
+
105
+ function readBreakerSummary() {
106
+ try {
107
+ const raw = JSON.parse(readFileSync(breakerFilePath(), 'utf8'))
108
+ const engines = raw?.engines && typeof raw.engines === 'object' ? raw.engines : {}
109
+ const tripped = []
110
+ let total = 0
111
+ for (const [name, info] of Object.entries(engines)) {
112
+ if (!info || typeof info !== 'object') continue
113
+ total += 1
114
+ if (info.state && info.state !== 'closed') {
115
+ tripped.push({
116
+ engine: name,
117
+ state: info.state,
118
+ opens: info.opens || 0,
119
+ lastError: String(info.last_error || '').slice(0, 60),
120
+ })
121
+ }
122
+ }
123
+ tripped.sort((a, b) => (b.opens || 0) - (a.opens || 0))
124
+ return { total, nonClosedCount: tripped.length, topTripped: tripped.slice(0, 8) }
125
+ } catch {
126
+ return { total: 0, nonClosedCount: 0, topTripped: [] }
127
+ }
128
+ }
129
+
130
+ export function createWorkbenchHandler(ctx, config, getCredentials, options = {}) {
131
+ const authVerifyCache = new Map()
132
+ const authVerifyInflight = new Set()
133
+ const cache = new Map()
134
+ const inflight = new Map()
135
+ const diagnostics = []
136
+ let watches = loadWatches()
137
+ let watchBusy = false
138
+
139
+ // 热榜触发端(inflight 复用 + 全失败 1h 退避)实现在 workbench-suggestions.js
140
+ const hotspotRefresher = createHotspotRefresher({
141
+ buildRunner: async () => {
142
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
143
+ return (cliArgs) => runArgoCli(cliArgs, { env, timeoutMs: 12000 })
144
+ },
145
+ })
146
+ const triggerDailyHotspotRefresh = hotspotRefresher.trigger
147
+ const hotspotRetryDue = hotspotRefresher.retryDue
148
+
149
+ const executeWatch = async (watch) => {
150
+ const started = Date.now()
151
+ const credentials = typeof getCredentials === 'function' ? getCredentials() : undefined
152
+ try {
153
+ const env = await resolveArgoEnv(config, { credentials }).catch(() => ({}))
154
+ const { cards } = await callArgoSearch(config, env, watch.query, watch.mode, true, AbortSignal.timeout(45000))
155
+ let summary = ''
156
+ if (cards.length > 0) {
157
+ const evidence = buildEvidenceContext(cards, 9000)
158
+ const llmRes = await streamLlmAnswer(ctx, {
159
+ system: buildSystemPrompt(watch.mode),
160
+ messages: [{
161
+ role: 'user',
162
+ content: [{ type: 'text', text: `定时追踪任务:${watch.query}\n\n最新检索证据:\n\n${evidence}\n\n请用简明结构概括最新动态,并在句末标注 [1]、[2] 引用编号。` }],
163
+ }],
164
+ signal: AbortSignal.timeout(35000),
165
+ onDelta: () => {},
166
+ })
167
+ summary = llmRes.text || buildFallbackSummary(watch.query, watch.mode, cards, llmRes)
168
+ } else {
169
+ summary = buildFallbackSummary(watch.query, watch.mode, cards)
170
+ }
171
+ watch.lastRunAt = new Date().toISOString()
172
+ watch.nextRunAt = new Date(Date.now() + watch.intervalMinutes * 60000).toISOString()
173
+ watch.lastStatus = 'ok'
174
+ watch.lastCardCount = cards.length
175
+ watch.lastSummary = summary
176
+ watch.lastCards = cards.slice(0, 10)
177
+ watch.lastDurationMs = Date.now() - started
178
+ } catch (err) {
179
+ watch.lastRunAt = new Date().toISOString()
180
+ watch.nextRunAt = new Date(Date.now() + watch.intervalMinutes * 60000).toISOString()
181
+ watch.lastStatus = `error: ${String(err?.message ?? err)}`
182
+ }
183
+ // 按 id upsert 合并写:磁盘是唯一真源,另一宿主对其他 watch 的增删改不被抹掉
184
+ // (旧 saveWatches(watches) 全量覆盖写,2026-11-21 审计 P1)
185
+ const updated = mutateWatches((list) => {
186
+ const idx = list.findIndex(w => w.id === watch.id)
187
+ if (idx >= 0) list[idx] = watch
188
+ else list.unshift(watch)
189
+ return list
190
+ })
191
+ if (Array.isArray(updated)) watches = updated
192
+ return watch
193
+ }
194
+
195
+ const timer = setInterval(async () => {
196
+ if (!hotspotRefresher.isBusy() && hotspotRetryDue(loadHotspotStore())) {
197
+ triggerDailyHotspotRefresh()
198
+ }
199
+ if (watchBusy) return
200
+ // 每 tick 重读磁盘:另一宿主刚增删的 watch 立即可见,不靠 60s 前的内存快照
201
+ watches = loadWatches()
202
+ const now = Date.now()
203
+ const due = watches.find(w => w.enabled !== false && (!w.nextRunAt || Date.parse(w.nextRunAt) <= now))
204
+ if (!due) return
205
+ // 跨宿主执行互斥:单锁串行化全部 watch 执行(最坏 ~80s << 5min stale 阈值),
206
+ // 抢不到说明另一宿主在跑,本轮让路——被让路的 watch 下轮仍 due 会重试
207
+ const execLock = acquireStateFileLock(`${WATCH_STORE_FILE}.exec.lock`)
208
+ if (!execLock) return
209
+ watchBusy = true
210
+ try { await executeWatch(due) } finally { watchBusy = false; releaseStateFileLock(execLock) }
211
+ }, 60 * 1000)
212
+ timer.unref?.()
213
+
214
+ const recordDiag = (entry) => {
215
+ diagnostics.unshift({ ...entry, ts: new Date().toISOString() })
216
+ if (diagnostics.length > MAX_DIAGNOSTICS) diagnostics.length = MAX_DIAGNOSTICS
217
+ }
218
+
219
+ const getCached = (key) => {
220
+ const hit = cache.get(key)
221
+ if (!hit) return null
222
+ if (Date.now() - hit.ts > CACHE_TTL_MS) {
223
+ cache.delete(key)
224
+ return null
225
+ }
226
+ return hit
227
+ }
228
+
229
+ const setCached = (key, value) => {
230
+ if (cache.size >= MAX_CACHE_ENTRIES) {
231
+ const oldest = cache.keys().next().value
232
+ if (oldest) cache.delete(oldest)
233
+ }
234
+ cache.set(key, { ...value, ts: Date.now() })
235
+ }
236
+
237
+ const workbenchHandler = async (req, res) => {
238
+ try {
239
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
240
+ const path = url.pathname
241
+
242
+ if (path === '/argo/workbench-client.js' && req.method === 'GET') {
243
+ const source = readStaticAssetCached(CLIENT_FILE)
244
+ res.statusCode = 200
245
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
246
+ res.setHeader('Cache-Control', 'no-store')
247
+ res.end(source)
248
+ return
249
+ }
250
+
251
+ if (path === '/argo/workbench-md.js' && req.method === 'GET') {
252
+ const source = readStaticAssetCached(MD_FILE)
253
+ res.statusCode = 200
254
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8')
255
+ res.setHeader('Cache-Control', 'no-store')
256
+ res.end(source)
257
+ return
258
+ }
259
+
260
+ if (path.startsWith('/argo/api/') && !checkLoopbackAndOrigin(ctx, req)) {
261
+ sendJson(res, 403, { error: 'forbidden_origin' })
262
+ return
263
+ }
264
+
265
+ if (path === '/argo/api/auth-status' && req.method === 'GET') {
266
+ const runCli = options.runAuthCli || (async (cliArgs) => {
267
+ const env = await resolveArgoEnv(config, { credentials: getCredentials?.() })
268
+ return runArgoCli(cliArgs, { env, timeoutMs: 8000 })
269
+ })
270
+ const items = await resolveAuthStatusWithBgVerify({
271
+ runCli, verifyCache: authVerifyCache, inflight: authVerifyInflight,
272
+ allowVerify: url.searchParams.get('verify') !== '0',
273
+ })
274
+ sendJson(res, 200, { ok: true, profiles: items })
275
+ return
276
+ }
277
+
278
+ if (path === '/argo/api/watches' && req.method === 'GET') {
279
+ sendJson(res, 200, { ok: true, items: watches })
280
+ return
281
+ }
282
+
283
+ if (path === '/argo/api/watches' && req.method === 'POST') {
284
+ const body = await readJsonBody(req)
285
+ const query = String(body.query || '').trim()
286
+ const mode = MODES.has(body.mode) ? body.mode : 'general'
287
+ const intervalMinutes = Math.max(60, Math.min(43200, Number(body.intervalMinutes) || 1440))
288
+ if (!query) { sendJson(res, 400, { error: 'missing_query' }); return }
289
+ const item = {
290
+ id: `w_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`,
291
+ query,
292
+ mode,
293
+ modeLabel: MODE_LABELS[mode] || mode,
294
+ intervalMinutes,
295
+ enabled: true,
296
+ createdAt: new Date().toISOString(),
297
+ nextRunAt: new Date(Date.now() + intervalMinutes * 60000).toISOString(),
298
+ lastRunAt: null,
299
+ lastStatus: 'pending',
300
+ lastCardCount: 0,
301
+ lastSummary: '',
302
+ lastCards: [],
303
+ }
304
+ const updatedList = mutateWatches((list) => {
305
+ list.unshift(item)
306
+ if (list.length > MAX_WATCHES) list.length = MAX_WATCHES
307
+ return list
308
+ })
309
+ if (!Array.isArray(updatedList)) { sendJson(res, 409, { error: 'watch_busy' }); return }
310
+ watches = updatedList
311
+ sendJson(res, 200, { ok: true, item, items: watches })
312
+ return
313
+ }
314
+
315
+ if (path === '/argo/api/watches/run' && req.method === 'POST') {
316
+ const body = await readJsonBody(req)
317
+ watches = loadWatches()
318
+ const target = watches.find(w => w.id === body.id)
319
+ if (!target) { sendJson(res, 404, { error: 'watch_not_found' }); return }
320
+ if (watchBusy) { sendJson(res, 409, { error: 'watch_busy' }); return }
321
+ // 与定时器同锁:手动触发与另一宿主的执行互斥
322
+ const execLock = acquireStateFileLock(`${WATCH_STORE_FILE}.exec.lock`)
323
+ if (!execLock) { sendJson(res, 409, { error: 'watch_busy' }); return }
324
+ watchBusy = true
325
+ try {
326
+ const updated = await executeWatch(target)
327
+ sendJson(res, 200, { ok: true, item: updated, items: watches })
328
+ } finally {
329
+ watchBusy = false
330
+ releaseStateFileLock(execLock)
331
+ }
332
+ return
333
+ }
334
+
335
+ if (path === '/argo/api/watches' && req.method === 'DELETE') {
336
+ const id = url.searchParams.get('id') || ''
337
+ const updatedList = mutateWatches((list) => list.filter(w => w.id !== id))
338
+ if (!Array.isArray(updatedList)) { sendJson(res, 409, { error: 'watch_busy' }); return }
339
+ watches = updatedList
340
+ sendJson(res, 200, { ok: true, items: watches })
341
+ return
342
+ }
343
+
344
+ if (path === '/argo/api/health' && req.method === 'GET') {
345
+ const hasLlm = Boolean(ctx.get?.('llm') && ctx.get?.('agentDefaultModel')?.currentSelection?.()?.model)
346
+ const hs = loadHotspotStore()
347
+ sendJson(res, 200, {
348
+ ok: true,
349
+ modes: Object.entries(MODE_LABELS).map(([id, label]) => ({ id, label })),
350
+ hasLlm,
351
+ egoSearch: readEgoSearchStatus(),
352
+ breaker: readBreakerSummary(),
353
+ hotspotSchedule: { refreshTime: hs.refreshTime, lastRefreshedAt: hs.lastRefreshedAt },
354
+ })
355
+ return
356
+ }
357
+
358
+ if (path === '/argo/api/suggestions' && req.method === 'GET') {
359
+ const reqMode = MODES.has(url.searchParams.get('mode')) ? url.searchParams.get('mode') : 'general'
360
+ const lang = url.searchParams.get('lang') || 'zh'
361
+ const shuffle = url.searchParams.get('shuffle') === '1'
362
+ const store = loadHotspotStore()
363
+ if (hotspotRetryDue(store)) triggerDailyHotspotRefresh()
364
+ // 本机模式建议词与 callLocalSeek 同源同路径
365
+ sendJson(res, 200, buildSuggestions(reqMode, lang, shuffle, {
366
+ watches,
367
+ hotspotStore: store,
368
+ cwd: resolveLocalSearchPath(config),
369
+ }))
370
+ return
371
+ }
372
+
373
+ if (path === '/argo/api/suggestions/config' && req.method === 'POST') {
374
+ const body = await readJsonBody(req)
375
+ let store = loadHotspotStore()
376
+ if (body.refreshTime !== undefined) {
377
+ const updated = updateRefreshTime(body.refreshTime)
378
+ if (!updated) { sendJson(res, 400, { error: 'invalid_refresh_time' }); return }
379
+ store = updated
380
+ }
381
+ if (body.refreshNow === true) {
382
+ store = await triggerDailyHotspotRefresh()
383
+ }
384
+ sendJson(res, 200, {
385
+ ok: true,
386
+ refreshTime: store.refreshTime,
387
+ lastRefreshedAt: store.lastRefreshedAt,
388
+ hotspotCount: (store.zh?.length || 0) + (store.en?.length || 0),
389
+ refreshing: hotspotRefresher.isBusy(),
390
+ // 锁被另一宿主占时如实回传 skipped,前端提示「另一宿主刷新中」,
391
+ // 不再拿旧时间戳冒充刚刷过(2026-11-21 审计:假成功边界)
392
+ skipped: store.skipped || null,
393
+ })
394
+ return
395
+ }
396
+
397
+ if (path === '/argo/api/ego-search' && req.method === 'POST') {
398
+ const body = await readJsonBody(req)
399
+ const action = body.enabled ? 'enable' : 'disable'
400
+ await new Promise((resolve) => {
401
+ execFile(
402
+ resolveArgoBin({ PATH: mergedLaunchdPath() }),
403
+ ['ego-search', action],
404
+ { timeout: 8000, env: { ...process.env, PATH: mergedLaunchdPath() } },
405
+ () => resolve(),
406
+ )
407
+ })
408
+ sendJson(res, 200, { ok: true, egoSearch: readEgoSearchStatus() })
409
+ return
410
+ }
411
+
412
+ if (path === '/argo/api/diagnostics' && req.method === 'GET') {
413
+ sendJson(res, 200, { ok: true, items: diagnostics })
414
+ return
415
+ }
416
+
417
+ if (path === '/argo/api/stream' && req.method === 'GET') {
418
+ const query = (url.searchParams.get('q') || '').trim()
419
+ const rawMode = (url.searchParams.get('mode') || 'general').trim()
420
+ const mode = MODES.has(rawMode) ? rawMode : 'general'
421
+ const refresh = url.searchParams.get('refresh') === '1'
422
+
423
+ if (!query) {
424
+ sendJson(res, 400, { error: 'missing_query' })
425
+ return
426
+ }
427
+
428
+ res.statusCode = 200
429
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
430
+ res.setHeader('Cache-Control', 'no-cache, no-transform')
431
+ res.setHeader('Connection', 'keep-alive')
432
+ res.flushHeaders?.()
433
+
434
+ const ac = new AbortController()
435
+ req.on('close', () => ac.abort())
436
+
437
+ const startedAt = Date.now()
438
+ const cacheKey = `${mode}::${query.toLowerCase()}`
439
+
440
+ try {
441
+ sendSse(res, 'status', { stage: 'searching', message: `正在通过 Argo 多源检索(${MODE_LABELS[mode]})…` })
442
+ const researchTracks = mode === 'research' ? buildCrossLingualTracks(query, 3) : null
443
+ sendSse(res, 'plan', {
444
+ query,
445
+ mode,
446
+ modeLabel: MODE_LABELS[mode],
447
+ tracks: researchTracks
448
+ ? researchTracks.map(t => t.title)
449
+ : (mode === 'local' ? ['本机 FTS/rg 索引检索'] : ['智能路由检索', '证据梳理与引用']),
450
+ })
451
+
452
+ const credentials = typeof getCredentials === 'function' ? getCredentials() : undefined
453
+ const env = await resolveArgoEnv(config, { credentials }).catch(() => ({}))
454
+ const clarifyPromise = runClarifyIfShort(query, mode, env, ac.signal)
455
+
456
+ let cards
457
+ let payload
458
+ let trackStats
459
+ let cached = !refresh ? getCached(cacheKey) : null
460
+ if (cached) {
461
+ cards = cached.cards
462
+ payload = cached.payload
463
+ trackStats = cached.trackStats
464
+ } else {
465
+ let pending = !refresh ? inflight.get(cacheKey) : null
466
+ if (!pending) {
467
+ // 共享去重任务使用独立 signal,防止客户端 A 断连误杀同 key 并发等待的客户端 B
468
+ const searchSignal = refresh ? ac.signal : new AbortController().signal
469
+ pending = callArgoSearch(config, env, query, mode, refresh, searchSignal, researchTracks)
470
+ .finally(() => inflight.delete(cacheKey))
471
+ if (!refresh) inflight.set(cacheKey, pending)
472
+ }
473
+ const resData = await pending
474
+ cards = resData.cards
475
+ payload = resData.payload
476
+ trackStats = resData.trackStats
477
+ if (cards.length > 0) setCached(cacheKey, { cards, payload, trackStats })
478
+ }
479
+
480
+ if (ac.signal.aborted) return
481
+
482
+ const clarify = await clarifyPromise
483
+ if (clarify) sendSse(res, 'clarify', clarify)
484
+
485
+ if (mode !== 'local' && cards.length > 0) {
486
+ sendSse(res, 'status', { stage: 'verifying', message: '正在计算证据可信度与交叉验证…' })
487
+ const scored = await runEvidenceScoring(query, cards, env, ac.signal)
488
+ cards = scored.cards
489
+ if (scored.evidenceSummary) sendSse(res, 'evidence', scored.evidenceSummary)
490
+ }
491
+
492
+ sendSse(res, 'cards', {
493
+ cards,
494
+ funnel: payload?.funnel || null,
495
+ engines: [...new Set(cards.map(c => c.source))],
496
+ })
497
+ if (ac.signal.aborted) return
498
+
499
+ sendSse(res, 'status', { stage: 'synthesizing', message: '正在结合检索证据生成结构化分析…' })
500
+
501
+ const system = buildSystemPrompt(mode)
502
+ const evidence = buildEvidenceContext(cards)
503
+ const userPrompt = cards.length > 0
504
+ ? `问题:${query}\n\n以下是检索到的多源证据:\n\n${evidence}\n\n请严格依据上述证据回答,并在句末标注 [1]、[2] 等引用编号。`
505
+ : `问题:${query}\n\n当前未检索到外部网页结果,请如实说明并给出可行的关键词调整建议。`
506
+
507
+ const llmRes = await streamLlmAnswer(ctx, {
508
+ system,
509
+ messages: [{ role: 'user', content: [{ type: 'text', text: userPrompt }] }],
510
+ signal: ac.signal,
511
+ onDelta: (delta) => sendSse(res, 'answer', { delta }),
512
+ })
513
+
514
+ let finalText = llmRes.text || ''
515
+ if (!llmRes.ok && finalText === '') {
516
+ if (llmRes.reason !== 'no_model') {
517
+ sendSse(res, 'answer-status', {
518
+ status: 'fallback',
519
+ message: `默认模型(${llmRes.model || 'unknown'})暂不可用:${llmRes.message || llmRes.reason},已自动切换为多源聚合直出视图`,
520
+ })
521
+ }
522
+ finalText = buildFallbackSummary(query, mode, cards, llmRes)
523
+ sendSse(res, 'answer', { delta: finalText })
524
+ } else if (!llmRes.ok && llmRes.reason !== 'aborted') {
525
+ sendSse(res, 'answer-status', {
526
+ status: 'interrupted',
527
+ message: llmRes.message || '模型输出中断,已保留已生成内容',
528
+ })
529
+ }
530
+
531
+ const citations = extractCitations(finalText, cards)
532
+ sendSse(res, 'citations', citations)
533
+ if (mode === 'research') {
534
+ const total = (researchTracks || []).length
535
+ // 真实 track 成败统计进门禁;旧缓存条目无 trackStats 时按结果有无推断,
536
+ // 不再恒注入 completedTracks/failedTracks: 0 的假章(2026-11-21 审计)
537
+ const stats = trackStats || {
538
+ total,
539
+ completed: cards.length > 0 ? total : 0,
540
+ failed: 0,
541
+ }
542
+ const gate = evaluateGates({
543
+ answer: finalText,
544
+ sources: cards.map(c => ({ url: c.url, title: c.title, domain: c.domain })),
545
+ tracks: researchTracks || [],
546
+ warnings: [],
547
+ stats: {
548
+ sourceCount: cards.length,
549
+ completedTracks: stats.completed,
550
+ failedTracks: stats.failed,
551
+ },
552
+ })
553
+ sendSse(res, 'gate', gate)
554
+ }
555
+ sendSse(res, 'done', {
556
+ durationMs: Date.now() - startedAt,
557
+ cardCount: cards.length,
558
+ verifiedCount: cards.filter(c => c.verified).length,
559
+ model: llmRes.model || 'none',
560
+ usage: llmRes.usage || null,
561
+ })
562
+
563
+ recordDiag({
564
+ query,
565
+ mode,
566
+ durationMs: Date.now() - startedAt,
567
+ cardCount: cards.length,
568
+ verifiedCount: cards.filter(c => c.verified).length,
569
+ citedCount: citations.citedIndices.length,
570
+ status: llmRes.ok ? 'ok' : (llmRes.reason || 'fallback'),
571
+ usage: llmRes.usage || null,
572
+ })
573
+ } catch (err) {
574
+ if (!ac.signal.aborted) {
575
+ sendSse(res, 'failure', { message: String(err?.message ?? err) })
576
+ recordDiag({
577
+ query,
578
+ mode,
579
+ durationMs: Date.now() - startedAt,
580
+ cardCount: 0,
581
+ status: 'error',
582
+ error: String(err?.message ?? err),
583
+ })
584
+ }
585
+ } finally {
586
+ if (!res.writableEnded) res.end()
587
+ }
588
+ return
589
+ }
590
+
591
+ if (path === '/argo/api/followup' && req.method === 'POST') {
592
+ const body = await readJsonBody(req)
593
+ const question = String(body.question || '').trim()
594
+ // 元素级过滤:null/非对象条目会在 buildEvidenceContext 与 history
595
+ // 映射处抛 TypeError(2026-11-18 实跑复现 cards:[null] 崩溃链)
596
+ const cards = Array.isArray(body.cards)
597
+ ? body.cards.filter(c => c && typeof c === 'object')
598
+ : []
599
+ const history = Array.isArray(body.history)
600
+ ? body.history.filter(h => h && typeof h === 'object')
601
+ : []
602
+ const mode = MODES.has(body.mode) ? body.mode : 'general'
603
+
604
+ if (!question) {
605
+ sendJson(res, 400, { error: 'missing_question' })
606
+ return
607
+ }
608
+
609
+ res.statusCode = 200
610
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
611
+ res.setHeader('Cache-Control', 'no-cache, no-transform')
612
+ res.setHeader('Connection', 'keep-alive')
613
+ res.flushHeaders?.()
614
+
615
+ const ac = new AbortController()
616
+ const onClose = () => { if (!res.writableEnded) ac.abort() }
617
+ if (typeof res.on === 'function') res.on('close', onClose)
618
+ else if (typeof req.on === 'function') req.on('close', onClose)
619
+
620
+ try {
621
+ const evidence = buildEvidenceContext(cards)
622
+ const messages = [
623
+ {
624
+ role: 'user',
625
+ content: [{ type: 'text', text: `原始问题:${body.query || ''}\n\n已检索证据:\n${evidence}` }],
626
+ },
627
+ ...history.slice(-6).map(item => ({
628
+ role: item.role === 'assistant' ? 'assistant' : 'user',
629
+ content: [{ type: 'text', text: String(item.text || '') }],
630
+ })),
631
+ {
632
+ role: 'user',
633
+ content: [{ type: 'text', text: `基于上述已检索证据继续追问:${question}\n请继续使用 [1]、[2] 引用编号;若当前证据未覆盖,请明确说明。` }],
634
+ },
635
+ ]
636
+
637
+ const llmRes = await streamLlmAnswer(ctx, {
638
+ system: buildSystemPrompt(mode),
639
+ messages,
640
+ signal: ac.signal,
641
+ onDelta: (delta) => sendSse(res, 'answer', { delta }),
642
+ })
643
+
644
+ if (!llmRes.ok && !llmRes.text) {
645
+ const msg = llmRes.reason === 'no_model'
646
+ ? '当前宿主未配置默认模型,无法进行多轮追问推理。'
647
+ : `默认模型(${llmRes.model || 'unknown'})调用未完成:${llmRes.message || llmRes.reason}`
648
+ sendSse(res, 'answer', { delta: msg })
649
+ }
650
+ sendSse(res, 'citations', extractCitations(llmRes.text || '', cards))
651
+ sendSse(res, 'done', { ok: llmRes.ok })
652
+ } catch (err) {
653
+ if (!ac.signal.aborted) {
654
+ sendSse(res, 'failure', { message: String(err?.message ?? err) })
655
+ }
656
+ } finally {
657
+ if (!res.writableEnded) res.end()
658
+ }
659
+ return
660
+ }
661
+
662
+ sendJson(res, 404, { error: 'not_found', path })
663
+ } catch (err) {
664
+ sendJson(res, 500, { error: 'internal_error', message: String(err?.message ?? err) })
665
+ }
666
+ }
667
+ workbenchHandler.dispose = () => clearInterval(timer)
668
+ return workbenchHandler
669
+ }
670
+
671
+ export function registerArgoWorkbench(ctx, config, getCredentials, options = {}) {
672
+ const attach = (targetCtx) => {
673
+ let webServer
674
+ try {
675
+ webServer = targetCtx?.get?.('webServer') ?? targetCtx?.webServer
676
+ } catch {
677
+ return undefined
678
+ }
679
+ if (!webServer || typeof webServer.register !== 'function') return undefined
680
+ const handler = createWorkbenchHandler(targetCtx, config, getCredentials, options)
681
+ const off = webServer.register({ kind: 'prefix', path: '/argo', handler })
682
+ return () => {
683
+ handler.dispose?.()
684
+ if (typeof off === 'function') off()
685
+ }
686
+ }
687
+
688
+ if (typeof ctx?.inject === 'function') {
689
+ try {
690
+ ctx.inject(['webServer'], (subCtx) => {
691
+ const off = attach(subCtx)
692
+ if (off && typeof subCtx.effect === 'function') subCtx.effect(() => off)
693
+ })
694
+ return undefined
695
+ } catch {
696
+ /* 测试环境或无 webServer 时静默跳过 */
697
+ }
698
+ }
699
+
700
+ const direct = attach(ctx)
701
+ if (direct && typeof ctx?.effect === 'function') ctx.effect(() => direct)
702
+ return direct
703
+ }