@abhishek944/pi-web-access 0.0.0-stage → 0.1.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 (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
@@ -0,0 +1,761 @@
1
+ import http, { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import { generateCuratorPage } from "./curator-page.ts";
3
+ import type { ProviderAvailability } from "./gemini-search.ts";
4
+ import type { SummaryMeta } from "./summary-review.ts";
5
+ import { resolveCuratorNetworkConfig } from "./utils.ts";
6
+
7
+ const STALE_THRESHOLD_MS = 30000;
8
+ const WATCHDOG_INTERVAL_MS = 1000;
9
+ const MAX_BODY_SIZE = 64 * 1024;
10
+
11
+ type ServerState = "SEARCHING" | "RESULT_SELECTION" | "COMPLETED";
12
+ type CuratorResultEventData = IndexedCuratorSearchEntry & { slotIndex?: number };
13
+ type CuratorSearchErrorEventData = { queryIndex: number; query: string; error: string; provider?: string; slotIndex?: number };
14
+ type CuratorStoredEvent =
15
+ | { event: "result"; data: CuratorResultEventData }
16
+ | { event: "search-error"; data: CuratorSearchErrorEventData };
17
+
18
+ export interface CuratorServerOptions {
19
+ queries: string[];
20
+ /** First index available to searches added while initial results are still streaming. */
21
+ initialResultIndexCapacity?: number;
22
+ sessionToken: string;
23
+ timeout: number;
24
+ availableProviders: ProviderAvailability;
25
+ defaultProvider: string;
26
+ searchProvider: string;
27
+ summaryModels: Array<{ value: string; label: string }>;
28
+ defaultSummaryModel: string | null;
29
+ }
30
+
31
+ export interface CuratorSearchEntry {
32
+ answer: string;
33
+ results: Array<{ title: string; url: string; domain: string; snippet?: string }>;
34
+ provider: string;
35
+ error?: string;
36
+ }
37
+
38
+ export interface IndexedCuratorSearchEntry extends CuratorSearchEntry {
39
+ queryIndex: number;
40
+ query: string;
41
+ }
42
+
43
+ export interface CuratorServerCallbacks {
44
+ onSubmit: (payload: { selectedQueryIndices: number[]; summary?: string; summaryMeta?: SummaryMeta; rawResults?: boolean; autoApproveRemainingSearches?: boolean }) => void;
45
+ onCancel: (reason: "user" | "timeout" | "stale") => void;
46
+ onProviderChange: (provider: string) => void;
47
+ onAddSearch: (query: string, provider?: string) => Promise<CuratorSearchEntry[]>;
48
+ onAddSearchResults: (entries: IndexedCuratorSearchEntry[]) => void;
49
+ onSummarize: (
50
+ selectedQueryIndices: number[],
51
+ signal: AbortSignal,
52
+ model?: string,
53
+ feedback?: string,
54
+ ) => Promise<{ summary: string; meta: SummaryMeta }>;
55
+ onRewriteQuery: (query: string, signal: AbortSignal) => Promise<string>;
56
+ }
57
+
58
+ export interface CuratorServerHandle {
59
+ server: http.Server;
60
+ url: string;
61
+ close: () => void;
62
+ pushResult: (queryIndex: number, data: CuratorSearchEntry & { query?: string; slotIndex?: number }) => void;
63
+ pushError: (queryIndex: number, error: string, provider?: string, meta?: { query?: string; slotIndex?: number }) => void;
64
+ searchesDone: () => void;
65
+ /** Reports browser connection state so a cancelled search can surface WHY it
66
+ * went stale (e.g. the browser never connected). */
67
+ getConnectionState: () => { browserConnected: boolean; lastHeartbeatAgeMs: number };
68
+ }
69
+
70
+ function sendJson(res: ServerResponse, status: number, payload: unknown): void {
71
+ res.writeHead(status, {
72
+ "Content-Type": "application/json",
73
+ "Cache-Control": "no-store",
74
+ });
75
+ res.end(JSON.stringify(payload));
76
+ }
77
+
78
+ function parseJSONBody(req: IncomingMessage): Promise<unknown> {
79
+ return new Promise((resolve, reject) => {
80
+ let body = "";
81
+ let size = 0;
82
+ req.on("data", (chunk: Buffer) => {
83
+ size += chunk.length;
84
+ if (size > MAX_BODY_SIZE) {
85
+ req.destroy();
86
+ reject(new Error("Request body too large"));
87
+ return;
88
+ }
89
+ body += chunk.toString();
90
+ });
91
+ req.on("end", () => {
92
+ try {
93
+ resolve(JSON.parse(body));
94
+ } catch (err) {
95
+ const message = err instanceof Error ? err.message : String(err);
96
+ reject(new Error(`Invalid JSON: ${message}`));
97
+ }
98
+ });
99
+ req.on("error", reject);
100
+ });
101
+ }
102
+
103
+ async function parseBodyOrSend(req: IncomingMessage, res: ServerResponse): Promise<unknown | null> {
104
+ try {
105
+ return await parseJSONBody(req);
106
+ } catch (err) {
107
+ const message = err instanceof Error ? err.message : "Invalid body";
108
+ const status = message === "Request body too large" ? 413 : 400;
109
+ sendJson(res, status, { ok: false, error: message });
110
+ return null;
111
+ }
112
+ }
113
+
114
+ function normalizeSelectedIndices(
115
+ value: unknown,
116
+ options: { allowEmpty: boolean; maxExclusive: number },
117
+ ): { ok: true; indices: number[] } | { ok: false; error: string } {
118
+ if (!Array.isArray(value)) {
119
+ return { ok: false, error: "Invalid selection" };
120
+ }
121
+
122
+ if (!options.allowEmpty && value.length === 0) {
123
+ return { ok: false, error: "Invalid selection" };
124
+ }
125
+
126
+ const normalized: number[] = [];
127
+ const seen = new Set<number>();
128
+ for (const item of value) {
129
+ if (typeof item !== "number" || !Number.isInteger(item) || item < 0) {
130
+ return { ok: false, error: "Invalid selection" };
131
+ }
132
+ if (item >= options.maxExclusive) {
133
+ return { ok: false, error: "Invalid selection" };
134
+ }
135
+ if (seen.has(item)) {
136
+ continue;
137
+ }
138
+ seen.add(item);
139
+ normalized.push(item);
140
+ }
141
+
142
+ if (!options.allowEmpty && normalized.length === 0) {
143
+ return { ok: false, error: "Invalid selection" };
144
+ }
145
+
146
+ return { ok: true, indices: normalized };
147
+ }
148
+
149
+ function normalizeSummaryMeta(value: unknown): SummaryMeta | null {
150
+ if (!value || typeof value !== "object") return null;
151
+ const meta = value as Record<string, unknown>;
152
+
153
+ const model = meta.model === null
154
+ ? null
155
+ : typeof meta.model === "string"
156
+ ? meta.model
157
+ : undefined;
158
+ if (model === undefined) return null;
159
+
160
+ const durationMs = meta.durationMs;
161
+ if (typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs < 0) return null;
162
+
163
+ const tokenEstimate = meta.tokenEstimate;
164
+ if (typeof tokenEstimate !== "number" || !Number.isFinite(tokenEstimate) || tokenEstimate < 0) return null;
165
+
166
+ const fallbackUsed = meta.fallbackUsed;
167
+ if (typeof fallbackUsed !== "boolean") return null;
168
+
169
+ const fallbackReason = typeof meta.fallbackReason === "string" ? meta.fallbackReason : undefined;
170
+ if (meta.fallbackReason !== undefined && fallbackReason === undefined) return null;
171
+
172
+ const phase = meta.phase === "summary-model" || meta.phase === "deterministic-fallback"
173
+ ? meta.phase
174
+ : undefined;
175
+ if (meta.phase !== undefined && phase === undefined) return null;
176
+ if (phase === "deterministic-fallback" && fallbackUsed !== true) return null;
177
+ if (phase === "summary-model" && fallbackUsed !== false) return null;
178
+
179
+ const edited = typeof meta.edited === "boolean" ? meta.edited : undefined;
180
+ if (meta.edited !== undefined && edited === undefined) return null;
181
+
182
+ return {
183
+ model,
184
+ durationMs,
185
+ tokenEstimate,
186
+ fallbackUsed,
187
+ ...(fallbackReason !== undefined ? { fallbackReason } : {}),
188
+ ...(phase !== undefined ? { phase } : {}),
189
+ ...(edited !== undefined ? { edited } : {}),
190
+ };
191
+ }
192
+
193
+ export function startCuratorServer(
194
+ options: CuratorServerOptions,
195
+ callbacks: CuratorServerCallbacks,
196
+ ): Promise<CuratorServerHandle> {
197
+ const {
198
+ queries,
199
+ initialResultIndexCapacity,
200
+ sessionToken,
201
+ timeout,
202
+ availableProviders,
203
+ defaultProvider,
204
+ searchProvider,
205
+ summaryModels,
206
+ defaultSummaryModel,
207
+ } = options;
208
+ let browserConnected = false;
209
+ let lastHeartbeatAt = Date.now();
210
+ let stateChangedAt = Date.now();
211
+ let clientIdleMs: number | null = null;
212
+ let clientTimeoutSeconds = timeout;
213
+ let completed = false;
214
+ let watchdog: NodeJS.Timeout | null = null;
215
+ let state: ServerState = "SEARCHING";
216
+ let sseResponse: ServerResponse | null = null;
217
+ const streamedEventsByResultIndex = new Map<number, CuratorStoredEvent>();
218
+ let searchStreamDone = queries.length === 0;
219
+ let nextQueryIndex = Math.max(queries.length, initialResultIndexCapacity ?? queries.length);
220
+ let summarizeAbortController: AbortController | null = null;
221
+ let summarizeRequestSeq = 0;
222
+
223
+ let sseKeepalive: NodeJS.Timeout | null = null;
224
+
225
+ const abortInFlightSummarize = (): void => {
226
+ if (!summarizeAbortController) return;
227
+ summarizeAbortController.abort();
228
+ summarizeAbortController = null;
229
+ };
230
+
231
+ const markCompleted = (): boolean => {
232
+ if (completed) return false;
233
+ completed = true;
234
+ state = "COMPLETED";
235
+ stateChangedAt = Date.now();
236
+ if (watchdog) {
237
+ clearInterval(watchdog);
238
+ watchdog = null;
239
+ }
240
+ if (sseKeepalive) {
241
+ clearInterval(sseKeepalive);
242
+ sseKeepalive = null;
243
+ }
244
+ abortInFlightSummarize();
245
+ if (sseResponse) {
246
+ try { sseResponse.end(); } catch {}
247
+ sseResponse = null;
248
+ }
249
+ return true;
250
+ };
251
+
252
+ const touchHeartbeat = (): void => {
253
+ lastHeartbeatAt = Date.now();
254
+ browserConnected = true;
255
+ };
256
+
257
+ const getEffectiveTimeoutMs = (): number => Math.max(1000, Math.floor(clientTimeoutSeconds) * 1000);
258
+
259
+ const shouldTimeoutFromClientIdle = (): boolean => (
260
+ state === "RESULT_SELECTION" &&
261
+ clientIdleMs !== null &&
262
+ clientIdleMs >= getEffectiveTimeoutMs()
263
+ );
264
+
265
+ function validateToken(body: unknown, res: ServerResponse): boolean {
266
+ if (!body || typeof body !== "object") {
267
+ sendJson(res, 400, { ok: false, error: "Invalid body" });
268
+ return false;
269
+ }
270
+ if ((body as { token?: string }).token !== sessionToken) {
271
+ sendJson(res, 403, { ok: false, error: "Invalid session" });
272
+ return false;
273
+ }
274
+ return true;
275
+ }
276
+
277
+ function isAvailableProvider(provider: string): boolean {
278
+ if (provider === "all") return availableProviders.all;
279
+ if (provider === "openai") return availableProviders.openai;
280
+ if (provider === "brave") return availableProviders.brave;
281
+ if (provider === "parallel") return availableProviders.parallel;
282
+ if (provider === "parallel-mcp") return availableProviders["parallel-mcp"];
283
+ if (provider === "tinyfish") return availableProviders.tinyfish;
284
+ if (provider === "searchinfinity") return availableProviders.searchinfinity;
285
+ if (provider === "querit") return availableProviders.querit;
286
+ if (provider === "tavily") return availableProviders.tavily;
287
+ if (provider === "tabstack") return availableProviders.tabstack;
288
+ if (provider === "firecrawl") return availableProviders.firecrawl;
289
+ if (provider === "jina") return availableProviders.jina;
290
+ if (provider === "kagi") return availableProviders.kagi;
291
+ if (provider === "bocha") return availableProviders.bocha;
292
+ if (provider === "ollama") return availableProviders.ollama;
293
+ if (provider === "searxng") return availableProviders.searxng;
294
+ if (provider === "degoog") return availableProviders.degoog;
295
+ if (provider === "duckduckgo") return availableProviders.duckduckgo;
296
+ if (provider === "perplexity") return availableProviders.perplexity;
297
+ if (provider === "exa") return availableProviders.exa;
298
+ if (provider === "gemini") return availableProviders.gemini;
299
+ if (provider === "kimi") return availableProviders.kimi;
300
+ if (provider === "anysearch") return availableProviders.anysearch;
301
+ if (provider === "xai") return availableProviders.xai;
302
+ if (provider === "mistral") return availableProviders.mistral;
303
+ if (provider === "you") return availableProviders.you;
304
+ if (provider === "baizhi") return availableProviders.baizhi;
305
+ if (provider === "zai") return availableProviders.zai;
306
+ if (provider === "valyu") return availableProviders.valyu;
307
+ if (provider === "keenable") return availableProviders.keenable;
308
+ if (provider === "ceramic") return availableProviders.ceramic;
309
+ if (provider === "linkup") return availableProviders.linkup;
310
+ if (provider === "ninerouter") return availableProviders.ninerouter;
311
+ if (provider === "cloudflare") return availableProviders.cloudflare;
312
+ if (provider === "deepseek") return availableProviders.deepseek;
313
+ return availableProviders.customProviders?.includes(provider) ?? false;
314
+ }
315
+
316
+ function writeSSE(res: ServerResponse, event: string, data: unknown): boolean {
317
+ const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
318
+ try {
319
+ res.write(payload);
320
+ return true;
321
+ } catch {
322
+ return false;
323
+ }
324
+ }
325
+
326
+ function sendSSE(event: string, data: unknown): void {
327
+ const res = sseResponse;
328
+ if (res && !res.writableEnded && res.socket && !res.socket.destroyed && writeSSE(res, event, data)) return;
329
+ if (sseResponse === res) sseResponse = null;
330
+ }
331
+
332
+ function retainStreamedEvent(event: CuratorStoredEvent): void {
333
+ streamedEventsByResultIndex.set(event.data.queryIndex, event);
334
+ }
335
+
336
+ function getStreamedEvents(): CuratorStoredEvent[] {
337
+ return [...streamedEventsByResultIndex.values()];
338
+ }
339
+
340
+ function replaySSE(res: ServerResponse): void {
341
+ for (const item of getStreamedEvents()) {
342
+ if (!writeSSE(res, item.event, item.data)) return;
343
+ }
344
+ if (searchStreamDone) writeSSE(res, "done", {});
345
+ }
346
+
347
+ const pageHtml = generateCuratorPage(
348
+ queries,
349
+ sessionToken,
350
+ timeout,
351
+ availableProviders,
352
+ defaultProvider,
353
+ searchProvider,
354
+ summaryModels,
355
+ defaultSummaryModel,
356
+ );
357
+
358
+ const server = http.createServer(async (req, res) => {
359
+ try {
360
+ const method = req.method || "GET";
361
+ const url = new URL(req.url || "/", `http://${req.headers.host || "127.0.0.1"}`);
362
+
363
+ if (method === "GET" && url.pathname === "/") {
364
+ const token = url.searchParams.get("session");
365
+ if (token !== sessionToken) {
366
+ res.writeHead(403, { "Content-Type": "text/plain" });
367
+ res.end("Invalid session");
368
+ return;
369
+ }
370
+ touchHeartbeat();
371
+ res.writeHead(200, {
372
+ "Content-Type": "text/html; charset=utf-8",
373
+ "Cache-Control": "no-store",
374
+ });
375
+ res.end(pageHtml);
376
+ return;
377
+ }
378
+
379
+ if (method === "GET" && url.pathname === "/events") {
380
+ const token = url.searchParams.get("session");
381
+ if (token !== sessionToken) {
382
+ res.writeHead(403, { "Content-Type": "text/plain" });
383
+ res.end("Invalid session");
384
+ return;
385
+ }
386
+ if (state === "COMPLETED") {
387
+ sendJson(res, 409, { ok: false, error: "No events available" });
388
+ return;
389
+ }
390
+ if (sseResponse) {
391
+ try { sseResponse.end(); } catch {}
392
+ }
393
+ res.writeHead(200, {
394
+ "Content-Type": "text/event-stream",
395
+ "Cache-Control": "no-cache",
396
+ Connection: "keep-alive",
397
+ "X-Accel-Buffering": "no",
398
+ });
399
+ res.flushHeaders();
400
+ if (res.socket) res.socket.setNoDelay(true);
401
+ sseResponse = res;
402
+ replaySSE(res);
403
+ if (sseKeepalive) clearInterval(sseKeepalive);
404
+ sseKeepalive = setInterval(() => {
405
+ if (sseResponse) {
406
+ try { sseResponse.write(":keepalive\n\n"); } catch {}
407
+ }
408
+ }, 15000);
409
+ req.on("close", () => {
410
+ if (sseResponse === res) sseResponse = null;
411
+ });
412
+ return;
413
+ }
414
+
415
+ if (method === "GET" && url.pathname === "/state") {
416
+ const token = url.searchParams.get("session");
417
+ if (token !== sessionToken) {
418
+ sendJson(res, 403, { ok: false, error: "Invalid session" });
419
+ return;
420
+ }
421
+ touchHeartbeat();
422
+ sendJson(res, 200, { ok: true, events: getStreamedEvents(), done: searchStreamDone });
423
+ return;
424
+ }
425
+
426
+ if (method === "POST" && url.pathname === "/heartbeat") {
427
+ const body = await parseBodyOrSend(req, res);
428
+ if (!body) return;
429
+ if (!validateToken(body, res)) return;
430
+ touchHeartbeat();
431
+ const heartbeat = body as { idleMs?: unknown; timeoutSec?: unknown };
432
+ if (typeof heartbeat.timeoutSec === "number" && Number.isFinite(heartbeat.timeoutSec) && heartbeat.timeoutSec > 0) {
433
+ clientTimeoutSeconds = Math.min(600, Math.floor(heartbeat.timeoutSec));
434
+ }
435
+ if (typeof heartbeat.idleMs === "number" && Number.isFinite(heartbeat.idleMs) && heartbeat.idleMs >= 0) {
436
+ clientIdleMs = Math.floor(heartbeat.idleMs);
437
+ }
438
+ const timedOut = shouldTimeoutFromClientIdle();
439
+ sendJson(res, 200, { ok: true });
440
+ if (timedOut && markCompleted()) {
441
+ setImmediate(() => callbacks.onCancel("timeout"));
442
+ }
443
+ return;
444
+ }
445
+
446
+ if (method === "POST" && url.pathname === "/provider") {
447
+ const body = await parseBodyOrSend(req, res);
448
+ if (!body) return;
449
+ if (!validateToken(body, res)) return;
450
+ const { provider } = body as { provider?: string };
451
+ if (typeof provider !== "string" || provider.length === 0) {
452
+ sendJson(res, 400, { ok: false, error: "Invalid provider" });
453
+ return;
454
+ }
455
+ if (!isAvailableProvider(provider)) {
456
+ sendJson(res, 400, { ok: false, error: `Provider unavailable: ${provider}` });
457
+ return;
458
+ }
459
+ setImmediate(() => callbacks.onProviderChange(provider));
460
+ sendJson(res, 200, { ok: true });
461
+ return;
462
+ }
463
+
464
+ if (method === "POST" && url.pathname === "/search") {
465
+ const body = await parseBodyOrSend(req, res);
466
+ if (!body) return;
467
+ if (!validateToken(body, res)) return;
468
+ if (state === "COMPLETED") {
469
+ sendJson(res, 409, { ok: false, error: "Session closed" });
470
+ return;
471
+ }
472
+ const { query, provider } = body as { query?: string; provider?: string };
473
+ if (typeof query !== "string" || query.trim().length === 0) {
474
+ sendJson(res, 400, { ok: false, error: "Invalid query" });
475
+ return;
476
+ }
477
+ if (provider !== undefined) {
478
+ if (typeof provider !== "string" || provider.length === 0) {
479
+ sendJson(res, 400, { ok: false, error: "Invalid provider" });
480
+ return;
481
+ }
482
+ if (!isAvailableProvider(provider)) {
483
+ sendJson(res, 400, { ok: false, error: `Provider unavailable: ${provider}` });
484
+ return;
485
+ }
486
+ }
487
+ const qi = nextQueryIndex++;
488
+ const trimmedQuery = query.trim();
489
+ touchHeartbeat();
490
+ try {
491
+ const results = await callbacks.onAddSearch(trimmedQuery, provider);
492
+ if (results.length === 0) throw new Error("Search returned no provider results");
493
+ const entries = results.map((result, index): IndexedCuratorSearchEntry => ({
494
+ ...result,
495
+ queryIndex: index === 0 ? qi : nextQueryIndex++,
496
+ query: trimmedQuery,
497
+ }));
498
+ callbacks.onAddSearchResults(entries);
499
+ sendJson(res, 200, { ok: true, ...entries[0], entries });
500
+ } catch (err) {
501
+ const message = err instanceof Error ? err.message : "Search failed";
502
+ const entry: IndexedCuratorSearchEntry = {
503
+ queryIndex: qi,
504
+ query: trimmedQuery,
505
+ answer: "",
506
+ results: [],
507
+ error: message,
508
+ provider: typeof provider === "string" && provider.length > 0 ? provider : defaultProvider,
509
+ };
510
+ callbacks.onAddSearchResults([entry]);
511
+ sendJson(res, 200, { ok: true, ...entry, entries: [entry] });
512
+ }
513
+ return;
514
+ }
515
+
516
+ if (method === "POST" && url.pathname === "/summarize") {
517
+ const body = await parseBodyOrSend(req, res);
518
+ if (!body) return;
519
+ if (!validateToken(body, res)) return;
520
+ if (state === "COMPLETED") {
521
+ sendJson(res, 409, { ok: false, error: "Session closed" });
522
+ return;
523
+ }
524
+
525
+ const parsed = normalizeSelectedIndices((body as { selected?: unknown }).selected, {
526
+ allowEmpty: false,
527
+ maxExclusive: nextQueryIndex,
528
+ });
529
+ if ("error" in parsed) {
530
+ sendJson(res, 400, { ok: false, error: parsed.error });
531
+ return;
532
+ }
533
+
534
+ let model: string | undefined;
535
+ const bodyModel = (body as { model?: unknown }).model;
536
+ if (bodyModel !== undefined) {
537
+ if (typeof bodyModel !== "string") {
538
+ sendJson(res, 400, { ok: false, error: "Invalid model" });
539
+ return;
540
+ }
541
+ const trimmedModel = bodyModel.trim();
542
+ model = trimmedModel.length > 0 ? trimmedModel : undefined;
543
+ }
544
+
545
+ const bodyFeedback = (body as { feedback?: unknown }).feedback;
546
+ const feedback = typeof bodyFeedback === "string" && bodyFeedback.trim().length > 0
547
+ ? bodyFeedback.trim()
548
+ : undefined;
549
+
550
+ abortInFlightSummarize();
551
+ const controller = new AbortController();
552
+ summarizeAbortController = controller;
553
+ const requestId = ++summarizeRequestSeq;
554
+
555
+ try {
556
+ const result = await callbacks.onSummarize(parsed.indices, controller.signal, model, feedback);
557
+ if (requestId !== summarizeRequestSeq || completed) {
558
+ sendJson(res, 409, { ok: false, error: "Summarize request superseded" });
559
+ return;
560
+ }
561
+ sendJson(res, 200, {
562
+ ok: true,
563
+ summary: result.summary,
564
+ meta: result.meta,
565
+ });
566
+ } catch (err) {
567
+ const message = err instanceof Error ? err.message : "Summary generation failed";
568
+ const status = controller.signal.aborted ? 409 : 500;
569
+ sendJson(res, status, { ok: false, error: message });
570
+ } finally {
571
+ if (summarizeAbortController === controller) {
572
+ summarizeAbortController = null;
573
+ }
574
+ }
575
+ return;
576
+ }
577
+
578
+ if (method === "POST" && url.pathname === "/rewrite") {
579
+ const body = await parseBodyOrSend(req, res);
580
+ if (!body) return;
581
+ if (!validateToken(body, res)) return;
582
+ if (state === "COMPLETED") {
583
+ sendJson(res, 409, { ok: false, error: "Session closed" });
584
+ return;
585
+ }
586
+ const { query } = body as { query?: unknown };
587
+ if (typeof query !== "string" || query.trim().length === 0) {
588
+ sendJson(res, 400, { ok: false, error: "Invalid query" });
589
+ return;
590
+ }
591
+ const controller = new AbortController();
592
+ req.on("close", () => controller.abort());
593
+ touchHeartbeat();
594
+ try {
595
+ const rewritten = await callbacks.onRewriteQuery(query.trim(), controller.signal);
596
+ sendJson(res, 200, { ok: true, query: rewritten });
597
+ } catch (err) {
598
+ const message = err instanceof Error ? err.message : "Rewrite failed";
599
+ const status = controller.signal.aborted ? 409 : 500;
600
+ sendJson(res, status, { ok: false, error: message });
601
+ }
602
+ return;
603
+ }
604
+
605
+ if (method === "POST" && url.pathname === "/submit") {
606
+ const body = await parseBodyOrSend(req, res);
607
+ if (!body) return;
608
+ if (!validateToken(body, res)) return;
609
+
610
+ const parsed = normalizeSelectedIndices((body as { selected?: unknown }).selected, {
611
+ allowEmpty: true,
612
+ maxExclusive: nextQueryIndex,
613
+ });
614
+ if ("error" in parsed) {
615
+ sendJson(res, 400, { ok: false, error: parsed.error });
616
+ return;
617
+ }
618
+
619
+ let summary: string | undefined;
620
+ const bodySummary = (body as { summary?: unknown }).summary;
621
+ if (bodySummary !== undefined) {
622
+ if (typeof bodySummary !== "string") {
623
+ sendJson(res, 400, { ok: false, error: "Invalid summary" });
624
+ return;
625
+ }
626
+ const trimmedSummary = bodySummary.trim();
627
+ summary = trimmedSummary.length > 0 ? trimmedSummary : undefined;
628
+ }
629
+
630
+ let summaryMeta: SummaryMeta | undefined;
631
+ const bodySummaryMeta = (body as { summaryMeta?: unknown }).summaryMeta;
632
+ if (bodySummaryMeta !== undefined) {
633
+ const parsedSummaryMeta = normalizeSummaryMeta(bodySummaryMeta);
634
+ if (!parsedSummaryMeta) {
635
+ sendJson(res, 400, { ok: false, error: "Invalid summaryMeta" });
636
+ return;
637
+ }
638
+ summaryMeta = parsedSummaryMeta;
639
+ }
640
+
641
+ if (state !== "SEARCHING" && state !== "RESULT_SELECTION") {
642
+ sendJson(res, 409, { ok: false, error: "Cannot submit in current state" });
643
+ return;
644
+ }
645
+ if (!markCompleted()) {
646
+ sendJson(res, 409, { ok: false, error: "Session closed" });
647
+ return;
648
+ }
649
+ const rawResults = (body as { rawResults?: unknown }).rawResults === true;
650
+ const autoApproveRemainingSearches = (body as { autoApproveRemainingSearches?: unknown }).autoApproveRemainingSearches === true;
651
+ sendJson(res, 200, { ok: true });
652
+ setImmediate(() => callbacks.onSubmit({
653
+ selectedQueryIndices: parsed.indices,
654
+ ...(summary !== undefined ? { summary } : {}),
655
+ ...(summaryMeta !== undefined ? { summaryMeta } : {}),
656
+ rawResults,
657
+ ...(autoApproveRemainingSearches ? { autoApproveRemainingSearches: true } : {}),
658
+ }));
659
+ return;
660
+ }
661
+
662
+ if (method === "POST" && url.pathname === "/cancel") {
663
+ const body = await parseBodyOrSend(req, res);
664
+ if (!body) return;
665
+ if (!validateToken(body, res)) return;
666
+ if (!markCompleted()) {
667
+ sendJson(res, 200, { ok: true });
668
+ return;
669
+ }
670
+ const { reason } = body as { reason?: string };
671
+ sendJson(res, 200, { ok: true });
672
+ const cancelReason = reason === "timeout" ? "timeout" : "user";
673
+ setImmediate(() => callbacks.onCancel(cancelReason));
674
+ return;
675
+ }
676
+
677
+ res.writeHead(404, { "Content-Type": "text/plain" });
678
+ res.end("Not found");
679
+ } catch (err) {
680
+ const message = err instanceof Error ? err.message : "Server error";
681
+ sendJson(res, 500, { ok: false, error: message });
682
+ }
683
+ });
684
+
685
+ return new Promise((resolve, reject) => {
686
+ const onError = (err: Error) => {
687
+ reject(new Error(`Curator server failed to start: ${err.message}`));
688
+ };
689
+
690
+ const networkConfig = resolveCuratorNetworkConfig();
691
+
692
+ server.once("error", onError);
693
+ server.listen(0, networkConfig.bind, () => {
694
+ server.off("error", onError);
695
+ const addr = server.address();
696
+ if (!addr || typeof addr === "string") {
697
+ reject(new Error("Curator server: invalid address"));
698
+ return;
699
+ }
700
+ const url = `http://${networkConfig.host}:${addr.port}/?session=${sessionToken}`;
701
+
702
+ watchdog = setInterval(() => {
703
+ if (completed) return;
704
+ if (!browserConnected) {
705
+ const noBrowserTimeoutMs = Math.max(5000, getEffectiveTimeoutMs());
706
+ if (state !== "RESULT_SELECTION") return;
707
+ if (Date.now() - stateChangedAt <= noBrowserTimeoutMs) return;
708
+ if (!markCompleted()) return;
709
+ setImmediate(() => callbacks.onCancel("timeout"));
710
+ return;
711
+ }
712
+ if (shouldTimeoutFromClientIdle()) {
713
+ if (!markCompleted()) return;
714
+ setImmediate(() => callbacks.onCancel("timeout"));
715
+ return;
716
+ }
717
+ if (Date.now() - lastHeartbeatAt <= STALE_THRESHOLD_MS) return;
718
+ const staleReason = state === "RESULT_SELECTION" ? "timeout" : "stale";
719
+ if (!markCompleted()) return;
720
+ setImmediate(() => callbacks.onCancel(staleReason));
721
+ }, WATCHDOG_INTERVAL_MS);
722
+
723
+ resolve({
724
+ server,
725
+ url,
726
+ close: () => {
727
+ const wasOpen = markCompleted();
728
+ try { server.close(); } catch {}
729
+ if (wasOpen) {
730
+ setImmediate(() => callbacks.onCancel("stale"));
731
+ }
732
+ },
733
+ pushResult: (queryIndex, data) => {
734
+ if (completed) return;
735
+ nextQueryIndex = Math.max(nextQueryIndex, queryIndex + 1);
736
+ const eventData: CuratorResultEventData = { ...data, queryIndex, query: data.query ?? queries[queryIndex] ?? "" };
737
+ retainStreamedEvent({ event: "result", data: eventData });
738
+ sendSSE("result", eventData);
739
+ },
740
+ pushError: (queryIndex, error, provider, meta) => {
741
+ if (completed) return;
742
+ nextQueryIndex = Math.max(nextQueryIndex, queryIndex + 1);
743
+ const eventData: CuratorSearchErrorEventData = { queryIndex, query: meta?.query ?? queries[queryIndex] ?? "", error, provider, slotIndex: meta?.slotIndex };
744
+ retainStreamedEvent({ event: "search-error", data: eventData });
745
+ sendSSE("search-error", eventData);
746
+ },
747
+ searchesDone: () => {
748
+ if (completed) return;
749
+ searchStreamDone = true;
750
+ sendSSE("done", {});
751
+ state = "RESULT_SELECTION";
752
+ stateChangedAt = Date.now();
753
+ },
754
+ getConnectionState: () => ({
755
+ browserConnected,
756
+ lastHeartbeatAgeMs: Date.now() - lastHeartbeatAt,
757
+ }),
758
+ });
759
+ });
760
+ });
761
+ }