@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,1162 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { awaitWithAbort } from "./abortable.ts";
4
+ import { activityMonitor } from "./activity.ts";
5
+ import { CredentialResolutionError } from "./credential-source.ts";
6
+ import { getApiKey, getVersionedApiBase, fetchGeminiApi, isGatewayConfigured, isGeminiApiAvailable, redactGeminiApiResponse } from "./gemini-api.ts";
7
+ import { isGeminiAdcAvailable } from "./gemini-adc.ts";
8
+ import { browserCookieAccessHint, browserCookieAccessHintLine, getGeminiWebAvailabilityDiagnostic, isGeminiWebAvailable, queryWithCookies, requestBrowserCookieAccess } from "./gemini-web.ts";
9
+ import type { BrowserCookieConsent } from "./gemini-web-config.ts";
10
+ import { isPerplexityAvailable, searchWithPerplexity, type SearchResult, type SearchResponse, type SearchOptions } from "./perplexity.ts";
11
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
12
+ import { judgeOffTopic, OFFTOPIC_JUDGE_MODELS, type OffTopicJudgeModel } from "./offtopic-judge.ts";
13
+ import { isExaAvailable, searchWithExa } from "./exa.ts";
14
+ import { isBraveAvailable, searchWithBrave } from "./brave.ts";
15
+ import {
16
+ isCurrentModelHostedSearchEligible,
17
+ isOpenAISearchAvailable,
18
+ isOpenAISubscriptionModelSelected,
19
+ OpenAIAlphaSearchUnsupportedError,
20
+ searchWithCurrentModelOpenAI,
21
+ searchWithOpenAI,
22
+ } from "./openai-search.ts";
23
+ import { isParallelAvailable, searchWithParallel } from "./parallel.ts";
24
+ import { isParallelMcpAvailable, searchWithParallelMcp } from "./parallel-mcp.ts";
25
+ import { isTinyFishAvailable, searchWithTinyFish } from "./tinyfish.ts";
26
+ import { isSearchinfinityAvailable, searchWithSearchinfinity } from "./searchinfinity.ts";
27
+ import { isQueritAvailable, searchWithQuerit } from "./querit.ts";
28
+ import { isTavilyAvailable, searchWithTavily } from "./tavily.ts";
29
+ import { isTabstackAvailable, searchWithTabstack } from "./tabstack.ts";
30
+ import { isYouAvailable, searchWithYou } from "./you.ts";
31
+ import { isFirecrawlAvailable, searchWithFirecrawl } from "./firecrawl.ts";
32
+ import { isJinaSearchAvailable, searchWithJina } from "./jina-search.ts";
33
+ import { isKagiAvailable, searchWithKagi } from "./kagi.ts";
34
+ import { isBochaAvailable, searchWithBocha } from "./bocha.ts";
35
+ import { isOllamaAvailable, searchWithOllama } from "./ollama.ts";
36
+ import { isSearXNGAvailable, searchWithSearXNG } from "./searxng.ts";
37
+ import { isDegoogAvailable, searchWithDegoog } from "./degoog.ts";
38
+ import { isDuckDuckGoAvailable, searchWithDuckDuckGo } from "./duckduckgo.ts";
39
+ import { isAnySearchAvailable, searchWithAnySearch } from "./anysearch.ts";
40
+ import { isXaiSearchAvailable, searchWithXai } from "./xai-search.ts";
41
+ import { isBaizhiAvailable, searchWithBaizhi } from "./baizhi.ts";
42
+ import { isZaiAvailable, searchWithZai } from "./zai.ts";
43
+ import { isValyuAvailable, searchWithValyu } from "./valyu.ts";
44
+ import { isKeenableAvailable, searchWithKeenable } from "./keenable.ts";
45
+ import { isCeramicAvailable, searchWithCeramic } from "./ceramic.ts";
46
+ import { isLinkupAvailable, searchWithLinkup } from "./linkup.ts";
47
+ import { isNineRouterAvailable, searchWithNineRouter } from "./ninerouter.ts";
48
+ import { isCloudflareSearchAvailable, searchWithCloudflare } from "./cloudflare-search.ts";
49
+ import { isDeepSeekAvailable, searchWithDeepSeek } from "./deepseek.ts";
50
+ import { isKimiSearchAvailable, searchWithKimi } from "./kimi-search.ts";
51
+ import { isMistralAvailable, searchWithMistral } from "./mistral-search.ts";
52
+ import { isCustomSearchProviderAvailable, parseCustomSearchProviders, searchWithCustomProvider, type CustomSearchProviderConfig } from "./custom-search.ts";
53
+ import { getWebSearchConfigPath } from "./utils.ts";
54
+ import { getRetrievalOnlyPolicy, isModelSearchProvider, retrievalOnlyError, retrievalOnlyExhaustedError } from "./retrieval-only.ts";
55
+
56
+ export const RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "kagi", "ollama", "anysearch", "xai", "mistral", "valyu", "bocha", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup", "ninerouter", "cloudflare", "tabstack"] as const;
57
+ // Former built-in providers. Naming one fails with a pointer to its custom-provider recipe
58
+ // instead of falling back to `auto`, unless customSearchProviders defines that name.
59
+ export const REMOVED_SEARCH_PROVIDERS = ["serper", "serpapi", "serply", "searchapi", "serpbase", "autom", "cloro", "xcrawl", "serpdive", "search1api", "outcrawl", "sofya", "specstream", "brightdata"] as const;
60
+
61
+ export type BuiltinSearchProvider = typeof RESOLVED_SEARCH_PROVIDERS[number];
62
+ /** A provider name defined under customSearchProviders in web-search.json. */
63
+ export type CustomSearchProvider = string & { readonly customSearchProvider: true };
64
+ export type ResolvedSearchProvider = BuiltinSearchProvider | CustomSearchProvider;
65
+ export type SearchProvider = "auto" | "all" | ResolvedSearchProvider;
66
+ export type SearchProviderSelection = SearchProvider | ResolvedSearchProvider[];
67
+ /** `customProviders` lists the allowed custom providers that have a credential source, in config order. */
68
+ export type ProviderAvailability = { all: boolean; customProviders?: string[] } & Record<BuiltinSearchProvider, boolean>;
69
+ export type SearchProviderErrorKind =
70
+ | "transient"
71
+ | "quota"
72
+ | "network"
73
+ | "credential"
74
+ | "config"
75
+ | "auth"
76
+ | "invalid-request"
77
+ | "invalid-response"
78
+ | "unsupported"
79
+ | "aborted"
80
+ | "unknown";
81
+
82
+ export interface SearchRoutingConfig {
83
+ providers: ResolvedSearchProvider[];
84
+ useCurrentModel?: boolean;
85
+ fallbackOn: Array<typeof VALID_ROUTING_KINDS[number]>;
86
+ /** Total budget for one routed search across every candidate, in milliseconds. */
87
+ timeoutMs?: number;
88
+ /** Classifier that judges the "off-topic" fallback; required when fallbackOn lists it. */
89
+ offTopicModel?: OffTopicJudgeModel;
90
+ }
91
+
92
+ export class SearchProviderError extends Error {
93
+ readonly provider: ResolvedSearchProvider;
94
+ readonly kind: SearchProviderErrorKind;
95
+ readonly status?: number;
96
+ readonly causeError: unknown;
97
+
98
+ constructor(
99
+ provider: ResolvedSearchProvider,
100
+ kind: SearchProviderErrorKind,
101
+ message: string,
102
+ status: number | undefined,
103
+ cause: unknown,
104
+ ) {
105
+ super(`${provider} search failed (${kind}): ${message}`);
106
+ this.name = "SearchProviderError";
107
+ this.provider = provider;
108
+ this.kind = kind;
109
+ this.status = status;
110
+ this.causeError = cause;
111
+ }
112
+ }
113
+
114
+ export interface ProviderSearchResponse extends SearchResponse {
115
+ provider: ResolvedSearchProvider;
116
+ }
117
+
118
+ export interface ProviderSearchFailure {
119
+ provider: ResolvedSearchProvider;
120
+ error: string;
121
+ }
122
+
123
+ export interface AttributedSearchResponse extends SearchResponse {
124
+ provider: ResolvedSearchProvider | "all";
125
+ providerResponses?: ProviderSearchResponse[];
126
+ providerErrors?: ProviderSearchFailure[];
127
+ }
128
+
129
+ const CONFIG_PATH = getWebSearchConfigPath();
130
+ const DEFAULT_SEARCH_MODEL = "gemini-3.6-flash";
131
+ // Explicit-only providers (Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup, 9router, Cloudflare, Tabstack, and custom providers) are deliberately absent:
132
+ // `all` must never fan out to an opt-in or paid provider without the user asking for it.
133
+ export const ALL_SEARCH_PROVIDERS: BuiltinSearchProvider[] = ["searxng", "openai", "exa", "brave", "parallel", "tinyfish", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "kagi", "ollama", "perplexity", "gemini", "bocha"];
134
+ const VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported", "empty", "domain-miss", "off-topic"] as const;
135
+ const MAX_ROUTING_TIMEOUT_MS = 600_000;
136
+
137
+ type SearchConfig = {
138
+ searchProvider: SearchProviderSelection;
139
+ searchProviderConfigured: boolean;
140
+ searchRouting?: SearchRoutingConfig;
141
+ searchModel?: string;
142
+ allowedProviders?: ResolvedSearchProvider[];
143
+ /** webSearch.allowedProviders as configured, before the retrieval-only policy narrowed it. */
144
+ allowedBeforePolicy?: ResolvedSearchProvider[];
145
+ customProviders: Map<string, CustomSearchProviderConfig>;
146
+ };
147
+
148
+ let cachedSearchConfig: SearchConfig | null = null;
149
+
150
+ function getSearchConfig(): SearchConfig {
151
+ if (cachedSearchConfig) return cachedSearchConfig;
152
+ if (!existsSync(CONFIG_PATH)) {
153
+ cachedSearchConfig = { searchProvider: "auto", searchProviderConfigured: false, customProviders: new Map() };
154
+ return cachedSearchConfig;
155
+ }
156
+
157
+ const rawText = readFileSync(CONFIG_PATH, "utf-8");
158
+ let raw: Record<string, unknown>;
159
+ try {
160
+ const parsed: unknown = JSON.parse(rawText);
161
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
162
+ throw new Error("expected a JSON object");
163
+ }
164
+ raw = parsed as Record<string, unknown>;
165
+ } catch (err) {
166
+ const message = err instanceof Error ? err.message : String(err);
167
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
168
+ }
169
+
170
+ const searchModel = normalizeSearchModel(raw.searchModel);
171
+ const customProviders = parseCustomSearchProviders(raw.customSearchProviders, RESOLVED_SEARCH_PROVIDERS, CONFIG_PATH);
172
+ const webSearch = raw.webSearch;
173
+ if (webSearch !== undefined && (!webSearch || typeof webSearch !== "object" || Array.isArray(webSearch))) {
174
+ throw new Error(`webSearch in ${CONFIG_PATH} must be an object`);
175
+ }
176
+ let allowedProviders = webSearch && Object.hasOwn(webSearch, "allowedProviders")
177
+ ? normalizeResolvedProviderList((webSearch as Record<string, unknown>).allowedProviders, `webSearch.allowedProviders in ${CONFIG_PATH}`, customProviders)
178
+ : undefined;
179
+ const searchProviderConfigured = Object.hasOwn(raw, "searchProvider") || Object.hasOwn(raw, "provider");
180
+ const searchProvider = normalizeSearchProviderSelection(raw.searchProvider ?? raw.provider, `provider in ${CONFIG_PATH}`, customProviders);
181
+ let searchRouting = Object.hasOwn(raw, "searchRouting") ? normalizeSearchRouting(raw.searchRouting, customProviders) : undefined;
182
+ const allowedBeforePolicy = allowedProviders;
183
+ if (getRetrievalOnlyPolicy().enabled) {
184
+ // A configured provider chooses where queries go, so naming a model is refused; lists are narrowed.
185
+ for (const key of ["searchProvider", "provider"] as const) {
186
+ if (Object.hasOwn(raw, key)) assertNoModelSearchProviders(normalizeSearchProviderSelection(raw[key], "provider", customProviders), `${key} in ${CONFIG_PATH}`);
187
+ }
188
+ if (allowedProviders) allowedProviders = withoutModelProviders(allowedProviders);
189
+ if (searchRouting) searchRouting = { ...searchRouting, providers: withoutModelProviders(searchRouting.providers) };
190
+ }
191
+ if (allowedProviders) {
192
+ if (Object.hasOwn(raw, "searchProvider")) {
193
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.searchProvider, "provider", customProviders), `searchProvider in ${CONFIG_PATH}`, allowedProviders);
194
+ }
195
+ if (Object.hasOwn(raw, "provider")) {
196
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.provider, "provider", customProviders), `provider in ${CONFIG_PATH}`, allowedProviders);
197
+ }
198
+ if (searchRouting) assertSearchProviderSelectionAllowed(searchRouting.providers, `searchRouting.providers in ${CONFIG_PATH}`, allowedProviders);
199
+ }
200
+ cachedSearchConfig = {
201
+ searchProvider,
202
+ searchProviderConfigured,
203
+ ...(searchRouting ? { searchRouting } : {}),
204
+ ...(searchModel ? { searchModel } : {}),
205
+ ...(allowedProviders ? { allowedProviders } : {}),
206
+ ...(allowedBeforePolicy ? { allowedBeforePolicy } : {}),
207
+ customProviders,
208
+ };
209
+ return cachedSearchConfig;
210
+ }
211
+
212
+ function normalizeSearchRouting(value: unknown, customProviders: ReadonlyMap<string, unknown>): SearchRoutingConfig {
213
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
214
+ throw new Error(`searchRouting in ${CONFIG_PATH} must be an object`);
215
+ }
216
+ const raw = value as Record<string, unknown>;
217
+ const providers = normalizeResolvedProviderList(raw.providers, `searchRouting.providers in ${CONFIG_PATH}`, customProviders);
218
+ const useCurrentModel = raw.useCurrentModel;
219
+ if (useCurrentModel !== undefined && typeof useCurrentModel !== "boolean") {
220
+ throw new Error(`searchRouting.useCurrentModel in ${CONFIG_PATH} must be a boolean`);
221
+ }
222
+ if (!Array.isArray(raw.fallbackOn) || raw.fallbackOn.length === 0) {
223
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} must be a non-empty array`);
224
+ }
225
+ const fallbackOn: SearchRoutingConfig["fallbackOn"] = [];
226
+ for (const kind of raw.fallbackOn) {
227
+ if (typeof kind !== "string" || !VALID_ROUTING_KINDS.includes(kind as typeof VALID_ROUTING_KINDS[number])) {
228
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} may only contain transient, quota, network, invalid-response, unsupported, empty, domain-miss, or off-topic`);
229
+ }
230
+ if (!fallbackOn.includes(kind as SearchRoutingConfig["fallbackOn"][number])) {
231
+ fallbackOn.push(kind as SearchRoutingConfig["fallbackOn"][number]);
232
+ }
233
+ }
234
+ const timeoutMs = raw.timeoutMs;
235
+ if (timeoutMs !== undefined && (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_ROUTING_TIMEOUT_MS)) {
236
+ throw new Error(`searchRouting.timeoutMs in ${CONFIG_PATH} must be an integer from 1 through ${MAX_ROUTING_TIMEOUT_MS}`);
237
+ }
238
+ const offTopicModel = raw.offTopicModel;
239
+ if (offTopicModel !== undefined && (typeof offTopicModel !== "string" || !Object.hasOwn(OFFTOPIC_JUDGE_MODELS, offTopicModel))) {
240
+ throw new Error(`searchRouting.offTopicModel in ${CONFIG_PATH} must be one of ${Object.keys(OFFTOPIC_JUDGE_MODELS).join(", ")}`);
241
+ }
242
+ if (fallbackOn.includes("off-topic") && offTopicModel === undefined) {
243
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} lists off-topic, which needs searchRouting.offTopicModel`);
244
+ }
245
+ return {
246
+ providers,
247
+ ...(useCurrentModel !== undefined ? { useCurrentModel: useCurrentModel as boolean } : {}),
248
+ fallbackOn,
249
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
250
+ ...(offTopicModel !== undefined ? { offTopicModel: offTopicModel as OffTopicJudgeModel } : {}),
251
+ };
252
+ }
253
+
254
+ export function getConfiguredSearchRouting(): SearchRoutingConfig | undefined {
255
+ const config = getSearchConfig();
256
+ return config.searchProviderConfigured ? undefined : config.searchRouting;
257
+ }
258
+
259
+ function normalizeSearchModel(value: unknown): string | undefined {
260
+ if (typeof value !== "string") return undefined;
261
+ const normalized = value.trim();
262
+ return normalized.length > 0 ? normalized : undefined;
263
+ }
264
+
265
+ // Built-in names are checked first so a call naming one never needs to read the config file.
266
+ // A removed name throws instead of returning undefined, so no caller can quietly route it to `auto`.
267
+ function knownProvider(name: string, customProviders?: ReadonlyMap<string, unknown>, label?: string): ResolvedSearchProvider | undefined {
268
+ if (RESOLVED_SEARCH_PROVIDERS.includes(name as BuiltinSearchProvider)) return name as BuiltinSearchProvider;
269
+ if ((customProviders ?? getSearchConfig().customProviders).has(name)) return name as CustomSearchProvider;
270
+ const removed = removedSearchProviderMessage(name);
271
+ if (removed) throw new Error(label ? `${label}: ${removed}` : removed);
272
+ return undefined;
273
+ }
274
+
275
+ export function removedSearchProviderMessage(name: string): string | undefined {
276
+ if (!REMOVED_SEARCH_PROVIDERS.includes(name as typeof REMOVED_SEARCH_PROVIDERS[number])) return undefined;
277
+ const unlocker = name === "brightdata" ? " Bright Data Web Unlocker page fetches still work." : "";
278
+ return `${name} was removed as a built-in provider. Add it as a custom provider: see https://github.com/nicobailon/pi-web-access/blob/main/docs/custom-providers.md#${name}${unlocker}`;
279
+ }
280
+
281
+ function normalizeResolvedProviderList(value: unknown, label: string, customProviders?: ReadonlyMap<string, unknown>): ResolvedSearchProvider[] {
282
+ if (!Array.isArray(value) || value.length === 0) {
283
+ throw new Error(`${label} must be a non-empty array`);
284
+ }
285
+ const providers: ResolvedSearchProvider[] = [];
286
+ for (const provider of value) {
287
+ const normalized = knownProvider(typeof provider === "string" ? provider.trim().toLowerCase() : "", customProviders, label);
288
+ if (normalized === undefined) {
289
+ throw new Error(`${label} contains an invalid provider: ${String(provider)}`);
290
+ }
291
+ if (providers.includes(normalized)) {
292
+ throw new Error(`${label} must not contain duplicates: ${normalized}`);
293
+ }
294
+ providers.push(normalized);
295
+ }
296
+ return providers;
297
+ }
298
+
299
+ export function assertSearchProviderSelectionAllowed(
300
+ selection: SearchProviderSelection,
301
+ label = "provider",
302
+ allowedProviders = getSearchConfig().allowedProviders,
303
+ ): void {
304
+ assertNoModelSearchProviders(selection);
305
+ if (!allowedProviders) return;
306
+ const requested = Array.isArray(selection)
307
+ ? selection
308
+ : selection === "auto" || selection === "all" ? [] : [selection];
309
+ const disabled = requested.filter(provider => !allowedProviders.includes(provider));
310
+ if (disabled.length > 0) {
311
+ throw new Error(`${label} ${disabled.length === 1 ? `references disabled provider "${disabled[0]}"` : `references disabled providers: ${disabled.join(", ")}`}; allowed by webSearch.allowedProviders: ${allowedProviders.join(", ")}`);
312
+ }
313
+ }
314
+
315
+ export function getAllowedSearchProviders(): readonly ResolvedSearchProvider[] {
316
+ const config = getSearchConfig();
317
+ const providers = config.allowedProviders ?? [...RESOLVED_SEARCH_PROVIDERS, ...config.customProviders.keys() as Iterable<CustomSearchProvider>];
318
+ return getRetrievalOnlyPolicy().enabled ? providers.filter(provider => !isModelSearchProvider(provider)) : providers;
319
+ }
320
+
321
+ function assertNoModelSearchProviders(selection: SearchProviderSelection, origin?: string): void {
322
+ const policy = getRetrievalOnlyPolicy();
323
+ if (!policy.enabled) return;
324
+ const blocked = (Array.isArray(selection) ? selection : [selection]).filter(isModelSearchProvider);
325
+ if (blocked.length === 0) return;
326
+ throw retrievalOnlyError(`Search provider ${JSON.stringify(blocked[0])}${origin ? ` set by ${origin}` : ""}`, policy);
327
+ }
328
+
329
+ /** The candidates that config allows but the retrieval-only policy keeps out. */
330
+ function modelProvidersSkippedByPolicy(candidates: readonly ResolvedSearchProvider[]): ResolvedSearchProvider[] {
331
+ if (!getRetrievalOnlyPolicy().enabled) return [];
332
+ const config = getSearchConfig();
333
+ const configured: readonly ResolvedSearchProvider[] = config.allowedBeforePolicy ?? RESOLVED_SEARCH_PROVIDERS;
334
+ return candidates.filter(provider => isModelSearchProvider(provider) && configured.includes(provider));
335
+ }
336
+
337
+ function withoutModelProviders(providers: ResolvedSearchProvider[]): ResolvedSearchProvider[] {
338
+ const kept = providers.filter(provider => !isModelSearchProvider(provider));
339
+ if (kept.length === 0) throw retrievalOnlyExhaustedError("search", providers);
340
+ return kept;
341
+ }
342
+
343
+ export function getCustomSearchProviderNames(): string[] {
344
+ return [...getSearchConfig().customProviders.keys()];
345
+ }
346
+
347
+ export function getAvailableCustomSearchProviders(): string[] {
348
+ const allowed = getAllowedSearchProviders();
349
+ return [...getSearchConfig().customProviders]
350
+ .filter(([name, custom]) => allowed.includes(name as CustomSearchProvider) && isCustomSearchProviderAvailable(name, custom))
351
+ .map(([name]) => name);
352
+ }
353
+
354
+ export function normalizeSearchProviderSelection(value: unknown, label = "provider", customProviders?: ReadonlyMap<string, unknown>): SearchProviderSelection {
355
+ if (Array.isArray(value)) return normalizeResolvedProviderList(value, label, customProviders);
356
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
357
+ if (normalized === "auto" || normalized === "all") return normalized;
358
+ return knownProvider(normalized, customProviders, label) ?? "auto";
359
+ }
360
+
361
+ /** Strict parser for tool-call `provider` arguments; config values keep the lenient normalizer. */
362
+ export function parseProviderArgument(value: unknown): SearchProviderSelection | undefined {
363
+ if (value === undefined) return undefined;
364
+ if (Array.isArray(value)) return normalizeResolvedProviderList(value, "provider");
365
+ const unknown = (name: string) => new Error(`Unknown search provider "${name}". Use auto, all, or one or more comma-separated names: ${getAllowedSearchProviders().join(", ")}`);
366
+ if (typeof value !== "string") throw unknown(String(value));
367
+ const normalized = value.trim().toLowerCase();
368
+ if (normalized === "") return undefined;
369
+ let names: string[];
370
+ if (normalized.startsWith("[")) {
371
+ let parsed: unknown[];
372
+ try {
373
+ parsed = JSON.parse(normalized);
374
+ } catch {
375
+ throw new Error("provider must be a provider name or comma-separated names; the given value is not valid JSON");
376
+ }
377
+ names = parsed.map(entry => String(entry).trim());
378
+ } else {
379
+ names = normalized.split(",").map(name => name.trim()).filter(Boolean);
380
+ if (names.length < 2) {
381
+ if (names[0] === "auto" || names[0] === "all") return names[0];
382
+ const single = knownProvider(names[0] ?? "");
383
+ if (single === undefined) throw unknown(names[0] ?? value);
384
+ return single;
385
+ }
386
+ }
387
+ if (names.some(name => name === "auto" || name === "all")) {
388
+ throw new Error('"auto" and "all" cannot be combined with provider names');
389
+ }
390
+ const invalid = names.find(name => knownProvider(name) === undefined);
391
+ if (invalid !== undefined) throw unknown(invalid);
392
+ return normalizeResolvedProviderList(names, "provider");
393
+ }
394
+
395
+ /** Validate the original arguments, before config can supply an implicit provider. */
396
+ export function validateSearchModelOverride(provider: unknown, model: unknown): string | undefined {
397
+ // Agents often fill optional fields with "", so a blank model means no override.
398
+ if (model === undefined || (typeof model === "string" && !model.trim())) return undefined;
399
+ if (typeof model !== "string") {
400
+ throw new Error("model must be a non-empty model ID");
401
+ }
402
+ const selected = parseProviderArgument(provider);
403
+ if (selected === undefined || Array.isArray(selected) || selected === "auto" || selected === "all") {
404
+ throw new Error("model requires one explicit provider: openai, xai, mistral, or gemini (API only); omitted, auto, all, and provider lists are ambiguous");
405
+ }
406
+ if (!["openai", "xai", "mistral", "gemini"].includes(selected)) {
407
+ throw new Error(`model is not supported for provider ${JSON.stringify(selected)}; use openai, xai, mistral, or gemini (API only)`);
408
+ }
409
+ assertSearchProviderSelectionAllowed(selected, "Requested provider");
410
+ return model.trim();
411
+ }
412
+
413
+ export interface FullSearchOptions extends SearchOptions {
414
+ provider?: SearchProviderSelection;
415
+ /** The caller already substituted the configured default for an omitted or "auto" provider. */
416
+ providerFromConfig?: boolean;
417
+ includeContent?: boolean;
418
+ extensionContext?: ExtensionContext;
419
+ /** Lets an explicit Gemini search ask the user to turn on browser cookie access. */
420
+ browserCookieConsent?: BrowserCookieConsent;
421
+ /** Forwarded to providers that understand them (category: Exa; objective: Exa, Parallel); ignored elsewhere. */
422
+ category?: string;
423
+ objective?: string;
424
+ }
425
+
426
+ function errorMessage(err: unknown): string {
427
+ return err instanceof Error ? err.message : String(err);
428
+ }
429
+
430
+ function isAbortError(err: unknown): boolean {
431
+ // A provider's own AbortSignal.timeout rejects with "The operation was aborted
432
+ // due to timeout" (often re-wrapped into a plain Error), which is a network
433
+ // failure to fall back from, not a user cancel.
434
+ const message = errorMessage(err).toLowerCase();
435
+ return message.includes("abort") && !message.includes("aborted due to timeout");
436
+ }
437
+
438
+ type TakeAutoResult = (result: SearchResponse | null, provider: ResolvedSearchProvider) => AttributedSearchResponse | null;
439
+
440
+ async function tryOpenAIInAuto(query: string, options: FullSearchOptions, fallbackErrors: string[], take: TakeAutoResult): Promise<AttributedSearchResponse | null> {
441
+ try {
442
+ if (await isOpenAISearchAvailable(options.extensionContext)) {
443
+ const result = await searchWithOpenAI(query, options, options.extensionContext);
444
+ return take(result, "openai");
445
+ }
446
+ } catch (err) {
447
+ if (isAbortError(err)) throw err;
448
+ fallbackErrors.push(`OpenAI: ${errorMessage(err)}`);
449
+ }
450
+ return null;
451
+ }
452
+
453
+ async function searchWithGemini(
454
+ query: string,
455
+ options: SearchOptions,
456
+ strictErrors: boolean,
457
+ ): Promise<SearchResponse | null> {
458
+ // Gemini Web cannot honor an explicit model, so never fall back to it.
459
+ if (options.model !== undefined) {
460
+ const result = await searchWithGeminiApi(query, options);
461
+ if (result) return result;
462
+ throw new Error("Gemini API search unavailable: an explicit model requires API-path authentication (API key, ADC, or gateway), not browser cookies");
463
+ }
464
+ const errors: string[] = [];
465
+
466
+ try {
467
+ const apiResult = await searchWithGeminiApi(query, options);
468
+ if (apiResult) return apiResult;
469
+ } catch (err) {
470
+ if (err instanceof CredentialResolutionError || isAbortError(err)) throw err;
471
+ errors.push(`Gemini API: ${errorMessage(err)}`);
472
+ }
473
+
474
+ try {
475
+ const webResult = await searchWithGeminiWeb(query, options);
476
+ if (webResult) return webResult;
477
+ const diagnostic = getGeminiWebAvailabilityDiagnostic();
478
+ if (diagnostic) errors.push(`Gemini Web: ${diagnostic}`);
479
+ } catch (err) {
480
+ if (isAbortError(err)) throw err;
481
+ errors.push(`Gemini Web: ${errorMessage(err)}`);
482
+ }
483
+
484
+ if (strictErrors && errors.length > 0) {
485
+ throw new Error(`Gemini search failed:\n - ${errors.join("\n - ")}`);
486
+ }
487
+
488
+ return null;
489
+ }
490
+
491
+ function providerErrorStatus(message: string): number | undefined {
492
+ const match = message.match(/\b(?:error|status|http)\s+(\d{3})\b/i);
493
+ if (!match) return undefined;
494
+ return Number(match[1]);
495
+ }
496
+
497
+ function classifyProviderError(provider: ResolvedSearchProvider, err: unknown): SearchProviderError {
498
+ if (err instanceof SearchProviderError) return err;
499
+ const message = errorMessage(err);
500
+ const lower = message.toLowerCase();
501
+ const status = providerErrorStatus(message);
502
+ // An HTTP 200 OpenAI stream reports its failure as an error type/code such as
503
+ // rate_limit_exceeded or server_error. Reading only that message with spaces
504
+ // lets the shared keywords below classify it like prose, without widening them
505
+ // for other providers, which echo foreign text (such as envelope codes)
506
+ // that must keep classifying as before. OpenAI error types
507
+ // the shared keywords don't name (usage limit, authentication_error,
508
+ // permission_error, invalid_api_key, api_error, internal_error, overloaded)
509
+ // are added per branch for these messages only.
510
+ const openAIStreamError = provider === "openai" && lower.includes("openai api stream error");
511
+ const text = openAIStreamError ? lower.replace(/_/g, " ") : lower;
512
+ let kind: SearchProviderErrorKind = "unknown";
513
+ const mentionsUnsupportedWebSearch = /(?:web[_ -]?search|web[_ -]?search_preview|(?:the )?tool)\b.*\b(?:unsupported|not supported|does not support|doesn't support|unknown|unrecognized|unavailable|not found)|\b(?:unsupported|not supported|does not support|doesn't support|unknown|unrecognized|unavailable|not found)\b.*\b(?:web[_ -]?search|web[_ -]?search_preview|(?:the )?tool)/i.test(lower);
514
+ if (err instanceof CredentialResolutionError || /(?:api )?key (?:not found|missing)|credential resolution/.test(lower)) {
515
+ kind = "credential";
516
+ } else if (isAbortError(err)) {
517
+ kind = "aborted";
518
+ } else if (lower.includes("aborted due to timeout")) {
519
+ // Before the response-format checks: providers wrap a body-read timeout as
520
+ // "invalid JSON: The operation was aborted due to timeout".
521
+ kind = "network";
522
+ } else if (err instanceof OpenAIAlphaSearchUnsupportedError) {
523
+ kind = "unsupported";
524
+ } else if (provider === "xai" && status === 403 && /spending[- ]limit|(?:no|out of) credits?|insufficient quota|quota (?:exceeded|exhausted)|credits? (?:exhausted|depleted|used up)/.test(lower)) {
525
+ kind = "quota";
526
+ } else if (status === 401 || status === 403) {
527
+ kind = "auth";
528
+ } else if (provider === "openai" && (status === 400 || status === 422) && mentionsUnsupportedWebSearch) {
529
+ kind = "unsupported";
530
+ } else if (status === 400 || status === 422) {
531
+ kind = "invalid-request";
532
+ } else if (status === 402 || status === 429 || (provider === "tavily" && status === 432)) {
533
+ kind = "quota";
534
+ } else if (status !== undefined && (status === 408 || status === 425 || status >= 500)) {
535
+ kind = "transient";
536
+ } else if (/rate limit|quota|too many requests/.test(text) || (openAIStreamError && /usage limit/.test(text))) {
537
+ kind = "quota";
538
+ } else if (/unauthorized|forbidden|permission denied/.test(text) || (openAIStreamError && /authentication error|permission error|invalid api key/.test(text))) {
539
+ kind = "auth";
540
+ } else if (/bad request|invalid request/.test(text)) {
541
+ kind = "invalid-request";
542
+ } else if (/invalid json|no parseable response|no parseable results|invalid response|returned empty response|no web_search_call/.test(text)) {
543
+ kind = "invalid-response";
544
+ } else if (/temporar|service unavailable|server error/.test(text) || (openAIStreamError && /internal error|\bapi error|overloaded/.test(text))) {
545
+ kind = "transient";
546
+ } else if (err instanceof TypeError || /fetch failed|network|econnreset|econnrefused|enotfound|etimedout|timed out|socket/.test(text)) {
547
+ kind = "network";
548
+ } else if (/invalid or missing|invalid config|failed to parse|must be an? |configuration/.test(text)) {
549
+ kind = "config";
550
+ } else if (openAIStreamError) {
551
+ // The same stream threw "no parseable response output" before its error was surfaced.
552
+ kind = "invalid-response";
553
+ }
554
+ return new SearchProviderError(provider, kind, message, status, err);
555
+ }
556
+
557
+ async function searchWithResolvedProvider(
558
+ provider: ResolvedSearchProvider,
559
+ query: string,
560
+ options: FullSearchOptions,
561
+ useCurrentModel = false,
562
+ // Only a single requested provider asks; fallback chains and "all" must never open a dialog.
563
+ askBrowserCookies = false,
564
+ ): Promise<ProviderSearchResponse> {
565
+ const custom = getSearchConfig().customProviders.get(provider);
566
+ if (custom) return { ...(await searchWithCustomProvider(provider, custom, query, options)), provider };
567
+ if (provider === "openai") {
568
+ const result = useCurrentModel
569
+ ? await searchWithCurrentModelOpenAI(query, options, options.extensionContext)
570
+ : await searchWithOpenAI(query, options, options.extensionContext);
571
+ return { ...result, provider };
572
+ }
573
+ if (provider === "brave") return { ...(await searchWithBrave(query, options)), provider };
574
+ if (provider === "parallel") return { ...(await searchWithParallel(query, options)), provider };
575
+ if (provider === "parallel-mcp") return { ...(await searchWithParallelMcp(query, options)), provider };
576
+ if (provider === "tinyfish") return { ...(await searchWithTinyFish(query, options)), provider };
577
+ if (provider === "searchinfinity") return { ...(await searchWithSearchinfinity(query, options)), provider };
578
+ if (provider === "querit") return { ...(await searchWithQuerit(query, options)), provider };
579
+ if (provider === "tavily") return { ...(await searchWithTavily(query, options)), provider };
580
+ if (provider === "tabstack") return { ...(await searchWithTabstack(query, options)), provider };
581
+ if (provider === "you") return { ...(await searchWithYou(query, options)), provider };
582
+ if (provider === "firecrawl") return { ...(await searchWithFirecrawl(query, options)), provider };
583
+ if (provider === "jina") return { ...(await searchWithJina(query, options)), provider };
584
+ if (provider === "kagi") return { ...(await searchWithKagi(query, options)), provider };
585
+ if (provider === "bocha") return { ...(await searchWithBocha(query, options)), provider };
586
+ if (provider === "ollama") return { ...(await searchWithOllama(query, options)), provider };
587
+ if (provider === "anysearch") return { ...(await searchWithAnySearch(query, options)), provider };
588
+ if (provider === "xai") return { ...(await searchWithXai(query, options, options.extensionContext)), provider };
589
+ if (provider === "mistral") return { ...(await searchWithMistral(query, options)), provider };
590
+ if (provider === "baizhi") return { ...(await searchWithBaizhi(query, options)), provider };
591
+ if (provider === "zai") return { ...(await searchWithZai(query, options)), provider };
592
+ if (provider === "valyu") return { ...(await searchWithValyu(query, options)), provider };
593
+ if (provider === "keenable") return { ...(await searchWithKeenable(query, options)), provider };
594
+ if (provider === "ceramic") return { ...(await searchWithCeramic(query, options)), provider };
595
+ if (provider === "linkup") return { ...(await searchWithLinkup(query, options)), provider };
596
+ if (provider === "ninerouter") return { ...(await searchWithNineRouter(query, options)), provider };
597
+ if (provider === "cloudflare") return { ...(await searchWithCloudflare(query, options)), provider };
598
+ if (provider === "deepseek") return { ...(await searchWithDeepSeek(query, options)), provider };
599
+ if (provider === "perplexity") return { ...(await searchWithPerplexity(query, options)), provider };
600
+ if (provider === "searxng") return { ...(await searchWithSearXNG(query, options)), provider };
601
+ if (provider === "degoog") return { ...(await searchWithDegoog(query, options)), provider };
602
+ if (provider === "duckduckgo") return { ...(await searchWithDuckDuckGo(query, options)), provider };
603
+ if (provider === "kimi") return { ...(await searchWithKimi(query, options, options.extensionContext)), provider };
604
+ if (provider === "gemini") {
605
+ let result: SearchResponse | null = null;
606
+ let failure: unknown;
607
+ try {
608
+ result = await searchWithGemini(query, options, true);
609
+ } catch (err) {
610
+ // A failing API route (429, 500) can still be rescued by Gemini Web; these can't.
611
+ if (options.model !== undefined || err instanceof CredentialResolutionError || isAbortError(err)) throw err;
612
+ failure = err;
613
+ }
614
+ if (!result && askBrowserCookies && await requestBrowserCookieAccess(options.browserCookieConsent, options.signal)) {
615
+ result = await searchWithGeminiWeb(query, options);
616
+ }
617
+ if (result) return { ...result, provider };
618
+ if (failure) throw failure;
619
+ throw new Error(
620
+ "Gemini search unavailable. Either:\n" +
621
+ ` 1. Configure geminiApiKey in ${CONFIG_PATH} or set GEMINI_API_KEY\n` +
622
+ " 2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing\n" +
623
+ " 3. Set geminiAuth to \"adc\" in web-search.json with a Google Cloud ADC + project/location\n" +
624
+ ` 4. ${browserCookieAccessHint(options.browserCookieConsent, " ")}`,
625
+ );
626
+ }
627
+ return { ...(await searchWithExa(query, options)), provider };
628
+ }
629
+
630
+ async function isResolvedProviderAvailable(provider: ResolvedSearchProvider, options: FullSearchOptions, useCurrentModel = false): Promise<boolean> {
631
+ const custom = getSearchConfig().customProviders.get(provider);
632
+ if (custom) return isCustomSearchProviderAvailable(provider, custom);
633
+ if (provider === "openai") {
634
+ return useCurrentModel
635
+ ? isCurrentModelHostedSearchEligible(options.extensionContext)
636
+ : isOpenAISearchAvailable(options.extensionContext);
637
+ }
638
+ if (provider === "brave") return isBraveAvailable();
639
+ if (provider === "parallel") return isParallelAvailable();
640
+ if (provider === "parallel-mcp") return isParallelMcpAvailable();
641
+ if (provider === "tinyfish") return isTinyFishAvailable();
642
+ if (provider === "searchinfinity") return isSearchinfinityAvailable();
643
+ if (provider === "querit") return isQueritAvailable();
644
+ if (provider === "tavily") return isTavilyAvailable();
645
+ if (provider === "tabstack") return isTabstackAvailable();
646
+ if (provider === "you") return isYouAvailable();
647
+ if (provider === "firecrawl") return isFirecrawlAvailable();
648
+ if (provider === "jina") return isJinaSearchAvailable();
649
+ if (provider === "kagi") return isKagiAvailable();
650
+ if (provider === "bocha") return isBochaAvailable();
651
+ if (provider === "ollama") return isOllamaAvailable();
652
+ if (provider === "anysearch") return isAnySearchAvailable();
653
+ if (provider === "xai") return isXaiSearchAvailable(options.extensionContext);
654
+ if (provider === "mistral") return isMistralAvailable();
655
+ if (provider === "baizhi") return isBaizhiAvailable();
656
+ if (provider === "zai") return isZaiAvailable();
657
+ if (provider === "valyu") return isValyuAvailable();
658
+ if (provider === "keenable") return isKeenableAvailable();
659
+ if (provider === "ceramic") return isCeramicAvailable();
660
+ if (provider === "linkup") return isLinkupAvailable();
661
+ if (provider === "ninerouter") return isNineRouterAvailable();
662
+ if (provider === "cloudflare") return isCloudflareSearchAvailable();
663
+ if (provider === "deepseek") return isDeepSeekAvailable();
664
+ if (provider === "perplexity") return isPerplexityAvailable();
665
+ if (provider === "searxng") return isSearXNGAvailable();
666
+ if (provider === "degoog") return isDegoogAvailable();
667
+ if (provider === "duckduckgo") return isDuckDuckGoAvailable();
668
+ if (provider === "gemini") return isGeminiApiAvailable() || await isGeminiWebOptionallyAvailable();
669
+ if (provider === "kimi") return isKimiSearchAvailable(options.extensionContext);
670
+ return isExaAvailable();
671
+ }
672
+
673
+ async function isGeminiWebOptionallyAvailable(): Promise<boolean> {
674
+ try {
675
+ return !!(await isGeminiWebAvailable());
676
+ } catch {
677
+ return false;
678
+ }
679
+ }
680
+
681
+ export function providerLabel(provider: ResolvedSearchProvider): string {
682
+ if (!RESOLVED_SEARCH_PROVIDERS.includes(provider as BuiltinSearchProvider)) return provider;
683
+ if (provider === "openai") return "OpenAI";
684
+ if (provider === "parallel-mcp") return "Parallel MCP";
685
+ if (provider === "tinyfish") return "TinyFish";
686
+ if (provider === "searchinfinity") return "Searchinfinity";
687
+ if (provider === "querit") return "Querit";
688
+ if (provider === "tabstack") return "Tabstack";
689
+ if (provider === "firecrawl") return "Firecrawl";
690
+ if (provider === "searxng") return "SearXNG";
691
+ if (provider === "degoog") return "degoog";
692
+ if (provider === "duckduckgo") return "DuckDuckGo";
693
+ if (provider === "kagi") return "Kagi";
694
+ if (provider === "bocha") return "Bocha";
695
+ if (provider === "kimi") return "Kimi";
696
+ if (provider === "ollama") return "Ollama";
697
+ if (provider === "xai") return "xAI";
698
+ if (provider === "mistral") return "Mistral";
699
+ if (provider === "you") return "You.com";
700
+ if (provider === "baizhi") return "Baizhi";
701
+ if (provider === "zai") return "Z.ai";
702
+ if (provider === "valyu") return "Valyu";
703
+ if (provider === "keenable") return "Keenable";
704
+ if (provider === "ceramic") return "Ceramic";
705
+ if (provider === "linkup") return "Linkup";
706
+ if (provider === "ninerouter") return "9router";
707
+ if (provider === "cloudflare") return "Cloudflare";
708
+ if (provider === "deepseek") return "DeepSeek";
709
+ return provider.charAt(0).toUpperCase() + provider.slice(1);
710
+ }
711
+
712
+ async function searchWithAllProvider(
713
+ provider: ResolvedSearchProvider,
714
+ query: string,
715
+ options: FullSearchOptions,
716
+ ): Promise<ProviderSearchResponse> {
717
+ if (provider !== "gemini") return searchWithResolvedProvider(provider, query, options);
718
+ const result = await searchWithGeminiApi(query, options);
719
+ if (result) return { ...result, provider };
720
+ throw new Error("Gemini API search returned no results.");
721
+ }
722
+
723
+ async function searchWithProviders(
724
+ query: string,
725
+ options: FullSearchOptions,
726
+ selectedProviders?: ResolvedSearchProvider[],
727
+ routing?: SearchRoutingConfig,
728
+ ): Promise<AttributedSearchResponse> {
729
+ const allowed = getAllowedSearchProviders();
730
+ const providers = selectedProviders ?? (await Promise.all(ALL_SEARCH_PROVIDERS.filter(provider => allowed.includes(provider)).map(async (provider) => ({
731
+ provider,
732
+ available: provider === "gemini"
733
+ ? isGeminiApiAvailable()
734
+ : await isResolvedProviderAvailable(provider, options),
735
+ })))).filter((entry) => entry.available).map((entry) => entry.provider);
736
+ if (providers.length === 0) {
737
+ const skipped = selectedProviders ? [] : modelProvidersSkippedByPolicy(ALL_SEARCH_PROVIDERS);
738
+ if (skipped.length > 0) throw retrievalOnlyExhaustedError("search", skipped);
739
+ throw new Error("No configured search provider available for provider \"all\". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup, 9router, Cloudflare, Tabstack, and custom providers are excluded.");
740
+ }
741
+
742
+ const settled = await Promise.allSettled(
743
+ providers.map((provider) => selectedProviders
744
+ ? searchWithResolvedProvider(provider, query, options)
745
+ : searchWithAllProvider(provider, query, options)),
746
+ );
747
+ if (options.signal?.aborted) throw new Error("Aborted");
748
+
749
+ const successes: ProviderSearchResponse[] = [];
750
+ const failures: Array<{ provider: ResolvedSearchProvider; error: string }> = [];
751
+ for (let index = 0; index < settled.length; index++) {
752
+ const outcome = settled[index];
753
+ if (outcome.status === "fulfilled") {
754
+ successes.push(outcome.value);
755
+ } else {
756
+ failures.push({ provider: providers[index], error: errorMessage(outcome.reason) });
757
+ }
758
+ }
759
+ if (successes.length === 0) {
760
+ const label = selectedProviders ? "Selected-provider" : "All-provider";
761
+ const failureMessage = `${label} search failed:\n - ${failures.map(({ provider, error }) => `${providerLabel(provider)}: ${error}`).join("\n - ")}`;
762
+ // Routing continues only when every array failure is a kind it would itself fall back on.
763
+ if (!routing || !settled.every((outcome, index) => outcome.status === "rejected" &&
764
+ routing.fallbackOn.includes(classifyProviderError(providers[index], outcome.reason).kind as SearchRoutingConfig["fallbackOn"][number]))) {
765
+ throw new Error(failureMessage);
766
+ }
767
+ const untried = routing.providers.filter((provider) => !providers.includes(provider));
768
+ try {
769
+ if (untried.length === 0) throw new Error("Configured search routing has no untried providers");
770
+ return await searchWithConfiguredRouting(query, options, { ...routing, providers: untried });
771
+ } catch (err) {
772
+ if (isAbortError(err)) throw err;
773
+ throw new Error(`${failureMessage}\n${errorMessage(err)}`);
774
+ }
775
+ }
776
+
777
+ const results: SearchResult[] = [];
778
+ const seenResultUrls = new Set<string>();
779
+ const inlineContent: NonNullable<SearchResponse["inlineContent"]> = [];
780
+ const seenInlineUrls = new Set<string>();
781
+ for (const response of successes) {
782
+ for (const result of response.results) {
783
+ if (seenResultUrls.has(result.url)) continue;
784
+ seenResultUrls.add(result.url);
785
+ results.push(result);
786
+ }
787
+ for (const content of response.inlineContent ?? []) {
788
+ if (seenInlineUrls.has(content.url)) continue;
789
+ seenInlineUrls.add(content.url);
790
+ inlineContent.push(content);
791
+ }
792
+ }
793
+
794
+ const answerSections = successes.map((response) =>
795
+ `## ${providerLabel(response.provider)}\n\n${response.answer || "(No answer text returned.)"}`
796
+ );
797
+ if (failures.length > 0) {
798
+ answerSections.push(
799
+ `## Provider errors\n\n${failures.map(({ provider, error }) => `- **${providerLabel(provider)}:** ${error}`).join("\n")}`,
800
+ );
801
+ }
802
+
803
+ return {
804
+ provider: "all",
805
+ answer: answerSections.join("\n\n"),
806
+ results,
807
+ providerResponses: successes,
808
+ ...(failures.length > 0 ? { providerErrors: failures } : {}),
809
+ ...(inlineContent.length > 0 ? { inlineContent } : {}),
810
+ };
811
+ }
812
+
813
+ /** A successful response a route may still move past: no results and no answer (`empty`), or no result on a requested domain (`domain-miss`). */
814
+ function weakResult(response: SearchResponse, domainFilter: string[] | undefined): { empty: boolean; domainMiss: boolean } {
815
+ const empty = response.results.length === 0 && !response.answer.trim();
816
+ const wanted = (domainFilter ?? [])
817
+ .filter((domain) => !domain.trim().startsWith("-"))
818
+ .flatMap((domain) => normalizeDomain(domain) ?? []);
819
+ const domainMiss = wanted.length > 0 && !response.results.some((result) => {
820
+ const host = URL.parse(result.url)?.hostname;
821
+ return host !== undefined && wanted.some((domain) => host === domain || host.endsWith(`.${domain}`));
822
+ });
823
+ return { empty, domainMiss };
824
+ }
825
+
826
+ async function searchWithConfiguredRouting(
827
+ query: string,
828
+ callerOptions: FullSearchOptions,
829
+ routing: SearchRoutingConfig,
830
+ ): Promise<AttributedSearchResponse> {
831
+ const deadline = routing.timeoutMs ? AbortSignal.timeout(routing.timeoutMs) : undefined;
832
+ const signal = deadline && (callerOptions.signal ? AbortSignal.any([callerOptions.signal, deadline]) : deadline);
833
+ const options: FullSearchOptions = signal ? { ...callerOptions, signal } : callerOptions;
834
+ const timedOut = () => deadline?.aborted === true && callerOptions.signal?.aborted !== true;
835
+ // Availability checks, Pi auth, and cookie scans ignore the signal, so race each step against it (caller abort or deadline); abandoned work finishes in the background and is ignored.
836
+ const untilDeadline = <T>(work: Promise<T>): Promise<T> => awaitWithAbort(work, signal);
837
+ const diagnostics: string[] = [];
838
+ let firstWeak: AttributedSearchResponse | undefined;
839
+ for (const provider of routing.providers) {
840
+ if (timedOut()) {
841
+ diagnostics.push(`routing timeout after ${routing.timeoutMs}ms`);
842
+ break;
843
+ }
844
+ const useCurrentModel = provider === "openai" && routing.useCurrentModel === true;
845
+ const available = await untilDeadline(isResolvedProviderAvailable(provider, options, useCurrentModel)).catch((err) => {
846
+ if (timedOut()) return undefined;
847
+ throw err;
848
+ });
849
+ if (available === undefined) {
850
+ diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
851
+ break;
852
+ }
853
+ if (!available) {
854
+ diagnostics.push(`${provider}: unavailable`);
855
+ continue;
856
+ }
857
+ try {
858
+ const response = await untilDeadline(searchWithResolvedProvider(provider, query, options, useCurrentModel));
859
+ const weak = weakResult(response, options.domainFilter);
860
+ let kind = weak.empty && routing.fallbackOn.includes("empty") ? "empty" : weak.domainMiss && routing.fallbackOn.includes("domain-miss") ? "domain-miss" : undefined;
861
+ // Over MCP there is no Pi model registry, so the off-topic check is inactive there.
862
+ const registry = options.extensionContext?.modelRegistry;
863
+ // The judge is a model call, so the retrieval-only policy keeps the response as is.
864
+ if (!kind && !weak.empty && routing.offTopicModel && routing.fallbackOn.includes("off-topic") && registry && !getRetrievalOnlyPolicy().enabled) {
865
+ // A deadline during the check keeps the response: it is still a success.
866
+ const judgment = await untilDeadline(judgeOffTopic(routing.offTopicModel, query, response, registry, options.signal))
867
+ .catch((err) => { if (timedOut()) return { error: `routing timeout after ${routing.timeoutMs}ms` }; throw err; });
868
+ if ("error" in judgment) {
869
+ const line = `${provider}: off-topic check failed: ${judgment.error}`;
870
+ diagnostics.push(line);
871
+ activityMonitor.logError(activityMonitor.logStart({ type: "api", query }), line);
872
+ } else if (judgment.probabilities.off_topic >= OFFTOPIC_JUDGE_MODELS[routing.offTopicModel]) kind = "off-topic";
873
+ }
874
+ if (!kind) return response;
875
+ diagnostics.push(`${provider} [${kind}]`);
876
+ firstWeak ??= response;
877
+ } catch (err) {
878
+ if (timedOut()) {
879
+ diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
880
+ break;
881
+ }
882
+ const classified = classifyProviderError(provider, err);
883
+ diagnostics.push(`${provider} [${classified.kind}]: ${errorMessage(err)}`);
884
+ if (!routing.fallbackOn.includes(classified.kind as SearchRoutingConfig["fallbackOn"][number])) {
885
+ throw classified;
886
+ }
887
+ }
888
+ }
889
+ // Like the built-in auto chain, hand back the first weak response rather than an error.
890
+ if (firstWeak) return firstWeak;
891
+ throw new Error(`Configured search routing exhausted:\n - ${diagnostics.join("\n - ")}`);
892
+ }
893
+
894
+ export async function search(query: string, options: FullSearchOptions = {}): Promise<AttributedSearchResponse> {
895
+ const config = getSearchConfig();
896
+ const provider = options.provider === undefined || options.provider === "auto"
897
+ ? config.searchProvider
898
+ : options.provider;
899
+ assertSearchProviderSelectionAllowed(provider, "Requested provider");
900
+ if (Array.isArray(provider)) {
901
+ // Only a config-default array falls back to searchRouting; a per-call array stays strict.
902
+ const fromConfig = options.providerFromConfig === true || options.provider === undefined || options.provider === "auto";
903
+ const routing = fromConfig ? config.searchRouting : undefined;
904
+ return searchWithProviders(query, options, normalizeResolvedProviderList(provider, "provider"), routing);
905
+ }
906
+ if (provider === "all") return searchWithProviders(query, options);
907
+ if (provider !== "auto") return searchWithResolvedProvider(provider, query, options, false, true);
908
+ if (!config.searchProviderConfigured && config.searchRouting) {
909
+ return searchWithConfiguredRouting(query, options, config.searchRouting);
910
+ }
911
+
912
+ const fallbackErrors: string[] = [];
913
+ // An empty 200 keeps the chain going; if every provider is empty, return the first.
914
+ let firstEmpty: AttributedSearchResponse | undefined;
915
+ const take: TakeAutoResult = (result, provider) => {
916
+ if (!result) return null;
917
+ const response = { ...result, provider };
918
+ if (result.results.length || result.answer.trim()) return response;
919
+ firstEmpty ??= response;
920
+ return null;
921
+ };
922
+ const allowed = new Set(getAllowedSearchProviders());
923
+ const attempt = async (provider: ResolvedSearchProvider): Promise<AttributedSearchResponse | null> => {
924
+ if (!allowed.has(provider) || !(await isResolvedProviderAvailable(provider, options))) return null;
925
+ try {
926
+ return take(await searchWithResolvedProvider(provider, query, options), provider);
927
+ } catch (err) {
928
+ if (isAbortError(err)) throw err;
929
+ fallbackErrors.push(`${providerLabel(provider)}: ${errorMessage(err)}`);
930
+ return null;
931
+ }
932
+ };
933
+
934
+ const searxng = await attempt("searxng");
935
+ if (searxng) return searxng;
936
+
937
+ let triedOpenAI = false;
938
+ if (allowed.has("openai") && (!options.extensionContext || isOpenAISubscriptionModelSelected(options.extensionContext))) {
939
+ triedOpenAI = true;
940
+ const result = await tryOpenAIInAuto(query, options, fallbackErrors, take);
941
+ if (result) return result;
942
+ }
943
+
944
+ if (allowed.has("exa") && isExaAvailable()) {
945
+ try {
946
+ const response = take(await searchWithExa(query, options), "exa");
947
+ if (response) return response;
948
+ } catch (err) {
949
+ if (err instanceof CredentialResolutionError || isAbortError(err)) throw err;
950
+ fallbackErrors.push(`Exa: ${errorMessage(err)}`);
951
+ }
952
+ }
953
+
954
+ if (allowed.has("openai") && !triedOpenAI) {
955
+ const result = await tryOpenAIInAuto(query, options, fallbackErrors, take);
956
+ if (result) return result;
957
+ }
958
+
959
+ for (const provider of ["brave", "parallel", "tinyfish", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "kagi", "bocha", "ollama", "perplexity"] as const) {
960
+ const response = await attempt(provider);
961
+ if (response) return response;
962
+ }
963
+
964
+ if (allowed.has("gemini")) try {
965
+ const response = take(await searchWithGemini(query, options, false), "gemini");
966
+ if (response) return response;
967
+ } catch (err) {
968
+ if (isAbortError(err)) throw err;
969
+ fallbackErrors.push(`Gemini: ${errorMessage(err)}`);
970
+ }
971
+
972
+ if (firstEmpty) return firstEmpty;
973
+ if (fallbackErrors.length > 0) {
974
+ throw new Error(`Auto provider search failed:\n - ${fallbackErrors.join("\n - ")}`);
975
+ }
976
+ const skipped = modelProvidersSkippedByPolicy(["openai", "gemini"]);
977
+ if (skipped.length > 0) throw retrievalOnlyExhaustedError("search", skipped);
978
+
979
+ throw new Error(
980
+ "No search provider available. Either:\n" +
981
+ " 1. Use /login to sign in with a Codex subscription for OpenAI web search\n" +
982
+ ` 2. Set openaiApiKey, braveApiKey, parallelApiKey, tinyfishApiKey, searchinfinityApiKey, queritApiKey, tavilyApiKey, firecrawlBaseUrl, jinaApiKey, kagiApiKey, ollamaApiKey, searxngBaseUrl, perplexityApiKey, exaApiKey, geminiApiKey, bochaApiKey, or cloudflareApiKey in ${CONFIG_PATH}\n` +
983
+ " 3. Set OPENAI_API_KEY, BRAVE_API_KEY, PARALLEL_API_KEY, TINYFISH_API_KEY, SEARCHINFINITY_API_KEY, QUERIT_API_KEY, TAVILY_API_KEY, FIRECRAWL_BASE_URL, JINA_API_KEY, KAGI_API_KEY, BOCHA_API_KEY, OLLAMA_API_KEY, SEARXNG_BASE_URL, EXA_API_KEY, PERPLEXITY_API_KEY, GEMINI_API_KEY, or CLOUDFLARE_API_KEY env vars\n" +
984
+ " 4. Set GOOGLE_GEMINI_BASE_URL with CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing\n" +
985
+ ` 5. ${browserCookieAccessHintLine()}\n` +
986
+ " 6. Explicitly select provider: \"anysearch\" for anonymous AnySearch, \"xai\" for Grok, \"mistral\" for Mistral Conversations web search, \"you\" for You.com, \"zai\" for Z.ai GLM Coding Plan search, \"valyu\" for research search, \"keenable\" for keyless Keenable search, \"ceramic\" for Ceramic search, \"deepseek\" for DeepSeek search, \"linkup\" for Linkup search, \"ninerouter\" for a 9router gateway, \"cloudflare\" for the Cloudflare Web Search API, \"tabstack\" for Tabstack Research, or a custom provider from customSearchProviders"
987
+ );
988
+ }
989
+
990
+ async function searchWithGeminiApi(query: string, options: SearchOptions = {}): Promise<SearchResponse | null> {
991
+ const requestSignal = AbortSignal.any([
992
+ AbortSignal.timeout(120000),
993
+ ...(options.signal ? [options.signal] : []),
994
+ ]);
995
+ const apiKey = isGeminiAdcAvailable() ? null : await getApiKey(requestSignal);
996
+ if (!apiKey && !isGatewayConfigured() && !isGeminiAdcAvailable()) return null;
997
+
998
+ const activityId = activityMonitor.logStart({ type: "api", query });
999
+
1000
+ try {
1001
+ const model = options.model ?? getSearchConfig().searchModel ?? DEFAULT_SEARCH_MODEL;
1002
+ const body = {
1003
+ contents: [{ role: "user", parts: [{ text: query }] }],
1004
+ tools: [{ google_search: {} }],
1005
+ };
1006
+
1007
+ const res = await fetchGeminiApi(`${getVersionedApiBase()}/models/${options.model !== undefined ? encodeURIComponent(model) : model}:generateContent`, {
1008
+ method: "POST",
1009
+ headers: { "Content-Type": "application/json" },
1010
+ body: JSON.stringify(body),
1011
+ signal: requestSignal,
1012
+ }, apiKey);
1013
+
1014
+ if (!res.ok) {
1015
+ const errorText = redactGeminiApiResponse(res, await res.text(), apiKey);
1016
+ throw new Error(`Gemini API error ${res.status}: ${errorText.slice(0, 300)}`);
1017
+ }
1018
+
1019
+ const data = await res.json() as GeminiSearchResponse;
1020
+ activityMonitor.logComplete(activityId, res.status);
1021
+
1022
+ const answer = data.candidates?.[0]?.content?.parts
1023
+ ?.map(p => p.text).filter(Boolean).join("\n") ?? "";
1024
+
1025
+ const metadata = data.candidates?.[0]?.groundingMetadata;
1026
+ const results = await resolveGroundingChunks(metadata?.groundingChunks, options.signal);
1027
+
1028
+ if (!answer && results.length === 0) {
1029
+ if (options.model !== undefined) throw new Error("Gemini API returned no answer or sources");
1030
+ return null;
1031
+ }
1032
+ return { answer, results };
1033
+ } catch (err) {
1034
+ const message = err instanceof Error ? err.message : String(err);
1035
+ if (message.toLowerCase().includes("abort")) {
1036
+ activityMonitor.logComplete(activityId, 0);
1037
+ } else {
1038
+ activityMonitor.logError(activityId, message);
1039
+ }
1040
+ throw err;
1041
+ }
1042
+ }
1043
+
1044
+ async function searchWithGeminiWeb(query: string, options: SearchOptions = {}): Promise<SearchResponse | null> {
1045
+ const cookies = await isGeminiWebAvailable();
1046
+ if (!cookies) return null;
1047
+
1048
+ const prompt = buildSearchPrompt(query, options);
1049
+ const activityId = activityMonitor.logStart({ type: "api", query });
1050
+
1051
+ try {
1052
+ const text = await queryWithCookies(prompt, cookies, {
1053
+ signal: options.signal,
1054
+ timeoutMs: 120000,
1055
+ });
1056
+
1057
+ activityMonitor.logComplete(activityId, 200);
1058
+
1059
+ const results = extractSourceUrls(text);
1060
+ return { answer: text, results };
1061
+ } catch (err) {
1062
+ const message = err instanceof Error ? err.message : String(err);
1063
+ if (message.toLowerCase().includes("abort")) {
1064
+ activityMonitor.logComplete(activityId, 0);
1065
+ } else {
1066
+ activityMonitor.logError(activityId, message);
1067
+ }
1068
+ throw err;
1069
+ }
1070
+ }
1071
+
1072
+ function buildSearchPrompt(query: string, options: SearchOptions): string {
1073
+ let prompt = `Search the web and answer the following question. Include source URLs for your claims.\nFormat your response as:\n1. A direct answer to the question\n2. Cited sources as markdown links\n\nQuestion: ${query}`;
1074
+
1075
+ if (options.recencyFilter) {
1076
+ const labels: Record<string, string> = {
1077
+ day: "past 24 hours",
1078
+ week: "past week",
1079
+ month: "past month",
1080
+ year: "past year",
1081
+ };
1082
+ prompt += `\n\nOnly include results from the ${labels[options.recencyFilter]}.`;
1083
+ }
1084
+
1085
+ if (options.domainFilter?.length) {
1086
+ const includes = options.domainFilter.filter(d => !d.startsWith("-"));
1087
+ const excludes = options.domainFilter.filter(d => d.startsWith("-")).map(d => d.slice(1));
1088
+ if (includes.length) prompt += `\n\nOnly cite sources from: ${includes.join(", ")}`;
1089
+ if (excludes.length) prompt += `\n\nDo not cite sources from: ${excludes.join(", ")}`;
1090
+ }
1091
+
1092
+ return prompt;
1093
+ }
1094
+
1095
+ function extractSourceUrls(markdown: string): SearchResult[] {
1096
+ const results: SearchResult[] = [];
1097
+ const seen = new Set<string>();
1098
+ const linkRegex = /\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g;
1099
+ for (const match of markdown.matchAll(linkRegex)) {
1100
+ const url = match[2];
1101
+ if (seen.has(url)) continue;
1102
+ seen.add(url);
1103
+ results.push({ title: match[1], url, snippet: "" });
1104
+ }
1105
+ return results;
1106
+ }
1107
+
1108
+ async function resolveGroundingChunks(
1109
+ chunks: GroundingChunk[] | undefined,
1110
+ signal?: AbortSignal,
1111
+ ): Promise<SearchResult[]> {
1112
+ if (!chunks?.length) return [];
1113
+
1114
+ const results: SearchResult[] = [];
1115
+ for (const chunk of chunks) {
1116
+ if (!chunk.web) continue;
1117
+ const title = chunk.web.title || "";
1118
+ let url = chunk.web.uri || "";
1119
+
1120
+ if (url.includes("vertexaisearch.cloud.google.com/grounding-api-redirect")) {
1121
+ const resolved = await resolveRedirect(url, signal);
1122
+ if (resolved) url = resolved;
1123
+ }
1124
+
1125
+ if (url) results.push({ title, url, snippet: "" });
1126
+ }
1127
+ return results;
1128
+ }
1129
+
1130
+ async function resolveRedirect(proxyUrl: string, signal?: AbortSignal): Promise<string | null> {
1131
+ try {
1132
+ const res = await fetch(proxyUrl, {
1133
+ method: "HEAD",
1134
+ redirect: "manual",
1135
+ signal: AbortSignal.any([
1136
+ AbortSignal.timeout(5000),
1137
+ ...(signal ? [signal] : []),
1138
+ ]),
1139
+ });
1140
+ return res.headers.get("location") || null;
1141
+ } catch {
1142
+ return null;
1143
+ }
1144
+ }
1145
+
1146
+ interface GeminiSearchResponse {
1147
+ candidates?: Array<{
1148
+ content?: { parts?: Array<{ text?: string }> };
1149
+ groundingMetadata?: {
1150
+ webSearchQueries?: string[];
1151
+ groundingChunks?: GroundingChunk[];
1152
+ groundingSupports?: Array<{
1153
+ segment?: { startIndex?: number; endIndex?: number; text?: string };
1154
+ groundingChunkIndices?: number[];
1155
+ }>;
1156
+ };
1157
+ }>;
1158
+ }
1159
+
1160
+ interface GroundingChunk {
1161
+ web?: { uri?: string; title?: string };
1162
+ }