@asterxsk/kiln 0.1.0 → 0.2.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 (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +170 -170
  3. package/agent/AGENTS.md +67 -67
  4. package/agent/README.md +5 -5
  5. package/agent/extensions/AGENTS.md +68 -68
  6. package/agent/extensions/ask-user/index.ts +418 -418
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  14. package/agent/extensions/background-terminals/output.test.ts +109 -109
  15. package/agent/extensions/background-terminals/package-lock.json +769 -769
  16. package/agent/extensions/background-terminals/package.json +17 -17
  17. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  18. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  19. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  20. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  21. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  22. package/agent/extensions/background-terminals/src/output.ts +84 -84
  23. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  24. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  25. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  26. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  27. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  28. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  29. package/agent/extensions/file-search/index.spec.ts +443 -443
  30. package/agent/extensions/file-search/index.ts +459 -459
  31. package/agent/extensions/file-search/package-lock.json +2253 -2253
  32. package/agent/extensions/file-search/package.json +23 -23
  33. package/agent/extensions/file-search/src/args.ts +122 -122
  34. package/agent/extensions/file-search/src/binaries.ts +422 -422
  35. package/agent/extensions/file-search/src/output.ts +126 -126
  36. package/agent/extensions/file-search/src/process.ts +146 -146
  37. package/agent/extensions/file-search/src/prompt.ts +52 -52
  38. package/agent/extensions/file-search/tsconfig.json +7 -7
  39. package/agent/extensions/modelconf/PLAN.md +915 -915
  40. package/agent/extensions/modelconf/index.ts +296 -296
  41. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  42. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  43. package/agent/extensions/pi-web-access/LICENSE +21 -21
  44. package/agent/extensions/pi-web-access/README.md +470 -470
  45. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  46. package/agent/extensions/pi-web-access/activity.ts +101 -101
  47. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  48. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  49. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  50. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  51. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  52. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  53. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  54. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  55. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  56. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  57. package/agent/extensions/pi-web-access/exa.ts +526 -526
  58. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  59. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  60. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  61. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  62. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  63. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  64. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  65. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  66. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  67. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  68. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  69. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  70. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  71. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  72. package/agent/extensions/pi-web-access/package.json +64 -64
  73. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  74. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  75. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  76. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  77. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  78. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  79. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  80. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  81. package/agent/extensions/pi-web-access/storage.ts +521 -521
  82. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  83. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  84. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  85. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  86. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  87. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  88. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  89. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  90. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  91. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  92. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  93. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  94. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  95. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  96. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  97. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  98. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  99. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  100. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  101. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  102. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  103. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  104. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  105. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  106. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  107. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  108. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  109. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  110. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  111. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  112. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  113. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  114. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  115. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  116. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  117. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  118. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  119. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  120. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  121. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  122. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  123. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  124. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  125. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  126. package/agent/extensions/pi-web-access/utils.ts +451 -451
  127. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  128. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  129. package/agent/extensions/shared/activity-status.ts +31 -31
  130. package/agent/extensions/shared/child-session.test.ts +270 -270
  131. package/agent/extensions/shared/child-session.ts +148 -148
  132. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  133. package/agent/extensions/shared/context-utilization.ts +47 -47
  134. package/agent/extensions/shared/dashboard-state.ts +99 -99
  135. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  136. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  137. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  138. package/agent/extensions/subagents/claude.test.ts +119 -119
  139. package/agent/extensions/subagents/codex.test.ts +102 -102
  140. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  141. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  142. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  143. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  144. package/agent/extensions/subagents/index.ts +779 -779
  145. package/agent/extensions/subagents/manager.test.ts +276 -276
  146. package/agent/extensions/subagents/package-lock.json +2244 -2244
  147. package/agent/extensions/subagents/package.json +19 -19
  148. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  149. package/agent/extensions/subagents/src/backend.ts +73 -73
  150. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  151. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  152. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  153. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  154. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  155. package/agent/extensions/subagents/src/domain.ts +253 -253
  156. package/agent/extensions/subagents/src/format.ts +74 -74
  157. package/agent/extensions/subagents/src/manager.ts +736 -736
  158. package/agent/extensions/subagents/src/prompt.ts +92 -92
  159. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  160. package/agent/extensions/subagents/src/runtime.ts +53 -53
  161. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  162. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  163. package/agent/extensions/subagents/takeover.test.ts +29 -29
  164. package/agent/extensions/subagents/tsconfig.json +7 -7
  165. package/agent/extensions/todo/AGENTS.md +38 -38
  166. package/agent/extensions/todo/LICENSE +21 -21
  167. package/agent/extensions/todo/config.ts +55 -55
  168. package/agent/extensions/todo/index.ts +151 -151
  169. package/agent/extensions/todo/locales/de.json +17 -17
  170. package/agent/extensions/todo/locales/en.json +15 -15
  171. package/agent/extensions/todo/locales/es.json +17 -17
  172. package/agent/extensions/todo/locales/fr.json +17 -17
  173. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  174. package/agent/extensions/todo/locales/pt.json +17 -17
  175. package/agent/extensions/todo/locales/ru.json +17 -17
  176. package/agent/extensions/todo/locales/uk.json +17 -17
  177. package/agent/extensions/todo/locales/zh.json +17 -17
  178. package/agent/extensions/todo/package-lock.json +3358 -3358
  179. package/agent/extensions/todo/package.json +67 -67
  180. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  181. package/agent/extensions/todo/state/invariants.ts +20 -20
  182. package/agent/extensions/todo/state/replay.ts +38 -38
  183. package/agent/extensions/todo/state/selectors.ts +107 -107
  184. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  185. package/agent/extensions/todo/state/state.ts +18 -18
  186. package/agent/extensions/todo/state/store.ts +82 -82
  187. package/agent/extensions/todo/state/task-graph.ts +57 -57
  188. package/agent/extensions/todo/todo-overlay.ts +200 -200
  189. package/agent/extensions/todo/todo.ts +155 -155
  190. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  191. package/agent/extensions/todo/tool/types.ts +206 -206
  192. package/agent/extensions/todo/view/format.ts +177 -177
  193. package/agent/install.ps1 +637 -527
  194. package/agent/install.sh +620 -511
  195. package/agent/keybindings.json +7 -7
  196. package/bin/kiln.js +124 -11
  197. package/package.json +8 -2
  198. package/agent/extensions/taste/index.ts +0 -443
  199. package/agent/extensions/taste/install.ps1 +0 -23
  200. package/agent/extensions/taste/install.sh +0 -21
  201. /package/agent/extensions/{status line → statusline}/index.ts +0 -0
  202. /package/agent/extensions/{status line → statusline}/install.ps1 +0 -0
  203. /package/agent/extensions/{status line → statusline}/install.sh +0 -0
@@ -1,1196 +1,1196 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { Readability } from "@mozilla/readability";
3
- import { resizeImage } from "@earendil-works/pi-coding-agent";
4
- import { parseHTML } from "linkedom";
5
- import TurndownService from "turndown";
6
- import pLimit from "p-limit";
7
- import { activityMonitor } from "./activity.ts";
8
- import { extractRSCContent } from "./rsc-extract.ts";
9
- import { extractPDFToMarkdown, isPDF, loadPDFConfig } from "./pdf-extract.ts";
10
- import { extractGitHub } from "./github-extract.ts";
11
- import { extractGitHubIssuePr } from "./github-issue-pr.ts";
12
- import { isYouTubeURL, isYouTubeEnabled, extractYouTube, extractYouTubeFrame, extractYouTubeFrames, getYouTubeStreamInfo } from "./youtube-extract.ts";
13
- import { CredentialResolutionError } from "./credential-source.ts";
14
- import { extractWithUrlContext, extractWithGeminiWeb } from "./gemini-url-context.ts";
15
- import { extractWithBrightDataUnlocker, isBrightDataUnlockerAvailable } from "./brightdata-unlocker.ts";
16
- import { isVideoFile, extractVideo, extractVideoFrame, getLocalVideoDuration } from "./video-extract.ts";
17
- import { appendDeclaredWebLinks, discoverDeclaredWebLinks, type DeclaredWebLink } from "./declared-web-links.ts";
18
- import { fetchRemoteUrl, loadFetchContentDomainPolicy, loadSsrfConfig, validateRemoteUrl, type DomainPolicy, type Lookup, type SsrfConfig } from "./ssrf-protection.ts";
19
- import { formatSeconds, getWebSearchConfigPath, type ProxiedRequestInit } from "./utils.ts";
20
- import { isImageEnabled } from "./feature-config.ts";
21
- import { assertAuthFetchUrl, authFetchRedirectGuard, type AuthFetchProfile } from "./auth-fetch.ts";
22
- import { getBrowserCookiesForHosts, getLastBrowserCookieDiagnostic } from "./chrome-cookies.ts";
23
- import { sanitizeInlineDataUris } from "./data-uri-sanitize.ts";
24
-
25
- const DEFAULT_TIMEOUT_MS = 30000;
26
- const CONCURRENT_LIMIT = 3;
27
-
28
- const NON_RECOVERABLE_ERRORS = ["Unsupported content type", "Response too large", "PDF extraction is disabled", "Image fetching is disabled"];
29
- const MIN_USEFUL_CONTENT = 500;
30
- const SUPPORTED_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
31
- const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
32
- const FETCH_PROVIDERS = ["http", "jina", "brightdata", "gemini"] as const;
33
- type FetchProvider = typeof FETCH_PROVIDERS[number];
34
- type FetchRouting = { providers: FetchProvider[]; allowRemoteHostedProviders: boolean };
35
- const DEFAULT_FETCH_PROVIDER_ORDER: FetchProvider[] = ["http", "jina", "brightdata", "gemini"];
36
- const REMOTE_HOSTED_FETCH_PROVIDERS = new Set<FetchProvider>(["jina", "brightdata", "gemini"]);
37
-
38
- async function extractWithDefuddle(text: string, url: string): Promise<{ title: string; content: string } | null> {
39
- const { Defuddle } = await import("defuddle/node");
40
- const { document } = parseHTML(text);
41
- const result = await Defuddle(document as unknown as Document, url, { markdown: true, useAsync: false });
42
- return typeof result.content === "string" ? { title: result.title, content: result.content } : null;
43
- }
44
-
45
- export { loadSsrfConfig } from "./ssrf-protection.ts";
46
-
47
- export function loadSsrfAllowRanges(): string[] {
48
- return loadSsrfConfig().allowRanges;
49
- }
50
-
51
- function errorMessage(err: unknown): string {
52
- return err instanceof Error ? err.message : String(err);
53
- }
54
-
55
- function isConfigParseError(err: unknown): boolean {
56
- return errorMessage(err).startsWith("Failed to parse ");
57
- }
58
-
59
- function isAbortError(err: unknown): boolean {
60
- return errorMessage(err).toLowerCase().includes("abort");
61
- }
62
-
63
- function isRedirectPolicyError(message: string): boolean {
64
- return message.startsWith("Authenticated fetch refused cross-origin redirect") ||
65
- message.startsWith("Blocked internal ") ||
66
- message.startsWith("Blocked hostname by fetch_content domain policy") ||
67
- message.startsWith("Hostname not allowed by fetch_content domain policy") ||
68
- message.startsWith("Too many redirects fetching ") ||
69
- message === "Only HTTP and HTTPS URLs can be fetched remotely" ||
70
- message === "URL must include a hostname" ||
71
- message.startsWith("Failed to resolve ");
72
- }
73
-
74
- function imageGateError(): string | null {
75
- try {
76
- return isImageEnabled() ? null : "Image fetching is disabled by image.enabled";
77
- } catch (err) {
78
- return errorMessage(err);
79
- }
80
- }
81
-
82
- async function resolveAuthCookieHeader(url: string | URL, profile: AuthFetchProfile): Promise<string> {
83
- const parsed = assertAuthFetchUrl(profile, url.toString());
84
- const result = await getBrowserCookiesForHosts({ hosts: [parsed.hostname], profile: profile.chromeProfile, requestUrl: parsed });
85
- if (result?.cookieHeader) return result.cookieHeader;
86
- if (!result) {
87
- const diagnostic = getLastBrowserCookieDiagnostic();
88
- throw new Error(`Authenticated fetch profile ${profile.name} could not read browser cookies${diagnostic ? `: ${diagnostic}` : ""}`);
89
- }
90
- throw new Error(`Authenticated fetch profile ${profile.name} could not build a cookie header`);
91
- }
92
-
93
- const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
94
-
95
- async function fetchAuthenticatedRemoteUrl(
96
- url: string,
97
- init: RequestInit,
98
- validationOptions: { ssrf: SsrfConfig; domainPolicy: DomainPolicy; lookup?: Lookup },
99
- profile: AuthFetchProfile,
100
- ): Promise<Response> {
101
- let current = await validateRemoteUrl(url, {
102
- allowRanges: validationOptions.ssrf.allowRanges,
103
- trustEnvProxy: validationOptions.ssrf.trustEnvProxy,
104
- domainPolicy: validationOptions.domainPolicy,
105
- ...(validationOptions.lookup ? { lookup: validationOptions.lookup } : {}),
106
- });
107
- let requestInit = init;
108
- for (let redirects = 0; redirects <= 5; redirects++) {
109
- const cookieHeader = await resolveAuthCookieHeader(current, profile);
110
- const headers = { ...(requestInit.headers as Record<string, string>), cookie: cookieHeader };
111
- const response = await fetch(current, { ...requestInit, headers, redirect: "manual" });
112
- if (!REDIRECT_STATUSES.has(response.status)) return response;
113
- const location = response.headers.get("location");
114
- if (!location) return response;
115
- if (redirects === 5) throw new Error(`Too many redirects fetching ${current.toString()}`);
116
- const from = current;
117
- current = await validateRemoteUrl(new URL(location, current), {
118
- allowRanges: validationOptions.ssrf.allowRanges,
119
- trustEnvProxy: validationOptions.ssrf.trustEnvProxy,
120
- domainPolicy: validationOptions.domainPolicy,
121
- ...(validationOptions.lookup ? { lookup: validationOptions.lookup } : {}),
122
- });
123
- authFetchRedirectGuard(profile, from, current);
124
- if (response.status === 303 || ((response.status === 301 || response.status === 302) && requestInit.method?.toUpperCase() === "POST")) {
125
- const { body: _body, ...nextInit } = requestInit;
126
- requestInit = { ...nextInit, method: "GET" };
127
- }
128
- }
129
- throw new Error(`Too many redirects fetching ${current.toString()}`);
130
- }
131
-
132
- function loadFetchRouting(): FetchRouting {
133
- if (!existsSync(WEB_SEARCH_CONFIG_PATH)) {
134
- return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
135
- }
136
-
137
- let raw: Record<string, unknown>;
138
- try {
139
- const parsed: unknown = JSON.parse(readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8"));
140
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
141
- throw new Error("expected a JSON object");
142
- }
143
- raw = parsed as Record<string, unknown>;
144
- } catch (err) {
145
- const message = err instanceof Error ? err.message : String(err);
146
- throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
147
- }
148
-
149
- if (!Object.hasOwn(raw, "fetchRouting")) {
150
- return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
151
- }
152
- const routing = raw.fetchRouting;
153
- if (!routing || typeof routing !== "object" || Array.isArray(routing)) {
154
- throw new Error(`fetchRouting in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
155
- }
156
-
157
- const routingConfig = routing as Record<string, unknown>;
158
- const providersValue = routingConfig.providers;
159
- let providers = DEFAULT_FETCH_PROVIDER_ORDER;
160
- if (providersValue !== undefined) {
161
- if (!Array.isArray(providersValue) || providersValue.length === 0) {
162
- throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array`);
163
- }
164
-
165
- providers = [];
166
- for (const provider of providersValue) {
167
- const normalized = typeof provider === "string" ? provider.trim().toLowerCase() : "";
168
- if (!FETCH_PROVIDERS.includes(normalized as FetchProvider)) {
169
- throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} contains an invalid provider: ${String(provider)}`);
170
- }
171
- if (providers.includes(normalized as FetchProvider)) {
172
- throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} must not contain duplicates: ${normalized}`);
173
- }
174
- providers.push(normalized as FetchProvider);
175
- }
176
- }
177
-
178
- const allowRemoteHostedProvidersValue = routingConfig.allowRemoteHostedProviders;
179
- if (allowRemoteHostedProvidersValue !== undefined && typeof allowRemoteHostedProvidersValue !== "boolean") {
180
- throw new Error(`fetchRouting.allowRemoteHostedProviders in ${WEB_SEARCH_CONFIG_PATH} must be a boolean`);
181
- }
182
-
183
- return { providers, allowRemoteHostedProviders: allowRemoteHostedProvidersValue === true };
184
- }
185
-
186
- /** Names of the search/fetch tools the caller has actually registered, so
187
- * failure guidance never points at tools that do not exist in the session. */
188
- export interface RegisteredToolNames {
189
- webSearch?: string;
190
- fetchContent?: string;
191
- }
192
-
193
- /** Guidance for definitive origin 404/410 responses: no extraction provider
194
- * can retrieve a page the origin says is gone, so point at the registered
195
- * search/fetch tools (when the caller knows them) instead of provider config. */
196
- function notFoundGuidance(result: ExtractedContent, toolNames?: RegisteredToolNames): string {
197
- const lines = [
198
- result.error ?? `HTTP ${result.status}`,
199
- "",
200
- `The origin server says this page does not exist (HTTP ${result.status}), so extraction providers cannot retrieve it.`,
201
- ];
202
- if (toolNames?.webSearch && toolNames.fetchContent) {
203
- lines.push(`The page may have moved or been renamed. Use ${toolNames.webSearch} to find the current URL, then retry ${toolNames.fetchContent} with it.`);
204
- } else if (toolNames?.webSearch) {
205
- lines.push(`The page may have moved or been renamed. Use ${toolNames.webSearch} to find the current URL.`);
206
- } else {
207
- lines.push("The page may have moved or been renamed. Find the current URL, then retry the fetch with it.");
208
- }
209
- return lines.join("\n");
210
- }
211
-
212
- function abortedResult(url: string): ExtractedContent {
213
- return { url, title: "", content: "", error: "Aborted" };
214
- }
215
-
216
- const turndown = new TurndownService({
217
- headingStyle: "atx",
218
- codeBlockStyle: "fenced",
219
- });
220
-
221
- const fetchLimit = pLimit(CONCURRENT_LIMIT);
222
-
223
- export interface VideoFrame {
224
- data: string;
225
- mimeType: string;
226
- timestamp: string;
227
- }
228
-
229
- export type FrameData = { data: string; mimeType: string };
230
- export type FrameResult = FrameData | { error: string };
231
-
232
- export interface ExtractedContent {
233
- url: string;
234
- title: string;
235
- content: string;
236
- error: string | null;
237
- thumbnail?: { data: string; mimeType: string };
238
- frames?: VideoFrame[];
239
- duration?: number;
240
- mimeType?: string;
241
- status?: number;
242
- }
243
-
244
- type HttpExtractedContent = ExtractedContent & { declaredLinks?: DeclaredWebLink[] };
245
-
246
- export interface ExtractOptions {
247
- timeoutMs?: number;
248
- forceClone?: boolean;
249
- prompt?: string;
250
- timestamp?: string;
251
- frames?: number;
252
- model?: string;
253
- mode?: "readable" | "raw" | "answer";
254
- answerModel?: string;
255
- authFetchProfile?: AuthFetchProfile;
256
- toolNames?: RegisteredToolNames;
257
- /** Optional http(s) proxy URL; routed through the curl-backed transport. */
258
- proxy?: string;
259
- /** Custom DNS resolver used for SSRF validation. Primarily a test seam. */
260
- lookup?: Lookup;
261
- }
262
-
263
- const JINA_READER_BASE = "https://r.jina.ai/";
264
- const JINA_TIMEOUT_MS = 30000;
265
-
266
- async function extractWithJinaReader(
267
- url: string,
268
- signal?: AbortSignal,
269
- lookup?: Lookup,
270
- ): Promise<ExtractedContent | null> {
271
- const jinaUrl = JINA_READER_BASE + url;
272
-
273
- const activityId = activityMonitor.logStart({ type: "api", query: `jina: ${url}` });
274
-
275
- try {
276
- const ssrf = loadSsrfConfig();
277
- const domainPolicy = loadFetchContentDomainPolicy();
278
- await validateRemoteUrl(url, {
279
- allowRanges: ssrf.allowRanges,
280
- trustEnvProxy: ssrf.trustEnvProxy,
281
- domainPolicy,
282
- ...(lookup ? { lookup } : {}),
283
- });
284
- const res = await fetch(jinaUrl, {
285
- headers: {
286
- "Accept": "text/markdown",
287
- "X-No-Cache": "true",
288
- },
289
- signal: AbortSignal.any([
290
- AbortSignal.timeout(JINA_TIMEOUT_MS),
291
- ...(signal ? [signal] : []),
292
- ]),
293
- });
294
-
295
- if (!res.ok) {
296
- activityMonitor.logComplete(activityId, res.status);
297
- return null;
298
- }
299
-
300
- const content = await res.text();
301
- activityMonitor.logComplete(activityId, res.status);
302
-
303
- const contentStart = content.indexOf("Markdown Content:");
304
- if (contentStart < 0) {
305
- return null;
306
- }
307
-
308
- const markdownPart = content.slice(contentStart + 17).trim(); // 17 = "Markdown Content:".length
309
-
310
- // Check for failed JS rendering or minimal content
311
- if (markdownPart.length < 100 ||
312
- markdownPart.startsWith("Loading...") ||
313
- markdownPart.startsWith("Please enable JavaScript")) {
314
- return null;
315
- }
316
-
317
- const title = extractHeadingTitle(markdownPart) ?? (new URL(url).pathname.split("/").pop() || url);
318
- return { url, title, content: markdownPart, error: null };
319
- } catch (err) {
320
- const message = err instanceof Error ? err.message : String(err);
321
- if (message.toLowerCase().includes("abort")) {
322
- activityMonitor.logComplete(activityId, 0);
323
- } else {
324
- activityMonitor.logError(activityId, message);
325
- }
326
- return null;
327
- }
328
- }
329
-
330
- function parseTimestamp(ts: string): number | null {
331
- const num = Number(ts);
332
- if (!isNaN(num) && num >= 0) return Math.floor(num);
333
- const parts = ts.split(":").map(Number);
334
- if (parts.some(p => isNaN(p) || p < 0)) return null;
335
- if (parts.length === 3) return Math.floor(parts[0] * 3600 + parts[1] * 60 + parts[2]);
336
- if (parts.length === 2) return Math.floor(parts[0] * 60 + parts[1]);
337
- return null;
338
- }
339
-
340
- type TimestampSpec = { type: "single"; seconds: number } | { type: "range"; start: number; end: number };
341
-
342
- function parseTimestampSpec(ts: string): TimestampSpec | null {
343
- const dashIdx = ts.indexOf("-", 1);
344
- if (dashIdx > 0) {
345
- const start = parseTimestamp(ts.slice(0, dashIdx));
346
- const end = parseTimestamp(ts.slice(dashIdx + 1));
347
- if (start !== null && end !== null && end > start) return { type: "range", start, end };
348
- }
349
- const seconds = parseTimestamp(ts);
350
- return seconds !== null ? { type: "single", seconds } : null;
351
- }
352
-
353
- const DEFAULT_RANGE_FRAMES = 6;
354
- const MIN_FRAME_INTERVAL = 5;
355
-
356
- function computeRangeTimestamps(start: number, end: number, maxFrames: number = DEFAULT_RANGE_FRAMES): number[] {
357
- if (maxFrames <= 1) return [start];
358
- const duration = end - start;
359
- const idealInterval = duration / (maxFrames - 1);
360
- if (idealInterval < MIN_FRAME_INTERVAL) {
361
- const timestamps: number[] = [];
362
- for (let t = start; t <= end && timestamps.length < maxFrames; t += MIN_FRAME_INTERVAL) {
363
- timestamps.push(t);
364
- }
365
- return timestamps;
366
- }
367
- return Array.from({ length: maxFrames }, (_, i) => Math.round(start + i * idealInterval));
368
- }
369
-
370
- function buildFrameResult(
371
- url: string, label: string, requestedCount: number,
372
- frames: VideoFrame[], error: string | null, duration?: number,
373
- ): ExtractedContent {
374
- if (frames.length === 0) {
375
- const msg = error ?? "Frame extraction failed";
376
- return { url, title: `Frames ${label} (0/${requestedCount})`, content: msg, error: msg };
377
- }
378
- return {
379
- url,
380
- title: `Frames ${label} (${frames.length}/${requestedCount})`,
381
- content: `${frames.length} frames extracted from ${label}`,
382
- error: null,
383
- frames,
384
- ...(duration !== undefined ? { duration } : {}),
385
- };
386
- }
387
-
388
- async function extractLocalFrames(
389
- filePath: string, timestamps: number[],
390
- ): Promise<{ frames: VideoFrame[]; error: string | null }> {
391
- const results = await Promise.all(timestamps.map(async (t) => {
392
- const frame = await extractVideoFrame(filePath, t);
393
- if ("error" in frame) return { error: frame.error };
394
- return { ...frame, timestamp: formatSeconds(t) };
395
- }));
396
- const frames = results.filter((f): f is VideoFrame => "data" in f);
397
- const firstError = results.find((f): f is { error: string } => "error" in f);
398
- return { frames, error: frames.length === 0 && firstError ? firstError.error : null };
399
- }
400
-
401
- type LocalVideoInfoResult =
402
- | { status: "video"; info: NonNullable<ReturnType<typeof isVideoFile>> }
403
- | { status: "not-video" }
404
- | { status: "invalid"; error: string };
405
-
406
- function safeVideoInfo(url: string): LocalVideoInfoResult {
407
- try {
408
- const info = isVideoFile(url);
409
- return info ? { status: "video", info } : { status: "not-video" };
410
- } catch (err) {
411
- return { status: "invalid", error: errorMessage(err) };
412
- }
413
- }
414
-
415
- export async function extractContent(
416
- url: string,
417
- signal?: AbortSignal,
418
- options?: ExtractOptions,
419
- ): Promise<ExtractedContent> {
420
- if (signal?.aborted) {
421
- return { url, title: "", content: "", error: "Aborted" };
422
- }
423
-
424
- let remoteUrl: URL | null = null;
425
- try {
426
- const parsed = new URL(url);
427
- if (parsed.protocol === "http:" || parsed.protocol === "https:") remoteUrl = parsed;
428
- } catch {
429
- }
430
- if (remoteUrl) {
431
- try {
432
- const ssrf = loadSsrfConfig();
433
- const domainPolicy = loadFetchContentDomainPolicy();
434
- await validateRemoteUrl(remoteUrl, {
435
- allowRanges: ssrf.allowRanges,
436
- trustEnvProxy: ssrf.trustEnvProxy,
437
- domainPolicy,
438
- ...(options?.lookup ? { lookup: options.lookup } : {}),
439
- });
440
- } catch (err) {
441
- return { url, title: "", content: "", error: errorMessage(err) };
442
- }
443
- }
444
-
445
- if (options?.authFetchProfile) {
446
- try {
447
- return await extractViaHttp(url, signal, options);
448
- } catch (err) {
449
- return { url, title: "", content: "", error: errorMessage(err) };
450
- }
451
- }
452
-
453
- if (options?.mode === "raw") {
454
- return extractViaHttp(url, signal, options);
455
- }
456
-
457
- if (options?.frames || options?.timestamp) {
458
- const disabled = imageGateError();
459
- if (disabled) return { url, title: "", content: "", error: disabled };
460
- }
461
-
462
- if (options?.frames && !options.timestamp) {
463
- const frameCount = options.frames;
464
- const ytInfo = isYouTubeURL(url);
465
- if (ytInfo.isYouTube && ytInfo.videoId) {
466
- const streamInfo = await getYouTubeStreamInfo(ytInfo.videoId);
467
- if ("error" in streamInfo) {
468
- return { url, title: "Frames", content: streamInfo.error, error: streamInfo.error };
469
- }
470
- if (streamInfo.duration === null) {
471
- const error = "Cannot determine video duration. Use a timestamp range instead.";
472
- return { url, title: "Frames", content: error, error };
473
- }
474
- const dur = Math.floor(streamInfo.duration);
475
- const timestamps = computeRangeTimestamps(0, dur, frameCount);
476
- const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
477
- const label = `${formatSeconds(0)}-${formatSeconds(dur)}`;
478
- return buildFrameResult(url, label, timestamps.length, result.frames, result.error, streamInfo.duration);
479
- }
480
-
481
- const localVideo = safeVideoInfo(url);
482
- if (localVideo.status === "invalid") {
483
- return { url, title: "", content: "", error: localVideo.error };
484
- }
485
- if (localVideo.status === "video") {
486
- const durationResult = await getLocalVideoDuration(localVideo.info.absolutePath);
487
- if (typeof durationResult !== "number") {
488
- return { url, title: "Frames", content: durationResult.error, error: durationResult.error };
489
- }
490
- const dur = Math.floor(durationResult);
491
- const timestamps = computeRangeTimestamps(0, dur, frameCount);
492
- const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
493
- const label = `${formatSeconds(0)}-${formatSeconds(dur)}`;
494
- return buildFrameResult(url, label, timestamps.length, result.frames, result.error, durationResult);
495
- }
496
-
497
- return { url, title: "", content: "", error: "Frame extraction only works with YouTube and local video files" };
498
- }
499
-
500
- if (options?.timestamp) {
501
- const spec = parseTimestampSpec(options.timestamp);
502
- if (!spec) {
503
- return {
504
- url,
505
- title: "",
506
- content: "",
507
- error: `Invalid timestamp format: "${options.timestamp}". Use "H:MM:SS", "MM:SS", "85", or "start-end".`,
508
- };
509
- }
510
-
511
- const frameCount = options.frames;
512
- const ytInfo = isYouTubeURL(url);
513
- if (ytInfo.isYouTube && ytInfo.videoId) {
514
- const streamInfo = await getYouTubeStreamInfo(ytInfo.videoId);
515
- if ("error" in streamInfo) {
516
- if (spec.type === "range") {
517
- const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
518
- return { url, title: `Frames ${label}`, content: streamInfo.error, error: streamInfo.error };
519
- }
520
- if (frameCount) {
521
- const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
522
- const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
523
- return { url, title: `Frames ${label}`, content: streamInfo.error, error: streamInfo.error };
524
- }
525
- return { url, title: `Frame at ${options.timestamp}`, content: streamInfo.error, error: streamInfo.error };
526
- }
527
-
528
- if (spec.type === "range") {
529
- const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
530
- if (streamInfo.duration !== null && spec.end > streamInfo.duration) {
531
- const error = `Timestamp ${formatSeconds(spec.end)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
532
- return { url, title: `Frames ${label}`, content: error, error };
533
- }
534
- const timestamps = frameCount
535
- ? computeRangeTimestamps(spec.start, spec.end, frameCount)
536
- : computeRangeTimestamps(spec.start, spec.end);
537
- const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
538
- return buildFrameResult(url, label, timestamps.length, result.frames, result.error, result.duration ?? undefined);
539
- }
540
-
541
- if (frameCount) {
542
- const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
543
- const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
544
- if (streamInfo.duration !== null && end > streamInfo.duration) {
545
- const error = `Timestamp ${formatSeconds(end)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
546
- return { url, title: `Frames ${label}`, content: error, error };
547
- }
548
- const timestamps = computeRangeTimestamps(spec.seconds, end, frameCount);
549
- const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
550
- return buildFrameResult(url, label, timestamps.length, result.frames, result.error, result.duration ?? undefined);
551
- }
552
-
553
- if (streamInfo.duration !== null && spec.seconds > streamInfo.duration) {
554
- const error = `Timestamp ${formatSeconds(spec.seconds)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
555
- return { url, title: `Frame at ${options.timestamp}`, content: error, error };
556
- }
557
- const frame = await extractYouTubeFrame(ytInfo.videoId, spec.seconds, streamInfo);
558
- if ("error" in frame) {
559
- return { url, title: `Frame at ${options.timestamp}`, content: frame.error, error: frame.error };
560
- }
561
- return { url, title: `Frame at ${options.timestamp}`, content: `Video frame at ${options.timestamp}`, error: null, thumbnail: frame };
562
- }
563
-
564
- const localVideo = safeVideoInfo(url);
565
- if (localVideo.status === "invalid") {
566
- return { url, title: "", content: "", error: localVideo.error };
567
- }
568
- if (localVideo.status === "video") {
569
- if (spec.type === "range") {
570
- const timestamps = frameCount
571
- ? computeRangeTimestamps(spec.start, spec.end, frameCount)
572
- : computeRangeTimestamps(spec.start, spec.end);
573
- const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
574
- const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
575
- return buildFrameResult(url, label, timestamps.length, result.frames, result.error);
576
- }
577
-
578
- if (frameCount) {
579
- const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
580
- const timestamps = computeRangeTimestamps(spec.seconds, end, frameCount);
581
- const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
582
- const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
583
- return buildFrameResult(url, label, timestamps.length, result.frames, result.error);
584
- }
585
-
586
- const frame = await extractVideoFrame(localVideo.info.absolutePath, spec.seconds);
587
- if ("error" in frame) {
588
- return { url, title: `Frame at ${options.timestamp}`, content: frame.error, error: frame.error };
589
- }
590
- return { url, title: `Frame at ${options.timestamp}`, content: `Video frame at ${options.timestamp}`, error: null, thumbnail: frame };
591
- }
592
-
593
- return { url, title: "", content: "", error: "Timestamp extraction only works with YouTube and local video files" };
594
- }
595
-
596
- const localVideo = safeVideoInfo(url);
597
- if (localVideo.status === "invalid") {
598
- return { url, title: "", content: "", error: localVideo.error };
599
- }
600
- if (localVideo.status === "video") {
601
- try {
602
- const result = await extractVideo(localVideo.info, signal, options);
603
- if (signal?.aborted) return abortedResult(url);
604
- return result ?? { url, title: "", content: "", error: `Video analysis requires Gemini access. Either:\n 1. Sign into gemini.google.com in Chrome (free, uses cookies)\n 2. Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH}` };
605
- } catch (err) {
606
- if (isAbortError(err)) return abortedResult(url);
607
- return { url, title: "", content: "", error: errorMessage(err) };
608
- }
609
- }
610
-
611
- try {
612
- if (!remoteUrl) new URL(url);
613
- } catch (err) {
614
- return { url, title: "", content: "", error: errorMessage(err) };
615
- }
616
-
617
- try {
618
- const ghIssuePrResult = await extractGitHubIssuePr(url, signal, options);
619
- if (ghIssuePrResult) return ghIssuePrResult;
620
- if (signal?.aborted) return abortedResult(url);
621
- } catch (err) {
622
- const message = errorMessage(err);
623
- if (isAbortError(err)) return abortedResult(url);
624
- if (isConfigParseError(err)) {
625
- return { url, title: "", content: "", error: message };
626
- }
627
- }
628
-
629
- try {
630
- const ghResult = await extractGitHub(url, signal, options?.forceClone);
631
- if (ghResult) return ghResult;
632
- if (signal?.aborted) return abortedResult(url);
633
- } catch (err) {
634
- const message = errorMessage(err);
635
- if (isAbortError(err)) return abortedResult(url);
636
- if (isConfigParseError(err)) {
637
- return { url, title: "", content: "", error: message };
638
- }
639
- }
640
-
641
- const ytInfo = isYouTubeURL(url);
642
- let youtubeEnabled = false;
643
- try {
644
- youtubeEnabled = isYouTubeEnabled();
645
- } catch (err) {
646
- return { url, title: "", content: "", error: errorMessage(err) };
647
- }
648
- if (ytInfo.isYouTube && youtubeEnabled) {
649
- try {
650
- const ytResult = await extractYouTube(url, signal, options?.prompt, options?.model);
651
- if (ytResult) return ytResult;
652
- if (signal?.aborted) return abortedResult(url);
653
- } catch (err) {
654
- const message = errorMessage(err);
655
- if (isAbortError(err)) return abortedResult(url);
656
- return { url, title: "", content: "", error: message };
657
- }
658
- return {
659
- url,
660
- title: "",
661
- content: "",
662
- error: "Could not extract YouTube video content. Sign into Google in a supported Chromium browser for automatic access, or set GEMINI_API_KEY.",
663
- };
664
- }
665
-
666
- if (signal?.aborted) return abortedResult(url);
667
-
668
- let fetchRouting: FetchRouting;
669
- try {
670
- fetchRouting = loadFetchRouting();
671
- } catch (err) {
672
- return { url, title: "", content: "", error: errorMessage(err) };
673
- }
674
- const providerOrder = remoteUrl && !fetchRouting.allowRemoteHostedProviders
675
- ? fetchRouting.providers.filter(provider => !REMOTE_HOSTED_FETCH_PROVIDERS.has(provider))
676
- : fetchRouting.providers;
677
- if (providerOrder.length === 0) {
678
- return {
679
- url,
680
- title: "",
681
- content: "",
682
- error: "Remote hosted fetch providers are disabled unless fetchRouting.allowRemoteHostedProviders is true",
683
- };
684
- }
685
-
686
- let httpResult: ExtractedContent | null = null;
687
- let declaredLinks: DeclaredWebLink[] = [];
688
- const withDeclaredLinks = (result: ExtractedContent): ExtractedContent => ({
689
- ...result,
690
- content: appendDeclaredWebLinks(result.content, declaredLinks),
691
- });
692
- const parseErrorResult = (message: string): ExtractedContent => httpResult
693
- ? { ...httpResult, error: message }
694
- : { url, title: "", content: "", error: message };
695
- const runHttpProvider = async (): Promise<ExtractedContent | null> => {
696
- const { declaredLinks: discoveredLinks = [], ...result } = await extractViaHttp(url, signal, options);
697
- httpResult = result;
698
- declaredLinks = discoveredLinks;
699
- if (signal?.aborted) return abortedResult(url);
700
- if (!httpResult.error) return httpResult;
701
- if (NON_RECOVERABLE_ERRORS.some(prefix => httpResult!.error!.startsWith(prefix)) || isRedirectPolicyError(httpResult.error) || isConfigParseError(httpResult.error)) {
702
- return httpResult;
703
- }
704
- return null;
705
- };
706
-
707
- let brightdataError: string | null = null;
708
-
709
- if (remoteUrl && providerOrder[0] !== "http") {
710
- const httpGateResult = await runHttpProvider();
711
- if (httpGateResult) return httpGateResult;
712
- }
713
-
714
- for (const provider of providerOrder) {
715
- if (signal?.aborted) return abortedResult(url);
716
-
717
- if (provider === "http") {
718
- const result = await runHttpProvider();
719
- if (result) return result;
720
- continue;
721
- }
722
-
723
-
724
- if (provider === "jina") {
725
- const jinaResult = await extractWithJinaReader(url, signal, options?.lookup);
726
- if (jinaResult) return withDeclaredLinks(jinaResult);
727
- continue;
728
- }
729
-
730
-
731
-
732
-
733
-
734
-
735
-
736
-
737
- if (provider === "brightdata") {
738
- try {
739
- if (isBrightDataUnlockerAvailable()) {
740
- const ssrf = loadSsrfConfig();
741
- const brightdataResult = await extractWithBrightDataUnlocker(url, signal, {
742
- timeoutMs: options?.timeoutMs,
743
- ...(options?.lookup ? { lookup: options.lookup } : {}),
744
- ssrf,
745
- });
746
- if (brightdataResult) return withDeclaredLinks(brightdataResult);
747
- }
748
- } catch (err) {
749
- if (isAbortError(err)) return abortedResult(url);
750
- brightdataError = errorMessage(err);
751
- if (isConfigParseError(err)) return parseErrorResult(brightdataError);
752
- }
753
- continue;
754
- }
755
-
756
- if (provider === "gemini") {
757
- let geminiResult: ExtractedContent | null = null;
758
- try {
759
- geminiResult = await extractWithUrlContext(url, signal)
760
- ?? await extractWithGeminiWeb(url, signal);
761
- } catch (err) {
762
- if (isAbortError(err)) return abortedResult(url);
763
- if (err instanceof CredentialResolutionError || isConfigParseError(err)) {
764
- return parseErrorResult(errorMessage(err));
765
- }
766
- }
767
- if (geminiResult) return withDeclaredLinks(geminiResult);
768
- }
769
- }
770
-
771
- if (signal?.aborted) return abortedResult(url);
772
- const finalHttpResult = httpResult as ExtractedContent | null;
773
- if (finalHttpResult && declaredLinks.length > 0) return { ...finalHttpResult, error: null };
774
-
775
- // A definitive 404/410 from the origin means no extraction provider can
776
- // retrieve the page, so the provider-configuration checklist below would
777
- // send users down the wrong path. Point at search instead.
778
- if (finalHttpResult?.status === 404 || finalHttpResult?.status === 410) {
779
- return { ...finalHttpResult, error: notFoundGuidance(finalHttpResult, options?.toolNames) };
780
- }
781
-
782
- const searchToolName = options?.toolNames?.webSearch;
783
- const guidance = [
784
- finalHttpResult?.error ?? "No fetch_content provider returned content",
785
- ...(brightdataError ? [`Bright Data fallback failed: ${brightdataError}`] : []),
786
- "",
787
- "Fallback options:",
788
- ` • Set brightdataApiKey and brightdataUnlockerZone in ${WEB_SEARCH_CONFIG_PATH} or BRIGHTDATA_API_KEY and BRIGHTDATA_UNLOCKER_ZONE`,
789
- ` • Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH}`,
790
- " • Sign into gemini.google.com in Chrome",
791
- ...(searchToolName ? [` • Use ${searchToolName} to find content about this topic`] : []),
792
- ].join("\n");
793
- return { ...(finalHttpResult ?? { url, title: "", content: "", error: null }), error: guidance };
794
- }
795
-
796
- function isLikelyJSRendered(html: string): boolean {
797
- const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
798
- if (!bodyMatch) return false;
799
-
800
- const bodyHtml = bodyMatch[1];
801
-
802
- const textContent = bodyHtml
803
- .replace(/<script[\s\S]*?<\/script>/gi, "")
804
- .replace(/<style[\s\S]*?<\/style>/gi, "")
805
- .replace(/<[^>]+>/g, "")
806
- .replace(/\s+/g, " ")
807
- .trim();
808
-
809
- const scriptCount = (html.match(/<script/gi) || []).length;
810
-
811
- return textContent.length < 500 && scriptCount > 3;
812
- }
813
-
814
- export async function readPDFResponseBuffer(response: Response, maxSizeMB: number): Promise<ArrayBuffer> {
815
- const maxBytes = maxSizeMB * 1024 * 1024;
816
- return readResponseBufferWithLimit(response, maxBytes, () => pdfSizeLimitError(maxSizeMB));
817
- }
818
-
819
- async function readTextResponseWithLimit(response: Response, maxBytes: number): Promise<string> {
820
- const buffer = await readResponseBufferWithLimit(response, maxBytes, () => responseSizeLimitError(maxBytes));
821
- const charset = response.headers.get("content-type")?.match(/charset\s*=\s*["']?([^;"'\s]+)/i)?.[1];
822
- try {
823
- return new TextDecoder(charset || "utf-8").decode(buffer);
824
- } catch {
825
- return new TextDecoder("utf-8").decode(buffer);
826
- }
827
- }
828
-
829
- function isTextContentType(contentType: string): boolean {
830
- const mimeType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
831
- return mimeType.startsWith("text/") ||
832
- mimeType === "application/json" ||
833
- mimeType === "application/ld+json" ||
834
- mimeType === "application/xml" ||
835
- mimeType === "application/xhtml+xml" ||
836
- mimeType === "application/javascript" ||
837
- mimeType === "application/x-javascript" ||
838
- mimeType.endsWith("+json") ||
839
- mimeType.endsWith("+xml");
840
- }
841
-
842
- async function readResponseBufferWithLimit(
843
- response: Response,
844
- maxBytes: number,
845
- buildError: () => Error,
846
- ): Promise<ArrayBuffer> {
847
- const reader = response.body?.getReader();
848
- if (!reader) {
849
- const buffer = await response.arrayBuffer();
850
- if (buffer.byteLength > maxBytes) throw buildError();
851
- return buffer;
852
- }
853
-
854
- const chunks: Uint8Array[] = [];
855
- let totalBytes = 0;
856
- try {
857
- while (true) {
858
- const { done, value } = await reader.read();
859
- if (done) break;
860
- if (!value) continue;
861
- totalBytes += value.byteLength;
862
- if (totalBytes > maxBytes) {
863
- await reader.cancel();
864
- throw buildError();
865
- }
866
- chunks.push(value);
867
- }
868
- } finally {
869
- reader.releaseLock();
870
- }
871
-
872
- const combined = new Uint8Array(totalBytes);
873
- let offset = 0;
874
- for (const chunk of chunks) {
875
- combined.set(chunk, offset);
876
- offset += chunk.byteLength;
877
- }
878
- return combined.buffer;
879
- }
880
-
881
- function pdfSizeLimitError(maxSizeMB: number): Error {
882
- return new Error(`PDF exceeds configured pdf.maxSizeMB limit (${maxSizeMB} MB)`);
883
- }
884
-
885
- function responseSizeLimitError(maxBytes: number): Error {
886
- return new Error(`Response too large (${Math.round(maxBytes / 1024 / 1024)}MB)`);
887
- }
888
-
889
- async function extractViaHttp(
890
- url: string,
891
- signal?: AbortSignal,
892
- options?: ExtractOptions,
893
- ): Promise<HttpExtractedContent> {
894
- const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
895
- const activityId = activityMonitor.logStart({ type: "fetch", url });
896
-
897
- const controller = new AbortController();
898
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
899
-
900
- const onAbort = () => controller.abort();
901
- signal?.addEventListener("abort", onAbort);
902
-
903
- try {
904
- const ssrf = loadSsrfConfig();
905
- const domainPolicy = loadFetchContentDomainPolicy();
906
- const authProfile = options?.authFetchProfile;
907
- const trustEnvProxy = options?.proxy === undefined && ssrf.trustEnvProxy;
908
- const requestInit: ProxiedRequestInit = {
909
- signal: controller.signal,
910
- __proxy: options?.proxy,
911
- headers: {
912
- "User-Agent": "OpenAI File Downloader, XaiImageApiFetch/1.0",
913
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
914
- "Accept-Language": "en-US,en;q=0.9",
915
- "Cache-Control": "no-cache",
916
- "Sec-Fetch-Dest": "document",
917
- "Sec-Fetch-Mode": "navigate",
918
- "Sec-Fetch-Site": "none",
919
- "Sec-Fetch-User": "?1",
920
- "Upgrade-Insecure-Requests": "1",
921
- },
922
- };
923
- const response = authProfile
924
- ? await fetchAuthenticatedRemoteUrl(url, requestInit, { ssrf: { ...ssrf, trustEnvProxy }, domainPolicy, ...(options?.lookup ? { lookup: options.lookup } : {}) }, authProfile)
925
- : await fetchRemoteUrl(
926
- url,
927
- requestInit,
928
- {
929
- allowRanges: ssrf.allowRanges,
930
- trustEnvProxy,
931
- domainPolicy,
932
- ...(options?.lookup ? { lookup: options.lookup } : {}),
933
- },
934
- );
935
-
936
- if (!response.ok && options?.mode !== "raw") {
937
- activityMonitor.logComplete(activityId, response.status);
938
- return {
939
- url,
940
- title: "",
941
- content: "",
942
- error: `HTTP ${response.status}: ${response.statusText}`,
943
- status: response.status,
944
- };
945
- }
946
-
947
- const contentLengthHeader = response.headers.get("content-length");
948
- const contentType = response.headers.get("content-type") || "";
949
- const mimeType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
950
- const isPDFContent = isPDF(url, contentType);
951
- const pdfConfig = isPDFContent ? loadPDFConfig() : null;
952
- if (isPDFContent && pdfConfig && !pdfConfig.enabled) {
953
- activityMonitor.logComplete(activityId, response.status);
954
- return { url, title: "", content: "", error: "PDF extraction is disabled by pdf.enabled", mimeType, status: response.status };
955
- }
956
- const maxResponseSize = (pdfConfig?.maxSizeMB ?? 5) * 1024 * 1024;
957
- if (contentLengthHeader) {
958
- const contentLength = Number.parseInt(contentLengthHeader, 10);
959
- if (Number.isFinite(contentLength) && contentLength > maxResponseSize) {
960
- activityMonitor.logComplete(activityId, response.status);
961
- return {
962
- url,
963
- title: "",
964
- content: "",
965
- error: pdfConfig
966
- ? pdfSizeLimitError(pdfConfig.maxSizeMB).message
967
- : `Response too large (${Math.round(contentLength / 1024 / 1024)}MB)`,
968
- };
969
- }
970
- }
971
-
972
- if (options?.mode === "raw") {
973
- if (!isTextContentType(contentType)) {
974
- activityMonitor.logComplete(activityId, response.status);
975
- return { url, title: "", content: "", error: `Unsupported content type in raw mode: ${mimeType || "missing"}`, mimeType, status: response.status };
976
- }
977
- const text = await readTextResponseWithLimit(response, maxResponseSize);
978
- activityMonitor.logComplete(activityId, response.status);
979
- return { url, title: extractTextTitle(text, url), content: text, error: null, mimeType, status: response.status };
980
- }
981
-
982
- if (SUPPORTED_IMAGE_TYPES.has(mimeType)) {
983
- const disabled = imageGateError();
984
- if (disabled) {
985
- activityMonitor.logComplete(activityId, response.status);
986
- return { url, title: "", content: "", error: disabled, mimeType, status: response.status };
987
- }
988
- try {
989
- const buffer = await readResponseBufferWithLimit(response, maxResponseSize, () => responseSizeLimitError(maxResponseSize));
990
- const resized = await resizeImage(new Uint8Array(buffer), mimeType, { maxWidth: 2000, maxHeight: 2000 });
991
- activityMonitor.logComplete(activityId, response.status);
992
- if (!resized) return { url, title: "", content: "", error: `Could not decode image: ${mimeType}`, mimeType, status: response.status };
993
- const title = new URL(response.url || url).pathname.split("/").pop() || url;
994
- return {
995
- url,
996
- title,
997
- content: `Image fetched (${resized.width}×${resized.height}, ${resized.mimeType})`,
998
- error: null,
999
- thumbnail: { data: resized.data, mimeType: resized.mimeType },
1000
- mimeType: resized.mimeType,
1001
- status: response.status,
1002
- };
1003
- } catch (err) {
1004
- const message = errorMessage(err);
1005
- activityMonitor.logError(activityId, message);
1006
- return { url, title: "", content: "", error: message, mimeType, status: response.status };
1007
- }
1008
- }
1009
-
1010
- if (isPDFContent && pdfConfig) {
1011
- try {
1012
- const buffer = await readPDFResponseBuffer(response, pdfConfig.maxSizeMB);
1013
- if (signal?.aborted) return abortedResult(url);
1014
- const result = await extractPDFToMarkdown(buffer, url, { signal });
1015
- activityMonitor.logComplete(activityId, response.status);
1016
- return {
1017
- url,
1018
- title: result.title,
1019
- content: `PDF extracted and saved to: ${result.outputPath}\n\nPages: ${result.pages}\nCharacters: ${result.chars}`,
1020
- error: null,
1021
- };
1022
- } catch (err) {
1023
- const message = err instanceof Error ? err.message : String(err);
1024
- activityMonitor.logError(activityId, message);
1025
- if (message.startsWith("PDF exceeds configured pdf.maxSizeMB limit")) {
1026
- return { url, title: "", content: "", error: message };
1027
- }
1028
- if (err instanceof CredentialResolutionError || isConfigParseError(err)) {
1029
- return { url, title: "", content: "", error: message };
1030
- }
1031
- return { url, title: "", content: "", error: `PDF extraction failed: ${message}` };
1032
- }
1033
- }
1034
-
1035
- if (contentType.includes("application/octet-stream") ||
1036
- contentType.includes("image/") ||
1037
- contentType.includes("audio/") ||
1038
- contentType.includes("video/") ||
1039
- contentType.includes("application/zip")) {
1040
- activityMonitor.logComplete(activityId, response.status);
1041
- return {
1042
- url,
1043
- title: "",
1044
- content: "",
1045
- error: `Unsupported content type: ${contentType.split(";")[0]}`,
1046
- };
1047
- }
1048
-
1049
- const text = await readTextResponseWithLimit(response, maxResponseSize);
1050
- const isHTML = contentType.includes("text/html") || contentType.includes("application/xhtml+xml");
1051
-
1052
- if (!isHTML) {
1053
- activityMonitor.logComplete(activityId, response.status);
1054
- const title = extractTextTitle(text, url);
1055
- return { url, title, content: text, error: null };
1056
- }
1057
-
1058
- const { document } = parseHTML(text);
1059
- const documentTitle = document.title?.trim() ?? "";
1060
- const declaredLinks = discoverDeclaredWebLinks(
1061
- document as unknown as Document,
1062
- response.headers.get("link"),
1063
- response.url || url,
1064
- );
1065
- const reader = new Readability(document as unknown as Document);
1066
- const article = reader.parse();
1067
-
1068
- if (!article) {
1069
- const rscResult = extractRSCContent(text);
1070
- if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT) {
1071
- activityMonitor.logComplete(activityId, response.status);
1072
- return {
1073
- url,
1074
- title: rscResult.title,
1075
- content: appendDeclaredWebLinks(rscResult.content, declaredLinks),
1076
- error: null,
1077
- declaredLinks,
1078
- };
1079
- }
1080
- controller.signal.throwIfAborted();
1081
- const defuddleResult = await extractWithDefuddle(text, response.url || url);
1082
- controller.signal.throwIfAborted();
1083
- if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT) {
1084
- activityMonitor.logComplete(activityId, response.status);
1085
- return {
1086
- url,
1087
- title: documentTitle || defuddleResult.title,
1088
- content: appendDeclaredWebLinks(defuddleResult.content, declaredLinks),
1089
- error: null,
1090
- declaredLinks,
1091
- };
1092
- }
1093
-
1094
- activityMonitor.logComplete(activityId, response.status);
1095
- const jsRendered = isLikelyJSRendered(text);
1096
- const errorMsg = jsRendered
1097
- ? "Page appears to be JavaScript-rendered (content loads dynamically)"
1098
- : "Could not extract readable content from HTML structure";
1099
-
1100
- return {
1101
- url,
1102
- title: documentTitle,
1103
- content: appendDeclaredWebLinks("", declaredLinks),
1104
- error: errorMsg,
1105
- declaredLinks,
1106
- };
1107
- }
1108
-
1109
- if (typeof article.content !== "string") {
1110
- throw new Error("Readability returned invalid article content");
1111
- }
1112
- const markdown = turndown.turndown(article.content);
1113
- activityMonitor.logComplete(activityId, response.status);
1114
-
1115
- if (markdown.length < MIN_USEFUL_CONTENT) {
1116
- const rscResult = extractRSCContent(text);
1117
- if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT) {
1118
- return {
1119
- url,
1120
- title: rscResult.title,
1121
- content: appendDeclaredWebLinks(rscResult.content, declaredLinks),
1122
- error: null,
1123
- declaredLinks,
1124
- };
1125
- }
1126
- controller.signal.throwIfAborted();
1127
- const defuddleResult = await extractWithDefuddle(text, response.url || url);
1128
- controller.signal.throwIfAborted();
1129
- if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT) {
1130
- return {
1131
- url,
1132
- title: article.title || documentTitle || defuddleResult.title,
1133
- content: appendDeclaredWebLinks(defuddleResult.content, declaredLinks),
1134
- error: null,
1135
- declaredLinks,
1136
- };
1137
- }
1138
- return {
1139
- url,
1140
- title: article.title || documentTitle,
1141
- content: appendDeclaredWebLinks(markdown, declaredLinks),
1142
- error: isLikelyJSRendered(text)
1143
- ? "Page appears to be JavaScript-rendered (content loads dynamically)"
1144
- : "Extracted content appears incomplete",
1145
- declaredLinks,
1146
- };
1147
- }
1148
-
1149
- return {
1150
- url,
1151
- title: article.title || documentTitle,
1152
- content: appendDeclaredWebLinks(markdown, declaredLinks),
1153
- error: null,
1154
- declaredLinks,
1155
- };
1156
- } catch (err) {
1157
- const message = err instanceof Error ? err.message : String(err);
1158
- if (message.toLowerCase().includes("abort")) {
1159
- activityMonitor.logComplete(activityId, 0);
1160
- } else {
1161
- activityMonitor.logError(activityId, message);
1162
- }
1163
- return { url, title: "", content: "", error: message };
1164
- } finally {
1165
- clearTimeout(timeoutId);
1166
- signal?.removeEventListener("abort", onAbort);
1167
- }
1168
- }
1169
-
1170
- export function extractHeadingTitle(text: string): string | null {
1171
- const match = text.match(/^#{1,2}\s+(.+)/m);
1172
- if (!match) return null;
1173
- const cleaned = match[1].replace(/\*+/g, "").trim();
1174
- return cleaned || null;
1175
- }
1176
-
1177
- function extractTextTitle(text: string, url: string): string {
1178
- return extractHeadingTitle(text) ?? (new URL(url).pathname.split("/").pop() || url);
1179
- }
1180
-
1181
- export async function fetchAllContent(
1182
- urls: string[],
1183
- signal?: AbortSignal,
1184
- options?: ExtractOptions,
1185
- ): Promise<ExtractedContent[]> {
1186
- const results = await Promise.all(urls.map((url) => fetchLimit(() => extractContent(url, signal, options))));
1187
- if (options?.mode === "raw") return results;
1188
- // Inline data: URIs in extracted markdown would otherwise flow into tool
1189
- // results and the fetch cache as opaque base64; typed thumbnail/frame image
1190
- // blocks are deliberate outputs and are left untouched.
1191
- return results.map((result, index) => {
1192
- if (!result.content) return result;
1193
- const sanitized = sanitizeInlineDataUris(result.content, `urls[${index}].content`);
1194
- return sanitized.omissions.length > 0 ? { ...result, content: sanitized.text } : result;
1195
- });
1196
- }
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { Readability } from "@mozilla/readability";
3
+ import { resizeImage } from "@earendil-works/pi-coding-agent";
4
+ import { parseHTML } from "linkedom";
5
+ import TurndownService from "turndown";
6
+ import pLimit from "p-limit";
7
+ import { activityMonitor } from "./activity.ts";
8
+ import { extractRSCContent } from "./rsc-extract.ts";
9
+ import { extractPDFToMarkdown, isPDF, loadPDFConfig } from "./pdf-extract.ts";
10
+ import { extractGitHub } from "./github-extract.ts";
11
+ import { extractGitHubIssuePr } from "./github-issue-pr.ts";
12
+ import { isYouTubeURL, isYouTubeEnabled, extractYouTube, extractYouTubeFrame, extractYouTubeFrames, getYouTubeStreamInfo } from "./youtube-extract.ts";
13
+ import { CredentialResolutionError } from "./credential-source.ts";
14
+ import { extractWithUrlContext, extractWithGeminiWeb } from "./gemini-url-context.ts";
15
+ import { extractWithBrightDataUnlocker, isBrightDataUnlockerAvailable } from "./brightdata-unlocker.ts";
16
+ import { isVideoFile, extractVideo, extractVideoFrame, getLocalVideoDuration } from "./video-extract.ts";
17
+ import { appendDeclaredWebLinks, discoverDeclaredWebLinks, type DeclaredWebLink } from "./declared-web-links.ts";
18
+ import { fetchRemoteUrl, loadFetchContentDomainPolicy, loadSsrfConfig, validateRemoteUrl, type DomainPolicy, type Lookup, type SsrfConfig } from "./ssrf-protection.ts";
19
+ import { formatSeconds, getWebSearchConfigPath, type ProxiedRequestInit } from "./utils.ts";
20
+ import { isImageEnabled } from "./feature-config.ts";
21
+ import { assertAuthFetchUrl, authFetchRedirectGuard, type AuthFetchProfile } from "./auth-fetch.ts";
22
+ import { getBrowserCookiesForHosts, getLastBrowserCookieDiagnostic } from "./chrome-cookies.ts";
23
+ import { sanitizeInlineDataUris } from "./data-uri-sanitize.ts";
24
+
25
+ const DEFAULT_TIMEOUT_MS = 30000;
26
+ const CONCURRENT_LIMIT = 3;
27
+
28
+ const NON_RECOVERABLE_ERRORS = ["Unsupported content type", "Response too large", "PDF extraction is disabled", "Image fetching is disabled"];
29
+ const MIN_USEFUL_CONTENT = 500;
30
+ const SUPPORTED_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
31
+ const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
32
+ const FETCH_PROVIDERS = ["http", "jina", "brightdata", "gemini"] as const;
33
+ type FetchProvider = typeof FETCH_PROVIDERS[number];
34
+ type FetchRouting = { providers: FetchProvider[]; allowRemoteHostedProviders: boolean };
35
+ const DEFAULT_FETCH_PROVIDER_ORDER: FetchProvider[] = ["http", "jina", "brightdata", "gemini"];
36
+ const REMOTE_HOSTED_FETCH_PROVIDERS = new Set<FetchProvider>(["jina", "brightdata", "gemini"]);
37
+
38
+ async function extractWithDefuddle(text: string, url: string): Promise<{ title: string; content: string } | null> {
39
+ const { Defuddle } = await import("defuddle/node");
40
+ const { document } = parseHTML(text);
41
+ const result = await Defuddle(document as unknown as Document, url, { markdown: true, useAsync: false });
42
+ return typeof result.content === "string" ? { title: result.title, content: result.content } : null;
43
+ }
44
+
45
+ export { loadSsrfConfig } from "./ssrf-protection.ts";
46
+
47
+ export function loadSsrfAllowRanges(): string[] {
48
+ return loadSsrfConfig().allowRanges;
49
+ }
50
+
51
+ function errorMessage(err: unknown): string {
52
+ return err instanceof Error ? err.message : String(err);
53
+ }
54
+
55
+ function isConfigParseError(err: unknown): boolean {
56
+ return errorMessage(err).startsWith("Failed to parse ");
57
+ }
58
+
59
+ function isAbortError(err: unknown): boolean {
60
+ return errorMessage(err).toLowerCase().includes("abort");
61
+ }
62
+
63
+ function isRedirectPolicyError(message: string): boolean {
64
+ return message.startsWith("Authenticated fetch refused cross-origin redirect") ||
65
+ message.startsWith("Blocked internal ") ||
66
+ message.startsWith("Blocked hostname by fetch_content domain policy") ||
67
+ message.startsWith("Hostname not allowed by fetch_content domain policy") ||
68
+ message.startsWith("Too many redirects fetching ") ||
69
+ message === "Only HTTP and HTTPS URLs can be fetched remotely" ||
70
+ message === "URL must include a hostname" ||
71
+ message.startsWith("Failed to resolve ");
72
+ }
73
+
74
+ function imageGateError(): string | null {
75
+ try {
76
+ return isImageEnabled() ? null : "Image fetching is disabled by image.enabled";
77
+ } catch (err) {
78
+ return errorMessage(err);
79
+ }
80
+ }
81
+
82
+ async function resolveAuthCookieHeader(url: string | URL, profile: AuthFetchProfile): Promise<string> {
83
+ const parsed = assertAuthFetchUrl(profile, url.toString());
84
+ const result = await getBrowserCookiesForHosts({ hosts: [parsed.hostname], profile: profile.chromeProfile, requestUrl: parsed });
85
+ if (result?.cookieHeader) return result.cookieHeader;
86
+ if (!result) {
87
+ const diagnostic = getLastBrowserCookieDiagnostic();
88
+ throw new Error(`Authenticated fetch profile ${profile.name} could not read browser cookies${diagnostic ? `: ${diagnostic}` : ""}`);
89
+ }
90
+ throw new Error(`Authenticated fetch profile ${profile.name} could not build a cookie header`);
91
+ }
92
+
93
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
94
+
95
+ async function fetchAuthenticatedRemoteUrl(
96
+ url: string,
97
+ init: RequestInit,
98
+ validationOptions: { ssrf: SsrfConfig; domainPolicy: DomainPolicy; lookup?: Lookup },
99
+ profile: AuthFetchProfile,
100
+ ): Promise<Response> {
101
+ let current = await validateRemoteUrl(url, {
102
+ allowRanges: validationOptions.ssrf.allowRanges,
103
+ trustEnvProxy: validationOptions.ssrf.trustEnvProxy,
104
+ domainPolicy: validationOptions.domainPolicy,
105
+ ...(validationOptions.lookup ? { lookup: validationOptions.lookup } : {}),
106
+ });
107
+ let requestInit = init;
108
+ for (let redirects = 0; redirects <= 5; redirects++) {
109
+ const cookieHeader = await resolveAuthCookieHeader(current, profile);
110
+ const headers = { ...(requestInit.headers as Record<string, string>), cookie: cookieHeader };
111
+ const response = await fetch(current, { ...requestInit, headers, redirect: "manual" });
112
+ if (!REDIRECT_STATUSES.has(response.status)) return response;
113
+ const location = response.headers.get("location");
114
+ if (!location) return response;
115
+ if (redirects === 5) throw new Error(`Too many redirects fetching ${current.toString()}`);
116
+ const from = current;
117
+ current = await validateRemoteUrl(new URL(location, current), {
118
+ allowRanges: validationOptions.ssrf.allowRanges,
119
+ trustEnvProxy: validationOptions.ssrf.trustEnvProxy,
120
+ domainPolicy: validationOptions.domainPolicy,
121
+ ...(validationOptions.lookup ? { lookup: validationOptions.lookup } : {}),
122
+ });
123
+ authFetchRedirectGuard(profile, from, current);
124
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && requestInit.method?.toUpperCase() === "POST")) {
125
+ const { body: _body, ...nextInit } = requestInit;
126
+ requestInit = { ...nextInit, method: "GET" };
127
+ }
128
+ }
129
+ throw new Error(`Too many redirects fetching ${current.toString()}`);
130
+ }
131
+
132
+ function loadFetchRouting(): FetchRouting {
133
+ if (!existsSync(WEB_SEARCH_CONFIG_PATH)) {
134
+ return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
135
+ }
136
+
137
+ let raw: Record<string, unknown>;
138
+ try {
139
+ const parsed: unknown = JSON.parse(readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8"));
140
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
141
+ throw new Error("expected a JSON object");
142
+ }
143
+ raw = parsed as Record<string, unknown>;
144
+ } catch (err) {
145
+ const message = err instanceof Error ? err.message : String(err);
146
+ throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
147
+ }
148
+
149
+ if (!Object.hasOwn(raw, "fetchRouting")) {
150
+ return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
151
+ }
152
+ const routing = raw.fetchRouting;
153
+ if (!routing || typeof routing !== "object" || Array.isArray(routing)) {
154
+ throw new Error(`fetchRouting in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
155
+ }
156
+
157
+ const routingConfig = routing as Record<string, unknown>;
158
+ const providersValue = routingConfig.providers;
159
+ let providers = DEFAULT_FETCH_PROVIDER_ORDER;
160
+ if (providersValue !== undefined) {
161
+ if (!Array.isArray(providersValue) || providersValue.length === 0) {
162
+ throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array`);
163
+ }
164
+
165
+ providers = [];
166
+ for (const provider of providersValue) {
167
+ const normalized = typeof provider === "string" ? provider.trim().toLowerCase() : "";
168
+ if (!FETCH_PROVIDERS.includes(normalized as FetchProvider)) {
169
+ throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} contains an invalid provider: ${String(provider)}`);
170
+ }
171
+ if (providers.includes(normalized as FetchProvider)) {
172
+ throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} must not contain duplicates: ${normalized}`);
173
+ }
174
+ providers.push(normalized as FetchProvider);
175
+ }
176
+ }
177
+
178
+ const allowRemoteHostedProvidersValue = routingConfig.allowRemoteHostedProviders;
179
+ if (allowRemoteHostedProvidersValue !== undefined && typeof allowRemoteHostedProvidersValue !== "boolean") {
180
+ throw new Error(`fetchRouting.allowRemoteHostedProviders in ${WEB_SEARCH_CONFIG_PATH} must be a boolean`);
181
+ }
182
+
183
+ return { providers, allowRemoteHostedProviders: allowRemoteHostedProvidersValue === true };
184
+ }
185
+
186
+ /** Names of the search/fetch tools the caller has actually registered, so
187
+ * failure guidance never points at tools that do not exist in the session. */
188
+ export interface RegisteredToolNames {
189
+ webSearch?: string;
190
+ fetchContent?: string;
191
+ }
192
+
193
+ /** Guidance for definitive origin 404/410 responses: no extraction provider
194
+ * can retrieve a page the origin says is gone, so point at the registered
195
+ * search/fetch tools (when the caller knows them) instead of provider config. */
196
+ function notFoundGuidance(result: ExtractedContent, toolNames?: RegisteredToolNames): string {
197
+ const lines = [
198
+ result.error ?? `HTTP ${result.status}`,
199
+ "",
200
+ `The origin server says this page does not exist (HTTP ${result.status}), so extraction providers cannot retrieve it.`,
201
+ ];
202
+ if (toolNames?.webSearch && toolNames.fetchContent) {
203
+ lines.push(`The page may have moved or been renamed. Use ${toolNames.webSearch} to find the current URL, then retry ${toolNames.fetchContent} with it.`);
204
+ } else if (toolNames?.webSearch) {
205
+ lines.push(`The page may have moved or been renamed. Use ${toolNames.webSearch} to find the current URL.`);
206
+ } else {
207
+ lines.push("The page may have moved or been renamed. Find the current URL, then retry the fetch with it.");
208
+ }
209
+ return lines.join("\n");
210
+ }
211
+
212
+ function abortedResult(url: string): ExtractedContent {
213
+ return { url, title: "", content: "", error: "Aborted" };
214
+ }
215
+
216
+ const turndown = new TurndownService({
217
+ headingStyle: "atx",
218
+ codeBlockStyle: "fenced",
219
+ });
220
+
221
+ const fetchLimit = pLimit(CONCURRENT_LIMIT);
222
+
223
+ export interface VideoFrame {
224
+ data: string;
225
+ mimeType: string;
226
+ timestamp: string;
227
+ }
228
+
229
+ export type FrameData = { data: string; mimeType: string };
230
+ export type FrameResult = FrameData | { error: string };
231
+
232
+ export interface ExtractedContent {
233
+ url: string;
234
+ title: string;
235
+ content: string;
236
+ error: string | null;
237
+ thumbnail?: { data: string; mimeType: string };
238
+ frames?: VideoFrame[];
239
+ duration?: number;
240
+ mimeType?: string;
241
+ status?: number;
242
+ }
243
+
244
+ type HttpExtractedContent = ExtractedContent & { declaredLinks?: DeclaredWebLink[] };
245
+
246
+ export interface ExtractOptions {
247
+ timeoutMs?: number;
248
+ forceClone?: boolean;
249
+ prompt?: string;
250
+ timestamp?: string;
251
+ frames?: number;
252
+ model?: string;
253
+ mode?: "readable" | "raw" | "answer";
254
+ answerModel?: string;
255
+ authFetchProfile?: AuthFetchProfile;
256
+ toolNames?: RegisteredToolNames;
257
+ /** Optional http(s) proxy URL; routed through the curl-backed transport. */
258
+ proxy?: string;
259
+ /** Custom DNS resolver used for SSRF validation. Primarily a test seam. */
260
+ lookup?: Lookup;
261
+ }
262
+
263
+ const JINA_READER_BASE = "https://r.jina.ai/";
264
+ const JINA_TIMEOUT_MS = 30000;
265
+
266
+ async function extractWithJinaReader(
267
+ url: string,
268
+ signal?: AbortSignal,
269
+ lookup?: Lookup,
270
+ ): Promise<ExtractedContent | null> {
271
+ const jinaUrl = JINA_READER_BASE + url;
272
+
273
+ const activityId = activityMonitor.logStart({ type: "api", query: `jina: ${url}` });
274
+
275
+ try {
276
+ const ssrf = loadSsrfConfig();
277
+ const domainPolicy = loadFetchContentDomainPolicy();
278
+ await validateRemoteUrl(url, {
279
+ allowRanges: ssrf.allowRanges,
280
+ trustEnvProxy: ssrf.trustEnvProxy,
281
+ domainPolicy,
282
+ ...(lookup ? { lookup } : {}),
283
+ });
284
+ const res = await fetch(jinaUrl, {
285
+ headers: {
286
+ "Accept": "text/markdown",
287
+ "X-No-Cache": "true",
288
+ },
289
+ signal: AbortSignal.any([
290
+ AbortSignal.timeout(JINA_TIMEOUT_MS),
291
+ ...(signal ? [signal] : []),
292
+ ]),
293
+ });
294
+
295
+ if (!res.ok) {
296
+ activityMonitor.logComplete(activityId, res.status);
297
+ return null;
298
+ }
299
+
300
+ const content = await res.text();
301
+ activityMonitor.logComplete(activityId, res.status);
302
+
303
+ const contentStart = content.indexOf("Markdown Content:");
304
+ if (contentStart < 0) {
305
+ return null;
306
+ }
307
+
308
+ const markdownPart = content.slice(contentStart + 17).trim(); // 17 = "Markdown Content:".length
309
+
310
+ // Check for failed JS rendering or minimal content
311
+ if (markdownPart.length < 100 ||
312
+ markdownPart.startsWith("Loading...") ||
313
+ markdownPart.startsWith("Please enable JavaScript")) {
314
+ return null;
315
+ }
316
+
317
+ const title = extractHeadingTitle(markdownPart) ?? (new URL(url).pathname.split("/").pop() || url);
318
+ return { url, title, content: markdownPart, error: null };
319
+ } catch (err) {
320
+ const message = err instanceof Error ? err.message : String(err);
321
+ if (message.toLowerCase().includes("abort")) {
322
+ activityMonitor.logComplete(activityId, 0);
323
+ } else {
324
+ activityMonitor.logError(activityId, message);
325
+ }
326
+ return null;
327
+ }
328
+ }
329
+
330
+ function parseTimestamp(ts: string): number | null {
331
+ const num = Number(ts);
332
+ if (!isNaN(num) && num >= 0) return Math.floor(num);
333
+ const parts = ts.split(":").map(Number);
334
+ if (parts.some(p => isNaN(p) || p < 0)) return null;
335
+ if (parts.length === 3) return Math.floor(parts[0] * 3600 + parts[1] * 60 + parts[2]);
336
+ if (parts.length === 2) return Math.floor(parts[0] * 60 + parts[1]);
337
+ return null;
338
+ }
339
+
340
+ type TimestampSpec = { type: "single"; seconds: number } | { type: "range"; start: number; end: number };
341
+
342
+ function parseTimestampSpec(ts: string): TimestampSpec | null {
343
+ const dashIdx = ts.indexOf("-", 1);
344
+ if (dashIdx > 0) {
345
+ const start = parseTimestamp(ts.slice(0, dashIdx));
346
+ const end = parseTimestamp(ts.slice(dashIdx + 1));
347
+ if (start !== null && end !== null && end > start) return { type: "range", start, end };
348
+ }
349
+ const seconds = parseTimestamp(ts);
350
+ return seconds !== null ? { type: "single", seconds } : null;
351
+ }
352
+
353
+ const DEFAULT_RANGE_FRAMES = 6;
354
+ const MIN_FRAME_INTERVAL = 5;
355
+
356
+ function computeRangeTimestamps(start: number, end: number, maxFrames: number = DEFAULT_RANGE_FRAMES): number[] {
357
+ if (maxFrames <= 1) return [start];
358
+ const duration = end - start;
359
+ const idealInterval = duration / (maxFrames - 1);
360
+ if (idealInterval < MIN_FRAME_INTERVAL) {
361
+ const timestamps: number[] = [];
362
+ for (let t = start; t <= end && timestamps.length < maxFrames; t += MIN_FRAME_INTERVAL) {
363
+ timestamps.push(t);
364
+ }
365
+ return timestamps;
366
+ }
367
+ return Array.from({ length: maxFrames }, (_, i) => Math.round(start + i * idealInterval));
368
+ }
369
+
370
+ function buildFrameResult(
371
+ url: string, label: string, requestedCount: number,
372
+ frames: VideoFrame[], error: string | null, duration?: number,
373
+ ): ExtractedContent {
374
+ if (frames.length === 0) {
375
+ const msg = error ?? "Frame extraction failed";
376
+ return { url, title: `Frames ${label} (0/${requestedCount})`, content: msg, error: msg };
377
+ }
378
+ return {
379
+ url,
380
+ title: `Frames ${label} (${frames.length}/${requestedCount})`,
381
+ content: `${frames.length} frames extracted from ${label}`,
382
+ error: null,
383
+ frames,
384
+ ...(duration !== undefined ? { duration } : {}),
385
+ };
386
+ }
387
+
388
+ async function extractLocalFrames(
389
+ filePath: string, timestamps: number[],
390
+ ): Promise<{ frames: VideoFrame[]; error: string | null }> {
391
+ const results = await Promise.all(timestamps.map(async (t) => {
392
+ const frame = await extractVideoFrame(filePath, t);
393
+ if ("error" in frame) return { error: frame.error };
394
+ return { ...frame, timestamp: formatSeconds(t) };
395
+ }));
396
+ const frames = results.filter((f): f is VideoFrame => "data" in f);
397
+ const firstError = results.find((f): f is { error: string } => "error" in f);
398
+ return { frames, error: frames.length === 0 && firstError ? firstError.error : null };
399
+ }
400
+
401
+ type LocalVideoInfoResult =
402
+ | { status: "video"; info: NonNullable<ReturnType<typeof isVideoFile>> }
403
+ | { status: "not-video" }
404
+ | { status: "invalid"; error: string };
405
+
406
+ function safeVideoInfo(url: string): LocalVideoInfoResult {
407
+ try {
408
+ const info = isVideoFile(url);
409
+ return info ? { status: "video", info } : { status: "not-video" };
410
+ } catch (err) {
411
+ return { status: "invalid", error: errorMessage(err) };
412
+ }
413
+ }
414
+
415
+ export async function extractContent(
416
+ url: string,
417
+ signal?: AbortSignal,
418
+ options?: ExtractOptions,
419
+ ): Promise<ExtractedContent> {
420
+ if (signal?.aborted) {
421
+ return { url, title: "", content: "", error: "Aborted" };
422
+ }
423
+
424
+ let remoteUrl: URL | null = null;
425
+ try {
426
+ const parsed = new URL(url);
427
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") remoteUrl = parsed;
428
+ } catch {
429
+ }
430
+ if (remoteUrl) {
431
+ try {
432
+ const ssrf = loadSsrfConfig();
433
+ const domainPolicy = loadFetchContentDomainPolicy();
434
+ await validateRemoteUrl(remoteUrl, {
435
+ allowRanges: ssrf.allowRanges,
436
+ trustEnvProxy: ssrf.trustEnvProxy,
437
+ domainPolicy,
438
+ ...(options?.lookup ? { lookup: options.lookup } : {}),
439
+ });
440
+ } catch (err) {
441
+ return { url, title: "", content: "", error: errorMessage(err) };
442
+ }
443
+ }
444
+
445
+ if (options?.authFetchProfile) {
446
+ try {
447
+ return await extractViaHttp(url, signal, options);
448
+ } catch (err) {
449
+ return { url, title: "", content: "", error: errorMessage(err) };
450
+ }
451
+ }
452
+
453
+ if (options?.mode === "raw") {
454
+ return extractViaHttp(url, signal, options);
455
+ }
456
+
457
+ if (options?.frames || options?.timestamp) {
458
+ const disabled = imageGateError();
459
+ if (disabled) return { url, title: "", content: "", error: disabled };
460
+ }
461
+
462
+ if (options?.frames && !options.timestamp) {
463
+ const frameCount = options.frames;
464
+ const ytInfo = isYouTubeURL(url);
465
+ if (ytInfo.isYouTube && ytInfo.videoId) {
466
+ const streamInfo = await getYouTubeStreamInfo(ytInfo.videoId);
467
+ if ("error" in streamInfo) {
468
+ return { url, title: "Frames", content: streamInfo.error, error: streamInfo.error };
469
+ }
470
+ if (streamInfo.duration === null) {
471
+ const error = "Cannot determine video duration. Use a timestamp range instead.";
472
+ return { url, title: "Frames", content: error, error };
473
+ }
474
+ const dur = Math.floor(streamInfo.duration);
475
+ const timestamps = computeRangeTimestamps(0, dur, frameCount);
476
+ const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
477
+ const label = `${formatSeconds(0)}-${formatSeconds(dur)}`;
478
+ return buildFrameResult(url, label, timestamps.length, result.frames, result.error, streamInfo.duration);
479
+ }
480
+
481
+ const localVideo = safeVideoInfo(url);
482
+ if (localVideo.status === "invalid") {
483
+ return { url, title: "", content: "", error: localVideo.error };
484
+ }
485
+ if (localVideo.status === "video") {
486
+ const durationResult = await getLocalVideoDuration(localVideo.info.absolutePath);
487
+ if (typeof durationResult !== "number") {
488
+ return { url, title: "Frames", content: durationResult.error, error: durationResult.error };
489
+ }
490
+ const dur = Math.floor(durationResult);
491
+ const timestamps = computeRangeTimestamps(0, dur, frameCount);
492
+ const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
493
+ const label = `${formatSeconds(0)}-${formatSeconds(dur)}`;
494
+ return buildFrameResult(url, label, timestamps.length, result.frames, result.error, durationResult);
495
+ }
496
+
497
+ return { url, title: "", content: "", error: "Frame extraction only works with YouTube and local video files" };
498
+ }
499
+
500
+ if (options?.timestamp) {
501
+ const spec = parseTimestampSpec(options.timestamp);
502
+ if (!spec) {
503
+ return {
504
+ url,
505
+ title: "",
506
+ content: "",
507
+ error: `Invalid timestamp format: "${options.timestamp}". Use "H:MM:SS", "MM:SS", "85", or "start-end".`,
508
+ };
509
+ }
510
+
511
+ const frameCount = options.frames;
512
+ const ytInfo = isYouTubeURL(url);
513
+ if (ytInfo.isYouTube && ytInfo.videoId) {
514
+ const streamInfo = await getYouTubeStreamInfo(ytInfo.videoId);
515
+ if ("error" in streamInfo) {
516
+ if (spec.type === "range") {
517
+ const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
518
+ return { url, title: `Frames ${label}`, content: streamInfo.error, error: streamInfo.error };
519
+ }
520
+ if (frameCount) {
521
+ const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
522
+ const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
523
+ return { url, title: `Frames ${label}`, content: streamInfo.error, error: streamInfo.error };
524
+ }
525
+ return { url, title: `Frame at ${options.timestamp}`, content: streamInfo.error, error: streamInfo.error };
526
+ }
527
+
528
+ if (spec.type === "range") {
529
+ const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
530
+ if (streamInfo.duration !== null && spec.end > streamInfo.duration) {
531
+ const error = `Timestamp ${formatSeconds(spec.end)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
532
+ return { url, title: `Frames ${label}`, content: error, error };
533
+ }
534
+ const timestamps = frameCount
535
+ ? computeRangeTimestamps(spec.start, spec.end, frameCount)
536
+ : computeRangeTimestamps(spec.start, spec.end);
537
+ const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
538
+ return buildFrameResult(url, label, timestamps.length, result.frames, result.error, result.duration ?? undefined);
539
+ }
540
+
541
+ if (frameCount) {
542
+ const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
543
+ const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
544
+ if (streamInfo.duration !== null && end > streamInfo.duration) {
545
+ const error = `Timestamp ${formatSeconds(end)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
546
+ return { url, title: `Frames ${label}`, content: error, error };
547
+ }
548
+ const timestamps = computeRangeTimestamps(spec.seconds, end, frameCount);
549
+ const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
550
+ return buildFrameResult(url, label, timestamps.length, result.frames, result.error, result.duration ?? undefined);
551
+ }
552
+
553
+ if (streamInfo.duration !== null && spec.seconds > streamInfo.duration) {
554
+ const error = `Timestamp ${formatSeconds(spec.seconds)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
555
+ return { url, title: `Frame at ${options.timestamp}`, content: error, error };
556
+ }
557
+ const frame = await extractYouTubeFrame(ytInfo.videoId, spec.seconds, streamInfo);
558
+ if ("error" in frame) {
559
+ return { url, title: `Frame at ${options.timestamp}`, content: frame.error, error: frame.error };
560
+ }
561
+ return { url, title: `Frame at ${options.timestamp}`, content: `Video frame at ${options.timestamp}`, error: null, thumbnail: frame };
562
+ }
563
+
564
+ const localVideo = safeVideoInfo(url);
565
+ if (localVideo.status === "invalid") {
566
+ return { url, title: "", content: "", error: localVideo.error };
567
+ }
568
+ if (localVideo.status === "video") {
569
+ if (spec.type === "range") {
570
+ const timestamps = frameCount
571
+ ? computeRangeTimestamps(spec.start, spec.end, frameCount)
572
+ : computeRangeTimestamps(spec.start, spec.end);
573
+ const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
574
+ const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
575
+ return buildFrameResult(url, label, timestamps.length, result.frames, result.error);
576
+ }
577
+
578
+ if (frameCount) {
579
+ const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
580
+ const timestamps = computeRangeTimestamps(spec.seconds, end, frameCount);
581
+ const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
582
+ const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
583
+ return buildFrameResult(url, label, timestamps.length, result.frames, result.error);
584
+ }
585
+
586
+ const frame = await extractVideoFrame(localVideo.info.absolutePath, spec.seconds);
587
+ if ("error" in frame) {
588
+ return { url, title: `Frame at ${options.timestamp}`, content: frame.error, error: frame.error };
589
+ }
590
+ return { url, title: `Frame at ${options.timestamp}`, content: `Video frame at ${options.timestamp}`, error: null, thumbnail: frame };
591
+ }
592
+
593
+ return { url, title: "", content: "", error: "Timestamp extraction only works with YouTube and local video files" };
594
+ }
595
+
596
+ const localVideo = safeVideoInfo(url);
597
+ if (localVideo.status === "invalid") {
598
+ return { url, title: "", content: "", error: localVideo.error };
599
+ }
600
+ if (localVideo.status === "video") {
601
+ try {
602
+ const result = await extractVideo(localVideo.info, signal, options);
603
+ if (signal?.aborted) return abortedResult(url);
604
+ return result ?? { url, title: "", content: "", error: `Video analysis requires Gemini access. Either:\n 1. Sign into gemini.google.com in Chrome (free, uses cookies)\n 2. Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH}` };
605
+ } catch (err) {
606
+ if (isAbortError(err)) return abortedResult(url);
607
+ return { url, title: "", content: "", error: errorMessage(err) };
608
+ }
609
+ }
610
+
611
+ try {
612
+ if (!remoteUrl) new URL(url);
613
+ } catch (err) {
614
+ return { url, title: "", content: "", error: errorMessage(err) };
615
+ }
616
+
617
+ try {
618
+ const ghIssuePrResult = await extractGitHubIssuePr(url, signal, options);
619
+ if (ghIssuePrResult) return ghIssuePrResult;
620
+ if (signal?.aborted) return abortedResult(url);
621
+ } catch (err) {
622
+ const message = errorMessage(err);
623
+ if (isAbortError(err)) return abortedResult(url);
624
+ if (isConfigParseError(err)) {
625
+ return { url, title: "", content: "", error: message };
626
+ }
627
+ }
628
+
629
+ try {
630
+ const ghResult = await extractGitHub(url, signal, options?.forceClone);
631
+ if (ghResult) return ghResult;
632
+ if (signal?.aborted) return abortedResult(url);
633
+ } catch (err) {
634
+ const message = errorMessage(err);
635
+ if (isAbortError(err)) return abortedResult(url);
636
+ if (isConfigParseError(err)) {
637
+ return { url, title: "", content: "", error: message };
638
+ }
639
+ }
640
+
641
+ const ytInfo = isYouTubeURL(url);
642
+ let youtubeEnabled = false;
643
+ try {
644
+ youtubeEnabled = isYouTubeEnabled();
645
+ } catch (err) {
646
+ return { url, title: "", content: "", error: errorMessage(err) };
647
+ }
648
+ if (ytInfo.isYouTube && youtubeEnabled) {
649
+ try {
650
+ const ytResult = await extractYouTube(url, signal, options?.prompt, options?.model);
651
+ if (ytResult) return ytResult;
652
+ if (signal?.aborted) return abortedResult(url);
653
+ } catch (err) {
654
+ const message = errorMessage(err);
655
+ if (isAbortError(err)) return abortedResult(url);
656
+ return { url, title: "", content: "", error: message };
657
+ }
658
+ return {
659
+ url,
660
+ title: "",
661
+ content: "",
662
+ error: "Could not extract YouTube video content. Sign into Google in a supported Chromium browser for automatic access, or set GEMINI_API_KEY.",
663
+ };
664
+ }
665
+
666
+ if (signal?.aborted) return abortedResult(url);
667
+
668
+ let fetchRouting: FetchRouting;
669
+ try {
670
+ fetchRouting = loadFetchRouting();
671
+ } catch (err) {
672
+ return { url, title: "", content: "", error: errorMessage(err) };
673
+ }
674
+ const providerOrder = remoteUrl && !fetchRouting.allowRemoteHostedProviders
675
+ ? fetchRouting.providers.filter(provider => !REMOTE_HOSTED_FETCH_PROVIDERS.has(provider))
676
+ : fetchRouting.providers;
677
+ if (providerOrder.length === 0) {
678
+ return {
679
+ url,
680
+ title: "",
681
+ content: "",
682
+ error: "Remote hosted fetch providers are disabled unless fetchRouting.allowRemoteHostedProviders is true",
683
+ };
684
+ }
685
+
686
+ let httpResult: ExtractedContent | null = null;
687
+ let declaredLinks: DeclaredWebLink[] = [];
688
+ const withDeclaredLinks = (result: ExtractedContent): ExtractedContent => ({
689
+ ...result,
690
+ content: appendDeclaredWebLinks(result.content, declaredLinks),
691
+ });
692
+ const parseErrorResult = (message: string): ExtractedContent => httpResult
693
+ ? { ...httpResult, error: message }
694
+ : { url, title: "", content: "", error: message };
695
+ const runHttpProvider = async (): Promise<ExtractedContent | null> => {
696
+ const { declaredLinks: discoveredLinks = [], ...result } = await extractViaHttp(url, signal, options);
697
+ httpResult = result;
698
+ declaredLinks = discoveredLinks;
699
+ if (signal?.aborted) return abortedResult(url);
700
+ if (!httpResult.error) return httpResult;
701
+ if (NON_RECOVERABLE_ERRORS.some(prefix => httpResult!.error!.startsWith(prefix)) || isRedirectPolicyError(httpResult.error) || isConfigParseError(httpResult.error)) {
702
+ return httpResult;
703
+ }
704
+ return null;
705
+ };
706
+
707
+ let brightdataError: string | null = null;
708
+
709
+ if (remoteUrl && providerOrder[0] !== "http") {
710
+ const httpGateResult = await runHttpProvider();
711
+ if (httpGateResult) return httpGateResult;
712
+ }
713
+
714
+ for (const provider of providerOrder) {
715
+ if (signal?.aborted) return abortedResult(url);
716
+
717
+ if (provider === "http") {
718
+ const result = await runHttpProvider();
719
+ if (result) return result;
720
+ continue;
721
+ }
722
+
723
+
724
+ if (provider === "jina") {
725
+ const jinaResult = await extractWithJinaReader(url, signal, options?.lookup);
726
+ if (jinaResult) return withDeclaredLinks(jinaResult);
727
+ continue;
728
+ }
729
+
730
+
731
+
732
+
733
+
734
+
735
+
736
+
737
+ if (provider === "brightdata") {
738
+ try {
739
+ if (isBrightDataUnlockerAvailable()) {
740
+ const ssrf = loadSsrfConfig();
741
+ const brightdataResult = await extractWithBrightDataUnlocker(url, signal, {
742
+ timeoutMs: options?.timeoutMs,
743
+ ...(options?.lookup ? { lookup: options.lookup } : {}),
744
+ ssrf,
745
+ });
746
+ if (brightdataResult) return withDeclaredLinks(brightdataResult);
747
+ }
748
+ } catch (err) {
749
+ if (isAbortError(err)) return abortedResult(url);
750
+ brightdataError = errorMessage(err);
751
+ if (isConfigParseError(err)) return parseErrorResult(brightdataError);
752
+ }
753
+ continue;
754
+ }
755
+
756
+ if (provider === "gemini") {
757
+ let geminiResult: ExtractedContent | null = null;
758
+ try {
759
+ geminiResult = await extractWithUrlContext(url, signal)
760
+ ?? await extractWithGeminiWeb(url, signal);
761
+ } catch (err) {
762
+ if (isAbortError(err)) return abortedResult(url);
763
+ if (err instanceof CredentialResolutionError || isConfigParseError(err)) {
764
+ return parseErrorResult(errorMessage(err));
765
+ }
766
+ }
767
+ if (geminiResult) return withDeclaredLinks(geminiResult);
768
+ }
769
+ }
770
+
771
+ if (signal?.aborted) return abortedResult(url);
772
+ const finalHttpResult = httpResult as ExtractedContent | null;
773
+ if (finalHttpResult && declaredLinks.length > 0) return { ...finalHttpResult, error: null };
774
+
775
+ // A definitive 404/410 from the origin means no extraction provider can
776
+ // retrieve the page, so the provider-configuration checklist below would
777
+ // send users down the wrong path. Point at search instead.
778
+ if (finalHttpResult?.status === 404 || finalHttpResult?.status === 410) {
779
+ return { ...finalHttpResult, error: notFoundGuidance(finalHttpResult, options?.toolNames) };
780
+ }
781
+
782
+ const searchToolName = options?.toolNames?.webSearch;
783
+ const guidance = [
784
+ finalHttpResult?.error ?? "No fetch_content provider returned content",
785
+ ...(brightdataError ? [`Bright Data fallback failed: ${brightdataError}`] : []),
786
+ "",
787
+ "Fallback options:",
788
+ ` • Set brightdataApiKey and brightdataUnlockerZone in ${WEB_SEARCH_CONFIG_PATH} or BRIGHTDATA_API_KEY and BRIGHTDATA_UNLOCKER_ZONE`,
789
+ ` • Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH}`,
790
+ " • Sign into gemini.google.com in Chrome",
791
+ ...(searchToolName ? [` • Use ${searchToolName} to find content about this topic`] : []),
792
+ ].join("\n");
793
+ return { ...(finalHttpResult ?? { url, title: "", content: "", error: null }), error: guidance };
794
+ }
795
+
796
+ function isLikelyJSRendered(html: string): boolean {
797
+ const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
798
+ if (!bodyMatch) return false;
799
+
800
+ const bodyHtml = bodyMatch[1];
801
+
802
+ const textContent = bodyHtml
803
+ .replace(/<script[\s\S]*?<\/script>/gi, "")
804
+ .replace(/<style[\s\S]*?<\/style>/gi, "")
805
+ .replace(/<[^>]+>/g, "")
806
+ .replace(/\s+/g, " ")
807
+ .trim();
808
+
809
+ const scriptCount = (html.match(/<script/gi) || []).length;
810
+
811
+ return textContent.length < 500 && scriptCount > 3;
812
+ }
813
+
814
+ export async function readPDFResponseBuffer(response: Response, maxSizeMB: number): Promise<ArrayBuffer> {
815
+ const maxBytes = maxSizeMB * 1024 * 1024;
816
+ return readResponseBufferWithLimit(response, maxBytes, () => pdfSizeLimitError(maxSizeMB));
817
+ }
818
+
819
+ async function readTextResponseWithLimit(response: Response, maxBytes: number): Promise<string> {
820
+ const buffer = await readResponseBufferWithLimit(response, maxBytes, () => responseSizeLimitError(maxBytes));
821
+ const charset = response.headers.get("content-type")?.match(/charset\s*=\s*["']?([^;"'\s]+)/i)?.[1];
822
+ try {
823
+ return new TextDecoder(charset || "utf-8").decode(buffer);
824
+ } catch {
825
+ return new TextDecoder("utf-8").decode(buffer);
826
+ }
827
+ }
828
+
829
+ function isTextContentType(contentType: string): boolean {
830
+ const mimeType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
831
+ return mimeType.startsWith("text/") ||
832
+ mimeType === "application/json" ||
833
+ mimeType === "application/ld+json" ||
834
+ mimeType === "application/xml" ||
835
+ mimeType === "application/xhtml+xml" ||
836
+ mimeType === "application/javascript" ||
837
+ mimeType === "application/x-javascript" ||
838
+ mimeType.endsWith("+json") ||
839
+ mimeType.endsWith("+xml");
840
+ }
841
+
842
+ async function readResponseBufferWithLimit(
843
+ response: Response,
844
+ maxBytes: number,
845
+ buildError: () => Error,
846
+ ): Promise<ArrayBuffer> {
847
+ const reader = response.body?.getReader();
848
+ if (!reader) {
849
+ const buffer = await response.arrayBuffer();
850
+ if (buffer.byteLength > maxBytes) throw buildError();
851
+ return buffer;
852
+ }
853
+
854
+ const chunks: Uint8Array[] = [];
855
+ let totalBytes = 0;
856
+ try {
857
+ while (true) {
858
+ const { done, value } = await reader.read();
859
+ if (done) break;
860
+ if (!value) continue;
861
+ totalBytes += value.byteLength;
862
+ if (totalBytes > maxBytes) {
863
+ await reader.cancel();
864
+ throw buildError();
865
+ }
866
+ chunks.push(value);
867
+ }
868
+ } finally {
869
+ reader.releaseLock();
870
+ }
871
+
872
+ const combined = new Uint8Array(totalBytes);
873
+ let offset = 0;
874
+ for (const chunk of chunks) {
875
+ combined.set(chunk, offset);
876
+ offset += chunk.byteLength;
877
+ }
878
+ return combined.buffer;
879
+ }
880
+
881
+ function pdfSizeLimitError(maxSizeMB: number): Error {
882
+ return new Error(`PDF exceeds configured pdf.maxSizeMB limit (${maxSizeMB} MB)`);
883
+ }
884
+
885
+ function responseSizeLimitError(maxBytes: number): Error {
886
+ return new Error(`Response too large (${Math.round(maxBytes / 1024 / 1024)}MB)`);
887
+ }
888
+
889
+ async function extractViaHttp(
890
+ url: string,
891
+ signal?: AbortSignal,
892
+ options?: ExtractOptions,
893
+ ): Promise<HttpExtractedContent> {
894
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
895
+ const activityId = activityMonitor.logStart({ type: "fetch", url });
896
+
897
+ const controller = new AbortController();
898
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
899
+
900
+ const onAbort = () => controller.abort();
901
+ signal?.addEventListener("abort", onAbort);
902
+
903
+ try {
904
+ const ssrf = loadSsrfConfig();
905
+ const domainPolicy = loadFetchContentDomainPolicy();
906
+ const authProfile = options?.authFetchProfile;
907
+ const trustEnvProxy = options?.proxy === undefined && ssrf.trustEnvProxy;
908
+ const requestInit: ProxiedRequestInit = {
909
+ signal: controller.signal,
910
+ __proxy: options?.proxy,
911
+ headers: {
912
+ "User-Agent": "OpenAI File Downloader, XaiImageApiFetch/1.0",
913
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
914
+ "Accept-Language": "en-US,en;q=0.9",
915
+ "Cache-Control": "no-cache",
916
+ "Sec-Fetch-Dest": "document",
917
+ "Sec-Fetch-Mode": "navigate",
918
+ "Sec-Fetch-Site": "none",
919
+ "Sec-Fetch-User": "?1",
920
+ "Upgrade-Insecure-Requests": "1",
921
+ },
922
+ };
923
+ const response = authProfile
924
+ ? await fetchAuthenticatedRemoteUrl(url, requestInit, { ssrf: { ...ssrf, trustEnvProxy }, domainPolicy, ...(options?.lookup ? { lookup: options.lookup } : {}) }, authProfile)
925
+ : await fetchRemoteUrl(
926
+ url,
927
+ requestInit,
928
+ {
929
+ allowRanges: ssrf.allowRanges,
930
+ trustEnvProxy,
931
+ domainPolicy,
932
+ ...(options?.lookup ? { lookup: options.lookup } : {}),
933
+ },
934
+ );
935
+
936
+ if (!response.ok && options?.mode !== "raw") {
937
+ activityMonitor.logComplete(activityId, response.status);
938
+ return {
939
+ url,
940
+ title: "",
941
+ content: "",
942
+ error: `HTTP ${response.status}: ${response.statusText}`,
943
+ status: response.status,
944
+ };
945
+ }
946
+
947
+ const contentLengthHeader = response.headers.get("content-length");
948
+ const contentType = response.headers.get("content-type") || "";
949
+ const mimeType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
950
+ const isPDFContent = isPDF(url, contentType);
951
+ const pdfConfig = isPDFContent ? loadPDFConfig() : null;
952
+ if (isPDFContent && pdfConfig && !pdfConfig.enabled) {
953
+ activityMonitor.logComplete(activityId, response.status);
954
+ return { url, title: "", content: "", error: "PDF extraction is disabled by pdf.enabled", mimeType, status: response.status };
955
+ }
956
+ const maxResponseSize = (pdfConfig?.maxSizeMB ?? 5) * 1024 * 1024;
957
+ if (contentLengthHeader) {
958
+ const contentLength = Number.parseInt(contentLengthHeader, 10);
959
+ if (Number.isFinite(contentLength) && contentLength > maxResponseSize) {
960
+ activityMonitor.logComplete(activityId, response.status);
961
+ return {
962
+ url,
963
+ title: "",
964
+ content: "",
965
+ error: pdfConfig
966
+ ? pdfSizeLimitError(pdfConfig.maxSizeMB).message
967
+ : `Response too large (${Math.round(contentLength / 1024 / 1024)}MB)`,
968
+ };
969
+ }
970
+ }
971
+
972
+ if (options?.mode === "raw") {
973
+ if (!isTextContentType(contentType)) {
974
+ activityMonitor.logComplete(activityId, response.status);
975
+ return { url, title: "", content: "", error: `Unsupported content type in raw mode: ${mimeType || "missing"}`, mimeType, status: response.status };
976
+ }
977
+ const text = await readTextResponseWithLimit(response, maxResponseSize);
978
+ activityMonitor.logComplete(activityId, response.status);
979
+ return { url, title: extractTextTitle(text, url), content: text, error: null, mimeType, status: response.status };
980
+ }
981
+
982
+ if (SUPPORTED_IMAGE_TYPES.has(mimeType)) {
983
+ const disabled = imageGateError();
984
+ if (disabled) {
985
+ activityMonitor.logComplete(activityId, response.status);
986
+ return { url, title: "", content: "", error: disabled, mimeType, status: response.status };
987
+ }
988
+ try {
989
+ const buffer = await readResponseBufferWithLimit(response, maxResponseSize, () => responseSizeLimitError(maxResponseSize));
990
+ const resized = await resizeImage(new Uint8Array(buffer), mimeType, { maxWidth: 2000, maxHeight: 2000 });
991
+ activityMonitor.logComplete(activityId, response.status);
992
+ if (!resized) return { url, title: "", content: "", error: `Could not decode image: ${mimeType}`, mimeType, status: response.status };
993
+ const title = new URL(response.url || url).pathname.split("/").pop() || url;
994
+ return {
995
+ url,
996
+ title,
997
+ content: `Image fetched (${resized.width}×${resized.height}, ${resized.mimeType})`,
998
+ error: null,
999
+ thumbnail: { data: resized.data, mimeType: resized.mimeType },
1000
+ mimeType: resized.mimeType,
1001
+ status: response.status,
1002
+ };
1003
+ } catch (err) {
1004
+ const message = errorMessage(err);
1005
+ activityMonitor.logError(activityId, message);
1006
+ return { url, title: "", content: "", error: message, mimeType, status: response.status };
1007
+ }
1008
+ }
1009
+
1010
+ if (isPDFContent && pdfConfig) {
1011
+ try {
1012
+ const buffer = await readPDFResponseBuffer(response, pdfConfig.maxSizeMB);
1013
+ if (signal?.aborted) return abortedResult(url);
1014
+ const result = await extractPDFToMarkdown(buffer, url, { signal });
1015
+ activityMonitor.logComplete(activityId, response.status);
1016
+ return {
1017
+ url,
1018
+ title: result.title,
1019
+ content: `PDF extracted and saved to: ${result.outputPath}\n\nPages: ${result.pages}\nCharacters: ${result.chars}`,
1020
+ error: null,
1021
+ };
1022
+ } catch (err) {
1023
+ const message = err instanceof Error ? err.message : String(err);
1024
+ activityMonitor.logError(activityId, message);
1025
+ if (message.startsWith("PDF exceeds configured pdf.maxSizeMB limit")) {
1026
+ return { url, title: "", content: "", error: message };
1027
+ }
1028
+ if (err instanceof CredentialResolutionError || isConfigParseError(err)) {
1029
+ return { url, title: "", content: "", error: message };
1030
+ }
1031
+ return { url, title: "", content: "", error: `PDF extraction failed: ${message}` };
1032
+ }
1033
+ }
1034
+
1035
+ if (contentType.includes("application/octet-stream") ||
1036
+ contentType.includes("image/") ||
1037
+ contentType.includes("audio/") ||
1038
+ contentType.includes("video/") ||
1039
+ contentType.includes("application/zip")) {
1040
+ activityMonitor.logComplete(activityId, response.status);
1041
+ return {
1042
+ url,
1043
+ title: "",
1044
+ content: "",
1045
+ error: `Unsupported content type: ${contentType.split(";")[0]}`,
1046
+ };
1047
+ }
1048
+
1049
+ const text = await readTextResponseWithLimit(response, maxResponseSize);
1050
+ const isHTML = contentType.includes("text/html") || contentType.includes("application/xhtml+xml");
1051
+
1052
+ if (!isHTML) {
1053
+ activityMonitor.logComplete(activityId, response.status);
1054
+ const title = extractTextTitle(text, url);
1055
+ return { url, title, content: text, error: null };
1056
+ }
1057
+
1058
+ const { document } = parseHTML(text);
1059
+ const documentTitle = document.title?.trim() ?? "";
1060
+ const declaredLinks = discoverDeclaredWebLinks(
1061
+ document as unknown as Document,
1062
+ response.headers.get("link"),
1063
+ response.url || url,
1064
+ );
1065
+ const reader = new Readability(document as unknown as Document);
1066
+ const article = reader.parse();
1067
+
1068
+ if (!article) {
1069
+ const rscResult = extractRSCContent(text);
1070
+ if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT) {
1071
+ activityMonitor.logComplete(activityId, response.status);
1072
+ return {
1073
+ url,
1074
+ title: rscResult.title,
1075
+ content: appendDeclaredWebLinks(rscResult.content, declaredLinks),
1076
+ error: null,
1077
+ declaredLinks,
1078
+ };
1079
+ }
1080
+ controller.signal.throwIfAborted();
1081
+ const defuddleResult = await extractWithDefuddle(text, response.url || url);
1082
+ controller.signal.throwIfAborted();
1083
+ if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT) {
1084
+ activityMonitor.logComplete(activityId, response.status);
1085
+ return {
1086
+ url,
1087
+ title: documentTitle || defuddleResult.title,
1088
+ content: appendDeclaredWebLinks(defuddleResult.content, declaredLinks),
1089
+ error: null,
1090
+ declaredLinks,
1091
+ };
1092
+ }
1093
+
1094
+ activityMonitor.logComplete(activityId, response.status);
1095
+ const jsRendered = isLikelyJSRendered(text);
1096
+ const errorMsg = jsRendered
1097
+ ? "Page appears to be JavaScript-rendered (content loads dynamically)"
1098
+ : "Could not extract readable content from HTML structure";
1099
+
1100
+ return {
1101
+ url,
1102
+ title: documentTitle,
1103
+ content: appendDeclaredWebLinks("", declaredLinks),
1104
+ error: errorMsg,
1105
+ declaredLinks,
1106
+ };
1107
+ }
1108
+
1109
+ if (typeof article.content !== "string") {
1110
+ throw new Error("Readability returned invalid article content");
1111
+ }
1112
+ const markdown = turndown.turndown(article.content);
1113
+ activityMonitor.logComplete(activityId, response.status);
1114
+
1115
+ if (markdown.length < MIN_USEFUL_CONTENT) {
1116
+ const rscResult = extractRSCContent(text);
1117
+ if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT) {
1118
+ return {
1119
+ url,
1120
+ title: rscResult.title,
1121
+ content: appendDeclaredWebLinks(rscResult.content, declaredLinks),
1122
+ error: null,
1123
+ declaredLinks,
1124
+ };
1125
+ }
1126
+ controller.signal.throwIfAborted();
1127
+ const defuddleResult = await extractWithDefuddle(text, response.url || url);
1128
+ controller.signal.throwIfAborted();
1129
+ if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT) {
1130
+ return {
1131
+ url,
1132
+ title: article.title || documentTitle || defuddleResult.title,
1133
+ content: appendDeclaredWebLinks(defuddleResult.content, declaredLinks),
1134
+ error: null,
1135
+ declaredLinks,
1136
+ };
1137
+ }
1138
+ return {
1139
+ url,
1140
+ title: article.title || documentTitle,
1141
+ content: appendDeclaredWebLinks(markdown, declaredLinks),
1142
+ error: isLikelyJSRendered(text)
1143
+ ? "Page appears to be JavaScript-rendered (content loads dynamically)"
1144
+ : "Extracted content appears incomplete",
1145
+ declaredLinks,
1146
+ };
1147
+ }
1148
+
1149
+ return {
1150
+ url,
1151
+ title: article.title || documentTitle,
1152
+ content: appendDeclaredWebLinks(markdown, declaredLinks),
1153
+ error: null,
1154
+ declaredLinks,
1155
+ };
1156
+ } catch (err) {
1157
+ const message = err instanceof Error ? err.message : String(err);
1158
+ if (message.toLowerCase().includes("abort")) {
1159
+ activityMonitor.logComplete(activityId, 0);
1160
+ } else {
1161
+ activityMonitor.logError(activityId, message);
1162
+ }
1163
+ return { url, title: "", content: "", error: message };
1164
+ } finally {
1165
+ clearTimeout(timeoutId);
1166
+ signal?.removeEventListener("abort", onAbort);
1167
+ }
1168
+ }
1169
+
1170
+ export function extractHeadingTitle(text: string): string | null {
1171
+ const match = text.match(/^#{1,2}\s+(.+)/m);
1172
+ if (!match) return null;
1173
+ const cleaned = match[1].replace(/\*+/g, "").trim();
1174
+ return cleaned || null;
1175
+ }
1176
+
1177
+ function extractTextTitle(text: string, url: string): string {
1178
+ return extractHeadingTitle(text) ?? (new URL(url).pathname.split("/").pop() || url);
1179
+ }
1180
+
1181
+ export async function fetchAllContent(
1182
+ urls: string[],
1183
+ signal?: AbortSignal,
1184
+ options?: ExtractOptions,
1185
+ ): Promise<ExtractedContent[]> {
1186
+ const results = await Promise.all(urls.map((url) => fetchLimit(() => extractContent(url, signal, options))));
1187
+ if (options?.mode === "raw") return results;
1188
+ // Inline data: URIs in extracted markdown would otherwise flow into tool
1189
+ // results and the fetch cache as opaque base64; typed thumbnail/frame image
1190
+ // blocks are deliberate outputs and are left untouched.
1191
+ return results.map((result, index) => {
1192
+ if (!result.content) return result;
1193
+ const sanitized = sanitizeInlineDataUris(result.content, `urls[${index}].content`);
1194
+ return sanitized.omissions.length > 0 ? { ...result, content: sanitized.text } : result;
1195
+ });
1196
+ }