@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/keenable.ts ADDED
@@ -0,0 +1,222 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.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 { redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
9
+
10
+ const KEENABLE_SEARCH_URL = "https://api.keenable.ai/v1/search";
11
+ // Without a key the request goes to the public endpoint, which identifies the caller
12
+ // by X-Keenable-Title instead of a credential and answers 400 when the header is missing.
13
+ const KEENABLE_PUBLIC_SEARCH_URL = "https://api.keenable.ai/v1/search/public";
14
+ const KEENABLE_CLIENT_TITLE = "pi-web-access";
15
+ const CONFIG_PATH = getWebSearchConfigPath();
16
+ const SEARCH_TIMEOUT_MS = 30_000;
17
+ const MAX_REQUEST_RESULTS = 50;
18
+ const MAX_SNIPPET_CHARS = 500;
19
+ const RECENCY_DAYS: Record<NonNullable<SearchOptions["recencyFilter"]>, number> = {
20
+ day: 1,
21
+ week: 7,
22
+ month: 30,
23
+ year: 365,
24
+ };
25
+
26
+ interface WebSearchConfig {
27
+ keenableBaseUrl?: unknown;
28
+ keenableApiKey?: unknown;
29
+ }
30
+
31
+ interface KeenableResult {
32
+ title?: unknown;
33
+ url?: unknown;
34
+ snippet?: unknown;
35
+ description?: unknown;
36
+ }
37
+
38
+ let cachedConfig: WebSearchConfig | null = null;
39
+
40
+ function loadConfig(): WebSearchConfig {
41
+ if (cachedConfig) return cachedConfig;
42
+ if (!existsSync(CONFIG_PATH)) {
43
+ cachedConfig = {};
44
+ return cachedConfig;
45
+ }
46
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
47
+ let parsed: unknown;
48
+ try {
49
+ parsed = JSON.parse(raw);
50
+ } catch (err) {
51
+ const message = err instanceof Error ? err.message : String(err);
52
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
53
+ }
54
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
55
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
56
+ }
57
+ cachedConfig = parsed as WebSearchConfig;
58
+ return cachedConfig;
59
+ }
60
+
61
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
62
+ return resolveCredential({
63
+ provider: "Keenable",
64
+ configuredValue: loadConfig().keenableApiKey,
65
+ environmentValue: process.env.KEENABLE_API_KEY,
66
+ signal,
67
+ });
68
+ }
69
+
70
+ interface DomainFilters {
71
+ include: string[];
72
+ exclude: string[];
73
+ }
74
+
75
+ function parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {
76
+ const filters: DomainFilters = { include: [], exclude: [] };
77
+ for (const raw of domainFilter ?? []) {
78
+ const domain = normalizeDomain(raw);
79
+ if (!domain) continue;
80
+ const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
81
+ if (!target.includes(domain)) target.push(domain);
82
+ }
83
+ return filters;
84
+ }
85
+
86
+ function passesDomainFilters(url: URL, filters: DomainFilters): boolean {
87
+ if (filters.include.length === 0 && filters.exclude.length === 0) return true;
88
+ const hostname = url.hostname.toLowerCase();
89
+ const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
90
+ if (filters.exclude.some(matches)) return false;
91
+ return filters.include.length === 0 || filters.include.some(matches);
92
+ }
93
+
94
+ // One domain uses the API's `site` field; the query syntax covers the rest, so no ranked
95
+ // window has to be filtered down locally to find in-domain pages.
96
+ function buildQuery(query: string, filters: DomainFilters, site: string | undefined): string {
97
+ const parts = [query];
98
+ if (!site && filters.include.length > 1) parts.push(`(${filters.include.map(domain => `site:${domain}`).join(" OR ")})`);
99
+ for (const domain of filters.exclude) parts.push(`-site:${domain}`);
100
+ return parts.join(" ");
101
+ }
102
+
103
+ function publishedAfter(recency: NonNullable<SearchOptions["recencyFilter"]>): string {
104
+ return new Date(Date.now() - RECENCY_DAYS[recency] * 86_400_000).toISOString().slice(0, 10);
105
+ }
106
+
107
+ function text(value: unknown): string {
108
+ return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
109
+ }
110
+
111
+ function errorMessage(err: unknown): string {
112
+ return err instanceof Error ? err.message : String(err);
113
+ }
114
+
115
+ function invalidResponse(message: string): Error {
116
+ return new Error(`Keenable returned invalid response: ${message}`);
117
+ }
118
+
119
+ function parseResponse(value: unknown): KeenableResult[] {
120
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidResponse("expected an object envelope");
121
+ const envelope = value as Record<string, unknown>;
122
+ if (!Array.isArray(envelope.results)) throw invalidResponse("expected results array");
123
+ return envelope.results as KeenableResult[];
124
+ }
125
+
126
+ // The public endpoint needs no key, so the provider is always usable once selected.
127
+ export function isKeenableAvailable(): boolean {
128
+ return true;
129
+ }
130
+
131
+ export async function searchWithKeenable(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
132
+ const apiKey = await getApiKey(options.signal);
133
+ const numResults = normalizeSearchResultCount(options.numResults);
134
+ const filters = parseDomainFilter(options.domainFilter);
135
+ const site = filters.include.length === 1 ? filters.include[0] : undefined;
136
+ // Results are reapplied to the domain filters locally, so leave a little headroom.
137
+ const hasDomainClauses = filters.include.length > 1 || filters.exclude.length > 0;
138
+ const body = {
139
+ query: buildQuery(query, filters, site),
140
+ max_results: hasDomainClauses ? Math.min(MAX_REQUEST_RESULTS, numResults + 5) : numResults,
141
+ snippet_max_length: MAX_SNIPPET_CHARS,
142
+ ...(site ? { site } : {}),
143
+ ...(options.recencyFilter ? { published_after: publishedAfter(options.recencyFilter) } : {}),
144
+ };
145
+ const headers: Record<string, string> = {
146
+ Accept: "application/json",
147
+ "Content-Type": "application/json",
148
+ "X-Keenable-Title": KEENABLE_CLIENT_TITLE,
149
+ ...(apiKey ? { "X-API-Key": apiKey } : {}),
150
+ };
151
+ const activityId = activityMonitor.logStart({ type: "api", query });
152
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
153
+ let response: Response;
154
+ let entries: KeenableResult[];
155
+ try {
156
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("keenable", apiKey ? KEENABLE_SEARCH_URL : KEENABLE_PUBLIC_SEARCH_URL, loadConfig().keenableBaseUrl), {
157
+ method: "POST",
158
+ headers,
159
+ body: JSON.stringify(body),
160
+ signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal,
161
+ }, ["X-API-Key"]);
162
+ if (!response.ok) {
163
+ const errorText = redactCredential(await response.text(), apiKey).slice(0, 300);
164
+ const hint = response.status === 429 && !apiKey
165
+ ? ` (keyless rate limit; set keenableApiKey or KEENABLE_API_KEY to raise it)`
166
+ : "";
167
+ throw new Error(`Keenable error ${response.status}: ${errorText}${hint}`);
168
+ }
169
+ let rawData: unknown;
170
+ try {
171
+ rawData = await response.json();
172
+ } catch (err) {
173
+ if (err instanceof Error && err.name === "TimeoutError") throw err;
174
+ throw new Error(`Keenable returned invalid JSON: ${errorMessage(err)}`);
175
+ }
176
+ entries = parseResponse(rawData);
177
+ } catch (err) {
178
+ if (options.signal?.aborted) {
179
+ activityMonitor.logComplete(activityId, 0);
180
+ throw new Error("Aborted");
181
+ }
182
+ const message = errorMessage(err);
183
+ const providerTimeout = timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError");
184
+ const outgoing = providerTimeout
185
+ ? new Error(`Keenable request timed out after ${Math.round(SEARCH_TIMEOUT_MS / 1000)}s`)
186
+ : (() => {
187
+ const redactedMessage = redactCredential(message, apiKey);
188
+ if (redactedMessage === message && err instanceof Error) return err;
189
+ const redactedError = new Error(redactedMessage);
190
+ if (err instanceof Error) redactedError.name = err.name;
191
+ return redactedError;
192
+ })();
193
+ activityMonitor.logError(activityId, redactCredential(errorMessage(outgoing), apiKey));
194
+ throw outgoing;
195
+ }
196
+ activityMonitor.logComplete(activityId, response.status);
197
+ const results: SearchResponse["results"] = [];
198
+ const seen = new Set<string>();
199
+ for (const entry of entries) {
200
+ if (!entry || typeof entry !== "object") continue;
201
+ if (typeof entry.url !== "string" || !entry.url) continue;
202
+ let resultUrl: URL;
203
+ try {
204
+ resultUrl = new URL(entry.url);
205
+ } catch {
206
+ continue;
207
+ }
208
+ if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
209
+ if (!passesDomainFilters(resultUrl, filters)) continue;
210
+ if (seen.has(resultUrl.href)) continue;
211
+ seen.add(resultUrl.href);
212
+ // The page text lives in `snippet`; `description` is usually empty and only a fallback.
213
+ const snippet = text(entry.snippet) || text(entry.description);
214
+ results.push({
215
+ title: text(entry.title) || `Source ${results.length + 1}`,
216
+ url: resultUrl.href,
217
+ snippet: snippet.slice(0, MAX_SNIPPET_CHARS),
218
+ });
219
+ if (results.length >= numResults) break;
220
+ }
221
+ return { answer: formatSearchResultsAsAnswer(results), results };
222
+ }
package/kimi-search.ts ADDED
@@ -0,0 +1,209 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { activityMonitor } from "./activity.ts";
4
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
5
+ import { redactCredential } from "./credential-source.ts";
6
+ import type { SearchOptions, SearchResponse, SearchResult } from "./perplexity.ts";
7
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
8
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
9
+
10
+ const KIMI_SEARCH_URL = "https://api.kimi.com/coding/v1/search";
11
+ const KIMI_PROVIDERS = ["kimi-coding", "kimi-code"] as const;
12
+ const SEARCH_TIMEOUT_MS = 30_000;
13
+
14
+ type ProviderHeaders = Record<string, string | null>;
15
+
16
+ interface KimiAuth {
17
+ apiKey: string;
18
+ headers: ProviderHeaders;
19
+ }
20
+
21
+ interface NormalizedDomainFilters {
22
+ allowed: string[];
23
+ blocked: string[];
24
+ }
25
+
26
+ function buildRequestHeaders(auth: KimiAuth): Headers {
27
+ const headers = new Headers();
28
+ for (const [name, value] of Object.entries(auth.headers)) {
29
+ if (value !== null) headers.set(name, value);
30
+ }
31
+ headers.set("Authorization", `Bearer ${auth.apiKey}`);
32
+ headers.set("Content-Type", "application/json");
33
+ headers.set("X-Msh-Tool-Call-Id", randomUUID());
34
+ return headers;
35
+ }
36
+
37
+ function bearerToken(headers: ProviderHeaders): string | undefined {
38
+ for (const [name, value] of Object.entries(headers)) {
39
+ if (name.toLowerCase() !== "authorization" || typeof value !== "string") continue;
40
+ const match = /^Bearer\s+(.+)$/i.exec(value.trim());
41
+ if (match?.[1]) return match[1];
42
+ }
43
+ return undefined;
44
+ }
45
+
46
+ async function resolveKimiAuth(ctx?: ExtensionContext): Promise<KimiAuth | undefined> {
47
+ if (!ctx) return undefined;
48
+
49
+ const models = ctx.modelRegistry.getAll();
50
+ let firstError: unknown;
51
+
52
+ for (const provider of KIMI_PROVIDERS) {
53
+ for (const model of models) {
54
+ if (model.provider !== provider) continue;
55
+ let resolved: Awaited<ReturnType<typeof ctx.modelRegistry.getApiKeyAndHeaders>>;
56
+ try {
57
+ resolved = await ctx.modelRegistry.getApiKeyAndHeaders(model);
58
+ } catch (err) {
59
+ firstError ??= err;
60
+ continue;
61
+ }
62
+ if (!resolved.ok) continue;
63
+ const headers = resolved.headers ?? {};
64
+ const apiKey = resolved.apiKey || bearerToken(headers);
65
+ if (apiKey) return { apiKey, headers };
66
+ }
67
+ }
68
+ if (firstError) throw firstError;
69
+ return undefined;
70
+ }
71
+
72
+ function normalizeDomainFilters(domainFilter: string[] | undefined): NormalizedDomainFilters {
73
+ const filters: NormalizedDomainFilters = { allowed: [], blocked: [] };
74
+ if (!domainFilter?.length) return filters;
75
+
76
+ for (const raw of domainFilter) {
77
+ const domain = normalizeDomain(raw);
78
+ if (!domain) continue;
79
+ const target = raw.trim().startsWith("-") ? filters.blocked : filters.allowed;
80
+ if (!target.includes(domain)) target.push(domain);
81
+ }
82
+ return filters;
83
+ }
84
+
85
+ function hostMatchesDomain(hostname: string, domain: string): boolean {
86
+ return hostname === domain || hostname.endsWith(`.${domain}`);
87
+ }
88
+
89
+ function matchesDomainFilters(url: string, filters: NormalizedDomainFilters): boolean {
90
+ if (filters.allowed.length === 0 && filters.blocked.length === 0) return true;
91
+
92
+ let hostname = "";
93
+ try {
94
+ hostname = new URL(url).hostname.toLowerCase();
95
+ } catch {
96
+ return false;
97
+ }
98
+ if (filters.allowed.length > 0 && !filters.allowed.some((domain) => hostMatchesDomain(hostname, domain))) {
99
+ return false;
100
+ }
101
+ return !filters.blocked.some((domain) => hostMatchesDomain(hostname, domain));
102
+ }
103
+
104
+ function normalizeResultUrl(value: unknown): string | null {
105
+ if (typeof value !== "string") return null;
106
+ const input = value.trim();
107
+ if (!input) return null;
108
+ try {
109
+ const url = new URL(input);
110
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
111
+ return url.href;
112
+ } catch {
113
+ return null;
114
+ }
115
+ }
116
+
117
+ function parseResults(value: unknown, options: SearchOptions): SearchResult[] {
118
+ if (!value || typeof value !== "object" || !Array.isArray((value as { search_results?: unknown }).search_results)) {
119
+ throw new Error("Kimi Code search API returned an invalid response: search_results must be an array");
120
+ }
121
+
122
+ const filters = normalizeDomainFilters(options.domainFilter);
123
+ const numResults = normalizeSearchResultCount(options.numResults);
124
+ const results: SearchResult[] = [];
125
+ for (const item of (value as { search_results: unknown[] }).search_results) {
126
+ if (!item || typeof item !== "object") continue;
127
+ const record = item as Record<string, unknown>;
128
+ const url = normalizeResultUrl(record.url);
129
+ if (!url || !matchesDomainFilters(url, filters)) continue;
130
+ results.push({
131
+ title: typeof record.title === "string" && record.title.trim() ? record.title : url,
132
+ url,
133
+ snippet: typeof record.snippet === "string" ? record.snippet : "",
134
+ });
135
+ if (results.length >= numResults) break;
136
+ }
137
+ return results;
138
+ }
139
+
140
+ export async function isKimiSearchAvailable(ctx?: ExtensionContext): Promise<boolean> {
141
+ try {
142
+ return !!(await resolveKimiAuth(ctx));
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ export async function searchWithKimi(
149
+ query: string,
150
+ options: SearchOptions = {},
151
+ ctx?: ExtensionContext,
152
+ ): Promise<SearchResponse> {
153
+ const auth = await resolveKimiAuth(ctx);
154
+ if (!auth) {
155
+ throw new Error("Kimi Code web search unavailable. Run /login kimi-coding to authenticate a Kimi Code Plan account.");
156
+ }
157
+
158
+ const activityId = activityMonitor.logStart({ type: "api", query });
159
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
160
+ const requestSignal = options.signal
161
+ ? AbortSignal.any([timeoutSignal, options.signal])
162
+ : timeoutSignal;
163
+ try {
164
+ const response = await fetch(KIMI_SEARCH_URL, {
165
+ method: "POST",
166
+ headers: buildRequestHeaders(auth),
167
+ body: JSON.stringify({ text_query: query }),
168
+ signal: requestSignal,
169
+ });
170
+
171
+ if (!response.ok) {
172
+ activityMonitor.logError(activityId, `HTTP ${response.status}`);
173
+ const errorText = redactCredential(await response.text(), auth.apiKey);
174
+ throw new Error(`Kimi Code search API error ${response.status}: ${errorText.slice(0, 300)}`);
175
+ }
176
+
177
+ let parsed: unknown;
178
+ try {
179
+ parsed = await response.json();
180
+ } catch (err) {
181
+ const message = err instanceof Error ? err.message : String(err);
182
+ throw new Error(`Kimi Code search API returned invalid JSON: ${message}`);
183
+ }
184
+ const results = parseResults(parsed, options);
185
+ if (results.length === 0) {
186
+ throw new Error("Kimi Code search API returned no results");
187
+ }
188
+
189
+ activityMonitor.logComplete(activityId, response.status);
190
+ return { answer: formatSearchResultsAsAnswer(results), results };
191
+ } catch (err) {
192
+ const message = err instanceof Error ? err.message : String(err);
193
+ const redactedMessage = redactCredential(message, auth.apiKey);
194
+ if (options.signal?.aborted) {
195
+ activityMonitor.logComplete(activityId, 0);
196
+ } else if (timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError")) {
197
+ activityMonitor.logError(activityId, "Kimi Code search API timed out");
198
+ throw new Error("Kimi Code search API timed out");
199
+ } else if (redactedMessage.toLowerCase().includes("abort")) {
200
+ activityMonitor.logComplete(activityId, 0);
201
+ } else {
202
+ activityMonitor.logError(activityId, redactedMessage);
203
+ }
204
+ if (redactedMessage === message) throw err;
205
+ const redactedError = new Error(redactedMessage);
206
+ if (err instanceof Error) redactedError.name = err.name;
207
+ throw redactedError;
208
+ }
209
+ }
package/linkup.ts ADDED
@@ -0,0 +1,170 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
4
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
5
+ import type { ExtractedContent } from "./extract.ts";
6
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
7
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
8
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
9
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
10
+
11
+ const LINKUP_SEARCH_URL = "https://api.linkup.so/v1/search";
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+ const SEARCH_TIMEOUT_MS = 60_000;
14
+ const DEPTHS = ["flash", "fast", "standard", "deep"] as const;
15
+ type LinkupDepth = typeof DEPTHS[number];
16
+
17
+ interface LinkupConfig {
18
+ linkupBaseUrl?: unknown;
19
+ linkupApiKey?: unknown;
20
+ linkupDepth?: unknown;
21
+ }
22
+
23
+ interface LinkupResult {
24
+ type?: unknown;
25
+ name?: unknown;
26
+ url?: unknown;
27
+ content?: unknown;
28
+ }
29
+
30
+ let cachedConfig: LinkupConfig | undefined;
31
+
32
+ function loadConfig(): LinkupConfig {
33
+ if (cachedConfig) return cachedConfig;
34
+ if (!existsSync(CONFIG_PATH)) return cachedConfig = {};
35
+ let parsed: unknown;
36
+ try {
37
+ parsed = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
38
+ } catch {
39
+ // JSON parse errors can quote credentials from the config file.
40
+ throw new Error(`Failed to parse ${CONFIG_PATH}: expected valid JSON`);
41
+ }
42
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
43
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
44
+ }
45
+ return cachedConfig = parsed as LinkupConfig;
46
+ }
47
+
48
+ function getDepth(): LinkupDepth {
49
+ const value = loadConfig().linkupDepth;
50
+ if (value === undefined) return "fast";
51
+ if (typeof value !== "string" || !DEPTHS.includes(value as LinkupDepth)) {
52
+ throw new Error(`linkupDepth in ${CONFIG_PATH} must be one of: ${DEPTHS.join(", ")}`);
53
+ }
54
+ return value as LinkupDepth;
55
+ }
56
+
57
+ function domainFilters(values: string[] | undefined): { include: string[]; exclude: string[] } {
58
+ const include: string[] = [];
59
+ const exclude: string[] = [];
60
+ for (const raw of values ?? []) {
61
+ const domain = normalizeDomain(raw);
62
+ if (!domain) continue;
63
+ const target = raw.trim().startsWith("-") ? exclude : include;
64
+ if (!target.includes(domain)) target.push(domain);
65
+ }
66
+ if (include.length > 100 || exclude.length > 100) {
67
+ throw new Error("Linkup domainFilter must contain at most 100 included and 100 excluded domains");
68
+ }
69
+ return { include, exclude };
70
+ }
71
+
72
+ function recencyToDate(filter: SearchOptions["recencyFilter"]): string | undefined {
73
+ if (!filter) return undefined;
74
+ const days = { day: 1, week: 7, month: 30, year: 365 }[filter];
75
+ return new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);
76
+ }
77
+
78
+ function text(value: unknown): string {
79
+ return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
80
+ }
81
+
82
+ function parseResponse(value: unknown): LinkupResult[] {
83
+ if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray((value as Record<string, unknown>).results)) {
84
+ throw new Error("Linkup returned invalid response: expected results array");
85
+ }
86
+ return (value as { results: LinkupResult[] }).results;
87
+ }
88
+
89
+ export function isLinkupAvailable(): boolean {
90
+ return hasCredentialSource({ provider: "Linkup", configuredValue: loadConfig().linkupApiKey, environmentValue: process.env.LINKUP_API_KEY });
91
+ }
92
+
93
+ export async function searchWithLinkup(query: string, options: SearchOptions & { includeContent?: boolean } = {}): Promise<SearchResponse> {
94
+ const depth = getDepth();
95
+ const filters = domainFilters(options.domainFilter);
96
+ const apiKey = await resolveCredential({
97
+ provider: "Linkup",
98
+ configuredValue: loadConfig().linkupApiKey,
99
+ environmentValue: process.env.LINKUP_API_KEY,
100
+ signal: options.signal,
101
+ });
102
+ if (!apiKey) {
103
+ throw new Error(`Linkup API key not found. Set linkupApiKey in ${CONFIG_PATH} or LINKUP_API_KEY. Get a key at https://app.linkup.so`);
104
+ }
105
+ const numResults = normalizeSearchResultCount(options.numResults);
106
+ const fromDate = recencyToDate(options.recencyFilter);
107
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
108
+ const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
109
+ const activityId = activityMonitor.logStart({ type: "api", query });
110
+ let entries: LinkupResult[];
111
+ try {
112
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("linkup", LINKUP_SEARCH_URL, loadConfig().linkupBaseUrl), {
113
+ method: "POST",
114
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
115
+ body: JSON.stringify({
116
+ q: query, depth, outputType: "searchResults", maxResults: numResults,
117
+ ...(fromDate ? { fromDate } : {}),
118
+ ...(filters.include.length ? { includeDomains: filters.include } : {}),
119
+ ...(filters.exclude.length ? { excludeDomains: filters.exclude } : {}),
120
+ }),
121
+ signal,
122
+ }, ["Authorization"]);
123
+ if (!response.ok) {
124
+ const body = redactCredential(await response.text(), apiKey).slice(0, 300);
125
+ throw new Error(`Linkup error ${response.status}: ${body}`);
126
+ }
127
+ let data: unknown;
128
+ try {
129
+ data = await response.json();
130
+ } catch (err) {
131
+ // Preserve transport and cancellation errors for routing. Syntax errors
132
+ // can quote response content, so do not echo their messages.
133
+ if (!(err instanceof SyntaxError)) throw err;
134
+ throw new Error("Linkup returned invalid JSON");
135
+ }
136
+ entries = parseResponse(data);
137
+ activityMonitor.logComplete(activityId, response.status);
138
+ } catch (err) {
139
+ if (options.signal?.aborted) {
140
+ activityMonitor.logComplete(activityId, 0);
141
+ throw new Error("Aborted");
142
+ }
143
+ const message = timeout.aborted || (err instanceof Error && err.name === "TimeoutError")
144
+ ? "Linkup request timed out after 60s"
145
+ : redactCredential(err instanceof Error ? err.message : String(err), apiKey);
146
+ activityMonitor.logError(activityId, message);
147
+ const outgoing = err instanceof TypeError ? new TypeError(message) : new Error(message);
148
+ if (err instanceof Error && !timeout.aborted) outgoing.name = err.name;
149
+ throw outgoing;
150
+ }
151
+ const results: SearchResponse["results"] = [];
152
+ const inlineContent: ExtractedContent[] = [];
153
+ const seen = new Set<string>();
154
+ for (const entry of entries) {
155
+ if (!entry || typeof entry !== "object" || entry.type !== "text" || typeof entry.url !== "string") continue;
156
+ let url: URL;
157
+ try { url = new URL(entry.url); } catch { continue; }
158
+ if (url.protocol !== "http:" && url.protocol !== "https:") continue;
159
+ const matches = (domain: string) => url.hostname === domain || url.hostname.endsWith(`.${domain}`);
160
+ if (filters.exclude.some(matches) || (filters.include.length && !filters.include.some(matches))) continue;
161
+ if (seen.has(url.href)) continue;
162
+ seen.add(url.href);
163
+ const title = text(entry.name) || `Source ${results.length + 1}`;
164
+ const content = typeof entry.content === "string" ? entry.content.trim().slice(0, 4_000) : "";
165
+ results.push({ title, url: url.href, snippet: text(content).slice(0, 500) });
166
+ if (options.includeContent && content) inlineContent.push({ url: url.href, title, content, error: null });
167
+ if (results.length >= numResults) break;
168
+ }
169
+ return { answer: formatSearchResultsAsAnswer(results), results, ...(inlineContent.length ? { inlineContent } : {}) };
170
+ }
package/mcp-cli.ts ADDED
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ // pi-web-access-mcp: serves the web tools over MCP stdio. stdout carries only
3
+ // JSON-RPC, so every diagnostic goes to stderr.
4
+
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import pkg from "./package.json" with { type: "json" };
7
+ import { createMcpServer } from "./mcp-server.ts";
8
+ import { createStandaloneWebToolCore } from "./web-tool-core.ts";
9
+
10
+ // Keep stray console output from dependencies off the JSON-RPC stream.
11
+ console.log = console.info = console.debug = console.error;
12
+
13
+ const core = createStandaloneWebToolCore();
14
+ const server = createMcpServer(core, { name: "pi-web-access", version: pkg.version }, core.enabledToolNames);
15
+ const transport = new StdioServerTransport();
16
+
17
+ let closing = false;
18
+ async function shutdown(code: number): Promise<void> {
19
+ if (closing) return;
20
+ closing = true;
21
+ try {
22
+ // Closing aborts in-flight tool calls through their request signals.
23
+ await server.close();
24
+ } catch (error) {
25
+ console.error("pi-web-access-mcp: error during shutdown:", error);
26
+ }
27
+ process.exit(code);
28
+ }
29
+
30
+ process.stdin.once("end", () => void shutdown(0));
31
+ process.stdin.once("close", () => void shutdown(0));
32
+ process.once("SIGINT", () => void shutdown(0));
33
+ process.once("SIGTERM", () => void shutdown(0));
34
+
35
+ try {
36
+ await server.connect(transport);
37
+ } catch (error) {
38
+ console.error("pi-web-access-mcp: failed to start:", error);
39
+ process.exit(1);
40
+ }