@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,855 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { activityMonitor } from "./activity.ts";
5
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
6
+ import type { SearchOptions, SearchResponse, SearchResult } from "./perplexity.ts";
7
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath } from "./utils.ts";
9
+
10
+ const OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
11
+ const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+ const SEARCH_TIMEOUT_MS = 60_000;
14
+
15
+ // The selected model runs the server-side web_search call and writes the cited summary.
16
+ // Prefer the newest low-cost ("luna") model, then the newest bare mainline id, then any
17
+ // other versioned GPT id (gateway providers such as opencode-go list only suffixed GPT
18
+ // ids next to non-OpenAI models; unversioned ids such as gpt-oss-* are skipped); price
19
+ // tiers ("pro"/"ultra" id segments) are excluded, and the numeric-aware sort keeps
20
+ // e.g. gpt-5.10 ahead of gpt-5.9.
21
+ const EXCLUDED_MODEL_SEGMENTS = new Set(["pro", "ultra"]);
22
+ const MODEL_PREFERENCE = [
23
+ (id: string) => id.includes("luna"),
24
+ (id: string) => /^gpt-\d+(\.\d+)?$/.test(id),
25
+ (id: string) => /^gpt-\d/.test(id),
26
+ ];
27
+ const DEFAULT_SEARCH_PROVIDERS: readonly string[] = ["openai-codex", "openai"];
28
+
29
+ function pickSearchModel<T extends { id: string }>(models: readonly T[]): T | undefined {
30
+ const candidates = models
31
+ .filter((model) => !model.id.split("-").some((segment) => EXCLUDED_MODEL_SEGMENTS.has(segment)))
32
+ .sort((a, b) => b.id.localeCompare(a.id, undefined, { numeric: true }));
33
+ for (const prefers of MODEL_PREFERENCE) {
34
+ const preferred = candidates.find((model) => prefers(model.id));
35
+ if (preferred) return preferred;
36
+ }
37
+ return candidates[0];
38
+ }
39
+
40
+ interface WebSearchConfig {
41
+ openaiApiKey?: unknown;
42
+ openaiResponsesUrl?: unknown;
43
+ openaiUseProviderBaseUrl?: unknown;
44
+ openaiUseAlphaSearch?: unknown;
45
+ openaiSearchModel?: unknown;
46
+ openaiSearchProviders?: unknown;
47
+ }
48
+
49
+ type ProviderHeaders = Record<string, string | null>;
50
+
51
+ class CustomOpenAIBaseUrlError extends Error {}
52
+
53
+ export class OpenAIAlphaSearchUnsupportedError extends Error {}
54
+
55
+ interface OpenAIAuth {
56
+ provider: string;
57
+ apiKey: string;
58
+ model: string;
59
+ headers: ProviderHeaders;
60
+ responsesUrl: string;
61
+ useCodexEndpoint?: boolean;
62
+ useProviderBaseUrl?: boolean;
63
+ }
64
+
65
+ type CurrentModel = NonNullable<ExtensionContext["model"]>;
66
+
67
+ interface CurrentModelSearchTarget {
68
+ responsesUrl: string;
69
+ useCodexEndpoint: boolean;
70
+ }
71
+
72
+ function isAzureResponsesUrl(url: URL): boolean {
73
+ return url.protocol === "https:" &&
74
+ [".openai.azure.com", ".cognitiveservices.azure.com", ".services.ai.azure.com"].some((suffix) => url.hostname.endsWith(suffix)) &&
75
+ /^\/openai\/v1(?:\/responses)?\/?$/u.test(url.pathname);
76
+ }
77
+
78
+ function resolveCurrentModelSearchTarget(model: CurrentModel): CurrentModelSearchTarget {
79
+ const url = new URL(model.baseUrl);
80
+ if (url.protocol !== "https:") throw new Error("Current model base URL must use HTTPS");
81
+
82
+ if (model.provider === "openai" && model.api === "openai-responses" && url.hostname.toLowerCase() === "api.openai.com") {
83
+ const pathname = url.pathname.replace(/\/+$/u, "");
84
+ url.pathname = `${pathname}/responses`;
85
+ return { responsesUrl: url.toString(), useCodexEndpoint: false };
86
+ }
87
+
88
+ if (
89
+ model.provider === "openai-codex" &&
90
+ model.api === "openai-codex-responses" &&
91
+ url.hostname.toLowerCase() === "chatgpt.com" &&
92
+ url.pathname.replace(/\/+$/u, "") === "/backend-api"
93
+ ) {
94
+ return { responsesUrl: CODEX_RESPONSES_URL, useCodexEndpoint: true };
95
+ }
96
+
97
+ if ((model.api === "openai-responses" || model.api === "azure-openai-responses") && isAzureResponsesUrl(url)) {
98
+ url.pathname = "/openai/v1/responses";
99
+ return { responsesUrl: url.toString(), useCodexEndpoint: false };
100
+ }
101
+
102
+ throw new Error("Current model is not backed by an official OpenAI or Azure Responses endpoint");
103
+ }
104
+
105
+ // The active model draws on a ChatGPT subscription: openai-codex, or openai signed in
106
+ // through Pi's "Sign in with ChatGPT" OAuth rather than an API key.
107
+ export function isOpenAISubscriptionModelSelected(ctx?: Pick<ExtensionContext, "model"> & { modelRegistry?: Pick<ExtensionContext["modelRegistry"], "isUsingOAuth"> }): boolean {
108
+ const model = ctx?.model;
109
+ if (model?.provider === "openai-codex") return true;
110
+ return model?.provider === "openai" && ctx?.modelRegistry?.isUsingOAuth?.(model) === true;
111
+ }
112
+
113
+ export function isCurrentModelHostedSearchEligible(ctx?: Pick<ExtensionContext, "model">): boolean {
114
+ const model = ctx?.model;
115
+ if (!model) return false;
116
+ try {
117
+ resolveCurrentModelSearchTarget(model);
118
+ // Azure model IDs are deployment names, which need not use a GPT prefix.
119
+ return /^gpt-/iu.test(model.id) || isAzureResponsesUrl(new URL(model.baseUrl));
120
+ } catch {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ interface NormalizedDomainFilters {
126
+ allowedDomains?: string[];
127
+ blockedDomains?: string[];
128
+ }
129
+
130
+ let cachedConfig: WebSearchConfig | null = null;
131
+
132
+ function loadConfig(): WebSearchConfig {
133
+ if (cachedConfig) return cachedConfig;
134
+ if (!existsSync(CONFIG_PATH)) {
135
+ cachedConfig = {};
136
+ return cachedConfig;
137
+ }
138
+
139
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
140
+ try {
141
+ cachedConfig = JSON.parse(raw) as WebSearchConfig;
142
+ return cachedConfig;
143
+ } catch (err) {
144
+ const message = err instanceof Error ? err.message : String(err);
145
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
146
+ }
147
+ }
148
+
149
+ function normalizeDomainFilters(domainFilter: string[] | undefined): NormalizedDomainFilters | null {
150
+ if (!domainFilter?.length) return null;
151
+
152
+ const allowedDomains: string[] = [];
153
+ const blockedDomains: string[] = [];
154
+ for (const raw of domainFilter) {
155
+ const domain = normalizeDomain(raw);
156
+ if (!domain) continue;
157
+ const target = raw.trim().startsWith("-") ? blockedDomains : allowedDomains;
158
+ if (!target.includes(domain)) target.push(domain);
159
+ }
160
+
161
+ return allowedDomains.length > 0 || blockedDomains.length > 0
162
+ ? {
163
+ ...(allowedDomains.length > 0 ? { allowedDomains: allowedDomains.slice(0, 100) } : {}),
164
+ ...(blockedDomains.length > 0 ? { blockedDomains: blockedDomains.slice(0, 100) } : {}),
165
+ }
166
+ : null;
167
+ }
168
+
169
+ function decodeJwtPayload(token: string): Record<string, unknown> | null {
170
+ const parts = token.split(".");
171
+ if (parts.length !== 3 || !parts[1]) return null;
172
+ try {
173
+ const padded = parts[1].replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(parts[1].length / 4) * 4, "=");
174
+ const parsed = JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
175
+ return parsed && typeof parsed === "object" ? parsed as Record<string, unknown> : null;
176
+ } catch {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ function isCodexJwt(token: string): boolean {
182
+ const payload = decodeJwtPayload(token);
183
+ return !!payload?.["https://api.openai.com/auth"];
184
+ }
185
+
186
+ function isOfficialOpenAIBaseUrl(baseUrl: string | undefined): boolean {
187
+ if (baseUrl === undefined) return false;
188
+ try {
189
+ return new URL(baseUrl).toString().replace(/\/+$/u, "") === "https://api.openai.com/v1";
190
+ } catch {
191
+ return false;
192
+ }
193
+ }
194
+
195
+ function extractAccountId(token: string): string | undefined {
196
+ const payload = decodeJwtPayload(token);
197
+ const auth = payload?.["https://api.openai.com/auth"];
198
+ if (!auth || typeof auth !== "object") return undefined;
199
+ const id = (auth as Record<string, unknown>).chatgpt_account_id;
200
+ return typeof id === "string" && id.trim().length > 0 ? id.trim() : undefined;
201
+ }
202
+
203
+ function resolveConfiguredResponsesUrl(value: unknown): string {
204
+ if (value === undefined) return OPENAI_RESPONSES_URL;
205
+ if (typeof value !== "string" || value.trim().length === 0) {
206
+ throw new Error(`openaiResponsesUrl in ${CONFIG_PATH} must be an absolute http(s) URL`);
207
+ }
208
+ let url: URL;
209
+ try {
210
+ url = new URL(value.trim());
211
+ } catch {
212
+ throw new Error(`openaiResponsesUrl in ${CONFIG_PATH} must be an absolute http(s) URL`);
213
+ }
214
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
215
+ throw new Error(`openaiResponsesUrl in ${CONFIG_PATH} must use http or https`);
216
+ }
217
+ if (url.hostname === "opencode.ai" && url.protocol !== "https:") {
218
+ throw new Error(`openaiResponsesUrl in ${CONFIG_PATH} must use HTTPS for opencode.ai`);
219
+ }
220
+ return url.toString();
221
+ }
222
+
223
+ function resolveUseProviderBaseUrl(config: WebSearchConfig): boolean {
224
+ if (config.openaiResponsesUrl !== undefined) return false;
225
+ const value = config.openaiUseProviderBaseUrl;
226
+ if (value === undefined) return false;
227
+ if (typeof value !== "boolean") {
228
+ throw new Error(`openaiUseProviderBaseUrl in ${CONFIG_PATH} must be a boolean`);
229
+ }
230
+ return value;
231
+ }
232
+
233
+ function resolveProviderResponsesUrl(baseUrl: unknown, useCodexEndpoint: boolean): string {
234
+ let url: URL;
235
+ try {
236
+ if (typeof baseUrl !== "string" || !baseUrl.trim()) throw new Error();
237
+ url = new URL(baseUrl.trim());
238
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
239
+ } catch {
240
+ throw new CustomOpenAIBaseUrlError("OpenAI search configuration: openaiUseProviderBaseUrl requires an absolute http(s) provider baseUrl");
241
+ }
242
+ if (url.hostname === "opencode.ai" && url.protocol !== "https:") {
243
+ throw new CustomOpenAIBaseUrlError("OpenAI search configuration: opencode.ai provider baseUrl must use HTTPS");
244
+ }
245
+ const path = url.pathname.replace(/\/+$/u, "");
246
+ if (path.endsWith("/responses")) {
247
+ url.pathname = path;
248
+ } else if (useCodexEndpoint && url.hostname.toLowerCase() === "chatgpt.com" && path === "/backend-api") {
249
+ url.pathname = "/backend-api/codex/responses";
250
+ } else {
251
+ url.pathname = `${path || "/v1"}/responses`;
252
+ }
253
+ return url.toString();
254
+ }
255
+
256
+ function resolveConfiguredSearchProviders(value: unknown): readonly string[] {
257
+ if (value === undefined) return DEFAULT_SEARCH_PROVIDERS;
258
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.trim().length === 0)) {
259
+ throw new Error(`openaiSearchProviders in ${CONFIG_PATH} must be an array of non-empty Pi provider ids`);
260
+ }
261
+ return value.map((entry) => entry.trim());
262
+ }
263
+
264
+ function resolveConfiguredSearchModel(value: unknown): string | undefined {
265
+ if (value == null) return undefined;
266
+ if (typeof value !== "string" || value.trim().length === 0) {
267
+ throw new Error(`openaiSearchModel in ${CONFIG_PATH} must be a non-empty string`);
268
+ }
269
+ return value.trim();
270
+ }
271
+
272
+ function toRequestHeaders(headers: ProviderHeaders): Record<string, string> {
273
+ const requestHeaders: Record<string, string> = {};
274
+ for (const [name, value] of Object.entries(headers)) {
275
+ if (value !== null) requestHeaders[name] = value;
276
+ }
277
+ return requestHeaders;
278
+ }
279
+
280
+ function applyOpenCodeDestinationHeaders(headers: HeadersInit, requestUrl: string, ctx?: Pick<ExtensionContext, "sessionManager">): Headers {
281
+ const requestHeaders = new Headers(headers);
282
+ requestHeaders.delete("x-opencode-session");
283
+ requestHeaders.delete("x-opencode-client");
284
+ const url = new URL(requestUrl);
285
+ const sessionId = ctx?.sessionManager?.getSessionId?.();
286
+ if (url.protocol === "https:" && url.hostname === "opencode.ai" && sessionId) {
287
+ requestHeaders.set("x-opencode-session", sessionId);
288
+ requestHeaders.set("x-opencode-client", "pi");
289
+ }
290
+ return requestHeaders;
291
+ }
292
+
293
+ async function resolvePiAuth(ctx: ExtensionContext, responsesUrl: string, providers: readonly string[], modelOverride?: string, hasExplicitResponsesUrl = false, useProviderBaseUrl = false): Promise<OpenAIAuth | undefined> {
294
+ let models: ReturnType<typeof ctx.modelRegistry.getAll>;
295
+ let invalidProviderUrlError: CustomOpenAIBaseUrlError | undefined;
296
+ try {
297
+ models = ctx.modelRegistry.getAll();
298
+ } catch {
299
+ return undefined;
300
+ }
301
+ for (const provider of providers) {
302
+ const preferred = pickSearchModel(models.filter((model) => model.provider === provider));
303
+ if (!preferred) continue;
304
+ let resolved: Awaited<ReturnType<typeof ctx.modelRegistry.getApiKeyAndHeaders>>;
305
+ try {
306
+ resolved = await ctx.modelRegistry.getApiKeyAndHeaders(preferred);
307
+ } catch {
308
+ continue;
309
+ }
310
+ if (!resolved.ok || !resolved.apiKey) continue;
311
+ // Auth can override the model's base URL. Do not guess Responses/web_search
312
+ // support from a gateway URL, or pair its credential with the official API.
313
+ const baseUrl = resolved.baseUrl ?? preferred.baseUrl;
314
+ const isOfficialBaseUrl = isOfficialOpenAIBaseUrl(baseUrl);
315
+ // Pi sends credentials for the official API base directly to api.openai.com, including
316
+ // "Sign in with ChatGPT" access tokens, which are ChatGPT JWTs but not Codex credentials.
317
+ const useCodexEndpoint = provider === "openai-codex" || (!isOfficialBaseUrl && isCodexJwt(resolved.apiKey));
318
+ if (!hasExplicitResponsesUrl && !useProviderBaseUrl && !useCodexEndpoint && baseUrl !== undefined && !isOfficialBaseUrl) {
319
+ throw new CustomOpenAIBaseUrlError(`OpenAI web search cannot reuse Pi credentials with a custom baseUrl by default. Set openaiResponsesUrl in ${CONFIG_PATH} to the full Responses endpoint for this credential.`);
320
+ }
321
+ let providerResponsesUrl = responsesUrl;
322
+ if (useProviderBaseUrl) {
323
+ try {
324
+ providerResponsesUrl = resolveProviderResponsesUrl(baseUrl, useCodexEndpoint);
325
+ } catch (err) {
326
+ if (!(err instanceof CustomOpenAIBaseUrlError)) throw err;
327
+ invalidProviderUrlError ??= err;
328
+ continue;
329
+ }
330
+ }
331
+ return {
332
+ provider,
333
+ apiKey: resolved.apiKey,
334
+ model: modelOverride ?? preferred.id,
335
+ headers: resolved.headers ?? {},
336
+ responsesUrl: providerResponsesUrl,
337
+ useCodexEndpoint,
338
+ ...(useProviderBaseUrl ? { useProviderBaseUrl: true } : {}),
339
+ };
340
+ }
341
+ if (invalidProviderUrlError) throw invalidProviderUrlError;
342
+ return undefined;
343
+ }
344
+
345
+ export async function resolveOpenAIAuth(ctx?: ExtensionContext, signal?: AbortSignal, model?: string): Promise<OpenAIAuth | undefined> {
346
+ const config = loadConfig();
347
+ const responsesUrl = resolveConfiguredResponsesUrl(config.openaiResponsesUrl);
348
+ const useProviderBaseUrl = resolveUseProviderBaseUrl(config);
349
+ const modelOverride = model ?? resolveConfiguredSearchModel(config.openaiSearchModel);
350
+ const providers = resolveConfiguredSearchProviders(config.openaiSearchProviders);
351
+ if (ctx) {
352
+ const auth = await resolvePiAuth(ctx, responsesUrl, providers, modelOverride, config.openaiResponsesUrl !== undefined, useProviderBaseUrl);
353
+ if (auth) return auth;
354
+ }
355
+ if (useProviderBaseUrl) {
356
+ throw new CustomOpenAIBaseUrlError("OpenAI search configuration: openaiUseProviderBaseUrl requires selected Pi provider credentials and a baseUrl; set openaiResponsesUrl for standalone API keys");
357
+ }
358
+
359
+ const hasSource = hasCredentialSource({
360
+ provider: "OpenAI",
361
+ configuredValue: config.openaiApiKey,
362
+ environmentValue: process.env.OPENAI_API_KEY,
363
+ });
364
+ if (!hasSource) return undefined;
365
+ const apiKey = await resolveCredential({
366
+ provider: "OpenAI",
367
+ configuredValue: config.openaiApiKey,
368
+ environmentValue: process.env.OPENAI_API_KEY,
369
+ signal,
370
+ });
371
+ return apiKey
372
+ ? { provider: "openai", apiKey, model: modelOverride ?? "gpt-6-luna", headers: {}, responsesUrl }
373
+ : undefined;
374
+ }
375
+
376
+ export async function isOpenAISearchAvailable(ctx?: ExtensionContext): Promise<boolean> {
377
+ const config = loadConfig();
378
+ const responsesUrl = resolveConfiguredResponsesUrl(config.openaiResponsesUrl);
379
+ const useProviderBaseUrl = resolveUseProviderBaseUrl(config);
380
+ const providers = resolveConfiguredSearchProviders(config.openaiSearchProviders);
381
+ try {
382
+ if (ctx && await resolvePiAuth(ctx, responsesUrl, providers, undefined, config.openaiResponsesUrl !== undefined, useProviderBaseUrl)) return true;
383
+ } catch (err) {
384
+ if (err instanceof CustomOpenAIBaseUrlError) return false;
385
+ throw err;
386
+ }
387
+ if (useProviderBaseUrl) return false;
388
+ return hasCredentialSource({
389
+ provider: "OpenAI",
390
+ configuredValue: config.openaiApiKey,
391
+ environmentValue: process.env.OPENAI_API_KEY,
392
+ });
393
+ }
394
+
395
+ async function resolveCurrentModelAuth(ctx: ExtensionContext, signal?: AbortSignal): Promise<OpenAIAuth> {
396
+ const model = ctx.model;
397
+ if (!model || !isCurrentModelHostedSearchEligible(ctx)) {
398
+ throw new Error("Current model is not eligible for OpenAI or Azure hosted web search");
399
+ }
400
+ const resolved = await ctx.modelRegistry.getApiKeyAndHeaders(model);
401
+ if (signal?.aborted) signal.throwIfAborted();
402
+ if (!resolved.ok) throw new Error(`OpenAI current model authentication failed: ${resolved.error}`);
403
+ if (!resolved.apiKey) throw new Error("OpenAI current model authentication failed: API key unavailable");
404
+ // Resolve the destination together with credentials; auth may override baseUrl.
405
+ const target = resolveCurrentModelSearchTarget({ ...model, baseUrl: resolved.baseUrl ?? model.baseUrl });
406
+ return {
407
+ provider: "openai",
408
+ apiKey: resolved.apiKey,
409
+ model: model.id,
410
+ headers: resolved.headers ?? {},
411
+ responsesUrl: target.responsesUrl,
412
+ useCodexEndpoint: target.useCodexEndpoint,
413
+ };
414
+ }
415
+
416
+ function buildInstructions(options: SearchOptions): string {
417
+ const lines = [
418
+ "Search the web and return a concise answer grounded only in the web results.",
419
+ "Include clickable source citations in the response text when possible.",
420
+ ];
421
+
422
+ if (options.recencyFilter) {
423
+ const labels: Record<string, string> = {
424
+ day: "past 24 hours",
425
+ week: "past week",
426
+ month: "past month",
427
+ year: "past year",
428
+ };
429
+ lines.push(`Prefer sources from the ${labels[options.recencyFilter]}.`);
430
+ }
431
+
432
+ if (typeof options.numResults === "number" && Number.isFinite(options.numResults) && options.numResults > 0) {
433
+ lines.push(`Prefer around ${Math.min(Math.floor(options.numResults), 20)} distinct sources.`);
434
+ }
435
+
436
+ const filters = normalizeDomainFilters(options.domainFilter);
437
+ if (filters?.allowedDomains?.length) lines.push(`Only use sources from: ${filters.allowedDomains.join(", ")}.`);
438
+ if (filters?.blockedDomains?.length) lines.push(`Do not use sources from: ${filters.blockedDomains.join(", ")}.`);
439
+
440
+ return lines.join(" ");
441
+ }
442
+
443
+ function buildWebSearchTool(options: SearchOptions): Record<string, unknown> {
444
+ const tool: Record<string, unknown> = { type: "web_search" };
445
+ const filters = normalizeDomainFilters(options.domainFilter);
446
+ if (filters) {
447
+ tool.filters = {
448
+ ...(filters.allowedDomains ? { allowed_domains: filters.allowedDomains } : {}),
449
+ ...(filters.blockedDomains ? { blocked_domains: filters.blockedDomains } : {}),
450
+ };
451
+ }
452
+ return tool;
453
+ }
454
+
455
+ interface ParsedOpenAIResponse {
456
+ payload: Record<string, unknown>;
457
+ webSearchCallSeen: boolean;
458
+ }
459
+
460
+ function isWebSearchCall(item: unknown): boolean {
461
+ return !!item && typeof item === "object" && (item as { type?: unknown }).type === "web_search_call";
462
+ }
463
+
464
+ async function parseOpenAIResponse(response: Response): Promise<ParsedOpenAIResponse> {
465
+ const text = await response.text();
466
+ const trimmed = text.trim();
467
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
468
+ try {
469
+ const parsed = JSON.parse(trimmed);
470
+ const payload = Array.isArray(parsed)
471
+ ? { output: parsed }
472
+ : parsed && typeof parsed === "object" ? parsed as Record<string, unknown> : { output: [] };
473
+ const output = Array.isArray(payload.output) ? payload.output : [];
474
+ return { payload, webSearchCallSeen: output.some(isWebSearchCall) };
475
+ } catch (err) {
476
+ const message = err instanceof Error ? err.message : String(err);
477
+ throw new Error(`OpenAI API returned invalid JSON: ${message}`);
478
+ }
479
+ }
480
+
481
+ const outputItems: unknown[] = [];
482
+ let completedResponse: Record<string, unknown> | null = null;
483
+ let webSearchCallSeen = false;
484
+ let streamError: { code?: unknown; type?: unknown; message?: unknown } | null = null;
485
+ for (const line of text.split("\n")) {
486
+ if (!line.startsWith("data: ")) continue;
487
+ const data = line.slice(6).trim();
488
+ if (!data || data === "[DONE]") continue;
489
+ try {
490
+ const parsed = JSON.parse(data) as Record<string, unknown>;
491
+ // The API can fail mid-stream with HTTP 200: a terminal `error` event and
492
+ // `response.failed` carry the real error (e.g. quota exhaustion), while no
493
+ // output items or completed response ever arrive. Surface it faithfully.
494
+ // `error` events are terminal in the Responses API, so a captured stream
495
+ // error deliberately takes precedence over any output parsed afterwards.
496
+ if (parsed.type === "error") {
497
+ const err = parsed.error;
498
+ streamError ??= err && typeof err === "object"
499
+ ? err as { code?: unknown; type?: unknown; message?: unknown }
500
+ : { code: parsed.code, message: typeof err === "string" ? err : (typeof parsed.message === "string" ? parsed.message : undefined) };
501
+ }
502
+ if (typeof parsed.type === "string" && parsed.type.startsWith("response.web_search_call")) webSearchCallSeen = true;
503
+ if (parsed.type === "response.output_item.done" && parsed.item) {
504
+ outputItems.push(parsed.item);
505
+ webSearchCallSeen ||= isWebSearchCall(parsed.item);
506
+ }
507
+ if ((parsed.type === "response.failed" || parsed.type === "response.incomplete" || parsed.type === "response.done" || parsed.type === "response.completed") && parsed.response && typeof parsed.response === "object") {
508
+ completedResponse = parsed.response as Record<string, unknown>;
509
+ const responseError = (completedResponse as { error?: unknown }).error;
510
+ if (responseError && typeof responseError === "object") {
511
+ streamError ??= responseError as { code?: unknown; type?: unknown; message?: unknown };
512
+ }
513
+ // A failed response can carry `error: null`; never let its partial
514
+ // output pass for a successful search.
515
+ if (parsed.type === "response.failed") {
516
+ // Wording keeps "invalid response" so provider routing classifies
517
+ // this the same as the old "no web_search_call" outcome.
518
+ streamError ??= { message: "response stream failed with no error payload (invalid response)" };
519
+ }
520
+ }
521
+ } catch {
522
+ }
523
+ }
524
+
525
+ if (streamError) {
526
+ const code = typeof streamError.code === "string" ? streamError.code : undefined;
527
+ const type = typeof streamError.type === "string" ? streamError.type : undefined;
528
+ const message = typeof streamError.message === "string" && streamError.message.trim().length > 0
529
+ ? streamError.message
530
+ : "OpenAI API stream failed";
531
+ const detail = [type, code].filter(Boolean).join("/");
532
+ throw new Error(`OpenAI API stream error${detail ? ` (${detail})` : ""}: ${message}`);
533
+ }
534
+
535
+ if (completedResponse) {
536
+ const output = Array.isArray(completedResponse.output) ? completedResponse.output : [];
537
+ const payload = output.length > 0 ? completedResponse : { ...completedResponse, output: outputItems };
538
+ return { payload, webSearchCallSeen: webSearchCallSeen || output.some(isWebSearchCall) };
539
+ }
540
+ if (outputItems.length > 0) return { payload: { output: outputItems }, webSearchCallSeen: webSearchCallSeen || outputItems.some(isWebSearchCall) };
541
+ throw new Error("OpenAI API returned no parseable response output");
542
+ }
543
+
544
+ function cleanSourceUrl(rawUrl: string): string {
545
+ try {
546
+ const url = new URL(rawUrl);
547
+ if (url.searchParams.get("utm_source") === "openai") url.searchParams.delete("utm_source");
548
+ return url.toString();
549
+ } catch {
550
+ return rawUrl.replace(/[?&]utm_source=openai$/, "");
551
+ }
552
+ }
553
+
554
+ function extractSnippetAround(text: string, start: unknown, end: unknown): string {
555
+ if (typeof start !== "number" || typeof end !== "number" || !text) return "";
556
+ const before = Math.max(0, start - 100);
557
+ const after = Math.min(text.length, end + 100);
558
+ const snippet = text.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
559
+ return snippet.length > 300 ? `${snippet.slice(0, 297)}...` : snippet;
560
+ }
561
+
562
+ function addResult(results: SearchResult[], seen: Set<string>, url: unknown, title: unknown, snippet = "", generated = false): void {
563
+ if (typeof url !== "string" || url.trim().length === 0) return;
564
+ const cleanUrl = cleanSourceUrl(url);
565
+ if (seen.has(cleanUrl)) return;
566
+ seen.add(cleanUrl);
567
+ results.push({
568
+ title: typeof title === "string" && title.trim().length > 0 ? title : cleanUrl,
569
+ url: cleanUrl,
570
+ snippet,
571
+ ...(generated && snippet ? { snippetSource: "generated" as const } : {}),
572
+ });
573
+ }
574
+
575
+ function extractSearchResults(output: unknown[], numResults: number | undefined): SearchResult[] {
576
+ const results: SearchResult[] = [];
577
+ const seenUrls = new Set<string>();
578
+
579
+ for (const item of output) {
580
+ if (!item || typeof item !== "object" || (item as { type?: unknown }).type !== "message") continue;
581
+ const content = (item as { content?: unknown }).content;
582
+ if (!Array.isArray(content)) continue;
583
+ for (const part of content) {
584
+ if (!part || typeof part !== "object") continue;
585
+ const text = typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "";
586
+ const annotations = (part as { annotations?: unknown }).annotations;
587
+ if (!Array.isArray(annotations)) continue;
588
+ for (const annotation of annotations) {
589
+ if (!annotation || typeof annotation !== "object" || (annotation as { type?: unknown }).type !== "url_citation") continue;
590
+ addResult(
591
+ results,
592
+ seenUrls,
593
+ (annotation as { url?: unknown }).url,
594
+ (annotation as { title?: unknown }).title,
595
+ extractSnippetAround(text, (annotation as { start_index?: unknown }).start_index, (annotation as { end_index?: unknown }).end_index),
596
+ true,
597
+ );
598
+ }
599
+ }
600
+ }
601
+
602
+ for (const item of output) {
603
+ if (!item || typeof item !== "object" || (item as { type?: unknown }).type !== "web_search_call") continue;
604
+ const value = item as { action?: unknown; sources?: unknown; results?: unknown };
605
+ const actionSources = value.action && typeof value.action === "object"
606
+ ? (value.action as { sources?: unknown }).sources
607
+ : undefined;
608
+ const sourceGroups = [actionSources, value.sources, value.results];
609
+ for (const group of sourceGroups) {
610
+ if (!Array.isArray(group)) continue;
611
+ for (const source of group) {
612
+ if (!source || typeof source !== "object") continue;
613
+ const record = source as Record<string, unknown>;
614
+ addResult(results, seenUrls, record.url ?? record.source_website_url, record.title ?? record.caption);
615
+ }
616
+ }
617
+ }
618
+
619
+ if (typeof numResults === "number" && Number.isFinite(numResults) && numResults > 0) {
620
+ return results.slice(0, Math.min(Math.floor(numResults), 20));
621
+ }
622
+ return results;
623
+ }
624
+
625
+ function extractAnswer(output: unknown[]): string {
626
+ const parts: string[] = [];
627
+ for (const item of output) {
628
+ if (!item || typeof item !== "object" || (item as { type?: unknown }).type !== "message") continue;
629
+ const content = (item as { content?: unknown }).content;
630
+ if (!Array.isArray(content)) continue;
631
+ for (const part of content) {
632
+ if (!part || typeof part !== "object") continue;
633
+ const text = (part as { text?: unknown }).text;
634
+ if (typeof text === "string" && text.trim().length > 0) parts.push(text);
635
+ }
636
+ }
637
+ return parts.join("\n").trim();
638
+ }
639
+
640
+ function isAlphaSearchEnabled(): boolean {
641
+ const value = loadConfig().openaiUseAlphaSearch;
642
+ if (value === undefined) return false;
643
+ if (typeof value !== "boolean") {
644
+ throw new Error(`openaiUseAlphaSearch in ${CONFIG_PATH} must be a boolean`);
645
+ }
646
+ return value;
647
+ }
648
+
649
+ function resolveAlphaSearchUrl(responsesUrl: string): string {
650
+ const url = new URL(responsesUrl);
651
+ const pathname = url.pathname.replace(/\/+$/u, "");
652
+ if (!pathname.endsWith("/responses")) {
653
+ throw new Error("OpenAI alpha/search configuration: endpoint path must end with /responses");
654
+ }
655
+ url.pathname = `${pathname.slice(0, -"/responses".length)}/alpha/search`;
656
+ return url.toString();
657
+ }
658
+
659
+ function buildAlphaSearchBody(query: string, options: SearchOptions, model: string): Record<string, unknown> {
660
+ const filters = normalizeDomainFilters(options.domainFilter);
661
+ if (filters?.blockedDomains?.length) {
662
+ throw new OpenAIAlphaSearchUnsupportedError("OpenAI alpha/search: unsupported excluded domains; use another search provider or disable openaiUseAlphaSearch");
663
+ }
664
+ const recencyDays = { day: 1, week: 7, month: 30, year: 365 };
665
+ return {
666
+ id: randomUUID(),
667
+ model,
668
+ commands: {
669
+ search_query: [{
670
+ q: query,
671
+ ...(options.recencyFilter ? { recency: recencyDays[options.recencyFilter] } : {}),
672
+ ...(filters?.allowedDomains ? { domains: filters.allowedDomains } : {}),
673
+ }],
674
+ },
675
+ };
676
+ }
677
+
678
+ function buildAlphaSearchHeaders(headers: Record<string, string>, apiKey: string): Headers {
679
+ const result = new Headers(headers);
680
+ for (const name of ["OpenAI-Beta", "Session_ID", "Conversation_ID", "X-Codex-Beta-Features", "X-Codex-Turn-State", "x-openai-internal-codex-responses-lite"]) {
681
+ result.delete(name);
682
+ }
683
+ result.set("Authorization", `Bearer ${apiKey}`);
684
+ result.set("Content-Type", "application/json");
685
+ result.set("Accept", "application/json");
686
+ result.set("Originator", "codex_cli_rs");
687
+ return result;
688
+ }
689
+
690
+ async function parseAlphaSearchResponse(response: Response, numResults = 5): Promise<SearchResponse> {
691
+ const text = await response.text();
692
+ let payload: unknown;
693
+ try {
694
+ payload = JSON.parse(text);
695
+ } catch {
696
+ throw new Error("OpenAI alpha/search returned invalid JSON");
697
+ }
698
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
699
+ throw new Error("OpenAI alpha/search returned an invalid response");
700
+ }
701
+ const record = payload as Record<string, unknown>;
702
+ const answer = typeof record.output === "string" ? record.output.trim() : "";
703
+ const results: SearchResult[] = [];
704
+ const seen = new Set<string>();
705
+ for (const item of Array.isArray(record.results) ? record.results : []) {
706
+ if (!item || typeof item !== "object" || item.type !== "text_result" || typeof item.url !== "string") continue;
707
+ try {
708
+ const url = new URL(item.url);
709
+ if (url.protocol !== "http:" && url.protocol !== "https:") continue;
710
+ } catch {
711
+ continue;
712
+ }
713
+ addResult(results, seen, item.url, item.title, typeof item.snippet === "string" ? item.snippet : "");
714
+ }
715
+ if (!answer && results.length === 0) {
716
+ throw new Error("OpenAI alpha/search returned no parseable results or plaintext output");
717
+ }
718
+ return {
719
+ answer,
720
+ results: typeof numResults === "number" && Number.isFinite(numResults) && numResults > 0
721
+ ? results.slice(0, Math.min(Math.floor(numResults), 20))
722
+ : results,
723
+ };
724
+ }
725
+
726
+ async function runOpenAISearch(
727
+ query: string,
728
+ options: SearchOptions,
729
+ auth: OpenAIAuth,
730
+ ctx?: Pick<ExtensionContext, "sessionManager">,
731
+ ): Promise<SearchResponse> {
732
+ const useAlphaSearch = isAlphaSearchEnabled();
733
+ const useCodexEndpoint = auth.useCodexEndpoint ?? (auth.provider === "openai-codex" || isCodexJwt(auth.apiKey));
734
+ const responsesUrl = useCodexEndpoint && !auth.useProviderBaseUrl ? CODEX_RESPONSES_URL : auth.responsesUrl;
735
+ const isAzure = isAzureResponsesUrl(new URL(responsesUrl));
736
+ if (isAzure && useAlphaSearch) {
737
+ throw new OpenAIAlphaSearchUnsupportedError("Azure OpenAI does not support Codex alpha/search; disable openaiUseAlphaSearch to use hosted web_search");
738
+ }
739
+ if (useAlphaSearch) options.signal?.throwIfAborted();
740
+ const requestUrl = useAlphaSearch ? resolveAlphaSearchUrl(responsesUrl) : responsesUrl;
741
+ const body = useAlphaSearch ? buildAlphaSearchBody(query, options, auth.model) : {
742
+ model: auth.model,
743
+ instructions: buildInstructions(options),
744
+ input: [{ role: "user", content: [{ type: "input_text", text: query }] }],
745
+ tools: [buildWebSearchTool(options)],
746
+ include: ["web_search_call.action.sources"],
747
+ store: false,
748
+ stream: true,
749
+ tool_choice: "required" as const,
750
+ parallel_tool_calls: true,
751
+ };
752
+ const activityId = activityMonitor.logStart({ type: "api", query });
753
+ const headers: Record<string, string> = {
754
+ ...toRequestHeaders(auth.headers),
755
+ Authorization: `Bearer ${auth.apiKey}`,
756
+ "Content-Type": "application/json",
757
+ "OpenAI-Beta": "responses=experimental",
758
+ };
759
+ if (useCodexEndpoint) {
760
+ const accountId = extractAccountId(auth.apiKey);
761
+ if (accountId) headers["chatgpt-account-id"] = accountId;
762
+ headers.originator = "pi";
763
+ }
764
+ const requestHeaders = applyOpenCodeDestinationHeaders(
765
+ useAlphaSearch ? buildAlphaSearchHeaders(headers, auth.apiKey) : headers,
766
+ requestUrl,
767
+ ctx,
768
+ );
769
+
770
+ if (isAzure) {
771
+ for (const name of ["Authorization", "api-key", "OpenAI-Beta", "chatgpt-account-id", "originator"]) requestHeaders.delete(name);
772
+ if (decodeJwtPayload(auth.apiKey)) {
773
+ requestHeaders.set("Authorization", `Bearer ${auth.apiKey}`);
774
+ } else {
775
+ requestHeaders.set("api-key", auth.apiKey);
776
+ }
777
+ }
778
+
779
+ try {
780
+ const response = await fetchWithCredentialRedirects(requestUrl, {
781
+ method: "POST",
782
+ headers: requestHeaders,
783
+ body: JSON.stringify(body),
784
+ signal: options.signal
785
+ ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])
786
+ : AbortSignal.timeout(SEARCH_TIMEOUT_MS),
787
+ }, ["Authorization", "api-key", "x-opencode-session", "x-opencode-client", "chatgpt-account-id", ...Object.keys(auth.headers)]);
788
+
789
+ if (!response.ok) {
790
+ activityMonitor.logError(activityId, `HTTP ${response.status}`);
791
+ const errorText = redactCredential(await response.text(), auth.apiKey);
792
+ const ErrorType = useAlphaSearch && [404, 405, 501].includes(response.status)
793
+ ? OpenAIAlphaSearchUnsupportedError
794
+ : Error;
795
+ throw new ErrorType(`OpenAI ${useAlphaSearch ? "alpha/search " : ""}API error ${response.status}: ${errorText.slice(0, 300)}`);
796
+ }
797
+
798
+ if (useAlphaSearch) {
799
+ const result = await parseAlphaSearchResponse(response, options.numResults);
800
+ activityMonitor.logComplete(activityId, response.status);
801
+ return result;
802
+ }
803
+ const parsed = await parseOpenAIResponse(response);
804
+ const output = Array.isArray(parsed.payload.output) ? parsed.payload.output : [];
805
+ if (!parsed.webSearchCallSeen) throw new Error("OpenAI web_search returned no web_search_call");
806
+ const answer = extractAnswer(output);
807
+ const results = extractSearchResults(output, options.numResults);
808
+
809
+ if (!answer && results.length === 0) {
810
+ throw new Error("OpenAI web_search returned no answer or sources");
811
+ }
812
+
813
+ activityMonitor.logComplete(activityId, response.status);
814
+ return { answer, results };
815
+ } catch (err) {
816
+ const message = err instanceof Error ? err.message : String(err);
817
+ const redactedMessage = redactCredential(message, auth.apiKey);
818
+ if (redactedMessage.toLowerCase().includes("abort")) {
819
+ activityMonitor.logComplete(activityId, 0);
820
+ } else {
821
+ activityMonitor.logError(activityId, redactedMessage);
822
+ }
823
+ if (redactedMessage === message) throw err;
824
+ const redactedError = new Error(redactedMessage);
825
+ if (err instanceof Error) redactedError.name = err.name;
826
+ throw redactedError;
827
+ }
828
+ }
829
+
830
+ export async function searchWithOpenAI(
831
+ query: string,
832
+ options: SearchOptions = {},
833
+ ctx?: ExtensionContext,
834
+ ): Promise<SearchResponse> {
835
+ const auth = await resolveOpenAIAuth(ctx, options.signal, options.model);
836
+ if (!auth) {
837
+ throw new Error(
838
+ "OpenAI web search unavailable. Either:\n" +
839
+ " 1. Use /login to sign in with a Codex subscription\n" +
840
+ ` 2. Create ${CONFIG_PATH} with { "openaiApiKey": "your-key" }\n` +
841
+ " 3. Set OPENAI_API_KEY environment variable",
842
+ );
843
+ }
844
+ return runOpenAISearch(query, options, auth, ctx);
845
+ }
846
+
847
+ export async function searchWithCurrentModelOpenAI(
848
+ query: string,
849
+ options: SearchOptions = {},
850
+ ctx?: ExtensionContext,
851
+ ): Promise<SearchResponse> {
852
+ if (!ctx) throw new Error("OpenAI current-model search requires an extension context");
853
+ const auth = await resolveCurrentModelAuth(ctx, options.signal);
854
+ return runOpenAISearch(query, options, auth, ctx);
855
+ }