@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/tinyfish.ts ADDED
@@ -0,0 +1,373 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
4
+ import type { ExtractedContent, ExtractOptions } 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 { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
9
+ import { getWebSearchConfigPath } from "./utils.ts";
10
+
11
+ const TINYFISH_SEARCH_URL = "https://api.search.tinyfish.ai";
12
+ const TINYFISH_FETCH_URL = "https://api.fetch.tinyfish.ai";
13
+ const CONFIG_PATH = getWebSearchConfigPath();
14
+ const SEARCH_TIMEOUT_MS = 60_000;
15
+ const FETCH_TIMEOUT_MS = 150_000;
16
+ const MAX_FETCH_URLS = 10;
17
+ const MAX_FETCH_PER_URL_TIMEOUT_MS = 110_000;
18
+
19
+ interface WebSearchConfig {
20
+ tinyfishApiKey?: unknown;
21
+ }
22
+
23
+ interface TinyFishSearchResult {
24
+ position?: number;
25
+ site_name?: string | null;
26
+ title?: string | null;
27
+ snippet?: string | null;
28
+ url?: string | null;
29
+ date?: string | null;
30
+ publisher?: string | null;
31
+ }
32
+
33
+ interface TinyFishSearchResponse {
34
+ query?: string;
35
+ results?: TinyFishSearchResult[];
36
+ total_results?: number;
37
+ page?: number;
38
+ }
39
+
40
+ interface TinyFishFetchResult {
41
+ url?: string;
42
+ final_url?: string;
43
+ title?: string | null;
44
+ text?: string | Record<string, unknown> | null;
45
+ format?: string;
46
+ }
47
+
48
+ interface TinyFishFetchError {
49
+ url?: string;
50
+ error?: string;
51
+ status?: number;
52
+ }
53
+
54
+ interface TinyFishFetchResponse {
55
+ results?: TinyFishFetchResult[];
56
+ errors?: TinyFishFetchError[];
57
+ }
58
+
59
+ interface TinyFishSearchOptions extends SearchOptions {
60
+ includeContent?: boolean;
61
+ }
62
+
63
+ let cachedConfig: WebSearchConfig | null = null;
64
+
65
+ function loadConfig(): WebSearchConfig {
66
+ if (cachedConfig) return cachedConfig;
67
+ if (!existsSync(CONFIG_PATH)) {
68
+ cachedConfig = {};
69
+ return cachedConfig;
70
+ }
71
+
72
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
73
+ try {
74
+ cachedConfig = JSON.parse(raw) as WebSearchConfig;
75
+ return cachedConfig;
76
+ } catch (err) {
77
+ const message = err instanceof Error ? err.message : String(err);
78
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
79
+ }
80
+ }
81
+
82
+ export function clearTinyFishConfigCache(): void {
83
+ cachedConfig = null;
84
+ }
85
+
86
+ async function getApiKey(signal?: AbortSignal): Promise<string> {
87
+ const key = await resolveCredential({
88
+ provider: "TinyFish",
89
+ configuredValue: loadConfig().tinyfishApiKey,
90
+ environmentValue: process.env.TINYFISH_API_KEY,
91
+ signal,
92
+ });
93
+ if (!key) {
94
+ throw new Error(
95
+ "TinyFish API key not found. Either:\n" +
96
+ ` 1. Create ${CONFIG_PATH} with { "tinyfishApiKey": "your-key" }\n` +
97
+ " 2. Set TINYFISH_API_KEY environment variable\n" +
98
+ "Get a key at https://agent.tinyfish.ai/api-keys",
99
+ );
100
+ }
101
+ return key;
102
+ }
103
+
104
+ export function isTinyFishAvailable(): boolean {
105
+ return hasCredentialSource({
106
+ provider: "TinyFish",
107
+ configuredValue: loadConfig().tinyfishApiKey,
108
+ environmentValue: process.env.TINYFISH_API_KEY,
109
+ });
110
+ }
111
+
112
+ function errorMessage(err: unknown): string {
113
+ return err instanceof Error ? err.message : String(err);
114
+ }
115
+
116
+ function requestSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
117
+ const timeout = AbortSignal.timeout(timeoutMs);
118
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
119
+ }
120
+
121
+ function mapDomainFilter(domainFilter: string[] | undefined): { includeDomains: string[]; excludeDomains: string[] } {
122
+ const includeDomains: string[] = [];
123
+ const excludeDomains: string[] = [];
124
+ for (const raw of domainFilter ?? []) {
125
+ const domain = normalizeDomain(raw);
126
+ if (!domain) continue;
127
+ const target = raw.trim().startsWith("-") ? excludeDomains : includeDomains;
128
+ if (!target.includes(domain)) target.push(domain);
129
+ }
130
+ return { includeDomains, excludeDomains };
131
+ }
132
+
133
+ function recencyMinutes(filter: SearchOptions["recencyFilter"]): number | undefined {
134
+ if (!filter) return undefined;
135
+ const minutes: Record<NonNullable<SearchOptions["recencyFilter"]>, number> = {
136
+ day: 1_440,
137
+ week: 10_080,
138
+ month: 43_200,
139
+ year: 525_600,
140
+ };
141
+ return minutes[filter];
142
+ }
143
+
144
+ function buildSearchUrl(query: string, options: SearchOptions, page: number): string {
145
+ const params = new URLSearchParams({ query });
146
+ const { includeDomains, excludeDomains } = mapDomainFilter(options.domainFilter);
147
+ if (includeDomains.length > 0) params.set("include_domains", includeDomains.join(","));
148
+ if (excludeDomains.length > 0) params.set("exclude_domains", excludeDomains.join(","));
149
+ const recency = recencyMinutes(options.recencyFilter);
150
+ if (recency !== undefined) params.set("recency_minutes", String(recency));
151
+ if (page > 0) params.set("page", String(page));
152
+ return `${TINYFISH_SEARCH_URL}?${params.toString()}`;
153
+ }
154
+
155
+ async function tinyFishJsonRequest<T>(
156
+ label: "Search" | "Fetch",
157
+ url: string,
158
+ apiKey: string,
159
+ init: RequestInit,
160
+ timeoutMs: number,
161
+ signal?: AbortSignal,
162
+ ): Promise<T> {
163
+ let response: Response;
164
+ try {
165
+ response = await fetch(url, {
166
+ ...init,
167
+ headers: {
168
+ "X-API-Key": apiKey,
169
+ ...(init.body ? { "Content-Type": "application/json" } : {}),
170
+ ...init.headers,
171
+ },
172
+ signal: requestSignal(signal, timeoutMs),
173
+ });
174
+ } catch (err) {
175
+ const message = errorMessage(err);
176
+ const redactedMessage = redactCredential(message, apiKey);
177
+ if (redactedMessage === message) throw err;
178
+ const redactedError = new Error(redactedMessage);
179
+ if (err instanceof Error) redactedError.name = err.name;
180
+ throw redactedError;
181
+ }
182
+
183
+ const raw = await response.text();
184
+ if (!response.ok) {
185
+ throw new Error(`TinyFish ${label} API error ${response.status}: ${redactCredential(raw, apiKey).slice(0, 300)}`);
186
+ }
187
+ try {
188
+ return JSON.parse(raw) as T;
189
+ } catch (err) {
190
+ throw new Error(`TinyFish ${label} API returned invalid JSON: ${errorMessage(err)}`);
191
+ }
192
+ }
193
+
194
+ function mapSearchResults(results: TinyFishSearchResult[] | undefined): SearchResponse["results"] {
195
+ if (!Array.isArray(results)) return [];
196
+ return results.flatMap((item) => {
197
+ if (!item || typeof item.url !== "string" || item.url.trim().length === 0) return [];
198
+ const url = item.url.trim();
199
+ return [{
200
+ title: typeof item.title === "string" && item.title.trim() ? item.title.trim() : url,
201
+ url,
202
+ snippet: typeof item.snippet === "string" ? item.snippet.replace(/\s+/g, " ").trim() : "",
203
+ }];
204
+ });
205
+ }
206
+
207
+ function deduplicateResults(results: SearchResponse["results"], limit: number): SearchResponse["results"] {
208
+ const seen = new Set<string>();
209
+ const unique: SearchResponse["results"] = [];
210
+ for (const result of results) {
211
+ if (seen.has(result.url)) continue;
212
+ seen.add(result.url);
213
+ unique.push(result);
214
+ if (unique.length >= limit) break;
215
+ }
216
+ return unique;
217
+ }
218
+
219
+ function fetchPerUrlTimeout(value: number | undefined): number {
220
+ if (typeof value !== "number" || !Number.isFinite(value)) return MAX_FETCH_PER_URL_TIMEOUT_MS;
221
+ return Math.max(1, Math.min(Math.floor(value), MAX_FETCH_PER_URL_TIMEOUT_MS));
222
+ }
223
+
224
+ function fetchBody(urls: string[], options: ExtractOptions = {}): Record<string, unknown> {
225
+ const body: Record<string, unknown> = {
226
+ urls,
227
+ format: "markdown",
228
+ per_url_timeout_ms: fetchPerUrlTimeout(options.timeoutMs),
229
+ };
230
+ const purpose = options.prompt?.trim();
231
+ if (purpose) body.purpose = purpose.slice(0, 2_000);
232
+ return body;
233
+ }
234
+
235
+ function findFetchError(errors: TinyFishFetchError[] | undefined, url: string): TinyFishFetchError | undefined {
236
+ if (!Array.isArray(errors)) return undefined;
237
+ return errors.find(item => item?.url === url) ?? errors[0];
238
+ }
239
+
240
+ function fetchResultContent(result: TinyFishFetchResult): string {
241
+ if (typeof result.text === "string") return result.text.trim();
242
+ if (result.text && typeof result.text === "object") return JSON.stringify(result.text, null, 2);
243
+ return "";
244
+ }
245
+
246
+ function mapFetchResult(result: TinyFishFetchResult | undefined, requestedUrl: string): ExtractedContent | null {
247
+ if (!result) return null;
248
+ const content = fetchResultContent(result);
249
+ if (!content) return null;
250
+ return {
251
+ url: requestedUrl,
252
+ title: typeof result.title === "string" ? result.title.trim() : "",
253
+ content,
254
+ error: null,
255
+ };
256
+ }
257
+
258
+ async function fetchBatch(
259
+ urls: string[],
260
+ apiKey: string,
261
+ signal?: AbortSignal,
262
+ options: ExtractOptions = {},
263
+ ): Promise<TinyFishFetchResponse> {
264
+ return tinyFishJsonRequest<TinyFishFetchResponse>(
265
+ "Fetch",
266
+ TINYFISH_FETCH_URL,
267
+ apiKey,
268
+ { method: "POST", body: JSON.stringify(fetchBody(urls, options)) },
269
+ FETCH_TIMEOUT_MS,
270
+ signal,
271
+ );
272
+ }
273
+
274
+ async function fetchInlineContent(
275
+ urls: string[],
276
+ apiKey: string,
277
+ signal?: AbortSignal,
278
+ ): Promise<ExtractedContent[]> {
279
+ const content: ExtractedContent[] = [];
280
+ for (let offset = 0; offset < urls.length; offset += MAX_FETCH_URLS) {
281
+ const batch = urls.slice(offset, offset + MAX_FETCH_URLS);
282
+ const data = await fetchBatch(batch, apiKey, signal);
283
+ if (!Array.isArray(data.results) || !Array.isArray(data.errors)) {
284
+ throw new Error("TinyFish Fetch API returned an unexpected response shape");
285
+ }
286
+ for (const url of batch) {
287
+ const result = Array.isArray(data.results)
288
+ ? data.results.find(item => item?.url === url || item?.final_url === url)
289
+ : undefined;
290
+ const mapped = mapFetchResult(result, url);
291
+ if (mapped) content.push(mapped);
292
+ }
293
+ }
294
+ return content;
295
+ }
296
+
297
+ export async function searchWithTinyFish(query: string, options: TinyFishSearchOptions = {}): Promise<SearchResponse> {
298
+ const apiKey = await getApiKey(options.signal);
299
+ const numResults = normalizeSearchResultCount(options.numResults);
300
+ const activityId = activityMonitor.logStart({ type: "api", query });
301
+ try {
302
+ const combined: SearchResponse["results"] = [];
303
+ const pages = numResults > 10 ? 2 : 1;
304
+ for (let page = 0; page < pages; page++) {
305
+ const data = await tinyFishJsonRequest<TinyFishSearchResponse>(
306
+ "Search",
307
+ buildSearchUrl(query, options, page),
308
+ apiKey,
309
+ { method: "GET" },
310
+ SEARCH_TIMEOUT_MS,
311
+ options.signal,
312
+ );
313
+ if (!Array.isArray(data.results)) throw new Error("TinyFish Search API returned an unexpected response shape");
314
+ combined.push(...mapSearchResults(data.results));
315
+ if (data.results.length < 10) break;
316
+ }
317
+
318
+ const results = deduplicateResults(combined, numResults);
319
+ const response: SearchResponse = { answer: formatSearchResultsAsAnswer(results), results };
320
+ if (options.includeContent && results.length > 0) {
321
+ const inlineContent = await fetchInlineContent(results.map(result => result.url), apiKey, options.signal);
322
+ if (inlineContent.length > 0) response.inlineContent = inlineContent;
323
+ }
324
+ activityMonitor.logComplete(activityId, 200);
325
+ return response;
326
+ } catch (err) {
327
+ const message = errorMessage(err);
328
+ const redactedMessage = redactCredential(message, apiKey);
329
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
330
+ else activityMonitor.logError(activityId, redactedMessage);
331
+ if (redactedMessage === message) throw err;
332
+ const redactedError = new Error(redactedMessage);
333
+ if (err instanceof Error) redactedError.name = err.name;
334
+ throw redactedError;
335
+ }
336
+ }
337
+
338
+ export async function extractWithTinyFish(
339
+ url: string,
340
+ signal?: AbortSignal,
341
+ options: ExtractOptions = {},
342
+ ): Promise<ExtractedContent | null> {
343
+ const apiKey = await getApiKey(signal);
344
+ const activityId = activityMonitor.logStart({ type: "fetch", url });
345
+ try {
346
+ const data = await fetchBatch([url], apiKey, signal, options);
347
+ if (!Array.isArray(data.results) || !Array.isArray(data.errors)) {
348
+ throw new Error("TinyFish Fetch API returned an unexpected response shape");
349
+ }
350
+ const result = data.results.find(item => item?.url === url || item?.final_url === url) ?? data.results[0];
351
+ const mapped = mapFetchResult(result, url);
352
+ if (mapped) {
353
+ activityMonitor.logComplete(activityId, 200);
354
+ return mapped;
355
+ }
356
+ const fetchError = findFetchError(data.errors, url);
357
+ if (fetchError) {
358
+ const status = typeof fetchError.status === "number" ? ` (HTTP ${fetchError.status})` : "";
359
+ throw new Error(`TinyFish Fetch failed for ${url}: ${fetchError.error || "unknown error"}${status}`);
360
+ }
361
+ activityMonitor.logComplete(activityId, 200);
362
+ return null;
363
+ } catch (err) {
364
+ const message = errorMessage(err);
365
+ const redactedMessage = redactCredential(message, apiKey);
366
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
367
+ else activityMonitor.logError(activityId, redactedMessage);
368
+ if (redactedMessage === message) throw err;
369
+ const redactedError = new Error(redactedMessage);
370
+ if (err instanceof Error) redactedError.name = err.name;
371
+ throw redactedError;
372
+ }
373
+ }
@@ -0,0 +1,169 @@
1
+ import { buildSessionContext, type ExtensionAPI, type ExtensionContext, type SessionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+
4
+ export type WebCapability = "search" | "source-check" | "fetch" | "stored-content";
5
+
6
+ export interface WebActivationTool {
7
+ name: string;
8
+ capability: WebCapability;
9
+ }
10
+
11
+ const LOADER_NAME = "web_enable";
12
+ const CAPABILITY_LABELS: Record<WebCapability, string> = {
13
+ search: "web search",
14
+ "source-check": "source checking",
15
+ fetch: "content fetching",
16
+ "stored-content": "stored-result retrieval",
17
+ };
18
+
19
+ function supportsDynamicTools(pi: ExtensionAPI): boolean {
20
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return false;
21
+ // Pi 0.86.0 shipped transcript-backed tool changes in the same release that made pi.on() return
22
+ // an unsubscribe function. Probe the host API object: an imported VERSION can come from a stale
23
+ // Pi package installed beside this extension instead of the running host.
24
+ const unsubscribe: unknown = pi.on("session_start", () => {});
25
+ if (typeof unsubscribe !== "function") return false;
26
+ unsubscribe();
27
+ return true;
28
+ }
29
+
30
+ // Mirrors pi-ai's per-API transcript handling: without these flags, Pi resends the whole transcript
31
+ // as a checkpoint when web_enable changes the tools and prompt, which can miss the prompt cache.
32
+ function addsToolsWithoutCheckpoint(model: ExtensionContext["model"]): boolean {
33
+ const compat = model?.compat as {
34
+ supportsMidConvoSystemMessages?: boolean;
35
+ supportsMidConvoToolChanges?: boolean;
36
+ supportsMidConvoToolAdditions?: boolean;
37
+ supportsAdditionalTools?: boolean;
38
+ supportsToolSearch?: boolean;
39
+ } | undefined;
40
+ if (!model || compat?.supportsMidConvoSystemMessages !== true) return false;
41
+ switch (model.api) {
42
+ case "anthropic-messages": return compat.supportsMidConvoToolChanges === true;
43
+ case "openai-completions": return compat.supportsMidConvoToolAdditions === true;
44
+ case "openai-responses":
45
+ case "openai-codex-responses":
46
+ case "azure-openai-responses": return compat.supportsAdditionalTools === true || compat.supportsToolSearch === true;
47
+ default: return false;
48
+ }
49
+ }
50
+
51
+ // Undefined when the transcript never declared tool changes.
52
+ function transcriptToolNames(messages: SessionContext["messages"]): Set<string> | undefined {
53
+ let tools: Set<string> | undefined;
54
+ for (const message of messages) {
55
+ if (message.role !== "system" || !("toolsAdded" in message || "toolsRemoved" in message)) continue;
56
+ tools ??= new Set();
57
+ for (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);
58
+ for (const tool of message.toolsAdded ?? []) tools.add(tool.name);
59
+ }
60
+ return tools;
61
+ }
62
+
63
+ export function registerWebToolActivation(pi: ExtensionAPI, tools: ReadonlyArray<WebActivationTool>, mode: "auto" | "dynamic"): void {
64
+ if (tools.length === 0) return;
65
+ if (!supportsDynamicTools(pi)) {
66
+ console.warn("[pi-web-access] Dynamic tool activation requires Pi 0.86.0 or newer; web tools remain eagerly available.");
67
+ return;
68
+ }
69
+ const names = tools.map(tool => tool.name);
70
+ const capabilities = tools.map(tool => CAPABILITY_LABELS[tool.capability]).join(", ");
71
+
72
+ const parameters = Type.Object({}, { additionalProperties: false });
73
+ pi.registerTool<typeof parameters, Record<string, unknown>>({
74
+ name: LOADER_NAME,
75
+ label: "Enable Web Access",
76
+ description: "Enable configured pi-web-access tools for web research and content retrieval. Does not search or fetch. Enabled tools are available on the next model request; disabled capabilities remain unavailable.",
77
+ promptSnippet: `If tools for ${capabilities} are not already available, call web_enable first whenever current, external, or linked information could help; the tools appear on the next model request.`,
78
+ parameters,
79
+ async execute() {
80
+ const registered = new Set(pi.getAllTools().map(tool => tool.name));
81
+ const unavailable = names.filter(name => !registered.has(name));
82
+ if (unavailable.length > 0) {
83
+ return {
84
+ isError: true,
85
+ content: [{ type: "text" as const, text: `Cannot enable unavailable tools: ${unavailable.join(", ")}.` }],
86
+ details: { unavailable },
87
+ };
88
+ }
89
+
90
+ try {
91
+ pi.setActiveTools([...new Set([...pi.getActiveTools(), ...names])]);
92
+ } catch (error) {
93
+ const message = error instanceof Error ? error.message : String(error);
94
+ return {
95
+ isError: true,
96
+ content: [{ type: "text" as const, text: `Activation failed: ${message}.` }],
97
+ details: { error: message },
98
+ };
99
+ }
100
+
101
+ const active = new Set(pi.getActiveTools());
102
+ const missing = names.filter(name => !active.has(name));
103
+ return missing.length > 0
104
+ ? {
105
+ isError: true,
106
+ content: [{ type: "text" as const, text: `Tools still inactive after activation: ${missing.join(", ")}.` }],
107
+ details: { missing },
108
+ }
109
+ : {
110
+ content: [{ type: "text" as const, text: `Enabled: ${names.join(", ")}.` }],
111
+ details: { enabled: names },
112
+ };
113
+ },
114
+ });
115
+
116
+ function loaderAvailable(): boolean {
117
+ return pi.getAllTools().some(tool => tool.name === LOADER_NAME);
118
+ }
119
+
120
+ let warned = false;
121
+ // A resumed transcript that declared its tools without the loader keeps that set; adding the
122
+ // loader there would record a mid-conversation tool change the user never asked for (#462).
123
+ let loaderSelected = true;
124
+ function selectFromSession(ctx: ExtensionContext): boolean {
125
+ if (!loaderAvailable()) return false;
126
+ try {
127
+ const messages = buildSessionContext(ctx.sessionManager.getBranch()).messages;
128
+ const declared = transcriptToolNames(messages);
129
+ // "auto" decides only for a session with no messages; recorded sessions keep their tools.
130
+ const eager = mode === "auto" && !declared && messages.length === 0 && !addsToolsWithoutCheckpoint(ctx.model);
131
+ // Sessions from before transcript tool declarations keep every web tool; fresh ones start with none.
132
+ const recorded = declared ?? new Set(messages.length > 0 || eager ? names : []);
133
+ loaderSelected = !eager && (!declared || declared.has(LOADER_NAME));
134
+ const others = pi.getActiveTools().filter(name => name !== LOADER_NAME && !names.includes(name));
135
+ pi.setActiveTools([...new Set([...others, ...names.filter(name => recorded.has(name)), ...(loaderSelected ? [LOADER_NAME] : [])])]);
136
+ return true;
137
+ } catch (error) {
138
+ if (!warned) {
139
+ warned = true;
140
+ console.warn(`[pi-web-access] Web tool activation setup failed; keeping the current tool selection: ${error instanceof Error ? error.message : String(error)}`);
141
+ }
142
+ return false;
143
+ }
144
+ }
145
+
146
+ // Pi declares the first tools with the first request, so until agent_start a model switch decides again,
147
+ // unless the web tools were changed since the last decision.
148
+ let undeclared: string | undefined;
149
+ const activationState = () => [LOADER_NAME, ...names].map(name => pi.getActiveTools().includes(name)).join();
150
+ function decide(ctx: ExtensionContext): void {
151
+ undeclared = selectFromSession(ctx) ? activationState() : undefined;
152
+ }
153
+ pi.on("session_start", (_event, ctx) => decide(ctx));
154
+ pi.on("session_tree", (_event, ctx) => decide(ctx));
155
+ pi.on("agent_start", () => { undeclared = undefined; });
156
+ pi.on("model_select", (_event, ctx) => {
157
+ if (mode === "auto" && ctx.isIdle() && undeclared !== undefined && undeclared === activationState()
158
+ && loaderSelected !== addsToolsWithoutCheckpoint(ctx.model)
159
+ && buildSessionContext(ctx.sessionManager.getBranch()).messages.length === 0) decide(ctx);
160
+ });
161
+ pi.on("before_agent_start", () => {
162
+ if (!loaderSelected || !loaderAvailable() || pi.getActiveTools().includes(LOADER_NAME)) return;
163
+ try {
164
+ pi.setActiveTools([...pi.getActiveTools(), LOADER_NAME]);
165
+ } catch {
166
+ // Best effort: preserve the current selection if Pi rejects the update.
167
+ }
168
+ });
169
+ }
@@ -0,0 +1,23 @@
1
+ // Some models send array arguments as a JSON string, for example
2
+ // `queries: "[\"a\", \"b\"]"`, which fails schema validation before the tool
3
+ // runs. Parse such strings back into arrays of strings, reject strings that start
4
+ // with "[" but are not valid JSON, and leave anything else as is.
5
+ export function parseStringifiedArrays(args: unknown, keys: readonly string[]): unknown {
6
+ if (!args || typeof args !== "object" || Array.isArray(args)) return args;
7
+ const input = args as Record<string, unknown>;
8
+ let output: Record<string, unknown> | undefined;
9
+ for (const key of keys) {
10
+ const value = input[key];
11
+ if (typeof value !== "string" || !value.trim().startsWith("[")) continue;
12
+ try {
13
+ const parsed: unknown = JSON.parse(value);
14
+ if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
15
+ output ??= { ...input };
16
+ output[key] = parsed;
17
+ }
18
+ } catch {
19
+ throw new Error(`${key} must be an array of strings; the given value is not valid JSON`);
20
+ }
21
+ }
22
+ return output ?? args;
23
+ }
@@ -0,0 +1,47 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import packageJson from "./package.json" with { type: "json" };
7
+
8
+ // major.minor.patch as one comparable number; undefined for anything else.
9
+ const versionNumber = (version: unknown) => typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version)
10
+ ? version.split(".").reduce((total, part) => total * 1e6 + Number(part), 0)
11
+ : undefined;
12
+
13
+ export async function showUpgradeNotice(
14
+ ctx: { hasUI: boolean; ui: { notify(message: string, type: "info"): void } },
15
+ stateDir = join(getAgentDir(), "pi-web-access"),
16
+ // npm installs run the bundle in dist/, a checkout runs this file from the package root.
17
+ changelogPath = fileURLToPath(new URL(/\/dist\/[^/]+$/.test(import.meta.url) ? "../CHANGELOG.md" : "./CHANGELOG.md", import.meta.url)),
18
+ version = packageJson.version,
19
+ ): Promise<void> {
20
+ if (!ctx.hasUI) return;
21
+ const statePath = join(stateDir, "last-seen-version.json");
22
+ const lastSeen = await readFile(statePath, "utf-8").then((raw) => JSON.parse(raw).version).catch(() => undefined);
23
+ const previous = versionNumber(lastSeen);
24
+ const current = versionNumber(version);
25
+ if (current === undefined || previous === current) return;
26
+ try {
27
+ mkdirSync(stateDir, { recursive: true });
28
+ writeFileSync(statePath, JSON.stringify({ version }));
29
+ } catch {
30
+ // Read-only installs cannot record the seen version. Without it the notice would repeat on every start, so skip it.
31
+ return;
32
+ }
33
+ if (previous === undefined || previous > current) return;
34
+
35
+ const bullets = (await readFile(changelogPath, "utf-8")).split(/^## /m).flatMap((section) => {
36
+ const released = versionNumber(/^\[([^\]]+)\]/.exec(section)?.[1]);
37
+ if (released === undefined || released <= previous || released > current) return [];
38
+ const highlights = section.split(/^### /m).find((part) => part.startsWith("Highlights")) ?? "";
39
+ return (highlights.match(/^- .*/gm) ?? []).map((bullet) => bullet.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim());
40
+ });
41
+ ctx.ui.notify([
42
+ `pi-web-access updated from ${lastSeen} to ${version}`,
43
+ ...bullets.slice(0, 5),
44
+ ...(bullets.length > 5 ? [`...and ${bullets.length - 5} more`] : []),
45
+ "Changelog: https://github.com/nicobailon/pi-web-access/blob/main/CHANGELOG.md",
46
+ ].join("\n"), "info");
47
+ }