@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/gemini-web.ts ADDED
@@ -0,0 +1,527 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { basename } from "node:path";
3
+ import { detectBrowserProfiles, getLastGoogleCookieDiagnostic, getLastGoogleCookieDiagnosticDetails, type BrowserCookieDiagnosticDetails, type CookieMap, getGoogleCookies } from "./chrome-cookies.ts";
4
+ import { getBrowserCookieSelection, isBrowserCookieAccessAllowed, normalizeChromeProfile, type BrowserCookieConsent } from "./gemini-web-config.ts";
5
+ import { getWebSearchConfigPath } from "./utils.ts";
6
+
7
+ const GEMINI_APP_URL = "https://gemini.google.com/app";
8
+ const GEMINI_STREAM_GENERATE_URL =
9
+ "https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate";
10
+ const GEMINI_UPLOAD_URL = "https://content-push.googleapis.com/upload";
11
+ const GEMINI_UPLOAD_PUSH_ID = "feeds/mcudyrk2a4khkz";
12
+ const GOOGLE_LIST_ACCOUNTS_URL =
13
+ "https://accounts.google.com/ListAccounts?gpsia=1&source=ChromiumBrowser&laf=b64bin&json=standard";
14
+
15
+ const USER_AGENT =
16
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
17
+
18
+ const MODEL_HEADER_NAME = "x-goog-ext-525001261-jspb";
19
+ export const DEFAULT_GEMINI_WEB_MODEL = "gemini-3.1-pro";
20
+ const MODEL_HEADERS: Record<string, string> = {
21
+ [DEFAULT_GEMINI_WEB_MODEL]: '[1,null,null,null,"9d8ca3786ebdfbea",null,null,0,[4]]',
22
+ "gemini-2.5-pro": '[1,null,null,null,"4af6c7f5da75d65d",null,null,0,[4]]',
23
+ "gemini-2.5-flash": '[1,null,null,null,"9ec249fc9ad08861",null,null,0,[4]]',
24
+ };
25
+
26
+ const REQUIRED_COOKIES = ["__Secure-1PSID", "__Secure-1PSIDTS"];
27
+
28
+ // Gemini Web talks to Google's frontend inside the host agent (pi), whose
29
+ // global undici dispatcher runs HTTP/1.1 with undici's default 16 KiB
30
+ // maxHeaderSize. Google's gemini.google.com /app response headers routinely
31
+ // exceed that budget over HTTP/1.1, so cookie-bearing requests fail with
32
+ // UND_ERR_HEADERS_OVERFLOW surfaced as "fetch failed". Route these requests
33
+ // through a dedicated undici Agent with a larger header budget instead; fall
34
+ // back to the ambient global fetch when undici is not resolvable (e.g.
35
+ // standalone test environments).
36
+ let geminiFetchImpl: typeof fetch | null = null;
37
+
38
+ // Test-only hook: lets tests inject a simulated transport instead of patching
39
+ // globalThis.fetch. Gemini Web deliberately bypasses the ambient global fetch
40
+ // (inside the pi host agent it is constrained to undici's 16 KiB
41
+ // maxHeaderSize and cannot serve Google's /app page over HTTP/1.1), so
42
+ // globalThis.fetch patching is no longer a reliable way to intercept these
43
+ // requests.
44
+ export function setGeminiFetchOverrideForTests(fetchImpl: typeof fetch | null): void {
45
+ geminiFetchOverride = fetchImpl;
46
+ }
47
+
48
+ let geminiFetchOverride: typeof fetch | null = null;
49
+
50
+ // The header budget Gemini Web needs for Google frontend responses.
51
+ // Google's /app page exceeds undici's default 16 KiB maxHeaderSize when
52
+ // served over HTTP/1.1, which is how pi's global dispatcher operates.
53
+ export const GEMINI_MAX_HEADER_SIZE = 4 * 1024 * 1024;
54
+
55
+ // Build a fetch that routes through a dedicated undici Agent with a larger
56
+ // header budget than the host agent's global dispatcher allows. Exported for
57
+ // tests so the agent configuration can be asserted without network access.
58
+ export function createGeminiFetch(undiciImpl: typeof import("undici")): typeof fetch {
59
+ const agent = new undiciImpl.EnvHttpProxyAgent({
60
+ allowH2: false,
61
+ connectTimeout: 30_000,
62
+ maxHeaderSize: GEMINI_MAX_HEADER_SIZE,
63
+ pipelining: 1,
64
+ });
65
+ // undici 8 types its fetch request/response structurally differently from
66
+ // the DOM lib types (duplex/textStream on Request, Symbol.dispose on
67
+ // Headers); the shape this module uses (status, ok, headers.get, text) is
68
+ // identical, so bridge the two.
69
+ type UndiciFetch = typeof undiciImpl.fetch;
70
+ return (input, init) =>
71
+ undiciImpl.fetch(
72
+ input as unknown as Parameters<UndiciFetch>[0],
73
+ { ...init, dispatcher: agent } as unknown as Parameters<UndiciFetch>[1],
74
+ ) as unknown as Promise<Response>;
75
+ }
76
+
77
+ export async function resolveGeminiFetch(): Promise<typeof fetch> {
78
+ if (geminiFetchOverride) return geminiFetchOverride;
79
+ if (geminiFetchImpl) return geminiFetchImpl;
80
+
81
+ let undici: typeof import("undici");
82
+ try {
83
+ undici = await import("undici");
84
+ } catch {
85
+ geminiFetchImpl = fetch;
86
+ return geminiFetchImpl;
87
+ }
88
+
89
+ geminiFetchImpl = createGeminiFetch(undici);
90
+ return geminiFetchImpl;
91
+ }
92
+
93
+ export interface GeminiWebOptions {
94
+ youtubeUrl?: string;
95
+ model?: string;
96
+ files?: GeminiWebFile[];
97
+ signal?: AbortSignal;
98
+ timeoutMs?: number;
99
+ }
100
+
101
+ export interface GeminiWebFile {
102
+ path: string;
103
+ mimeType: string;
104
+ }
105
+
106
+ export async function isGeminiWebAvailable(chromeProfile?: string): Promise<CookieMap | null> {
107
+ if (!isBrowserCookieAccessAllowed()) return null;
108
+
109
+ const configured = getBrowserCookieSelection();
110
+ const result = await getGoogleCookies({
111
+ browser: configured.browser,
112
+ profile: normalizeChromeProfile(chromeProfile) ?? configured.profile,
113
+ requiredCookies: REQUIRED_COOKIES,
114
+ });
115
+ if (!result) return null;
116
+ return result.cookies;
117
+ }
118
+
119
+ export function getGeminiWebAvailabilityDiagnostic(): string | null {
120
+ return isBrowserCookieAccessAllowed() ? getLastGoogleCookieDiagnostic() : null;
121
+ }
122
+
123
+ const SIGN_IN_HINT = "Sign into gemini.google.com in a supported Chromium-based browser";
124
+
125
+ /** Tells the agent how the user can let Gemini Web use the Google login from their browser.
126
+ * Lines after the first start with indent. */
127
+ export function browserCookieAccessHint(consent?: BrowserCookieConsent, indent = ""): string {
128
+ if (isBrowserCookieAccessAllowed()) return SIGN_IN_HINT;
129
+ const found = detectBrowserProfiles();
130
+ const where = found.length > 0
131
+ ? `Found on this machine: ${found.map(({ name, profiles }) => `${name} (${profiles.join(", ")})`).join(", ")}.`
132
+ : "No supported Chromium-based browser profile was found on this machine.";
133
+ const json = found.length > 0
134
+ ? `"allowBrowserCookies": true, "browserCookies": { "browser": "${found[0].browser}" }`
135
+ : `"allowBrowserCookies": true`;
136
+ return [
137
+ `Gemini can use the Google login from the user's browser (free), but reading browser cookies is off. ${where}`,
138
+ `To turn it on, add to ${getWebSearchConfigPath()}: ${json}${consent?.command ? `, or run ${consent.command}` : ""}.`,
139
+ "This reads the user's browser cookies: ask the user first, and don't change this setting yourself.",
140
+ ].join(`\n${indent}`);
141
+ }
142
+
143
+ /** browserCookieAccessHint in one line, for lists of setup options. */
144
+ export function browserCookieAccessHintLine(): string {
145
+ if (isBrowserCookieAccessAllowed()) return SIGN_IN_HINT;
146
+ const [first] = detectBrowserProfiles();
147
+ return `Sign into gemini.google.com in ${first?.name ?? "a supported Chromium-based browser"} and set allowBrowserCookies: true in ${getWebSearchConfigPath()} (reads browser cookies; ask the user first)`;
148
+ }
149
+
150
+ /** For routes where Gemini Web is the only way left: asks the user when cookie access is off.
151
+ * True when access is now on and the caller should try Gemini Web again. */
152
+ export async function requestBrowserCookieAccess(consent: BrowserCookieConsent | undefined, signal: AbortSignal | undefined): Promise<boolean> {
153
+ if (!consent?.ask || signal?.aborted || isBrowserCookieAccessAllowed()) return false;
154
+ return consent.ask(signal);
155
+ }
156
+
157
+ export function getGeminiWebAvailabilityDiagnosticDetails(): BrowserCookieDiagnosticDetails | null {
158
+ return isBrowserCookieAccessAllowed() ? getLastGoogleCookieDiagnosticDetails() : null;
159
+ }
160
+
161
+ export async function getActiveGoogleEmail(cookies: CookieMap): Promise<string | null> {
162
+ const cookieHeader = buildCookieHeader(cookies);
163
+ if (!cookieHeader) return null;
164
+
165
+ try {
166
+ const html = await fetchWithCookieRedirects(
167
+ GEMINI_APP_URL,
168
+ cookieHeader,
169
+ 10,
170
+ AbortSignal.timeout(10000),
171
+ );
172
+ const email = extractEmailFromGeminiHtml(html);
173
+ if (email) return email;
174
+ } catch {
175
+ }
176
+
177
+ try {
178
+ const response = await fetchWithCookieRedirects(
179
+ GOOGLE_LIST_ACCOUNTS_URL,
180
+ cookieHeader,
181
+ 10,
182
+ AbortSignal.timeout(10000),
183
+ );
184
+ return extractEmailFromListAccounts(response);
185
+ } catch {
186
+ return null;
187
+ }
188
+ }
189
+
190
+ export async function queryWithCookies(
191
+ prompt: string,
192
+ cookieMap: CookieMap,
193
+ options: GeminiWebOptions = {},
194
+ ): Promise<string> {
195
+ const model = options.model ?? DEFAULT_GEMINI_WEB_MODEL;
196
+ if (!MODEL_HEADERS[model]) {
197
+ throw new Error(`Gemini Web does not support model ${model}; configure Gemini API or choose a supported Gemini Web model.`);
198
+ }
199
+ const timeoutMs = options.timeoutMs ?? 120000;
200
+
201
+ let fullPrompt = prompt;
202
+ if (options.youtubeUrl) {
203
+ fullPrompt = `${fullPrompt}\n\nYouTube video: ${options.youtubeUrl}`;
204
+ }
205
+
206
+ const result = await runGeminiWebOnce(fullPrompt, cookieMap, model, options.files, timeoutMs, options.signal);
207
+
208
+ if (result.errorMessage) throw new Error(result.errorMessage);
209
+ if (!result.text) throw new Error("Gemini Web returned empty response");
210
+ return result.text;
211
+ }
212
+
213
+ interface GeminiWebResult {
214
+ text: string;
215
+ errorCode?: number;
216
+ errorMessage?: string;
217
+ }
218
+
219
+ async function runGeminiWebOnce(
220
+ prompt: string,
221
+ cookieMap: CookieMap,
222
+ model: string,
223
+ files: GeminiWebFile[] | undefined,
224
+ timeoutMs: number,
225
+ signal?: AbortSignal,
226
+ ): Promise<GeminiWebResult> {
227
+ const effectiveSignal = withTimeout(signal, timeoutMs);
228
+ const cookieHeader = buildCookieHeader(cookieMap);
229
+ const accessToken = await fetchAccessToken(cookieHeader, effectiveSignal);
230
+
231
+ const uploaded: Array<{ id: string; name: string }> = [];
232
+ if (files) {
233
+ for (const file of files) {
234
+ uploaded.push(await uploadFile(file, cookieHeader, effectiveSignal));
235
+ }
236
+ }
237
+
238
+ const fReq = buildFReqPayload(prompt, uploaded);
239
+ const params = new URLSearchParams();
240
+ params.set("at", accessToken);
241
+ params.set("f.req", fReq);
242
+
243
+ const res = await (await resolveGeminiFetch())(GEMINI_STREAM_GENERATE_URL, {
244
+ method: "POST",
245
+ redirect: "error",
246
+ headers: {
247
+ "content-type": "application/x-www-form-urlencoded;charset=utf-8",
248
+ host: "gemini.google.com",
249
+ origin: "https://gemini.google.com",
250
+ referer: "https://gemini.google.com/",
251
+ "x-same-domain": "1",
252
+ "user-agent": USER_AGENT,
253
+ cookie: cookieHeader,
254
+ [MODEL_HEADER_NAME]: MODEL_HEADERS[model],
255
+ },
256
+ body: params.toString(),
257
+ signal: effectiveSignal,
258
+ });
259
+
260
+ const rawText = await res.text();
261
+
262
+ if (!res.ok) {
263
+ return { text: "", errorMessage: `Gemini request failed: ${res.status}` };
264
+ }
265
+
266
+ try {
267
+ return parseStreamGenerateResponse(rawText);
268
+ } catch (err) {
269
+ let errorCode: number | undefined;
270
+ try {
271
+ const json = JSON.parse(trimJsonEnvelope(rawText));
272
+ errorCode = extractErrorCode(json);
273
+ } catch {
274
+ }
275
+ return {
276
+ text: "",
277
+ errorCode,
278
+ errorMessage: err instanceof Error ? err.message : String(err),
279
+ };
280
+ }
281
+ }
282
+
283
+ async function fetchAccessToken(
284
+ cookieHeader: string,
285
+ signal: AbortSignal,
286
+ ): Promise<string> {
287
+ const html = await fetchWithCookieRedirects(GEMINI_APP_URL, cookieHeader, 10, signal);
288
+
289
+ for (const key of ["SNlM0e", "thykhd"]) {
290
+ const match = html.match(new RegExp(`"${key}":"(.*?)"`));
291
+ if (match?.[1]) return match[1];
292
+ }
293
+
294
+ throw new Error("Unable to authenticate with Gemini. Make sure you're signed into gemini.google.com in a supported Chromium-based browser.");
295
+ }
296
+
297
+ async function fetchWithCookieRedirects(
298
+ url: string,
299
+ cookieHeader: string,
300
+ maxRedirects: number,
301
+ signal: AbortSignal,
302
+ ): Promise<string> {
303
+ let current = url;
304
+ const allowedOrigin = new URL(url).origin;
305
+ for (let i = 0; i <= maxRedirects; i++) {
306
+ const res = await (await resolveGeminiFetch())(current, {
307
+ headers: { "user-agent": USER_AGENT, cookie: cookieHeader },
308
+ redirect: "manual",
309
+ signal,
310
+ });
311
+ if (res.status >= 300 && res.status < 400) {
312
+ const location = res.headers.get("location");
313
+ if (location) {
314
+ const next = new URL(location, current);
315
+ if (next.origin !== allowedOrigin) {
316
+ throw new Error(`Refusing to send Google cookies across origins: ${allowedOrigin} -> ${next.origin}`);
317
+ }
318
+ current = next.toString();
319
+ continue;
320
+ }
321
+ }
322
+ return await res.text();
323
+ }
324
+ throw new Error(`Too many redirects (>${maxRedirects})`);
325
+ }
326
+
327
+ function extractEmailFromGeminiHtml(html: string): string | null {
328
+ const patterns = [
329
+ // Gemini bootstraps the active account in oPEP7c. Prefer it over generic
330
+ // feature/config entries that may contain other signed-in Google accounts.
331
+ /"oPEP7c"\s*:\s*"([^"]+)"/,
332
+ // The Google account menu aria-label is rendered for the active account.
333
+ /aria-label="Google Account:[^"]*?\(([^)]+)\)"/,
334
+ /"displayEmail"\s*:\s*"([^"]+)"/,
335
+ /"defaultEmail"\s*:\s*"([^"]+)"/,
336
+ /"email"\s*:\s*"([^"]+)"/,
337
+ /"identifier"\s*:\s*"([^"]+)"/,
338
+ /"gaiaIdentifier"\s*:\s*"([^"]+)"/,
339
+ ];
340
+
341
+ for (const pattern of patterns) {
342
+ const match = html.match(pattern);
343
+ const email = normalizeEmail(match?.[1]);
344
+ if (email) return email;
345
+ }
346
+
347
+ return findFirstEmail(html);
348
+ }
349
+
350
+ function extractEmailFromListAccounts(text: string): string | null {
351
+ const trimmed = text.replace(/^\)\]\}'\s*/, "");
352
+ try {
353
+ return findEmailInValue(JSON.parse(trimmed)) ?? findFirstEmail(trimmed);
354
+ } catch {
355
+ return findFirstEmail(trimmed);
356
+ }
357
+ }
358
+
359
+ function findEmailInValue(value: unknown): string | null {
360
+ if (typeof value === "string") return normalizeEmail(value);
361
+ if (Array.isArray(value)) {
362
+ for (const item of value) {
363
+ const email = findEmailInValue(item);
364
+ if (email) return email;
365
+ }
366
+ return null;
367
+ }
368
+ if (value && typeof value === "object") {
369
+ for (const item of Object.values(value as Record<string, unknown>)) {
370
+ const email = findEmailInValue(item);
371
+ if (email) return email;
372
+ }
373
+ }
374
+ return null;
375
+ }
376
+
377
+ function findFirstEmail(text: string): string | null {
378
+ const normalized = decodeEmailEscapes(text);
379
+ const match = normalized.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i);
380
+ return match?.[0] ?? null;
381
+ }
382
+
383
+ function normalizeEmail(value: string | undefined): string | null {
384
+ if (!value) return null;
385
+ const normalized = decodeEmailEscapes(value.trim());
386
+ return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(normalized) ? normalized : null;
387
+ }
388
+
389
+ function decodeEmailEscapes(value: string): string {
390
+ return value
391
+ .replace(/\\u0040/gi, "@")
392
+ .replace(/\\x40/gi, "@")
393
+ .replace(/&#64;/gi, "@")
394
+ .replace(/&commat;/gi, "@")
395
+ .replace(/\\"/g, "\"")
396
+ .replace(/\\\\/g, "\\");
397
+ }
398
+
399
+ async function uploadFile(
400
+ file: GeminiWebFile,
401
+ cookieHeader: string,
402
+ signal: AbortSignal,
403
+ ): Promise<{ id: string; name: string }> {
404
+ const data = readFileSync(file.path);
405
+ const fileName = basename(file.path);
406
+ const boundary = "----FormBoundary" + Math.random().toString(36).slice(2);
407
+ const header = `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\nContent-Type: ${file.mimeType}\r\n\r\n`;
408
+ const footer = `\r\n--${boundary}--\r\n`;
409
+
410
+ const body = Buffer.concat([
411
+ Buffer.from(header, "utf-8"),
412
+ data,
413
+ Buffer.from(footer, "utf-8"),
414
+ ]);
415
+
416
+ const res = await (await resolveGeminiFetch())(GEMINI_UPLOAD_URL, {
417
+ method: "POST",
418
+ redirect: "error",
419
+ headers: {
420
+ "content-type": `multipart/form-data; boundary=${boundary}`,
421
+ "push-id": GEMINI_UPLOAD_PUSH_ID,
422
+ "user-agent": USER_AGENT,
423
+ cookie: cookieHeader,
424
+ },
425
+ body,
426
+ signal,
427
+ });
428
+
429
+ if (!res.ok) {
430
+ const text = await res.text();
431
+ throw new Error(`File upload failed: ${res.status} (${text.slice(0, 200)})`);
432
+ }
433
+
434
+ return { id: await res.text(), name: fileName };
435
+ }
436
+
437
+ function buildFReqPayload(
438
+ prompt: string,
439
+ uploaded: Array<{ id: string; name: string }>,
440
+ ): string {
441
+ const promptPayload =
442
+ uploaded.length > 0
443
+ ? [prompt, 0, null, uploaded.map((file) => [[file.id, 1], file.name])]
444
+ : [prompt];
445
+ const innerList = [promptPayload, null, null];
446
+ return JSON.stringify([null, JSON.stringify(innerList)]);
447
+ }
448
+
449
+ function withTimeout(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
450
+ const timeout = AbortSignal.timeout(timeoutMs);
451
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
452
+ }
453
+
454
+ function buildCookieHeader(cookieMap: CookieMap): string {
455
+ return Object.entries(cookieMap)
456
+ .filter(([, value]) => typeof value === "string" && value.length > 0)
457
+ .map(([name, value]) => `${name}=${value}`)
458
+ .join("; ");
459
+ }
460
+
461
+ function getNestedValue(value: unknown, pathParts: number[]): unknown {
462
+ let current: unknown = value;
463
+ for (const part of pathParts) {
464
+ if (current == null) return undefined;
465
+ if (!Array.isArray(current)) return undefined;
466
+ current = (current as unknown[])[part];
467
+ }
468
+ return current;
469
+ }
470
+
471
+ function trimJsonEnvelope(text: string): string {
472
+ const start = text.indexOf("[");
473
+ const end = text.lastIndexOf("]");
474
+ if (start === -1 || end === -1 || end <= start) {
475
+ throw new Error("Gemini response did not contain a JSON payload.");
476
+ }
477
+ return text.slice(start, end + 1);
478
+ }
479
+
480
+ function extractErrorCode(responseJson: unknown): number | undefined {
481
+ const code = getNestedValue(responseJson, [0, 5, 2, 0, 1, 0]);
482
+ return typeof code === "number" && code >= 0 ? code : undefined;
483
+ }
484
+
485
+ function extractCandidateText(candidate: unknown): string {
486
+ const textRaw = getNestedValue(candidate, [1, 0]);
487
+ let text = typeof textRaw === "string" ? textRaw : "";
488
+
489
+ if (/^http:\/\/googleusercontent\.com\/card_content\/\d+/.test(text)) {
490
+ const alt = getNestedValue(candidate, [22, 0]);
491
+ if (typeof alt === "string" && alt.length > 0) text = alt;
492
+ }
493
+
494
+ return text;
495
+ }
496
+
497
+ function parseStreamGenerateResponse(rawText: string): GeminiWebResult {
498
+ const responseJson = JSON.parse(trimJsonEnvelope(rawText));
499
+ const errorCode = extractErrorCode(responseJson);
500
+
501
+ const parts = Array.isArray(responseJson) ? responseJson : [];
502
+ let firstCandidateSeen: unknown = undefined;
503
+ let latestNonEmptyText = "";
504
+
505
+ for (let i = 0; i < parts.length; i++) {
506
+ const partBody = getNestedValue(parts[i], [2]);
507
+ if (!partBody || typeof partBody !== "string") continue;
508
+ try {
509
+ const parsed = JSON.parse(partBody);
510
+ const candidateList = getNestedValue(parsed, [4]);
511
+ if (!Array.isArray(candidateList) || candidateList.length === 0) continue;
512
+
513
+ const firstCandidate = (candidateList as unknown[])[0];
514
+ if (firstCandidateSeen === undefined) firstCandidateSeen = firstCandidate;
515
+
516
+ const text = extractCandidateText(firstCandidate);
517
+ if (text.length > 0) latestNonEmptyText = text;
518
+ } catch {
519
+ }
520
+ }
521
+
522
+ const text = latestNonEmptyText.length > 0
523
+ ? latestNonEmptyText
524
+ : extractCandidateText(firstCandidateSeen);
525
+
526
+ return { text, errorCode };
527
+ }