@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/utils.ts ADDED
@@ -0,0 +1,693 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { isIP } from "node:net";
6
+ import { homedir, hostname, tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ let cachedWebSearchConfigDir: string | undefined;
10
+
11
+ export function getWebSearchConfigDir(): string {
12
+ if (cachedWebSearchConfigDir) return cachedWebSearchConfigDir;
13
+
14
+ const explicitDir = process.env.PI_CODING_AGENT_DIR;
15
+ if (explicitDir) return cachedWebSearchConfigDir = explicitDir;
16
+
17
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME;
18
+ if (xdgConfigHome) {
19
+ const xdgDir = join(xdgConfigHome, "pi");
20
+ if (existsSync(join(xdgDir, "web-search.json"))) return cachedWebSearchConfigDir = xdgDir;
21
+
22
+ const legacyDir = join(homedir(), ".pi");
23
+ if (existsSync(join(legacyDir, "web-search.json"))) return cachedWebSearchConfigDir = legacyDir;
24
+ return cachedWebSearchConfigDir = xdgDir;
25
+ }
26
+ const agentDir = join(homedir(), ".pi", "agent");
27
+ if (existsSync(join(agentDir, "web-search.json"))) return cachedWebSearchConfigDir = agentDir;
28
+
29
+ const legacyDir = join(homedir(), ".pi");
30
+ if (existsSync(join(legacyDir, "web-search.json"))) return cachedWebSearchConfigDir = legacyDir;
31
+
32
+ return cachedWebSearchConfigDir = agentDir;
33
+ }
34
+
35
+ export function getWebSearchConfigPath(): string {
36
+ return join(getWebSearchConfigDir(), "web-search.json");
37
+ }
38
+
39
+ interface ApiBaseUrlOptions {
40
+ configKey: string;
41
+ configuredValue: unknown;
42
+ defaultValue: string;
43
+ environmentKey: string;
44
+ environmentValue: string | undefined;
45
+ }
46
+
47
+ export function isLoopbackHostname(hostnameValue: string): boolean {
48
+ const normalized = hostnameValue.replace(/^\[|\]$/g, "").replace(/\.$/, "").toLowerCase();
49
+ return normalized === "localhost"
50
+ || normalized === "::1"
51
+ || (isIP(normalized) === 4 && normalized.split(".", 1)[0] === "127");
52
+ }
53
+
54
+ export function isRecord(value: unknown): value is Record<string, unknown> {
55
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56
+ }
57
+
58
+ function allowsHttpBaseUrls(): boolean {
59
+ const environmentValue = process.env.PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS;
60
+ if (environmentValue !== undefined) {
61
+ const value = environmentValue.trim().toLowerCase();
62
+ if (value === "true" || value === "1") return true;
63
+ if (value === "false" || value === "0") return false;
64
+ throw new Error("Invalid configuration: PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS must be true, false, 1, or 0");
65
+ }
66
+ const path = getWebSearchConfigPath();
67
+ if (!existsSync(path)) return false;
68
+ let raw: unknown;
69
+ try {
70
+ raw = JSON.parse(readFileSync(path, "utf-8"));
71
+ } catch (err) {
72
+ throw new Error(`Failed to parse ${path}: ${err instanceof Error ? err.message : String(err)}`);
73
+ }
74
+ const value = isRecord(raw) ? raw.allowHttpBaseUrls : undefined;
75
+ if (value !== undefined && typeof value !== "boolean") throw new Error(`allowHttpBaseUrls in ${path} must be a boolean`);
76
+ return value === true;
77
+ }
78
+
79
+ export function resolveApiBaseUrl(options: ApiBaseUrlOptions): string {
80
+ const fromEnvironment = options.environmentValue !== undefined;
81
+ const value = fromEnvironment ? options.environmentValue : options.configuredValue;
82
+ if (value === undefined) return options.defaultValue;
83
+
84
+ const source = fromEnvironment
85
+ ? options.environmentKey
86
+ : `${options.configKey} in ${getWebSearchConfigPath()}`;
87
+ if (typeof value !== "string" || value.trim().length === 0) {
88
+ throw new Error(`${source} must be an absolute HTTP(S) URL`);
89
+ }
90
+
91
+ let url: URL;
92
+ try {
93
+ url = new URL(value.trim());
94
+ } catch {
95
+ throw new Error(`${source} must be an absolute HTTP(S) URL`);
96
+ }
97
+ if (url.protocol !== "https:" && (url.protocol !== "http:" || (!isLoopbackHostname(url.hostname) && !allowsHttpBaseUrls()))) {
98
+ throw new Error(`${source} must be an absolute HTTPS URL`);
99
+ }
100
+ if (url.username || url.password) {
101
+ throw new Error(`${source} must not include credentials`);
102
+ }
103
+ if (url.search || url.hash) {
104
+ throw new Error(`${source} must not include query parameters or fragments`);
105
+ }
106
+
107
+ url.search = "";
108
+ url.hash = "";
109
+ url.pathname = url.pathname.replace(/\/+$/, "");
110
+ return url.toString().replace(/\/+$/, "");
111
+ }
112
+
113
+ // Other tools commonly set the bare OLLAMA_BASE_URL (a local Ollama server) and DEEPSEEK_BASE_URL
114
+ // (an OpenAI-compatible root ending in /v1), and the Tabstack SDKs read TABSTACK_BASE_URL as a /v1 root,
115
+ // so these providers read PI_-prefixed names instead.
116
+ const PI_PREFIXED_ENVIRONMENT_STEMS = new Set(["ollama", "deepseek", "tabstack"]);
117
+
118
+ /** Resolve a provider's API root without dropping its endpoint path or a gateway prefix. */
119
+ export function resolveProviderApiUrl(configStem: string, defaultUrl: string, configuredValue: unknown): string {
120
+ const official = new URL(defaultUrl);
121
+ const environmentKey = (PI_PREFIXED_ENVIRONMENT_STEMS.has(configStem) ? "PI_" : "")
122
+ + configStem.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase() + "_BASE_URL";
123
+ const baseUrl = resolveApiBaseUrl({
124
+ configKey: configStem + "BaseUrl",
125
+ configuredValue,
126
+ defaultValue: official.origin,
127
+ environmentKey,
128
+ environmentValue: process.env[environmentKey],
129
+ });
130
+ return baseUrl + official.pathname + official.search;
131
+ }
132
+
133
+ const API_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
134
+ const API_REQUEST_BODY_HEADERS = ["Content-Encoding", "Content-Language", "Content-Location", "Content-Type"];
135
+ const MAX_API_REDIRECTS = 5;
136
+
137
+ export async function fetchWithCredentialRedirects(
138
+ url: string,
139
+ init: RequestInit,
140
+ credentialHeaders: readonly string[],
141
+ credentialQueryParams: readonly string[] = [],
142
+ ): Promise<Response> {
143
+ let current = new URL(url);
144
+ const source = new URL(url);
145
+ for (const name of credentialQueryParams) source.searchParams.delete(name);
146
+ let requestInit = init;
147
+
148
+ for (let redirects = 0; ; redirects++) {
149
+ const response = await fetch(current, { ...requestInit, redirect: "manual" });
150
+ if (!API_REDIRECT_STATUSES.has(response.status)) return response;
151
+
152
+ const location = response.headers.get("location");
153
+ if (!location) return response;
154
+ if (redirects === MAX_API_REDIRECTS) {
155
+ throw new Error(`Too many API redirects from ${source}`);
156
+ }
157
+
158
+ const next = new URL(location, current);
159
+ if (next.protocol !== "http:" && next.protocol !== "https:") {
160
+ throw new Error(`API redirect from ${current.origin} must use HTTP(S)`);
161
+ }
162
+ const method = requestInit.method?.toUpperCase() ?? "GET";
163
+ if (
164
+ ((response.status === 301 || response.status === 302) && method === "POST")
165
+ || (response.status === 303 && method !== "GET" && method !== "HEAD")
166
+ ) {
167
+ const headers = new Headers(requestInit.headers);
168
+ for (const name of API_REQUEST_BODY_HEADERS) headers.delete(name);
169
+ const { body: _body, ...withoutBody } = requestInit;
170
+ requestInit = { ...withoutBody, method: "GET", headers };
171
+ }
172
+ if (next.origin !== current.origin) {
173
+ for (const name of credentialQueryParams) next.searchParams.delete(name);
174
+ const headers = new Headers(requestInit.headers);
175
+ for (const name of credentialHeaders) headers.delete(name);
176
+ requestInit = { ...requestInit, headers };
177
+ }
178
+ current = next;
179
+ }
180
+ }
181
+
182
+ export interface CuratorNetworkConfig {
183
+ /** Whether remote access was opted into via curatorRemote. */
184
+ enabled: boolean;
185
+ host: string;
186
+ bind: string;
187
+ }
188
+
189
+ const LOCAL_CURATOR_NETWORK_DEFAULTS: CuratorNetworkConfig = { enabled: false, host: "localhost", bind: "127.0.0.1" };
190
+
191
+ function trimmedString(value: unknown): string | undefined {
192
+ if (typeof value !== "string") return undefined;
193
+ const trimmed = value.trim();
194
+ return trimmed.length > 0 ? trimmed : undefined;
195
+ }
196
+
197
+ /** Resolves the curator server bind address and URL host from `curatorRemote`. */
198
+ export function resolveCuratorNetworkConfig(): CuratorNetworkConfig {
199
+ const configPath = getWebSearchConfigPath();
200
+ if (!existsSync(configPath)) return LOCAL_CURATOR_NETWORK_DEFAULTS;
201
+
202
+ let raw: unknown;
203
+ try {
204
+ raw = JSON.parse(readFileSync(configPath, "utf-8"));
205
+ } catch {
206
+ return LOCAL_CURATOR_NETWORK_DEFAULTS;
207
+ }
208
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return LOCAL_CURATOR_NETWORK_DEFAULTS;
209
+
210
+ const curatorRemote = (raw as Record<string, unknown>).curatorRemote;
211
+ if (curatorRemote === true) return { enabled: true, host: hostname(), bind: "0.0.0.0" };
212
+
213
+ if (curatorRemote && typeof curatorRemote === "object" && !Array.isArray(curatorRemote)) {
214
+ const obj = curatorRemote as Record<string, unknown>;
215
+ return {
216
+ enabled: true,
217
+ host: trimmedString(obj.host) ?? hostname(),
218
+ bind: trimmedString(obj.bind) ?? "0.0.0.0",
219
+ };
220
+ }
221
+
222
+ return LOCAL_CURATOR_NETWORK_DEFAULTS;
223
+ }
224
+
225
+ export function formatSeconds(s: number): string {
226
+ const h = Math.floor(s / 3600);
227
+ const m = Math.floor((s % 3600) / 60);
228
+ const sec = s % 60;
229
+ if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`;
230
+ return `${m}:${String(sec).padStart(2, "0")}`;
231
+ }
232
+
233
+ export function readExecError(err: unknown): { code?: string; stderr: string; message: string } {
234
+ if (!err || typeof err !== "object") {
235
+ return { stderr: "", message: String(err) };
236
+ }
237
+ const code = (err as { code?: string }).code;
238
+ const message = (err as { message?: string }).message ?? "";
239
+ const stderrRaw = (err as { stderr?: Buffer | string }).stderr;
240
+ const stderr = Buffer.isBuffer(stderrRaw)
241
+ ? stderrRaw.toString("utf-8")
242
+ : typeof stderrRaw === "string"
243
+ ? stderrRaw
244
+ : "";
245
+ return { code, stderr, message };
246
+ }
247
+
248
+ export function isTimeoutError(err: unknown): boolean {
249
+ if (!err || typeof err !== "object") return false;
250
+ if ((err as { killed?: boolean }).killed) return true;
251
+ const name = (err as { name?: string }).name;
252
+ const code = (err as { code?: string }).code;
253
+ const message = (err as { message?: string }).message ?? "";
254
+ return name === "AbortError" || code === "ETIMEDOUT" || message.toLowerCase().includes("timed out");
255
+ }
256
+
257
+ export function trimErrorText(text: string): string {
258
+ return text.replace(/\s+/g, " ").trim().slice(0, 200);
259
+ }
260
+
261
+ // Fit frames in 2000×2000 like Pi's tool-result images, so answer mode, which sends frames to another
262
+ // model without that resize, never uploads full 4K frames. Smaller frames are not enlarged.
263
+ export const FRAME_SCALE_FILTER = "scale=w='min(2000,iw)':h='min(2000,ih)':force_original_aspect_ratio=decrease";
264
+
265
+ export function mapFfmpegError(err: unknown): string {
266
+ const { code, stderr, message } = readExecError(err);
267
+ if (code === "ENOENT") return "ffmpeg is not installed. Install with: brew install ffmpeg";
268
+ if (isTimeoutError(err)) return "ffmpeg timed out extracting frame";
269
+ if (stderr.includes("403")) return "Stream URL returned 403 — may have expired, try again";
270
+ const snippet = trimErrorText(stderr || message);
271
+ return snippet ? `ffmpeg failed: ${snippet}` : "ffmpeg failed";
272
+ }
273
+
274
+ // Pi can load this module several times in one process (extension reloads use fresh module
275
+ // instances), while the fetch wrapper below is process-global. Every instance must therefore write
276
+ // the proxy context into the one store the installed wrapper reads.
277
+ const sharedProxyState = globalThis as { [key: symbol]: AsyncLocalStorage<string | null> | undefined };
278
+ const proxyStorage = sharedProxyState[Symbol.for("pi-web-access.proxyStorage")] ??= new AsyncLocalStorage<string | null>();
279
+
280
+ export function normalizeProxyUrl(value: unknown, source: string): string | null {
281
+ if (value === undefined || value === null) return null;
282
+ if (typeof value !== "string") throw new Error(`${source} must be an http(s) or socks proxy URL string`);
283
+ const trimmed = value.trim();
284
+ if (!trimmed) return null;
285
+ let parsed: URL;
286
+ try {
287
+ parsed = new URL(trimmed);
288
+ } catch {
289
+ throw new Error(`${source} must be a valid proxy URL: ${JSON.stringify(trimmed)}`);
290
+ }
291
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:" &&
292
+ parsed.protocol !== "socks4:" && parsed.protocol !== "socks4a:" &&
293
+ parsed.protocol !== "socks5:" && parsed.protocol !== "socks5h:") {
294
+ throw new Error(`${source} must use the http://, https://, or socks scheme: ${trimmed}`);
295
+ }
296
+ if (!parsed.hostname) throw new Error(`${source} must include a proxy host: ${trimmed}`);
297
+ parsed.hash = "";
298
+ parsed.search = "";
299
+ const serialized = parsed.toString();
300
+ // WHATWG URL drops default ports, but curl defaults proxy URLs to 1080.
301
+ // Keep HTTP(S) defaults explicit, including credentials and IPv6 hosts.
302
+ if (!parsed.port && (parsed.protocol === "http:" || parsed.protocol === "https:")) {
303
+ const authorityEnd = serialized.indexOf("/", parsed.protocol.length + 2);
304
+ const port = parsed.protocol === "https:" ? 443 : 80;
305
+ return `${serialized.slice(0, authorityEnd)}:${port}${serialized.slice(authorityEnd)}`;
306
+ }
307
+ return serialized;
308
+ }
309
+
310
+ function redactProxyUrl(value: string): string {
311
+ const parsed = new URL(value);
312
+ if (parsed.username) parsed.username = "redacted";
313
+ if (parsed.password) parsed.password = "redacted";
314
+ return parsed.toString();
315
+ }
316
+
317
+ function loadProxyConfig(): { proxy: string | null; locked: boolean } {
318
+ let config: { proxy?: unknown; lockProxy?: unknown } = {};
319
+ const path = getWebSearchConfigPath();
320
+ if (existsSync(path)) {
321
+ let raw: unknown;
322
+ try {
323
+ raw = JSON.parse(readFileSync(path, "utf-8"));
324
+ } catch (err) {
325
+ const message = err instanceof Error ? err.message : String(err);
326
+ throw new Error(`Failed to load proxy config from ${path}: ${message}`);
327
+ }
328
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) config = raw as typeof config;
329
+ }
330
+ if (config.lockProxy !== undefined && typeof config.lockProxy !== "boolean") throw new Error(`lockProxy in ${path} must be true or false`);
331
+ const locked = config.lockProxy === true;
332
+ const proxy = config.proxy === undefined ? null : normalizeProxyUrl(config.proxy, `proxy in ${path}`);
333
+ if (locked && proxy === null) throw new Error(`lockProxy is set in ${path} but no proxy is configured there; set proxy or remove lockProxy`);
334
+ return { proxy, locked };
335
+ }
336
+
337
+ export function loadConfiguredProxy(): string | null {
338
+ return loadProxyConfig().proxy;
339
+ }
340
+
341
+ export function runWithProxy<T>(proxy: string | undefined, fn: () => T): T {
342
+ const { proxy: configured, locked } = loadProxyConfig();
343
+ if (proxy === undefined) {
344
+ if (configured === null) return fn();
345
+ installGlobalProxyFetch();
346
+ return proxyStorage.run(configured, fn);
347
+ }
348
+ const normalized = normalizeProxyUrl(proxy, "proxy");
349
+ if (locked && normalized !== configured) {
350
+ throw new Error(`proxy argument rejected: lockProxy is set in ${getWebSearchConfigPath()}; omit proxy to use the configured proxy`);
351
+ }
352
+ if (normalized !== null) installGlobalProxyFetch();
353
+ return proxyStorage.run(normalized, fn);
354
+ }
355
+
356
+ export function getActiveProxy(): string | null {
357
+ return proxyStorage.getStore() ?? null;
358
+ }
359
+
360
+ export function hasScopedProxyDecision(): boolean {
361
+ return proxyStorage.getStore() !== undefined;
362
+ }
363
+
364
+ function noProxyEntryMatches(hostname: string, entry: string): boolean {
365
+ if (!entry) return false;
366
+ if (entry === "*") return true;
367
+ let host = entry;
368
+ if (host.startsWith("[")) {
369
+ const close = host.indexOf("]");
370
+ if (close > 0) host = host.slice(0, close + 1);
371
+ } else {
372
+ const colon = host.lastIndexOf(":");
373
+ if (colon > -1 && /^\d+$/.test(host.slice(colon + 1))) host = host.slice(0, colon);
374
+ }
375
+ host = host.toLowerCase().replace(/^\[|\]$/g, "");
376
+ if (!host) return false;
377
+ return hostname === host || hostname.endsWith(host.startsWith(".") ? host : `.${host}`);
378
+ }
379
+
380
+ /** True when a URL must NOT be sent through the active proxy. */
381
+ export function isProxyBypassedUrl(url: URL): boolean {
382
+ const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
383
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "::1") return true;
384
+ // GCE metadata server (and any GCE_METADATA_HOST override) must be reached directly, never via proxy.
385
+ const gceHost = process.env.GCE_METADATA_HOST?.trim().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
386
+ if (hostname === "metadata.google.internal" || hostname === "169.254.169.254" || (gceHost && noProxyEntryMatches(hostname, gceHost))) return true;
387
+ const noProxy = process.env.NO_PROXY || process.env.no_proxy;
388
+ if (noProxy && noProxy.split(",").some((entry) => noProxyEntryMatches(hostname, entry.trim()))) return true;
389
+ return false;
390
+ }
391
+
392
+ export interface ProxiedRequestInit extends RequestInit {
393
+ /** Caller-supplied proxy; bypasses AsyncLocalStorage for pLimit-safe contexts. */
394
+ __proxy?: string;
395
+ }
396
+
397
+ interface ProxiedFetch {
398
+ (input: RequestInfo | URL, init?: ProxiedRequestInit): Promise<Response>;
399
+ __piWebAccessSharedProxyFetch?: boolean;
400
+ /** Marker set by versions before the shared store. */
401
+ __piWebAccessProxyFetch?: boolean;
402
+ }
403
+
404
+ /** Wraps globalThis.fetch so every http(s) call routes through curl while a proxy is active. Idempotent. */
405
+ export function installGlobalProxyFetch(): void {
406
+ const current = globalThis.fetch as ProxiedFetch;
407
+ // Wrappers from versions before the shared store read their own module's context, so they are
408
+ // wrapped again rather than trusted; this wrapper passes direct calls through to them unchanged.
409
+ if (typeof current !== "function" || current.__piWebAccessSharedProxyFetch === true) return;
410
+ const nativeFetch = current;
411
+ const wrapped: ProxiedFetch = (async (input: RequestInfo | URL, init?: ProxiedRequestInit) => {
412
+ // Prefer caller-attached __proxy (survives pLimit context loss) over AsyncLocalStorage.
413
+ // Unlike the scoped value, an attached proxy has not necessarily been normalized.
414
+ const proxy = init?.__proxy !== undefined ? normalizeProxyUrl(init.__proxy, "proxy") : getActiveProxy();
415
+ if (!proxy) return nativeFetch(input, init);
416
+ let url: URL | null = null;
417
+ try {
418
+ url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
419
+ } catch {
420
+ url = null;
421
+ }
422
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:") || isProxyBypassedUrl(url)) {
423
+ return nativeFetch(input, init);
424
+ }
425
+ if (input instanceof Request) {
426
+ const request = new Request(input, init);
427
+ request.signal.throwIfAborted();
428
+ // Abort body buffering as well as the curl process.
429
+ const body = request.body === null ? null : new Uint8Array(await new Response(
430
+ request.body.pipeThrough(new TransformStream(), { signal: request.signal }),
431
+ ).arrayBuffer());
432
+ init = { ...init, method: request.method, headers: request.headers, body, signal: request.signal, redirect: request.redirect };
433
+ }
434
+ return fetchViaCurl(url, init ?? {}, { command: ["curl"], proxy });
435
+ });
436
+ wrapped.__piWebAccessSharedProxyFetch = true;
437
+ // On top of a pre-fix wrapper, also carry its marker so that copy stops wrapping again.
438
+ if (current.__piWebAccessProxyFetch === true) wrapped.__piWebAccessProxyFetch = true;
439
+ globalThis.fetch = wrapped;
440
+ }
441
+
442
+ /** A fetch for the extension's own page requests that runs the `fetchContent.curl` command instead of
443
+ * Node's fetch. It uses a proxy the way the proxy transport does: a per-call `__proxy` wins, `""`
444
+ * connects directly, and loopback and NO_PROXY hosts are never proxied. With no proxy decision,
445
+ * `envProxy` names the env proxy the SSRF check trusted for the URL. Callers pass a URL. */
446
+ export function createCurlFetch(
447
+ command: readonly string[],
448
+ { maxBytes, envProxy }: { maxBytes: number; envProxy: (url: URL) => string | null },
449
+ ): typeof fetch {
450
+ return async (input: RequestInfo | URL, init?: ProxiedRequestInit) => {
451
+ const url = new URL(input instanceof Request ? input.url : input);
452
+ let proxy: string | null;
453
+ if (init?.__proxy !== undefined || hasScopedProxyDecision()) {
454
+ const chosen = init?.__proxy !== undefined ? normalizeProxyUrl(init.__proxy, "proxy") : getActiveProxy();
455
+ proxy = chosen && !isProxyBypassedUrl(url) ? chosen : null;
456
+ } else {
457
+ proxy = envProxy(url);
458
+ }
459
+ return fetchViaCurl(url, init ?? {}, {
460
+ command,
461
+ proxy,
462
+ maxBytes,
463
+ notFound: `fetchContent.curl command not found: ${command[0]}`,
464
+ });
465
+ };
466
+ }
467
+
468
+ // GET bodies are decoded by --compressed, so their length/encoding headers no longer match.
469
+ // HEAD has no body, and its Content-Length is usually why the caller asked.
470
+ function parseHeaderDump(dump: string, keepLengthHeaders: boolean): { status: number; statusText: string; headers: Array<[string, string]> } {
471
+ const blocks = dump.split(/\r?\n\r?\n/).filter((block) => /^HTTP\/[\d.]+\s+\d{3}/.test(block.trim()));
472
+ const block = (blocks.length > 0 ? blocks[blocks.length - 1] : "").trim();
473
+ const lines = block.split(/\r?\n/);
474
+ let status = 0;
475
+ let statusText = "";
476
+ const headers: Array<[string, string]> = [];
477
+ for (const line of lines) {
478
+ const match = /^HTTP\/[\d.]+\s+(\d{3})(?:\s+(.*))?$/.exec(line.trim());
479
+ if (match) {
480
+ status = Number(match[1]);
481
+ statusText = match[2] ?? "";
482
+ headers.length = 0;
483
+ continue;
484
+ }
485
+ const separator = line.indexOf(":");
486
+ if (separator > 0) {
487
+ const name = line.slice(0, separator).trim();
488
+ if (!keepLengthHeaders && (name.toLowerCase() === "content-encoding" || name.toLowerCase() === "content-length")) continue;
489
+ headers.push([name, line.slice(separator + 1).trim()]);
490
+ }
491
+ }
492
+ return { status, statusText, headers };
493
+ }
494
+
495
+ class CurlTransportError extends Error {}
496
+
497
+ interface CurlTransport {
498
+ /** Executable and any leading arguments, e.g. ["curl"] or ["curl-impersonate", "--impersonate", "chrome146"]. */
499
+ command: readonly string[];
500
+ /** Proxy written to curl's -K config file (never argv), or null to connect directly. */
501
+ proxy: string | null;
502
+ /** Error message when the executable is missing; defaults to the proxy transport's message. */
503
+ notFound?: string;
504
+ /** Largest body to download; curl stops a bigger one instead of saving all of it. */
505
+ maxBytes?: number;
506
+ }
507
+
508
+ async function fetchViaCurl(url: URL, init: RequestInit, transport: CurlTransport): Promise<Response> {
509
+ let current = url;
510
+ let currentInit = init;
511
+ for (let redirects = 0; ; redirects++) {
512
+ const response = await fetchViaCurlOnce(current, currentInit, transport);
513
+ const location = response.headers.get("location");
514
+ if (!location || ![301, 302, 303, 307, 308].includes(response.status)) {
515
+ if (redirects > 0) Object.defineProperty(response, "redirected", { value: true, configurable: true });
516
+ return response;
517
+ }
518
+ if (currentInit.redirect === "manual") return response;
519
+ if (currentInit.redirect === "error") throw new TypeError(`Proxy fetch redirect blocked from ${current.toString()}`);
520
+ if (redirects === 20) throw new Error(`Too many proxy redirects from ${url.toString()}`);
521
+
522
+ const next = new URL(location, current);
523
+ if (next.protocol !== "http:" && next.protocol !== "https:") throw new Error(`Proxy redirect from ${current.origin} must use HTTP(S)`);
524
+
525
+ let headers = new Headers(currentInit.headers);
526
+ let nextInit: RequestInit;
527
+ const method = currentInit.method?.toUpperCase() ?? "GET";
528
+ if (((response.status === 301 || response.status === 302) && method === "POST") || (response.status === 303 && method !== "GET" && method !== "HEAD")) {
529
+ for (const name of ["Content-Encoding", "Content-Language", "Content-Location", "Content-Type"]) headers.delete(name);
530
+ const { body: _body, ...withoutBody } = currentInit;
531
+ nextInit = { ...withoutBody, method: "GET", headers };
532
+ } else {
533
+ nextInit = { ...currentInit, headers };
534
+ }
535
+
536
+ if (next.origin !== current.origin) {
537
+ headers = new Headers();
538
+ nextInit = { ...nextInit, headers };
539
+ }
540
+ current = next;
541
+ currentInit = nextInit;
542
+ }
543
+ }
544
+
545
+ async function fetchViaCurlOnce(url: URL, init: RequestInit, { command, proxy, notFound, maxBytes }: CurlTransport): Promise<Response> {
546
+ const method = (init.method ?? "GET").toUpperCase();
547
+ const headers = new Headers(init.headers);
548
+
549
+ const dir = await mkdtemp(join(tmpdir(), "pi-web-access-proxy-"));
550
+ const headerFile = join(dir, "headers");
551
+ const bodyFile = join(dir, "body");
552
+ const requestBodyFile = join(dir, "request-body");
553
+ const requestHeaderFile = join(dir, "request-headers");
554
+ const proxyConfigFile = join(dir, "proxy");
555
+
556
+ const args: string[] = [
557
+ "--silent",
558
+ "--show-error",
559
+ "--compressed",
560
+ // The caller checks each redirect, so curl must not follow one, even with -L in the command or ~/.curlrc.
561
+ "--no-location",
562
+ // URLs are validated as written, so curl must send [ ] { } literally instead of expanding them into other URLs.
563
+ "--globoff",
564
+ "--connect-timeout", "20",
565
+ // The proxy URL can hold a password, so it goes through a config file in the private dir, never argv,
566
+ // which other processes can read. An empty proxy also stops curl from using proxy environment variables,
567
+ // which Node's fetch ignores.
568
+ "-K", proxyConfigFile,
569
+ // The caller already chose the proxy; curl must not send a host direct because of its own NO_PROXY reading.
570
+ ...(proxy ? ["--noproxy", ""] : []),
571
+ "-D", headerFile,
572
+ "--output", bodyFile,
573
+ "--write-out", "%{json}",
574
+ ];
575
+
576
+ if (method === "HEAD") args.push("--head");
577
+ else if (method !== "GET") args.push("-X", method);
578
+ if (maxBytes !== undefined) args.push("--max-filesize", String(maxBytes));
579
+
580
+ // Header values (cookies, API keys) go through a file in the private dir, never argv, which other processes can read.
581
+ const headerLines: string[] = [];
582
+ for (const [name, value] of headers.entries()) {
583
+ if (value === "") continue;
584
+ headerLines.push(`${name}: ${value}`);
585
+ }
586
+
587
+ const body = init.body;
588
+ let requestBody: Buffer | undefined;
589
+ if (body !== undefined && body !== null) {
590
+ if (typeof body === "string") requestBody = Buffer.from(body, "utf-8");
591
+ else if (body instanceof URLSearchParams) requestBody = Buffer.from(body.toString(), "utf-8");
592
+ else if (body instanceof ArrayBuffer) requestBody = Buffer.from(body);
593
+ else if (ArrayBuffer.isView(body)) requestBody = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
594
+ else throw new Error(`Unsupported request body type for proxy fetch: ${typeof body}`);
595
+ args.push("--data-binary", `@${requestBodyFile}`);
596
+ if (method === "GET") args.unshift("-X", "GET");
597
+ } else if ((method === "POST" || method === "PUT") && !headers.has("content-length")) {
598
+ // Native fetch sends a zero length for a bodyless POST/PUT; some origins answer 411 without it.
599
+ headerLines.push("Content-Length: 0");
600
+ }
601
+ if (headerLines.length > 0) args.push("-H", `@${requestHeaderFile}`);
602
+
603
+ args.push(url.toString());
604
+
605
+ const signal = init.signal ?? null;
606
+ let stdout: string;
607
+ try {
608
+ // Written inside the try so a failed or partial write still removes the dir and any secrets in it.
609
+ if (requestBody) await writeFile(requestBodyFile, requestBody, { mode: 0o600 });
610
+ // Escaping newlines keeps a malformed proxy value from adding other curl options to the file.
611
+ const quotedProxy = (proxy ?? "").replace(/[\\"]/g, "\\$&").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
612
+ await writeFile(proxyConfigFile, `proxy = "${quotedProxy}"\n`, { mode: 0o600 });
613
+ if (headerLines.length > 0) await writeFile(requestHeaderFile, `${headerLines.join("\n")}\n`, { mode: 0o600 });
614
+ stdout = await new Promise<string>((resolve, reject) => {
615
+ if (signal?.aborted) {
616
+ reject(new DOMException("The operation was aborted.", "AbortError"));
617
+ return;
618
+ }
619
+ const child = spawn(command[0], [...command.slice(1), ...args], { windowsHide: true });
620
+ let out = "";
621
+ let stderr = "";
622
+ const onAbort = () => { try { child.kill(); } catch {} };
623
+ if (signal) {
624
+ signal.addEventListener("abort", onAbort, { once: true });
625
+ }
626
+ child.stdout?.on("data", (chunk: Buffer) => { out += chunk.toString("utf-8"); });
627
+ child.stderr?.on("data", (chunk: Buffer) => { if (stderr.length < 4096) stderr += chunk.toString("utf-8"); });
628
+ child.once("error", (err: NodeJS.ErrnoException) => {
629
+ signal?.removeEventListener("abort", onAbort);
630
+ reject(new CurlTransportError(err.code === "ENOENT"
631
+ ? notFound ?? "curl executable not found on PATH; proxy transport requires curl"
632
+ : `${command[0]} failed to start: ${err.message}`));
633
+ });
634
+ child.once("close", (code) => {
635
+ signal?.removeEventListener("abort", onAbort);
636
+ if (signal?.aborted) return reject(new DOMException("The operation was aborted.", "AbortError"));
637
+ // A failed transfer can still write headers, part of the body and the write-out JSON.
638
+ // Exit 63 is --max-filesize; report it like the size limit of a Node fetch.
639
+ if (code === 63 && maxBytes !== undefined) {
640
+ return reject(new CurlTransportError(`Response too large (over ${Math.round(maxBytes / 1024 / 1024)}MB)`));
641
+ }
642
+ if (code !== 0) {
643
+ return reject(new CurlTransportError(`${command[0]} exited with code ${code ?? "unknown"}${proxy ? ` via ${redactProxyUrl(proxy)}` : ""}${stderr.trim() ? `: ${stderr.trim()}` : ""}`));
644
+ }
645
+ resolve(out);
646
+ });
647
+ });
648
+ } catch (err) {
649
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
650
+ if (err instanceof CurlTransportError) throw new Error(err.message);
651
+ throw err;
652
+ }
653
+
654
+ let bodyBuffer = Buffer.alloc(0);
655
+ let dump = "";
656
+ try {
657
+ [dump, bodyBuffer] = await Promise.all([readFile(headerFile, "utf-8"), readFile(bodyFile)]);
658
+ } catch {
659
+ // HEAD or empty responses may not produce output files.
660
+ } finally {
661
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
662
+ }
663
+
664
+ const { status, statusText, headers: responseHeaders } = parseHeaderDump(dump, method === "HEAD");
665
+ if (status === 0) {
666
+ throw new Error(proxy
667
+ ? `Proxy fetch to ${url.toString()} via ${redactProxyUrl(proxy)} returned no HTTP status`
668
+ : `${command[0]} fetch to ${url.toString()} returned no HTTP status`);
669
+ }
670
+
671
+ let finalUrl = url.toString();
672
+ let redirected = false;
673
+ try {
674
+ const trimmed = stdout.trim();
675
+ if (trimmed.startsWith("{")) {
676
+ const writeOut = JSON.parse(trimmed) as { url_effective?: string; num_redirects?: number };
677
+ if (writeOut.url_effective) finalUrl = writeOut.url_effective;
678
+ redirected = (writeOut.num_redirects ?? 0) > 0;
679
+ }
680
+ } catch {
681
+ // Older curl without %{json}; the header dump already provided the status.
682
+ }
683
+
684
+ const nullBody = method === "HEAD" || status === 204 || status === 205 || status === 304;
685
+ const response = new Response(nullBody ? null : new Uint8Array(bodyBuffer), {
686
+ status,
687
+ statusText: statusText || undefined,
688
+ headers: new Headers(responseHeaders),
689
+ });
690
+ Object.defineProperty(response, "url", { value: finalUrl, configurable: true });
691
+ Object.defineProperty(response, "redirected", { value: redirected, configurable: true });
692
+ return response;
693
+ }