@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/xai-search.ts ADDED
@@ -0,0 +1,443 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { activityMonitor } from "./activity.ts";
4
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
5
+ import type { SearchOptions, SearchResponse, SearchResult } from "./perplexity.ts";
6
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
7
+ import { getWebSearchConfigPath } from "./utils.ts";
8
+
9
+ // xAI's Agent Tools API: hosted `web_search` and opt-in `x_search` tools on an
10
+ // OpenAI-compatible Responses endpoint. The search runs inside xAI's own inference, so — unlike
11
+ // every keyed backend here — it is paid for by whatever credential answers for
12
+ // the model, including a SuperGrok / X Premium subscription resolved through
13
+ // pi's model registry.
14
+ //
15
+ // Note for anyone extending this: xAI's older Live Search (`search_parameters`
16
+ // on /v1/chat/completions) is GONE. It now answers 410 with "Live search is
17
+ // deprecated. Please switch to the Agent Tools API". Do not add it back.
18
+ //
19
+ // The request body is deliberately minimal — model, input, tools — because that
20
+ // is the shape verified against a live subscription account. `stream`,
21
+ // `include`, `tool_choice` and `parallel_tool_calls` are all sent by the OpenAI
22
+ // backend but were NOT verified here, and a 400 from an unsupported field would
23
+ // cost the user their search. Responses API inline citations are enabled by
24
+ // default; sources may also come back in a search call's `action.sources`.
25
+
26
+ const XAI_RESPONSES_URL = "https://api.x.ai/v1/responses";
27
+ const CONFIG_PATH = getWebSearchConfigPath();
28
+ const DEFAULT_SEARCH_TIMEOUT_MS = 60_000;
29
+ const MAX_SEARCH_TIMEOUT_MS = 600_000;
30
+
31
+ // Ordered best-first. pi's builtin xai catalog is small and xAI retires models
32
+ // briskly, so this is a preference list, not an assumption: the first one the
33
+ // registry actually knows wins, and an unknown id is skipped rather than sent.
34
+ // xAI's current X Search docs use grok-4.6. Keep the existing web-only default
35
+ // unchanged, while preferring the documented model when X Search is opted in.
36
+ const WEB_SEARCH_AUTH_MODEL_CANDIDATES = ["grok-4.5", "grok-4.3", "grok-build-0.1"] as const;
37
+ const X_SEARCH_AUTH_MODEL_CANDIDATES = ["grok-4.6", ...WEB_SEARCH_AUTH_MODEL_CANDIDATES] as const;
38
+
39
+ type XaiSearchTool = "web_search" | "x_search";
40
+ const DEFAULT_XAI_SEARCH_TOOLS = ["web_search"] as const satisfies readonly XaiSearchTool[];
41
+
42
+ interface WebSearchConfig {
43
+ xaiApiKey?: unknown;
44
+ xaiResponsesUrl?: unknown;
45
+ xaiSearchModel?: unknown;
46
+ xaiSearchTimeoutMs?: unknown;
47
+ xaiSearchTools?: unknown;
48
+ }
49
+
50
+ type ProviderHeaders = Record<string, string | null>;
51
+
52
+ interface XaiAuth {
53
+ apiKey: string;
54
+ model: string;
55
+ headers: ProviderHeaders;
56
+ }
57
+
58
+ let cachedConfig: WebSearchConfig | null = null;
59
+
60
+ function loadConfig(): WebSearchConfig {
61
+ if (cachedConfig) return cachedConfig;
62
+ if (!existsSync(CONFIG_PATH)) {
63
+ cachedConfig = {};
64
+ return cachedConfig;
65
+ }
66
+
67
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
68
+ try {
69
+ cachedConfig = JSON.parse(raw) as WebSearchConfig;
70
+ return cachedConfig;
71
+ } catch (err) {
72
+ const message = err instanceof Error ? err.message : String(err);
73
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
74
+ }
75
+ }
76
+
77
+ function resolveConfiguredSearchModel(value: unknown): string | undefined {
78
+ if (value == null) return undefined;
79
+ if (typeof value !== "string" || value.trim().length === 0) {
80
+ throw new Error(`xaiSearchModel in ${CONFIG_PATH} must be a non-empty string`);
81
+ }
82
+ return value.trim();
83
+ }
84
+
85
+ // A custom endpoint (for example a gateway relaying to a Grok subscription)
86
+ // only ever receives the configured xAI API key, never Pi's xAI sign-in.
87
+ function resolveConfiguredResponsesUrl(value: unknown): string | undefined {
88
+ if (value === undefined) return undefined;
89
+ if (typeof value !== "string" || value.trim().length === 0) {
90
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH} must be an absolute http(s) URL`);
91
+ }
92
+ let url: URL;
93
+ try {
94
+ url = new URL(value.trim());
95
+ } catch {
96
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH} must be an absolute http(s) URL`);
97
+ }
98
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
99
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH} must use http or https`);
100
+ }
101
+ return url.toString();
102
+ }
103
+
104
+ function resolveConfiguredSearchTimeoutMs(value: unknown): number {
105
+ if (value === undefined) return DEFAULT_SEARCH_TIMEOUT_MS;
106
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
107
+ throw new Error(`xaiSearchTimeoutMs in ${CONFIG_PATH} must be a positive integer`);
108
+ }
109
+ return Math.min(value, MAX_SEARCH_TIMEOUT_MS);
110
+ }
111
+
112
+ function resolveConfiguredSearchTools(value: unknown): XaiSearchTool[] {
113
+ if (value === undefined) return [...DEFAULT_XAI_SEARCH_TOOLS];
114
+ if (!Array.isArray(value) || value.length === 0) {
115
+ throw new Error(`xaiSearchTools in ${CONFIG_PATH} must be a non-empty array containing only web_search or x_search`);
116
+ }
117
+
118
+ const tools: XaiSearchTool[] = [];
119
+ for (const tool of value) {
120
+ if (tool !== "web_search" && tool !== "x_search") {
121
+ throw new Error(`xaiSearchTools in ${CONFIG_PATH} may only contain web_search or x_search`);
122
+ }
123
+ if (tools.includes(tool)) {
124
+ throw new Error(`xaiSearchTools in ${CONFIG_PATH} must not contain duplicates: ${tool}`);
125
+ }
126
+ tools.push(tool);
127
+ }
128
+ return tools;
129
+ }
130
+
131
+ function modelCandidatesForTools(tools: readonly XaiSearchTool[]): readonly string[] {
132
+ return tools.includes("x_search") ? X_SEARCH_AUTH_MODEL_CANDIDATES : WEB_SEARCH_AUTH_MODEL_CANDIDATES;
133
+ }
134
+
135
+ function toRequestHeaders(headers: ProviderHeaders): Record<string, string> {
136
+ const requestHeaders: Record<string, string> = {};
137
+ for (const [name, value] of Object.entries(headers)) {
138
+ if (value !== null) requestHeaders[name] = value;
139
+ }
140
+ return requestHeaders;
141
+ }
142
+
143
+ /**
144
+ * Resolve auth from pi's model registry first, so a Grok subscription pays for
145
+ * its own searches and no api key has to be configured at all. Mirrors how the
146
+ * OpenAI backend picks up a Codex sign-in.
147
+ */
148
+ async function resolvePiAuth(
149
+ ctx: ExtensionContext,
150
+ modelOverride: string | undefined,
151
+ tools: readonly XaiSearchTool[],
152
+ ): Promise<XaiAuth | undefined> {
153
+ for (const modelId of modelCandidatesForTools(tools)) {
154
+ try {
155
+ const model = ctx.modelRegistry.find("xai", modelId);
156
+ if (!model) continue;
157
+ const resolved = await ctx.modelRegistry.getApiKeyAndHeaders(model);
158
+ if (resolved.ok && resolved.apiKey) {
159
+ return { apiKey: resolved.apiKey, model: modelOverride ?? modelId, headers: resolved.headers ?? {} };
160
+ }
161
+ } catch {
162
+ }
163
+ }
164
+ return undefined;
165
+ }
166
+
167
+ export async function resolveXaiAuth(ctx?: ExtensionContext, signal?: AbortSignal, model?: string): Promise<XaiAuth | undefined> {
168
+ const config = loadConfig();
169
+ const modelOverride = model ?? resolveConfiguredSearchModel(config.xaiSearchModel);
170
+ const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
171
+ if (ctx && resolveConfiguredResponsesUrl(config.xaiResponsesUrl) === undefined) {
172
+ const auth = await resolvePiAuth(ctx, modelOverride, tools);
173
+ if (auth) return auth;
174
+ }
175
+
176
+ const hasSource = hasCredentialSource({
177
+ provider: "xAI",
178
+ configuredValue: config.xaiApiKey,
179
+ environmentValue: process.env.XAI_API_KEY,
180
+ });
181
+ if (!hasSource) return undefined;
182
+ const apiKey = await resolveCredential({
183
+ provider: "xAI",
184
+ configuredValue: config.xaiApiKey,
185
+ environmentValue: process.env.XAI_API_KEY,
186
+ signal,
187
+ });
188
+ return apiKey ? { apiKey, model: modelOverride ?? modelCandidatesForTools(tools)[0], headers: {} } : undefined;
189
+ }
190
+
191
+ export async function isXaiSearchAvailable(ctx?: ExtensionContext): Promise<boolean> {
192
+ let config: WebSearchConfig;
193
+ let tools: XaiSearchTool[];
194
+ let customUrl: string | undefined;
195
+ try {
196
+ config = loadConfig();
197
+ tools = resolveConfiguredSearchTools(config.xaiSearchTools);
198
+ customUrl = resolveConfiguredResponsesUrl(config.xaiResponsesUrl);
199
+ resolveConfiguredSearchTimeoutMs(config.xaiSearchTimeoutMs);
200
+ } catch {
201
+ return false;
202
+ }
203
+ if (ctx && customUrl === undefined && await resolvePiAuth(ctx, undefined, tools)) return true;
204
+ return hasCredentialSource({
205
+ provider: "xAI",
206
+ configuredValue: config.xaiApiKey,
207
+ environmentValue: process.env.XAI_API_KEY,
208
+ });
209
+ }
210
+
211
+ /**
212
+ * Recency, result count and domain filters are folded into the prompt rather
213
+ * than sent as tool parameters. xAI's filter field names are not verified, and
214
+ * an unknown field risks a 400 that costs the whole search; steering through
215
+ * the instruction text degrades to "the model ignored it" instead.
216
+ */
217
+ function buildInput(query: string, options: SearchOptions, tools: readonly XaiSearchTool[]): string {
218
+ let searchInstruction: string;
219
+ if (tools.includes("x_search") && tools.includes("web_search")) {
220
+ searchInstruction = "Search the web and X and answer using only what the search results say.";
221
+ } else if (tools.includes("x_search")) {
222
+ searchInstruction = "Search X and answer using only what the X results say.";
223
+ } else {
224
+ searchInstruction = "Search the web and answer using only what the web results say.";
225
+ }
226
+ const lines = [
227
+ searchInstruction,
228
+ "Cite your sources inline.",
229
+ ];
230
+
231
+ if (options.recencyFilter) {
232
+ const labels: Record<string, string> = {
233
+ day: "past 24 hours",
234
+ week: "past week",
235
+ month: "past month",
236
+ year: "past year",
237
+ };
238
+ lines.push(`Prefer sources from the ${labels[options.recencyFilter]}.`);
239
+ }
240
+
241
+ if (typeof options.numResults === "number" && Number.isFinite(options.numResults) && options.numResults > 0) {
242
+ lines.push(`Prefer around ${Math.min(Math.floor(options.numResults), 20)} distinct sources.`);
243
+ }
244
+
245
+ const allowed: string[] = [];
246
+ const blocked: string[] = [];
247
+ for (const raw of options.domainFilter ?? []) {
248
+ const domain = normalizeDomain(raw);
249
+ if (!domain) continue;
250
+ const target = raw.trim().startsWith("-") ? blocked : allowed;
251
+ if (!target.includes(domain)) target.push(domain);
252
+ }
253
+ if (allowed.length > 0) lines.push(`Only use sources from: ${allowed.slice(0, 100).join(", ")}.`);
254
+ if (blocked.length > 0) lines.push(`Do not use sources from: ${blocked.slice(0, 100).join(", ")}.`);
255
+
256
+ return `${lines.join(" ")}\n\n${query}`;
257
+ }
258
+
259
+ function addResult(results: SearchResult[], seen: Set<string>, url: unknown, title: unknown, snippet = "", generated = false): void {
260
+ if (typeof url !== "string" || url.trim().length === 0) return;
261
+ if (seen.has(url)) return;
262
+ seen.add(url);
263
+ results.push({
264
+ title: typeof title === "string" && title.trim().length > 0 ? title : url,
265
+ url,
266
+ snippet,
267
+ ...(generated && snippet ? { snippetSource: "generated" as const } : {}),
268
+ });
269
+ }
270
+
271
+ function addSource(results: SearchResult[], seen: Set<string>, source: unknown): void {
272
+ if (typeof source === "string") {
273
+ addResult(results, seen, source, undefined);
274
+ return;
275
+ }
276
+ if (!source || typeof source !== "object") return;
277
+ const record = source as Record<string, unknown>;
278
+ addResult(results, seen, record.url ?? record.source_website_url, record.title ?? record.caption);
279
+ }
280
+
281
+ function addSources(results: SearchResult[], seen: Set<string>, sources: unknown): void {
282
+ if (!Array.isArray(sources)) return;
283
+ for (const source of sources) addSource(results, seen, source);
284
+ }
285
+
286
+ function extractSnippetAround(text: string, start: unknown, end: unknown): string {
287
+ if (typeof start !== "number" || typeof end !== "number" || !text) return "";
288
+ const before = Math.max(0, start - 100);
289
+ const after = Math.min(text.length, end + 100);
290
+ const snippet = text.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
291
+ return snippet.length > 300 ? `${snippet.slice(0, 297)}...` : snippet;
292
+ }
293
+
294
+ function extractAnswer(output: unknown[]): string {
295
+ const parts: string[] = [];
296
+ for (const item of output) {
297
+ if (!item || typeof item !== "object" || (item as { type?: unknown }).type !== "message") continue;
298
+ const content = (item as { content?: unknown }).content;
299
+ if (!Array.isArray(content)) continue;
300
+ for (const part of content) {
301
+ if (!part || typeof part !== "object") continue;
302
+ const text = (part as { text?: unknown }).text;
303
+ if (typeof text === "string" && text.trim().length > 0) parts.push(text);
304
+ }
305
+ }
306
+ return parts.join("\n").trim();
307
+ }
308
+
309
+ /**
310
+ * Keep annotation sources first because they carry titles and offsets and must
311
+ * win URL deduplication. Raw source lists from web/X search calls are next,
312
+ * followed by xAI's response-level `citations` URL list. The latter is usually
313
+ * strings, but object entries are tolerated when a compatible gateway adds
314
+ * metadata.
315
+ */
316
+ function extractSearchResults(output: unknown[], citations: unknown, numResults: number | undefined): SearchResult[] {
317
+ const results: SearchResult[] = [];
318
+ const seenUrls = new Set<string>();
319
+
320
+ for (const item of output) {
321
+ if (!item || typeof item !== "object" || (item as { type?: unknown }).type !== "message") continue;
322
+ const content = (item as { content?: unknown }).content;
323
+ if (!Array.isArray(content)) continue;
324
+ for (const part of content) {
325
+ if (!part || typeof part !== "object") continue;
326
+ const text = typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "";
327
+ const annotations = (part as { annotations?: unknown }).annotations;
328
+ if (!Array.isArray(annotations)) continue;
329
+ for (const annotation of annotations) {
330
+ if (!annotation || typeof annotation !== "object") continue;
331
+ if ((annotation as { type?: unknown }).type !== "url_citation") continue;
332
+ addResult(
333
+ results,
334
+ seenUrls,
335
+ (annotation as { url?: unknown }).url,
336
+ (annotation as { title?: unknown }).title,
337
+ extractSnippetAround(text, (annotation as { start_index?: unknown }).start_index, (annotation as { end_index?: unknown }).end_index),
338
+ true,
339
+ );
340
+ }
341
+ }
342
+ }
343
+
344
+ for (const item of output) {
345
+ if (!item || typeof item !== "object") continue;
346
+ const type = (item as { type?: unknown }).type;
347
+ if (type !== "web_search_call" && type !== "x_search_call") continue;
348
+ const value = item as { action?: unknown; sources?: unknown; results?: unknown };
349
+ const actionSources = value.action && typeof value.action === "object"
350
+ ? (value.action as { sources?: unknown }).sources
351
+ : undefined;
352
+ for (const group of [actionSources, value.sources, value.results]) addSources(results, seenUrls, group);
353
+ }
354
+
355
+ addSources(results, seenUrls, citations);
356
+
357
+ if (typeof numResults === "number" && Number.isFinite(numResults) && numResults > 0) {
358
+ return results.slice(0, Math.min(Math.floor(numResults), 20));
359
+ }
360
+ return results;
361
+ }
362
+
363
+ export async function searchWithXai(
364
+ query: string,
365
+ options: SearchOptions = {},
366
+ ctx?: ExtensionContext,
367
+ ): Promise<SearchResponse> {
368
+ const config = loadConfig();
369
+ const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
370
+ const customUrl = resolveConfiguredResponsesUrl(config.xaiResponsesUrl);
371
+ const timeoutMs = resolveConfiguredSearchTimeoutMs(config.xaiSearchTimeoutMs);
372
+ const auth = await resolveXaiAuth(ctx, options.signal, options.model);
373
+ if (!auth) {
374
+ if (customUrl) {
375
+ throw new Error(
376
+ `xAI search unavailable: xaiResponsesUrl is set, so Pi's xAI sign-in is not used. ` +
377
+ `Set xaiApiKey in ${CONFIG_PATH} or the XAI_API_KEY environment variable to the key for that endpoint.`,
378
+ );
379
+ }
380
+ throw new Error(
381
+ "xAI search unavailable. Either:\n" +
382
+ " 1. Use /login to sign in with a SuperGrok or X Premium subscription\n" +
383
+ ` 2. Create ${CONFIG_PATH} with { "xaiApiKey": "your-key" }\n` +
384
+ " 3. Set XAI_API_KEY environment variable",
385
+ );
386
+ }
387
+
388
+ const activityId = activityMonitor.logStart({ type: "api", query });
389
+ try {
390
+ const response = await fetch(customUrl ?? XAI_RESPONSES_URL, {
391
+ method: "POST",
392
+ headers: {
393
+ ...toRequestHeaders(auth.headers),
394
+ Authorization: `Bearer ${auth.apiKey}`,
395
+ "Content-Type": "application/json",
396
+ },
397
+ body: JSON.stringify({
398
+ model: auth.model,
399
+ input: buildInput(query, options, tools),
400
+ tools: tools.map((type) => ({ type })),
401
+ }),
402
+ signal: options.signal
403
+ ? AbortSignal.any([AbortSignal.timeout(timeoutMs), options.signal])
404
+ : AbortSignal.timeout(timeoutMs),
405
+ });
406
+
407
+ if (!response.ok) {
408
+ activityMonitor.logError(activityId, `HTTP ${response.status}`);
409
+ const errorText = redactCredential(await response.text(), auth.apiKey);
410
+ throw new Error(`xAI API error ${response.status}: ${errorText.slice(0, 300)}`);
411
+ }
412
+
413
+ let parsed: Record<string, unknown>;
414
+ try {
415
+ parsed = await response.json() as Record<string, unknown>;
416
+ } catch (err) {
417
+ const message = err instanceof Error ? err.message : String(err);
418
+ throw new Error(`xAI API returned invalid JSON: ${message}`);
419
+ }
420
+ const output = Array.isArray(parsed.output) ? parsed.output : [];
421
+ const answer = extractAnswer(output);
422
+ const results = extractSearchResults(output, parsed.citations, options.numResults);
423
+
424
+ if (!answer && results.length === 0) {
425
+ throw new Error(`xAI ${tools.join("+")} returned no answer or sources`);
426
+ }
427
+
428
+ activityMonitor.logComplete(activityId, response.status);
429
+ return { answer, results };
430
+ } catch (err) {
431
+ const message = err instanceof Error ? err.message : String(err);
432
+ const redactedMessage = redactCredential(message, auth.apiKey);
433
+ if (redactedMessage.toLowerCase().includes("abort")) {
434
+ activityMonitor.logComplete(activityId, 0);
435
+ } else {
436
+ activityMonitor.logError(activityId, redactedMessage);
437
+ }
438
+ if (redactedMessage === message) throw err;
439
+ const redactedError = new Error(redactedMessage);
440
+ if (err instanceof Error) redactedError.name = err.name;
441
+ throw redactedError;
442
+ }
443
+ }
package/you.ts ADDED
@@ -0,0 +1,165 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
4
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
5
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
6
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
7
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
9
+
10
+ const YOU_SEARCH_URL = "https://ydc-index.io/v1/search";
11
+ const CONFIG_PATH = getWebSearchConfigPath();
12
+ const SEARCH_TIMEOUT_MS = 60_000;
13
+
14
+ interface WebSearchConfig {
15
+ youBaseUrl?: unknown;
16
+ youApiKey?: unknown;
17
+ }
18
+
19
+ let cachedConfig: WebSearchConfig | null = null;
20
+
21
+ function loadConfig(): WebSearchConfig {
22
+ if (cachedConfig) return cachedConfig;
23
+ if (!existsSync(CONFIG_PATH)) {
24
+ cachedConfig = {};
25
+ return cachedConfig;
26
+ }
27
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
28
+ let parsed: unknown;
29
+ try {
30
+ parsed = JSON.parse(raw);
31
+ } catch (err) {
32
+ const message = err instanceof Error ? err.message : String(err);
33
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
34
+ }
35
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
36
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
37
+ }
38
+ cachedConfig = parsed as WebSearchConfig;
39
+ return cachedConfig;
40
+ }
41
+
42
+ async function requireApiKey(signal?: AbortSignal): Promise<string> {
43
+ const apiKey = await resolveCredential({
44
+ provider: "You.com",
45
+ configuredValue: loadConfig().youApiKey,
46
+ environmentValue: process.env.YDC_API_KEY,
47
+ signal,
48
+ });
49
+ if (!apiKey) {
50
+ throw new Error(
51
+ "You.com API key not found. Either:\n" +
52
+ ` 1. Create ${CONFIG_PATH} with { "youApiKey": "your-key" }\n` +
53
+ " 2. Set YDC_API_KEY environment variable\n" +
54
+ "Get a key at https://you.com/platform/api-keys",
55
+ );
56
+ }
57
+ return apiKey;
58
+ }
59
+
60
+ function mapDomainFilter(domainFilter: string[] | undefined): { include_domains?: string[]; exclude_domains?: string[] } {
61
+ const include_domains: string[] = [];
62
+ const exclude_domains: string[] = [];
63
+ for (const raw of domainFilter ?? []) {
64
+ const domain = normalizeDomain(raw);
65
+ if (!domain) continue;
66
+ const target = raw.trim().startsWith("-") ? exclude_domains : include_domains;
67
+ if (!target.includes(domain)) target.push(domain);
68
+ }
69
+ return {
70
+ ...(include_domains.length > 0 ? { include_domains } : {}),
71
+ ...(exclude_domains.length > 0 ? { exclude_domains } : {}),
72
+ };
73
+ }
74
+
75
+ function errorMessage(err: unknown): string {
76
+ return err instanceof Error ? err.message : String(err);
77
+ }
78
+
79
+ function parseWebResults(value: unknown): unknown[] {
80
+ const results = value && typeof value === "object" ? (value as { results?: unknown }).results : undefined;
81
+ const web = results && typeof results === "object" ? (results as { web?: unknown }).web : undefined;
82
+ if (!Array.isArray(web)) throw new Error("You.com returned invalid response: expected results.web array");
83
+ return web;
84
+ }
85
+
86
+ export function isYouAvailable(): boolean {
87
+ return hasCredentialSource({ provider: "You.com", configuredValue: loadConfig().youApiKey, environmentValue: process.env.YDC_API_KEY });
88
+ }
89
+
90
+ export async function searchWithYou(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
91
+ const apiKey = await requireApiKey(options.signal);
92
+ const numResults = normalizeSearchResultCount(options.numResults);
93
+ const body = {
94
+ query,
95
+ count: numResults,
96
+ ...(options.recencyFilter ? { freshness: options.recencyFilter } : {}),
97
+ ...mapDomainFilter(options.domainFilter),
98
+ };
99
+ const activityId = activityMonitor.logStart({ type: "api", query });
100
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
101
+ let response: Response;
102
+ let entries: unknown[];
103
+ try {
104
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("you", YOU_SEARCH_URL, loadConfig().youBaseUrl), {
105
+ method: "POST",
106
+ headers: { Accept: "application/json", "Content-Type": "application/json", "X-API-Key": apiKey },
107
+ body: JSON.stringify(body),
108
+ signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal,
109
+ }, ["X-API-Key"]);
110
+ if (!response.ok) {
111
+ const errorText = await response.text();
112
+ throw new Error(`You.com error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
113
+ }
114
+ let rawData: unknown;
115
+ try {
116
+ rawData = await response.json();
117
+ } catch (err) {
118
+ if (err instanceof Error && err.name === "TimeoutError") throw err;
119
+ throw new Error(`You.com returned invalid JSON: ${errorMessage(err)}`);
120
+ }
121
+ entries = parseWebResults(rawData);
122
+ } catch (err) {
123
+ if (options.signal?.aborted) {
124
+ activityMonitor.logComplete(activityId, 0);
125
+ throw new Error("Aborted");
126
+ }
127
+ const message = errorMessage(err);
128
+ const providerTimeout = timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError");
129
+ const outgoing = providerTimeout
130
+ ? new Error(`You.com request timed out after ${Math.round(SEARCH_TIMEOUT_MS / 1000)}s`)
131
+ : (() => {
132
+ const redactedMessage = redactCredential(message, apiKey);
133
+ if (redactedMessage === message && err instanceof Error) return err;
134
+ const redactedError = new Error(redactedMessage);
135
+ if (err instanceof Error) redactedError.name = err.name;
136
+ return redactedError;
137
+ })();
138
+ activityMonitor.logError(activityId, redactCredential(errorMessage(outgoing), apiKey));
139
+ throw outgoing;
140
+ }
141
+ activityMonitor.logComplete(activityId, response.status);
142
+ const results: SearchResponse["results"] = [];
143
+ for (const entry of entries) {
144
+ if (!entry || typeof entry !== "object") continue;
145
+ const { url, title, description, snippets } = entry as Record<string, unknown>;
146
+ if (typeof url !== "string" || !url) continue;
147
+ let resultUrl: URL;
148
+ try {
149
+ resultUrl = new URL(url);
150
+ } catch {
151
+ continue;
152
+ }
153
+ if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
154
+ const snippet = typeof description === "string" && description.trim()
155
+ ? description
156
+ : Array.isArray(snippets) && typeof snippets[0] === "string" ? snippets[0] : "";
157
+ results.push({
158
+ title: typeof title === "string" && title.trim() ? title.trim() : `Source ${results.length + 1}`,
159
+ url: resultUrl.href,
160
+ snippet,
161
+ });
162
+ if (results.length >= numResults) break;
163
+ }
164
+ return { answer: formatSearchResultsAsAnswer(results), results };
165
+ }