@abhishek944/pi-web-access 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
@@ -0,0 +1,226 @@
1
+ import { activityMonitor } from "./activity.ts";
2
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
3
+ import { applyDomainFilter } 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 { fetchWithCredentialRedirects, isRecord, resolveApiBaseUrl } from "./utils.ts";
8
+
9
+ export interface CustomSearchProviderConfig {
10
+ url: string;
11
+ method: "GET" | "POST";
12
+ apiKey?: string;
13
+ apiKeyHeader?: string;
14
+ apiKeyPrefix?: string;
15
+ apiKeyQuery?: string;
16
+ headers: Record<string, string>;
17
+ query: Record<string, string>;
18
+ body?: Record<string, unknown>;
19
+ results: string;
20
+ fields: { title: string; url: string; snippet?: string };
21
+ }
22
+
23
+ const NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
24
+ const ENTRY_KEYS = new Set(["url", "method", "apiKey", "apiKeyHeader", "apiKeyPrefix", "apiKeyQuery", "headers", "query", "body", "results", "fields"]);
25
+ const SEARCH_TIMEOUT_MS = 60_000;
26
+
27
+ function optionalString(entry: Record<string, unknown>, key: string, label: string): string | undefined {
28
+ const value = entry[key];
29
+ if (value === undefined) return undefined;
30
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${label}.${key} must be a non-empty string`);
31
+ return value;
32
+ }
33
+
34
+ function stringMap(entry: Record<string, unknown>, key: string, label: string): Record<string, string> {
35
+ const value = entry[key];
36
+ if (value === undefined) return {};
37
+ if (!isRecord(value)) throw new Error(`${label}.${key} must be an object of strings`);
38
+ for (const [name, item] of Object.entries(value)) {
39
+ if (typeof item !== "string") throw new Error(`${label}.${key}.${name} must be a string`);
40
+ }
41
+ return value as Record<string, string>;
42
+ }
43
+
44
+ function parseEntry(value: unknown, label: string): CustomSearchProviderConfig {
45
+ if (!isRecord(value)) throw new Error(`${label} must be an object`);
46
+ const unknown = Object.keys(value).filter((key) => !ENTRY_KEYS.has(key));
47
+ if (unknown.length > 0) throw new Error(`${label} has unknown field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
48
+ const rawUrl = optionalString(value, "url", label);
49
+ if (rawUrl === undefined) throw new Error(`${label}.url is required`);
50
+ // Validated like a base URL, but sent exactly as configured: a trailing slash can be part of the endpoint.
51
+ resolveApiBaseUrl({ configKey: `${label}.url`, configuredValue: rawUrl, defaultValue: rawUrl, environmentKey: "", environmentValue: undefined });
52
+ const url = new URL(rawUrl.trim()).href;
53
+ const method = value.method ?? "GET";
54
+ if (method !== "GET" && method !== "POST") throw new Error(`${label}.method must be "GET" or "POST"`);
55
+ const apiKey = optionalString(value, "apiKey", label);
56
+ const apiKeyHeader = optionalString(value, "apiKeyHeader", label);
57
+ const apiKeyPrefix = value.apiKeyPrefix === undefined ? undefined : typeof value.apiKeyPrefix === "string" ? value.apiKeyPrefix : null;
58
+ if (apiKeyPrefix === null) throw new Error(`${label}.apiKeyPrefix must be a string`);
59
+ const apiKeyQuery = optionalString(value, "apiKeyQuery", label);
60
+ if (apiKey === undefined && (apiKeyHeader || apiKeyQuery || apiKeyPrefix !== undefined)) {
61
+ throw new Error(`${label} sets where the API key goes but has no apiKey`);
62
+ }
63
+ if (apiKey !== undefined && (apiKeyHeader === undefined) === (apiKeyQuery === undefined)) {
64
+ throw new Error(`${label}.apiKey needs exactly one of apiKeyHeader or apiKeyQuery`);
65
+ }
66
+ if (apiKeyPrefix !== undefined && apiKeyHeader === undefined) throw new Error(`${label}.apiKeyPrefix needs apiKeyHeader`);
67
+ if (value.body !== undefined) {
68
+ if (method !== "POST") throw new Error(`${label}.body needs method "POST"`);
69
+ if (!isRecord(value.body)) throw new Error(`${label}.body must be a JSON object`);
70
+ }
71
+ const results = value.results ?? "";
72
+ if (typeof results !== "string") throw new Error(`${label}.results must be a string path`);
73
+ const fields = value.fields;
74
+ if (!isRecord(fields)) throw new Error(`${label}.fields must be an object with title and url`);
75
+ const unknownFields = Object.keys(fields).filter((key) => key !== "title" && key !== "url" && key !== "snippet");
76
+ if (unknownFields.length > 0) throw new Error(`${label}.fields has unknown field${unknownFields.length === 1 ? "" : "s"}: ${unknownFields.join(", ")}`);
77
+ const title = optionalString(fields, "title", `${label}.fields`);
78
+ const resultUrl = optionalString(fields, "url", `${label}.fields`);
79
+ if (title === undefined || resultUrl === undefined) throw new Error(`${label}.fields needs title and url`);
80
+ const snippet = optionalString(fields, "snippet", `${label}.fields`);
81
+ return {
82
+ url,
83
+ method,
84
+ ...(apiKey !== undefined ? { apiKey } : {}),
85
+ ...(apiKeyHeader !== undefined ? { apiKeyHeader } : {}),
86
+ ...(apiKeyPrefix !== undefined ? { apiKeyPrefix } : {}),
87
+ ...(apiKeyQuery !== undefined ? { apiKeyQuery } : {}),
88
+ headers: stringMap(value, "headers", label),
89
+ query: stringMap(value, "query", label),
90
+ ...(value.body !== undefined ? { body: value.body as Record<string, unknown> } : {}),
91
+ results,
92
+ fields: { title, url: resultUrl, ...(snippet !== undefined ? { snippet } : {}) },
93
+ };
94
+ }
95
+
96
+ /** Validates `customSearchProviders`; `reserved` holds names a custom provider may not take. */
97
+ export function parseCustomSearchProviders(value: unknown, reserved: readonly string[], configPath: string): Map<string, CustomSearchProviderConfig> {
98
+ const providers = new Map<string, CustomSearchProviderConfig>();
99
+ if (value === undefined) return providers;
100
+ if (!isRecord(value)) throw new Error(`customSearchProviders in ${configPath} must be an object`);
101
+ for (const [name, entry] of Object.entries(value)) {
102
+ const label = `customSearchProviders.${name} in ${configPath}`;
103
+ if (!NAME_PATTERN.test(name)) throw new Error(`${label}: a provider name may contain only lowercase letters, digits, and "-"`);
104
+ if (name === "auto" || name === "all" || reserved.includes(name)) throw new Error(`${label}: "${name}" is already a built-in provider name`);
105
+ try {
106
+ providers.set(name, parseEntry(entry, `customSearchProviders.${name}`));
107
+ } catch (err) {
108
+ const message = errorMessage(err);
109
+ throw new Error(message.includes(configPath) ? message : `${message} (in ${configPath})`);
110
+ }
111
+ }
112
+ return providers;
113
+ }
114
+
115
+ export function isCustomSearchProviderAvailable(name: string, config: CustomSearchProviderConfig): boolean {
116
+ return config.apiKey === undefined || hasCredentialSource({ provider: name, configuredValue: config.apiKey });
117
+ }
118
+
119
+ function fill(template: string, query: string, count: number): string {
120
+ return template.replace(/\{(query|count)\}/g, (_match, key: string) => key === "query" ? query : String(count));
121
+ }
122
+
123
+ function fillBody(value: unknown, query: string, count: number): unknown {
124
+ if (value === "{count}") return count;
125
+ if (typeof value === "string") return fill(value, query, count);
126
+ if (Array.isArray(value)) return value.map((item) => fillBody(item, query, count));
127
+ if (isRecord(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, fillBody(item, query, count)]));
128
+ return value;
129
+ }
130
+
131
+ function readPath(value: unknown, path: string): unknown {
132
+ if (path === "") return value;
133
+ let current = value;
134
+ for (const key of path.split(".")) {
135
+ if (!isRecord(current)) return undefined;
136
+ current = current[key];
137
+ }
138
+ return current;
139
+ }
140
+
141
+ function errorMessage(err: unknown): string {
142
+ return err instanceof Error ? err.message : String(err);
143
+ }
144
+
145
+ // Recency has no generic request form, so `recencyFilter` is not applied; domain filters are applied to the returned URLs.
146
+ export async function searchWithCustomProvider(
147
+ name: string,
148
+ config: CustomSearchProviderConfig,
149
+ query: string,
150
+ options: SearchOptions = {},
151
+ ): Promise<SearchResponse> {
152
+ const apiKey = config.apiKey === undefined
153
+ ? null
154
+ : await resolveCredential({ provider: name, configuredValue: config.apiKey, signal: options.signal });
155
+ if (config.apiKey !== undefined && !apiKey) throw new Error(`${name} API key not found: set apiKey in customSearchProviders.${name}`);
156
+ const numResults = normalizeSearchResultCount(options.numResults);
157
+ // Domain filters run on the returned URLs, so ask for a few extra results.
158
+ const count = options.domainFilter?.length ? Math.min(20, numResults + 5) : numResults;
159
+ const url = new URL(config.url);
160
+ for (const [key, value] of Object.entries(config.query)) url.searchParams.set(key, fill(value, query, count));
161
+ if (apiKey && config.apiKeyQuery) url.searchParams.set(config.apiKeyQuery, apiKey);
162
+ const redact = (text: string) => redactCredential(text, apiKey);
163
+ const activityId = activityMonitor.logStart({ type: "api", query });
164
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
165
+ let response: Response;
166
+ let data: unknown;
167
+ try {
168
+ // Built inside the try: an invalid header value is quoted, key included, in the error, so it must be redacted.
169
+ // Headers matches names case-insensitively, so a configured "content-type" isn't sent twice.
170
+ const headers = new Headers({ Accept: "application/json", ...config.headers });
171
+ if (config.body !== undefined) headers.set("Content-Type", "application/json");
172
+ if (apiKey && config.apiKeyHeader) headers.set(config.apiKeyHeader, (config.apiKeyPrefix ?? "") + apiKey);
173
+ response = await fetchWithCredentialRedirects(url.toString(), {
174
+ method: config.method,
175
+ headers,
176
+ ...(config.body !== undefined ? { body: JSON.stringify(fillBody(config.body, query, count)) } : {}),
177
+ signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal,
178
+ }, config.apiKeyHeader ? [config.apiKeyHeader] : [], config.apiKeyQuery ? [config.apiKeyQuery] : []);
179
+ if (!response.ok) {
180
+ throw new Error(`${name} API error ${response.status}: ${redact(await response.text()).slice(0, 300)}`);
181
+ }
182
+ try {
183
+ data = await response.json();
184
+ } catch (err) {
185
+ // Only a parse failure is invalid JSON; a dropped connection keeps its own classification.
186
+ // The parser's message quotes the body, which can hold a partial key that redaction can't match.
187
+ if (!(err instanceof SyntaxError)) throw err;
188
+ throw new Error(`${name} API returned invalid JSON`);
189
+ }
190
+ } catch (err) {
191
+ if (options.signal?.aborted) {
192
+ activityMonitor.logComplete(activityId, 0);
193
+ throw new Error("Aborted");
194
+ }
195
+ // A proxy can turn the provider timeout into a plain abort; name it so routing falls back.
196
+ if (timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError")) {
197
+ const timedOut = new Error(`${name} request timed out after ${SEARCH_TIMEOUT_MS / 1000}s`);
198
+ activityMonitor.logError(activityId, timedOut.message);
199
+ throw timedOut;
200
+ }
201
+ const message = redact(errorMessage(err));
202
+ activityMonitor.logError(activityId, message);
203
+ if (message === errorMessage(err)) throw err;
204
+ const redacted = new Error(message);
205
+ if (err instanceof Error) redacted.name = err.name;
206
+ throw redacted;
207
+ }
208
+ activityMonitor.logComplete(activityId, response.status);
209
+ // SERP APIs often omit the results array when nothing matched.
210
+ const entries = readPath(data, config.results) ?? [];
211
+ if (!Array.isArray(entries)) {
212
+ throw new Error(`${name} API returned invalid response: expected an array at ${config.results ? `"${config.results}"` : "the top level"}`);
213
+ }
214
+ const mapped: SearchResponse["results"] = [];
215
+ for (const entry of entries) {
216
+ const title = readPath(entry, config.fields.title);
217
+ const link = readPath(entry, config.fields.url);
218
+ if (typeof title !== "string" || !title.trim() || typeof link !== "string") continue;
219
+ const parsed = URL.parse(link.trim());
220
+ if (!parsed || (parsed.protocol !== "http:" && parsed.protocol !== "https:")) continue;
221
+ const snippet = config.fields.snippet === undefined ? undefined : readPath(entry, config.fields.snippet);
222
+ mapped.push({ title: title.trim(), url: parsed.href, snippet: typeof snippet === "string" ? snippet.trim() : "" });
223
+ }
224
+ const results = applyDomainFilter(mapped, options.domainFilter).slice(0, numResults);
225
+ return { answer: formatSearchResultsAsAnswer(results), results };
226
+ }
@@ -0,0 +1,406 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { createHash } from "node:crypto";
3
+
4
+ // Replaces inline RFC 2397 data: URIs in extracted text with explicit bounded
5
+ // omission markers so base64 payloads never reach model-visible tool results,
6
+ // the fetch cache, or session persistence. Carved out of the original
7
+ // persistence-safety layer; only the text-sanitization path is retained.
8
+
9
+ const MAX_DATA_URI_HEADER_CHARS = 1024;
10
+ const MAX_MIME_CHARS = 127;
11
+ const MAX_MARKER_SOURCE_CHARS = 180;
12
+
13
+ export type DataUriEncoding = "base64" | "percent-encoded";
14
+ export type DigestBasis = "decoded" | "encoded";
15
+
16
+ export interface DataUriOmission {
17
+ ordinal: number;
18
+ sourcePath: string;
19
+ mimeType: string;
20
+ encoding: DataUriEncoding;
21
+ encodedBytes: number;
22
+ decodedBytes: number | null;
23
+ decodeError?: string;
24
+ sha256: string;
25
+ digestBasis: DigestBasis;
26
+ retrieval: "not-retained";
27
+ }
28
+
29
+
30
+ interface InternalDataUriOmission extends DataUriOmission {
31
+ markerStart: number;
32
+ markerEnd: number;
33
+ }
34
+
35
+ interface SanitizationState {
36
+ nextOrdinal: number;
37
+ omissions: InternalDataUriOmission[];
38
+ }
39
+
40
+
41
+ function sha256Bytes(value: string | Uint8Array): string {
42
+ return createHash("sha256").update(value).digest("hex");
43
+ }
44
+
45
+
46
+ function asciiLowerCode(code: number): number {
47
+ return code >= 65 && code <= 90 ? code + 32 : code;
48
+ }
49
+
50
+ function matchesDataScheme(text: string, index: number): boolean {
51
+ return index + 5 <= text.length
52
+ && asciiLowerCode(text.charCodeAt(index)) === 100
53
+ && asciiLowerCode(text.charCodeAt(index + 1)) === 97
54
+ && asciiLowerCode(text.charCodeAt(index + 2)) === 116
55
+ && asciiLowerCode(text.charCodeAt(index + 3)) === 97
56
+ && text.charCodeAt(index + 4) === 58;
57
+ }
58
+
59
+ function isSchemeBoundary(text: string, index: number): boolean {
60
+ if (index === 0) return true;
61
+ const code = text.charCodeAt(index - 1);
62
+ const alphaNumeric = (code >= 48 && code <= 57)
63
+ || (code >= 65 && code <= 90)
64
+ || (code >= 97 && code <= 122);
65
+ return !alphaNumeric && code !== 43 && code !== 45 && code !== 46;
66
+ }
67
+
68
+ function findNextDataScheme(text: string, from: number): number {
69
+ for (let i = from; i + 5 <= text.length; i++) {
70
+ if (matchesDataScheme(text, i) && isSchemeBoundary(text, i)) return i;
71
+ }
72
+ return -1;
73
+ }
74
+
75
+ type DataUriEnclosure =
76
+ | { kind: "quote"; close: "\"" | "'" | "`" }
77
+ | { kind: "parentheses" }
78
+ | { kind: "angle" }
79
+ | null;
80
+
81
+ interface ScannedDataUriCandidate {
82
+ end: number;
83
+ comma: number;
84
+ enclosure: DataUriEnclosure;
85
+ }
86
+
87
+ function dataUriEnclosure(text: string, start: number): DataUriEnclosure {
88
+ if (start === 0) return null;
89
+ const immediateIndex = start - 1;
90
+ const immediate = text[immediateIndex];
91
+ if (immediate === "\"" || immediate === "'" || immediate === "`") {
92
+ const beforeQuote = immediateIndex > 0 ? text[immediateIndex - 1] : "";
93
+ const likelyOpeningQuote = immediateIndex === 0
94
+ || beforeQuote === "="
95
+ || beforeQuote === "("
96
+ || beforeQuote === "["
97
+ || beforeQuote === "{"
98
+ || beforeQuote === ":"
99
+ || beforeQuote === ","
100
+ || /\s/.test(beforeQuote);
101
+ if (likelyOpeningQuote) return { kind: "quote", close: immediate };
102
+ }
103
+
104
+ let openerIndex = immediateIndex;
105
+ while (openerIndex >= 0 && (text[openerIndex] === " " || text[openerIndex] === "\t")) openerIndex--;
106
+ const opener = text[openerIndex];
107
+ if (opener === "(") return { kind: "parentheses" };
108
+ if (opener === "<") return { kind: "angle" };
109
+ return null;
110
+ }
111
+
112
+ function isBareDataUriTerminator(ch: string): boolean {
113
+ const code = ch.charCodeAt(0);
114
+ return code <= 32
115
+ || code === 127
116
+ || ch === "\""
117
+ || ch === "`"
118
+ || ch === "<"
119
+ || ch === ">";
120
+ }
121
+
122
+ /** Scan one candidate exactly once. Enclosures consume malformed whitespace and
123
+ * balanced inner parentheses so invalid payload suffixes cannot escape. */
124
+ function scanDataUriCandidate(text: string, start: number): ScannedDataUriCandidate {
125
+ const enclosure = dataUriEnclosure(text, start);
126
+ let comma = -1;
127
+ let depth = enclosure?.kind === "parentheses" ? 1 : 0;
128
+ let index = start + 5;
129
+
130
+ for (; index < text.length; index++) {
131
+ const ch = text[index];
132
+ if (enclosure?.kind === "quote") {
133
+ if (ch === enclosure.close) break;
134
+ } else if (enclosure?.kind === "parentheses") {
135
+ if (ch === "(") {
136
+ depth++;
137
+ } else if (ch === ")") {
138
+ depth--;
139
+ if (depth === 0) break;
140
+ }
141
+ } else if (enclosure?.kind === "angle") {
142
+ if (ch === ">") break;
143
+ } else if (isBareDataUriTerminator(ch)) {
144
+ break;
145
+ }
146
+ if (comma < 0 && ch === ",") comma = index;
147
+ }
148
+
149
+ return { end: index, comma, enclosure };
150
+ }
151
+
152
+ function headerEndsWithBase64(text: string, headerStart: number, comma: number): boolean {
153
+ let end = comma;
154
+ while (end > headerStart && (text[end - 1] === " " || text[end - 1] === "\t")) end--;
155
+ const token = "base64";
156
+ if (end - headerStart < token.length + 1) return false;
157
+ const tokenStart = end - token.length;
158
+ for (let i = 0; i < token.length; i++) {
159
+ if (asciiLowerCode(text.charCodeAt(tokenStart + i)) !== token.charCodeAt(i)) return false;
160
+ }
161
+ return tokenStart > headerStart && text[tokenStart - 1] === ";";
162
+ }
163
+
164
+ function isMimeTokenChar(code: number): boolean {
165
+ if (code < 33 || code > 126) return false;
166
+ // RFC 2045 token = printable ASCII excluding tspecials. Slash is handled
167
+ // separately as the single type/subtype separator.
168
+ switch (code) {
169
+ case 34: // "
170
+ case 40: // (
171
+ case 41: // )
172
+ case 44: // ,
173
+ case 47: // /
174
+ case 58: // :
175
+ case 59: // ;
176
+ case 60: // <
177
+ case 61: // =
178
+ case 62: // >
179
+ case 63: // ?
180
+ case 64: // @
181
+ case 91: // [
182
+ case 92: // backslash
183
+ case 93: // ]
184
+ return false;
185
+ default:
186
+ return true;
187
+ }
188
+ }
189
+
190
+ function normalizeMimeType(text: string, headerStart: number, comma: number): string {
191
+ let end = headerStart;
192
+ while (end < comma && text[end] !== ";") end++;
193
+ if (end === headerStart) return "text/plain";
194
+ if (end - headerStart > MAX_MIME_CHARS) return "application/octet-stream";
195
+
196
+ let slashCount = 0;
197
+ for (let i = headerStart; i < end; i++) {
198
+ const code = text.charCodeAt(i);
199
+ if (code === 47) {
200
+ slashCount++;
201
+ if (i === headerStart || i === end - 1) return "application/octet-stream";
202
+ continue;
203
+ }
204
+ if (!isMimeTokenChar(code)) return "application/octet-stream";
205
+ }
206
+ if (slashCount !== 1) return "application/octet-stream";
207
+ return text.slice(headerStart, end).toLowerCase();
208
+ }
209
+
210
+ function hexValue(code: number): number {
211
+ if (code >= 48 && code <= 57) return code - 48;
212
+ if (code >= 65 && code <= 70) return code - 55;
213
+ if (code >= 97 && code <= 102) return code - 87;
214
+ return -1;
215
+ }
216
+
217
+ function decodePercentEncoded(payload: string): { bytes: Buffer } | { error: string } {
218
+ const output = Buffer.allocUnsafe(Buffer.byteLength(payload, "utf8"));
219
+ let outputOffset = 0;
220
+ let cursor = 0;
221
+
222
+ while (cursor < payload.length) {
223
+ const percent = payload.indexOf("%", cursor);
224
+ const runEnd = percent < 0 ? payload.length : percent;
225
+ if (runEnd > cursor) {
226
+ const run = Buffer.from(payload.slice(cursor, runEnd), "utf8");
227
+ run.copy(output, outputOffset);
228
+ outputOffset += run.length;
229
+ }
230
+ if (percent < 0) break;
231
+ if (percent + 2 >= payload.length) return { error: "invalid-percent-escape" };
232
+ const high = hexValue(payload.charCodeAt(percent + 1));
233
+ const low = hexValue(payload.charCodeAt(percent + 2));
234
+ if (high < 0 || low < 0) return { error: "invalid-percent-escape" };
235
+ output[outputOffset++] = (high << 4) | low;
236
+ cursor = percent + 3;
237
+ }
238
+
239
+ return { bytes: output.subarray(0, outputOffset) };
240
+ }
241
+
242
+ function isBase64AlphabetByte(byte: number): boolean {
243
+ return (byte >= 65 && byte <= 90)
244
+ || (byte >= 97 && byte <= 122)
245
+ || (byte >= 48 && byte <= 57)
246
+ || byte === 43
247
+ || byte === 47;
248
+ }
249
+
250
+ function decodeBase64Payload(payload: string): { bytes: Buffer } | { error: string } {
251
+ const percentDecoded = decodePercentEncoded(payload);
252
+ if ("error" in percentDecoded) return percentDecoded;
253
+ const encoded = percentDecoded.bytes;
254
+ let paddingStart = encoded.length;
255
+ let paddingCount = 0;
256
+
257
+ for (let i = 0; i < encoded.length; i++) {
258
+ const byte = encoded[i];
259
+ if (byte > 127) return { error: "non-ascii-base64" };
260
+ if (byte === 61) {
261
+ if (paddingStart === encoded.length) paddingStart = i;
262
+ paddingCount++;
263
+ continue;
264
+ }
265
+ if (paddingStart !== encoded.length) return { error: "invalid-base64-padding" };
266
+ if (!isBase64AlphabetByte(byte)) return { error: "invalid-base64-character" };
267
+ }
268
+
269
+ if (paddingCount > 2) return { error: "invalid-base64-padding" };
270
+ if (paddingCount > 0 && encoded.length % 4 !== 0) return { error: "invalid-base64-padding" };
271
+ if (paddingCount === 0 && encoded.length % 4 === 1) return { error: "invalid-base64-length" };
272
+ if (paddingCount === 1 && paddingStart % 4 !== 3) return { error: "invalid-base64-padding" };
273
+ if (paddingCount === 2 && paddingStart % 4 !== 2) return { error: "invalid-base64-padding" };
274
+
275
+ return { bytes: Buffer.from(encoded.toString("ascii"), "base64") };
276
+ }
277
+
278
+ function safeMarkerSource(sourcePath: string): string {
279
+ const source = sourcePath || "value";
280
+ let safe = "";
281
+ for (const ch of source) {
282
+ const code = ch.charCodeAt(0);
283
+ const allowed = (code >= 48 && code <= 57)
284
+ || (code >= 65 && code <= 90)
285
+ || (code >= 97 && code <= 122)
286
+ || ch === "."
287
+ || ch === "_"
288
+ || ch === "-"
289
+ || ch === "["
290
+ || ch === "]"
291
+ || ch === "*"
292
+ || ch === "$";
293
+ safe += allowed ? ch : "_";
294
+ }
295
+ if (safe.length <= MAX_MARKER_SOURCE_CHARS) return safe;
296
+ const suffix = sha256Bytes(source).slice(0, 12);
297
+ return `${safe.slice(0, MAX_MARKER_SOURCE_CHARS - suffix.length - 1)}~${suffix}`;
298
+ }
299
+
300
+ function buildDataUriMarker(omission: DataUriOmission): string {
301
+ const decoded = omission.decodedBytes === null ? "unknown" : String(omission.decodedBytes);
302
+ const decodeError = omission.decodeError ? `; decodeError=${omission.decodeError}` : "";
303
+ return `[pi-web-access inline data URI omitted; ordinal=${omission.ordinal}; source=${omission.sourcePath}; mime=${omission.mimeType}; encoding=${omission.encoding}; encodedBytes=${omission.encodedBytes}; decodedBytes=${decoded}${decodeError}; sha256=${omission.sha256}; digestBasis=${omission.digestBasis}; retrieval=not-retained]`;
304
+ }
305
+
306
+ function sanitizeTextInternal(text: string, sourcePath: string, state: SanitizationState): string {
307
+ let scanFrom = 0;
308
+ let retainedFrom = 0;
309
+ let outputLength = 0;
310
+ const pieces: string[] = [];
311
+
312
+ while (scanFrom < text.length) {
313
+ const start = findNextDataScheme(text, scanFrom);
314
+ if (start < 0) break;
315
+ const candidate = scanDataUriCandidate(text, start);
316
+ const end = candidate.end;
317
+ const headerStart = start + 5;
318
+ const missingComma = candidate.comma < 0;
319
+ // A bare prose label such as "data: value" is not an inline URI. Enclosed
320
+ // or non-empty comma-less candidates are malformed URIs and are removed.
321
+ if (missingComma && end === headerStart && candidate.enclosure === null) {
322
+ scanFrom = end;
323
+ continue;
324
+ }
325
+ const headerEnd = missingComma ? end : candidate.comma;
326
+ const headerLength = headerEnd - headerStart;
327
+ const encoding: DataUriEncoding = headerEndsWithBase64(text, headerStart, headerEnd)
328
+ ? "base64"
329
+ : "percent-encoded";
330
+ const mimeType = normalizeMimeType(text, headerStart, headerEnd);
331
+ // Without the required comma, the post-scheme bytes are ambiguous. Count
332
+ // and digest the whole omitted segment on the encoded basis rather than
333
+ // retaining any header/payload-looking suffix.
334
+ const payload = missingComma
335
+ ? text.slice(headerStart, end)
336
+ : text.slice(candidate.comma + 1, end);
337
+ const encodedBytes = Buffer.byteLength(payload, "utf8");
338
+
339
+ let decodedBytes: number | null = null;
340
+ let decodeError: string | undefined;
341
+ let digestBasis: DigestBasis = "encoded";
342
+ let digest = "";
343
+
344
+ if (missingComma) {
345
+ decodeError = "missing-comma";
346
+ digest = sha256Bytes(payload);
347
+ } else if (headerLength > MAX_DATA_URI_HEADER_CHARS) {
348
+ decodeError = "header-too-long";
349
+ digest = sha256Bytes(payload);
350
+ } else {
351
+ const decoded = encoding === "base64"
352
+ ? decodeBase64Payload(payload)
353
+ : decodePercentEncoded(payload);
354
+ if ("error" in decoded) {
355
+ decodeError = decoded.error;
356
+ digest = sha256Bytes(payload);
357
+ } else {
358
+ decodedBytes = decoded.bytes.length;
359
+ digestBasis = "decoded";
360
+ digest = sha256Bytes(decoded.bytes);
361
+ }
362
+ }
363
+
364
+ const omission: DataUriOmission = {
365
+ ordinal: state.nextOrdinal++,
366
+ sourcePath: safeMarkerSource(sourcePath),
367
+ mimeType,
368
+ encoding,
369
+ encodedBytes,
370
+ decodedBytes,
371
+ ...(decodeError ? { decodeError } : {}),
372
+ sha256: digest,
373
+ digestBasis,
374
+ retrieval: "not-retained",
375
+ };
376
+ const marker = buildDataUriMarker(omission);
377
+ const prefix = text.slice(retainedFrom, start);
378
+ pieces.push(prefix, marker);
379
+ outputLength += prefix.length;
380
+ const markerStart = outputLength;
381
+ outputLength += marker.length;
382
+ state.omissions.push({ ...omission, markerStart, markerEnd: outputLength });
383
+ retainedFrom = end;
384
+ scanFrom = end;
385
+ }
386
+
387
+ if (state.omissions.length === 0 && retainedFrom === 0) return text;
388
+ pieces.push(text.slice(retainedFrom));
389
+ return pieces.join("");
390
+ }
391
+
392
+
393
+ /** Replace every recognized RFC 2397-style inline data URI in one string. */
394
+ export function sanitizeInlineDataUris(
395
+ text: string,
396
+ sourcePath: string,
397
+ ): { text: string; omissions: DataUriOmission[] } {
398
+ const state: SanitizationState = { nextOrdinal: 1, omissions: [] };
399
+ const sanitized = sanitizeTextInternal(text, sourcePath, state);
400
+ return {
401
+ text: sanitized,
402
+ omissions: state.omissions.map(({ markerStart: _start, markerEnd: _end, ...omission }) => omission),
403
+ };
404
+ }
405
+
406
+ /** Sanitize every string leaf in a JSON-compatible value with one ordinal sequence. */