@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
package/jina-search.ts ADDED
@@ -0,0 +1,275 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
4
+ import type { ExtractedContent } from "./extract.ts";
5
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
6
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
7
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
8
+ import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
9
+
10
+ const JINA_SEARCH_BASE_URL = "https://s.jina.ai/";
11
+ const CONFIG_PATH = getWebSearchConfigPath();
12
+ const SEARCH_TIMEOUT_MS = 60_000;
13
+
14
+ interface WebSearchConfig {
15
+ jinaSearchBaseUrl?: unknown;
16
+ jinaApiKey?: unknown;
17
+ }
18
+
19
+ interface JinaSearchItem {
20
+ title?: unknown;
21
+ url?: unknown;
22
+ description?: unknown;
23
+ content?: unknown;
24
+ }
25
+
26
+ interface JinaSearchEnvelope {
27
+ code?: unknown;
28
+ data?: unknown;
29
+ }
30
+
31
+ interface JinaSearchOptions extends SearchOptions {
32
+ includeContent?: boolean;
33
+ }
34
+
35
+ let cachedConfig: WebSearchConfig | null = null;
36
+
37
+ function loadConfig(): WebSearchConfig {
38
+ if (cachedConfig) return cachedConfig;
39
+ if (!existsSync(CONFIG_PATH)) {
40
+ cachedConfig = {};
41
+ return cachedConfig;
42
+ }
43
+
44
+ const raw = readFileSync(CONFIG_PATH, "utf8");
45
+ try {
46
+ const parsed: unknown = JSON.parse(raw);
47
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
48
+ throw new Error("expected a JSON object");
49
+ }
50
+ cachedConfig = parsed as WebSearchConfig;
51
+ return cachedConfig;
52
+ } catch (err) {
53
+ const message = err instanceof Error ? err.message : String(err);
54
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
55
+ }
56
+ }
57
+
58
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
59
+ return resolveCredential({
60
+ provider: "Jina Search",
61
+ configuredValue: loadConfig().jinaApiKey,
62
+ environmentValue: process.env.JINA_API_KEY,
63
+ signal,
64
+ });
65
+ }
66
+
67
+ async function requireApiKey(signal?: AbortSignal): Promise<string> {
68
+ const apiKey = await getApiKey(signal);
69
+ if (!apiKey) {
70
+ throw new Error(
71
+ "Jina Search API key not found. Either:\n" +
72
+ ` 1. Create ${CONFIG_PATH} with { "jinaApiKey": "your-key" }\n` +
73
+ " 2. Set JINA_API_KEY environment variable\n" +
74
+ "Get a key at https://jina.ai/api-dashboard",
75
+ );
76
+ }
77
+ return apiKey;
78
+ }
79
+
80
+ function normalizeDomain(value: string): string | null {
81
+ let input = value.trim().toLowerCase();
82
+ if (input.startsWith("-")) input = input.slice(1).trim();
83
+ if (!input) return null;
84
+ try {
85
+ const parsed = input.includes("://") ? new URL(input) : new URL(`https://${input}`);
86
+ input = parsed.hostname;
87
+ } catch {
88
+ input = input.split("/")[0]?.split(":")[0] ?? "";
89
+ }
90
+ input = input.replace(/^\.+|\.+$/g, "");
91
+ return /^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(input) ? input : null;
92
+ }
93
+
94
+ function mapDomainFilter(domainFilter: string[] | undefined): { includes: string[]; excludes: string[] } {
95
+ const includes: string[] = [];
96
+ const excludes: string[] = [];
97
+ for (const raw of domainFilter ?? []) {
98
+ const domain = normalizeDomain(raw);
99
+ if (!domain) continue;
100
+ const target = raw.trim().startsWith("-") ? excludes : includes;
101
+ if (!target.includes(domain)) target.push(domain);
102
+ }
103
+ return { includes, excludes };
104
+ }
105
+
106
+ function buildSearchRequest(query: string, options: JinaSearchOptions, numResults: number): { url: string; filters: ReturnType<typeof mapDomainFilter> } {
107
+ const filters = mapDomainFilter(options.domainFilter);
108
+ const recency = options.recencyFilter ? ` published in the past ${options.recencyFilter}` : "";
109
+ const exclusions = filters.excludes.map((domain) => ` -site:${domain}`).join("");
110
+ const constrainedQuery = `${query.trim()}${exclusions}${recency}`.trim();
111
+ if (/^\.{1,2}$/.test(constrainedQuery)) throw new Error("Jina Search query must not be a dot path segment");
112
+ const url = new URL(encodeURIComponent(constrainedQuery), resolveProviderApiUrl("jinaSearch", JINA_SEARCH_BASE_URL, loadConfig().jinaSearchBaseUrl));
113
+ url.searchParams.set("count", String(numResults));
114
+ for (const domain of filters.includes) url.searchParams.append("site", domain);
115
+ return { url: url.toString(), filters };
116
+ }
117
+
118
+ function requestSignal(signal?: AbortSignal): { signal: AbortSignal; timeout: AbortSignal } {
119
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
120
+ return {
121
+ timeout,
122
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
123
+ };
124
+ }
125
+
126
+ function errorMessage(err: unknown): string {
127
+ return err instanceof Error ? err.message : String(err);
128
+ }
129
+
130
+ function parseItems(value: unknown): JinaSearchItem[] {
131
+ if (Array.isArray(value)) return value as JinaSearchItem[];
132
+ if (!value || typeof value !== "object") {
133
+ throw new Error("Jina Search API returned invalid response: expected an object or array");
134
+ }
135
+ const envelope = value as JinaSearchEnvelope;
136
+ if (typeof envelope.code === "number" && envelope.code !== 200) {
137
+ throw new Error(`Jina Search API error ${envelope.code}: response envelope reported failure`);
138
+ }
139
+ if (!Array.isArray(envelope.data)) {
140
+ throw new Error("Jina Search API returned invalid response: expected data array");
141
+ }
142
+ return envelope.data as JinaSearchItem[];
143
+ }
144
+
145
+ function passesDomainFilter(url: string, filters: ReturnType<typeof mapDomainFilter>): boolean {
146
+ let hostname: string;
147
+ try {
148
+ hostname = new URL(url).hostname.toLowerCase();
149
+ } catch {
150
+ return false;
151
+ }
152
+ const matches = (domain: string): boolean => hostname === domain || hostname.endsWith(`.${domain}`);
153
+ if (filters.includes.length > 0 && !filters.includes.some(matches)) return false;
154
+ return !filters.excludes.some(matches);
155
+ }
156
+
157
+ function mapItems(items: JinaSearchItem[], numResults: number, filters: ReturnType<typeof mapDomainFilter>): {
158
+ results: SearchResponse["results"];
159
+ content: ExtractedContent[];
160
+ } {
161
+ const results: SearchResponse["results"] = [];
162
+ const content: ExtractedContent[] = [];
163
+ const seen = new Set<string>();
164
+ for (const item of items) {
165
+ const url = typeof item?.url === "string" ? item.url.trim() : "";
166
+ if (!url || seen.has(url) || !passesDomainFilter(url, filters)) continue;
167
+ seen.add(url);
168
+ const title = typeof item.title === "string" && item.title.trim()
169
+ ? item.title.trim()
170
+ : `Source ${results.length + 1}`;
171
+ const snippet = typeof item.description === "string"
172
+ ? item.description.replace(/\s+/g, " ").trim()
173
+ : "";
174
+ results.push({ title, url, snippet });
175
+ if (typeof item.content === "string" && item.content.trim()) {
176
+ content.push({ url, title, content: item.content.trim(), error: null });
177
+ }
178
+ if (results.length >= numResults) break;
179
+ }
180
+ return { results, content };
181
+ }
182
+
183
+ function rethrowRequestError(
184
+ err: unknown,
185
+ apiKey: string,
186
+ activityId: string,
187
+ request: ReturnType<typeof requestSignal>,
188
+ callerSignal?: AbortSignal,
189
+ ): never {
190
+ if (request.timeout.aborted && !callerSignal?.aborted) {
191
+ activityMonitor.logComplete(activityId, 408);
192
+ throw new Error("Jina Search API error 408: request timed out");
193
+ }
194
+ const message = errorMessage(err);
195
+ const redactedMessage = redactCredential(message, apiKey);
196
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
197
+ else activityMonitor.logError(activityId, redactedMessage);
198
+ if (redactedMessage === message) throw err;
199
+ const redactedError = new Error(redactedMessage);
200
+ if (err instanceof Error) redactedError.name = err.name;
201
+ throw redactedError;
202
+ }
203
+
204
+ export function isJinaSearchAvailable(): boolean {
205
+ return hasCredentialSource({
206
+ provider: "Jina Search",
207
+ configuredValue: loadConfig().jinaApiKey,
208
+ environmentValue: process.env.JINA_API_KEY,
209
+ });
210
+ }
211
+
212
+ export async function searchWithJina(query: string, options: JinaSearchOptions = {}): Promise<SearchResponse> {
213
+ const apiKey = await requireApiKey(options.signal);
214
+ const numResults = normalizeSearchResultCount(options.numResults);
215
+ const { url, filters } = buildSearchRequest(query, options, numResults);
216
+ const activityId = activityMonitor.logStart({ type: "api", query });
217
+ const request = requestSignal(options.signal);
218
+ let response: Response;
219
+ try {
220
+ response = await fetchWithCredentialRedirects(String(url), {
221
+ headers: {
222
+ "Accept": "application/json",
223
+ "Authorization": `Bearer ${apiKey}`,
224
+ "User-Agent": "pi-web-access",
225
+ "X-Respond-With": options.includeContent ? "content" : "no-content",
226
+ "X-Retain-Images": "none",
227
+ },
228
+ signal: request.signal,
229
+ }, ["Authorization"]);
230
+ } catch (err) {
231
+ rethrowRequestError(err, apiKey, activityId, request, options.signal);
232
+ }
233
+
234
+ if (!response.ok) {
235
+ let body: string;
236
+ try {
237
+ body = redactCredential(await response.text(), apiKey);
238
+ } catch (err) {
239
+ rethrowRequestError(err, apiKey, activityId, request, options.signal);
240
+ }
241
+ activityMonitor.logComplete(activityId, response.status);
242
+ throw new Error(`Jina Search API error ${response.status}: ${body.slice(0, 300)}`);
243
+ }
244
+
245
+ let raw: unknown;
246
+ try {
247
+ raw = await response.json();
248
+ } catch (err) {
249
+ if (!(err instanceof SyntaxError)) {
250
+ rethrowRequestError(err, apiKey, activityId, request, options.signal);
251
+ }
252
+ activityMonitor.logComplete(activityId, response.status);
253
+ throw new Error("Jina Search API returned invalid JSON");
254
+ }
255
+
256
+ let mapped: ReturnType<typeof mapItems>;
257
+ try {
258
+ mapped = mapItems(parseItems(raw), numResults, filters);
259
+ } catch (err) {
260
+ const message = errorMessage(err);
261
+ const redactedMessage = redactCredential(message, apiKey);
262
+ activityMonitor.logError(activityId, redactedMessage);
263
+ if (redactedMessage === message) throw err;
264
+ const redactedError = new Error(redactedMessage);
265
+ if (err instanceof Error) redactedError.name = err.name;
266
+ throw redactedError;
267
+ }
268
+ activityMonitor.logComplete(activityId, response.status);
269
+ const result: SearchResponse = {
270
+ answer: formatSearchResultsAsAnswer(mapped.results),
271
+ results: mapped.results,
272
+ };
273
+ if (options.includeContent && mapped.content.length > 0) result.inlineContent = mapped.content;
274
+ return result;
275
+ }
package/kagi.ts ADDED
@@ -0,0 +1,257 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import type { ExtractedContent, ExtractOptions } from "./extract.ts";
4
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
5
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
6
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
7
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { fetchRemoteUrl, loadFetchContentDomainPolicy, loadSsrfConfig, validateRemoteUrl, type SsrfConfig } from "./ssrf-protection.ts";
9
+ import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
10
+
11
+ const KAGI_SEARCH_URL = "https://kagi.com/api/v1/search";
12
+ const KAGI_EXTRACT_URL = "https://kagi.com/api/v1/extract";
13
+ const CONFIG_PATH = getWebSearchConfigPath();
14
+ const SEARCH_TIMEOUT_MS = 60_000;
15
+
16
+ interface WebSearchConfig {
17
+ kagiBaseUrl?: unknown;
18
+ kagiApiKey?: unknown;
19
+ }
20
+
21
+ interface KagiSearchOptions extends SearchOptions {
22
+ includeContent?: boolean;
23
+ }
24
+
25
+ export interface KagiExtractOptions extends Pick<ExtractOptions, "timeoutMs" | "lookup"> {
26
+ ssrf?: SsrfConfig;
27
+ }
28
+
29
+ let cachedConfig: WebSearchConfig | null = null;
30
+
31
+ function loadConfig(): WebSearchConfig {
32
+ if (cachedConfig) return cachedConfig;
33
+ if (!existsSync(CONFIG_PATH)) {
34
+ cachedConfig = {};
35
+ return cachedConfig;
36
+ }
37
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
38
+ let parsed: unknown;
39
+ try {
40
+ parsed = JSON.parse(raw);
41
+ } catch (err) {
42
+ const message = err instanceof Error ? err.message : String(err);
43
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
44
+ }
45
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
46
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
47
+ }
48
+ cachedConfig = parsed as WebSearchConfig;
49
+ return cachedConfig;
50
+ }
51
+
52
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
53
+ return resolveCredential({
54
+ provider: "Kagi",
55
+ configuredValue: loadConfig().kagiApiKey,
56
+ environmentValue: process.env.KAGI_API_KEY,
57
+ signal,
58
+ });
59
+ }
60
+
61
+ async function requireApiKey(signal?: AbortSignal): Promise<string> {
62
+ const apiKey = await getApiKey(signal);
63
+ if (!apiKey) {
64
+ throw new Error(
65
+ "Kagi API key not found. Either:\n" +
66
+ ` 1. Create ${CONFIG_PATH} with { "kagiApiKey": "your-key" }\n` +
67
+ " 2. Set KAGI_API_KEY environment variable\n" +
68
+ "Create a key at https://kagi.com/settings?p=api",
69
+ );
70
+ }
71
+ return apiKey;
72
+ }
73
+
74
+ function errorMessage(err: unknown): string {
75
+ return err instanceof Error ? err.message : String(err);
76
+ }
77
+
78
+ function invalidResponse(message: string): Error {
79
+ return new Error(`Kagi API returned invalid response: ${message}`);
80
+ }
81
+
82
+ function firstString(...values: unknown[]): string | null {
83
+ for (const value of values) {
84
+ if (typeof value === "string" && value.trim()) return value.trim();
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function appendSearchItems(value: unknown, results: SearchResponse["results"], inlineContent: ExtractedContent[]): void {
90
+ if (Array.isArray(value)) {
91
+ for (const item of value) appendSearchItems(item, results, inlineContent);
92
+ return;
93
+ }
94
+ if (!value || typeof value !== "object") return;
95
+ const item = value as Record<string, unknown>;
96
+ const url = firstString(item.url, item.href, item.link);
97
+ if (!url) return;
98
+ const title = firstString(item.title, item.name) ?? url;
99
+ const snippet = firstString(item.snippet, item.description, item.summary, item.content, item.markdown, item.text) ?? "";
100
+ results.push({ title, url, snippet });
101
+ const content = firstString(item.markdown, item.content, item.text);
102
+ if (content) inlineContent.push({ url, title, content, error: null });
103
+ }
104
+
105
+ function parseErrors(value: unknown): string | null {
106
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
107
+ const envelope = value as Record<string, unknown>;
108
+ const rawErrors = envelope.errors ?? envelope.error;
109
+ if (!Array.isArray(rawErrors)) return null;
110
+ const messages = rawErrors.map((entry) => {
111
+ if (!entry || typeof entry !== "object") return String(entry);
112
+ const raw = entry as Record<string, unknown>;
113
+ return firstString(raw.message, raw.msg, raw.code) ?? JSON.stringify(raw);
114
+ });
115
+ return messages.length > 0 ? messages.join("; ") : null;
116
+ }
117
+
118
+ function parseSearchResponse(value: unknown): { results: SearchResponse["results"]; inlineContent: ExtractedContent[] } {
119
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidResponse("expected an object envelope");
120
+ const message = parseErrors(value);
121
+ if (message) throw invalidResponse(message);
122
+ const envelope = value as Record<string, unknown>;
123
+ const results: SearchResponse["results"] = [];
124
+ const inlineContent: ExtractedContent[] = [];
125
+ const data = envelope.data;
126
+ const items = (typeof data === "object" && data !== null && !Array.isArray(data))
127
+ ? (data as Record<string, unknown>).search
128
+ : data;
129
+ appendSearchItems(items, results, inlineContent);
130
+ return { results, inlineContent };
131
+ }
132
+
133
+ function parseExtractResponse(value: unknown, requestedUrl: string): ExtractedContent | null {
134
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidResponse("expected extract object envelope");
135
+ const message = parseErrors(value);
136
+ if (message) throw invalidResponse(message);
137
+ const envelope = value as Record<string, unknown>;
138
+ const candidates = Array.isArray(envelope.data) ? envelope.data : [envelope.data ?? envelope];
139
+ for (const candidate of candidates) {
140
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) continue;
141
+ const item = candidate as Record<string, unknown>;
142
+ const content = firstString(item.markdown, item.content, item.text);
143
+ if (!content) continue;
144
+ return {
145
+ url: firstString(item.url, item.href, item.link) ?? requestedUrl,
146
+ title: firstString(item.title, item.name) ?? requestedUrl,
147
+ content,
148
+ error: null,
149
+ };
150
+ }
151
+ return null;
152
+ }
153
+
154
+ export function isKagiAvailable(): boolean {
155
+ return hasCredentialSource({ provider: "Kagi", configuredValue: loadConfig().kagiApiKey, environmentValue: process.env.KAGI_API_KEY });
156
+ }
157
+
158
+ export async function searchWithKagi(query: string, options: KagiSearchOptions = {}): Promise<SearchResponse> {
159
+ const apiKey = await requireApiKey(options.signal);
160
+ const numResults = normalizeSearchResultCount(options.numResults);
161
+ const activityId = activityMonitor.logStart({ type: "api", query });
162
+ let response: Response;
163
+ try {
164
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("kagi", KAGI_SEARCH_URL, loadConfig().kagiBaseUrl), {
165
+ method: "POST",
166
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
167
+ body: JSON.stringify({ query, limit: numResults }),
168
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS),
169
+ }, ["Authorization"]);
170
+ } catch (err) {
171
+ const message = errorMessage(err);
172
+ const redactedMessage = redactCredential(message, apiKey);
173
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
174
+ else activityMonitor.logError(activityId, redactedMessage);
175
+ if (redactedMessage === message) throw err;
176
+ const redactedError = new Error(redactedMessage);
177
+ if (err instanceof Error) redactedError.name = err.name;
178
+ throw redactedError;
179
+ }
180
+ if (!response.ok) {
181
+ activityMonitor.logComplete(activityId, response.status);
182
+ const errorText = redactCredential(await response.text(), apiKey);
183
+ throw new Error(`Kagi API error ${response.status}: ${errorText.slice(0, 300)}`);
184
+ }
185
+ let rawData: unknown;
186
+ try {
187
+ rawData = await response.json();
188
+ } catch (err) {
189
+ activityMonitor.logComplete(activityId, response.status);
190
+ throw new Error(`Kagi API returned invalid JSON: ${errorMessage(err)}`);
191
+ }
192
+ const parsed = parseSearchResponse(rawData);
193
+ activityMonitor.logComplete(activityId, response.status);
194
+ const results = parsed.results.slice(0, numResults);
195
+ const mapped: SearchResponse = { answer: formatSearchResultsAsAnswer(results), results };
196
+ if (options.includeContent) {
197
+ const urls = new Set(results.map(result => result.url));
198
+ const inlineContent = parsed.inlineContent.filter(content => urls.has(content.url));
199
+ if (inlineContent.length > 0) mapped.inlineContent = inlineContent;
200
+ }
201
+ return mapped;
202
+ }
203
+
204
+ export function isKagiExtractAvailable(): boolean {
205
+ return isKagiAvailable();
206
+ }
207
+
208
+ export async function extractWithKagi(url: string, signal?: AbortSignal, options: KagiExtractOptions = {}): Promise<ExtractedContent | null> {
209
+ const ssrf = options.ssrf ?? loadSsrfConfig();
210
+ const domainPolicy = loadFetchContentDomainPolicy();
211
+ await validateRemoteUrl(url, {
212
+ allowRanges: ssrf.allowRanges,
213
+ trustEnvProxy: ssrf.trustEnvProxy,
214
+ domainPolicy,
215
+ ...(options.lookup ? { lookup: options.lookup } : {}),
216
+ });
217
+ const apiKey = await requireApiKey(signal);
218
+ const activityId = activityMonitor.logStart({ type: "api", query: `kagi extract: ${url}` });
219
+ let response: Response;
220
+ try {
221
+ response = await fetchRemoteUrl(resolveProviderApiUrl("kagi", KAGI_EXTRACT_URL, loadConfig().kagiBaseUrl), {
222
+ method: "POST",
223
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
224
+ body: JSON.stringify({ pages: [{ url }] }),
225
+ signal: signal ? AbortSignal.any([AbortSignal.timeout(options.timeoutMs ?? SEARCH_TIMEOUT_MS), signal]) : AbortSignal.timeout(options.timeoutMs ?? SEARCH_TIMEOUT_MS),
226
+ }, {
227
+ allowRanges: ssrf.allowRanges,
228
+ trustEnvProxy: ssrf.trustEnvProxy,
229
+ onRedirect: ({ from, to, init }) => to.origin === from.origin ? init : { ...init, headers: { "Content-Type": "application/json", Accept: "application/json" } },
230
+ ...(options.lookup ? { lookup: options.lookup } : {}),
231
+ });
232
+ } catch (err) {
233
+ const message = errorMessage(err);
234
+ const redactedMessage = redactCredential(message, apiKey);
235
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
236
+ else activityMonitor.logError(activityId, redactedMessage);
237
+ if (redactedMessage === message) throw err;
238
+ const redactedError = new Error(redactedMessage);
239
+ if (err instanceof Error) redactedError.name = err.name;
240
+ throw redactedError;
241
+ }
242
+ if (!response.ok) {
243
+ activityMonitor.logComplete(activityId, response.status);
244
+ const errorText = redactCredential(await response.text(), apiKey);
245
+ throw new Error(`Kagi Extract API error ${response.status}: ${errorText.slice(0, 300)}`);
246
+ }
247
+ let rawData: unknown;
248
+ try {
249
+ rawData = await response.json();
250
+ } catch (err) {
251
+ activityMonitor.logComplete(activityId, response.status);
252
+ throw new Error(`Kagi Extract API returned invalid JSON: ${errorMessage(err)}`);
253
+ }
254
+ const parsed = parseExtractResponse(rawData, url);
255
+ activityMonitor.logComplete(activityId, response.status);
256
+ return parsed;
257
+ }