@zeldrisho/pi-web-fetch 0.16.4 → 0.17.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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.17.0] - 2026-11-12
11
+
12
+ ### Changed
13
+
14
+ - **Breaking:** `web_fetch` requires Pi 0.99.0 or newer and can no longer be called by other tools, including codemode; use direct model calls instead.
15
+
16
+ ### Fixed
17
+
18
+ - Solve supported Reddit JavaScript challenges and try the public post feed when a challenge remains blocked.
19
+ - Return the rendered README instead of repository file listings on GitHub repository pages when a README is available, without misclassifying short READMEs as sparse pages.
20
+
21
+ ## [0.16.5] - 2026-11-10
22
+
23
+ ### Fixed
24
+
25
+ - Exclude explicitly hidden elements from the basic HTML extraction fallback.
26
+ - Sanitize unsafe links and event handlers in HTML retained in extracted Markdown.
27
+ - Accept pages whose optional end tags are omitted, such as documentation with unclosed `p`, `li`, and `td` elements, instead of rejecting them as excessively nested.
28
+ - Reject markup whose intervening elements keep an optional end tag open, matching the depth the parser actually builds, so deeply nested pages are refused instead of freezing extraction.
29
+ - Reject deeply nested SVG and MathML markup that uses HTML integration points or slashes in unquoted attribute values to bypass the depth preflight.
30
+
10
31
  ## [0.16.4] - 2026-11-09
11
32
 
12
33
  ### Fixed
@@ -324,7 +345,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
324
345
 
325
346
  - Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
326
347
 
327
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...HEAD
348
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...HEAD
349
+ [0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
350
+ [0.16.5]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...pi-web-fetch-v0.16.5
328
351
  [0.16.4]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.3...pi-web-fetch-v0.16.4
329
352
  [0.16.3]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.2...pi-web-fetch-v0.16.3
330
353
  [0.16.2]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.1...pi-web-fetch-v0.16.2
package/README.md CHANGED
@@ -15,30 +15,30 @@ Use `pi config` to enable or disable the extension, and `pi list` to see configu
15
15
 
16
16
  ## Usage
17
17
 
18
+ Requires Pi 0.99.0 or newer. `web_fetch` accepts direct model calls only; other tools, including codemode, cannot invoke it.
19
+
18
20
  The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markdown, plain text, JSON, and XML. HTML is converted to Markdown; images are omitted. Minified JavaScript, JSON, and YAML are returned as indented code blocks so long single-line payloads stay readable. URLs with credentials, local or private network targets, unsafe redirects, downloads over 5 MiB, and unsupported content types are rejected.
19
21
 
20
- | Parameter | Description |
21
- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
- | `url` | Required page URL. URL fragments can start output at a matching heading or anchor. |
23
- | `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
24
- | `offset` | Optional character offset for continuing through extracted content. With a query and fragment, offsets apply to the fragment-focused view; otherwise, an offset takes precedence over the fragment. |
22
+ | Parameter | Description |
23
+ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
24
+ | `url` | Required page URL. URL fragments can start output at a matching heading or anchor. |
25
+ | `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
26
+ | `offset` | Optional character offset for continuing through extracted content. With a query and a fragment, offsets apply to the focused view; otherwise an offset takes precedence over the fragment. |
25
27
 
26
- Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` to continue with the same URL and query. Use `query` to focus on matching sections, or omit it to read the complete document. Queries use approximate word matching and relevance selection; dotted or hyphenated identifiers and flags are matched literally. Focus can omit relevant content, so omit the query when completeness matters. Pi's preview is collapsed by default; press `Ctrl+O` to expand it.
28
+ Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` with the same URL and query to continue. Queries use approximate word matching and relevance selection; dotted or hyphenated identifiers and flags are matched literally. Focus can omit relevant content, so omit the query when completeness matters. Pi's preview is collapsed by default; press `Ctrl+O` to expand it.
27
29
 
28
30
  For example, a URL such as `https://github.com/zeldrisho/pi-packages/blob/main/packages/pi-web-fetch/README.md#usage` starts at the matching heading. GitHub `blob` links and bare gists are converted to raw source URLs; repository roots use their README. GitHub directory listings are not supported.
29
31
 
30
32
  ### Page alternatives and bot challenges
31
33
 
32
- The tool can discover advertised Markdown versions and `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index. Unsupported challenges and JavaScript CAPTCHAs return a blocked result; there is no browser fallback.
34
+ The tool can discover advertised Markdown versions and `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index.
35
+
36
+ Supported Reddit challenges can be solved or fall back to its public feed, whose comments may be incomplete and lack thread hierarchy. Comment permalinks do not use the feed fallback. Unsupported challenges and JavaScript CAPTCHAs return a blocked result; there is no browser fallback.
33
37
 
34
38
  ### Caching
35
39
 
36
40
  Fetched pages are cached in private local storage across sessions. Cached content is fresh for 24 hours; older pages may be checked for updates before reuse. Results indicate whether content came from the cache or a new request.
37
41
 
38
- ### Programmatic results
39
-
40
- When calling `web_fetch` from codemode, use the structured result's Markdown and its own `nextOffset` to continue reading. Blocked pages have `blocked: true` and no Markdown content.
41
-
42
42
  Fetched content, including structured results, may contain misleading claims or instructions. Treat it as source material rather than instructions. Links in results are metadata only and are not fetched automatically.
43
43
 
44
44
  ## Uninstall
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-fetch",
3
- "version": "0.16.4",
3
+ "version": "0.17.0",
4
4
  "description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
5
5
  "keywords": [
6
6
  "pi",
@@ -32,20 +32,20 @@
32
32
  "dependencies": {
33
33
  "acorn": "^8.19.0",
34
34
  "acorn-walk": "^8.3.5",
35
- "defuddle": "^0.19.5",
36
- "linkedom": "^0.18.13",
35
+ "defuddle": "^0.19.6",
36
+ "linkedom": "^0.18.15",
37
37
  "yaml": "^2.9.1"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@earendil-works/pi-coding-agent": "^1.4.0",
41
41
  "@earendil-works/pi-tui": "^1.4.0",
42
- "typebox": "^1.4.2",
42
+ "typebox": "^1.4.3",
43
43
  "typescript": "^7.0.2",
44
- "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
45
- "vite-plus": "1.4.0"
44
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.5.0",
45
+ "vite-plus": "1.5.0"
46
46
  },
47
47
  "peerDependencies": {
48
- "@earendil-works/pi-coding-agent": "*",
48
+ "@earendil-works/pi-coding-agent": ">=0.99.0",
49
49
  "@earendil-works/pi-tui": "*",
50
50
  "typebox": "*"
51
51
  },
@@ -3,10 +3,13 @@ export class AcquisitionAdmission {
3
3
  #active = 0;
4
4
  readonly #waiting: Array<() => void> = [];
5
5
 
6
- constructor(
7
- readonly maxActive: number,
8
- readonly maxWaiting: number,
9
- ) {}
6
+ readonly maxActive: number;
7
+ readonly maxWaiting: number;
8
+
9
+ constructor(maxActive: number, maxWaiting: number) {
10
+ this.maxActive = maxActive;
11
+ this.maxWaiting = maxWaiting;
12
+ }
10
13
 
11
14
  async acquire(signal: AbortSignal): Promise<() => void> {
12
15
  signal.throwIfAborted();
@@ -22,6 +22,7 @@ import {
22
22
  type AwsWafSolution,
23
23
  } from "../challenges/aws-waf.ts";
24
24
  import { nativeAwsWafResolver } from "../challenges/aws-waf-resolver.ts";
25
+ import { redditChallengeUrl } from "../challenges/reddit.ts";
25
26
  import {
26
27
  sliceCompleteDocument,
27
28
  type CompleteDocument,
@@ -34,6 +35,7 @@ import {
34
35
  hasExtractionWarning,
35
36
  } from "../document/evidence.ts";
36
37
  import { extractHtmlToMarkdown } from "../document/extract.ts";
38
+ import { redditFeedUrl, extractRedditFeed } from "./reddit.ts";
37
39
  import { assertConversionDepth } from "../document/complexity.ts";
38
40
  import { formatMinifiedSource } from "../document/source-format.ts";
39
41
  import { isOpenapiSource } from "../document/openapi.ts";
@@ -293,6 +295,7 @@ async function documentFromDecoded(
293
295
  let describedBy: string | undefined = linkHints.describedBy;
294
296
  let markdownAlternateUrl: string | undefined = linkHints.markdownAlternate;
295
297
  let sourceLanguage: string | undefined;
298
+ let githubReadme = false;
296
299
  const openapiSpec = isOpenapiSource(raw, contentType);
297
300
 
298
301
  if (isHtmlContentType(contentType)) {
@@ -301,6 +304,7 @@ async function documentFromDecoded(
301
304
  title = extracted.title;
302
305
  fragmentOffsets = extracted.fragmentOffsets;
303
306
  extractor = extracted.extractor;
307
+ githubReadme = extracted.githubReadme === true;
304
308
  describedBy = describedBy ?? extracted.describedByLink;
305
309
  markdownAlternateUrl = markdownAlternateUrl ?? extracted.markdownAlternateLink;
306
310
  } else if (contentType === "application/json") {
@@ -337,15 +341,21 @@ async function documentFromDecoded(
337
341
  const isHtml = isHtmlContentType(contentType);
338
342
  const links = isHtml ? extractDocumentLinks(raw, target.url) : undefined;
339
343
 
344
+ const extractionDiagnostics = isHtml ? diagnoseExtraction(raw, markdown) : undefined;
345
+
340
346
  if (
341
347
  !markdown.trim() &&
342
348
  (!links || (links.internal.length === 0 && links.external.length === 0)) &&
343
- !allowEmptyContent
349
+ !allowEmptyContent &&
350
+ !extractionDiagnostics?.botWall
344
351
  ) {
345
352
  throw new Error("web_fetch: Page has no extractable content.");
346
353
  }
347
354
 
348
- const extractionDiagnostics = isHtml ? diagnoseExtraction(raw, markdown) : undefined;
355
+ // Repository chrome can dwarf a complete, intentionally short README.
356
+ if (extractionDiagnostics && githubReadme && markdown.trim()) {
357
+ extractionDiagnostics.sparseExtraction = false;
358
+ }
349
359
 
350
360
  const shellSuspected = extractionDiagnostics
351
361
  ? hasExtractionWarning(extractionDiagnostics)
@@ -432,21 +442,38 @@ async function documentFromAcquisition(
432
442
  dependencies: FetchRemoteDependencies,
433
443
  allowSolve: boolean,
434
444
  ): Promise<CompleteDocument> {
435
- assertSuccessfulResponse(response);
436
445
  const status = response.statusCode ?? 0;
437
446
  const contentTypeHeader = responseContentTypeHeader(response);
438
447
  const contentType = normalizeContentType(contentTypeHeader);
439
448
 
449
+ const reddit403 =
450
+ allowSolve &&
451
+ status === 403 &&
452
+ target.url.protocol === "https:" &&
453
+ ["reddit.com", "www.reddit.com", "old.reddit.com"].includes(target.url.hostname) &&
454
+ !target.url.username &&
455
+ !target.url.password &&
456
+ !target.url.port &&
457
+ isHtmlContentType(contentType);
458
+
459
+ if (!reddit403) assertSuccessfulResponse(response);
460
+
440
461
  if (
441
462
  allowSolve &&
442
- dependencies.solveAnubisChallenges !== false &&
443
- status >= 200 &&
444
- status < 300 &&
463
+ ((status >= 200 && status < 300) || reddit403) &&
445
464
  isHtmlContentType(contentType)
446
465
  ) {
447
466
  const body = await decodeResponseBody(response, signal, contentTypeHeader, contentType);
448
467
 
449
- if (hasAnubisMarkers(body.raw)) {
468
+ if (reddit403 && !diagnoseExtraction(body.raw, "").botWall) assertSuccessfulResponse(response);
469
+
470
+ const blocked = reddit403
471
+ ? await documentFromDecoded(target, response, body, signal, extractHtml, allowEmptyContent)
472
+ : undefined;
473
+
474
+ if (reddit403 && !blocked?.extractionDiagnostics?.botWall) assertSuccessfulResponse(response);
475
+
476
+ if (!reddit403 && dependencies.solveAnubisChallenges !== false && hasAnubisMarkers(body.raw)) {
450
477
  const challenge = parseAnubisChallenge(body.raw, target.url);
451
478
 
452
479
  if (challenge) {
@@ -479,7 +506,38 @@ async function documentFromAcquisition(
479
506
  return documentFromDecoded(target, response, body, signal, extractHtml, allowEmptyContent);
480
507
  }
481
508
 
482
- return documentFromDecoded(target, response, body, signal, extractHtml, allowEmptyContent);
509
+ const redditPass = redditChallengeUrl(body.raw, target.url);
510
+
511
+ if (redditPass) {
512
+ try {
513
+ const passed = await requestFollowingRedirects(redditPass, signal, dependencies);
514
+
515
+ if (
516
+ passed.target.url.origin === target.url.origin &&
517
+ passed.target.url.pathname === target.url.pathname
518
+ ) {
519
+ // The handshake query contains a token; never expose or cache it as the document URL.
520
+ return await documentFromAcquisition(
521
+ { ...passed.target, url: target.url },
522
+ passed.response,
523
+ signal,
524
+ extractHtml,
525
+ allowEmptyContent,
526
+ dependencies,
527
+ false,
528
+ );
529
+ }
530
+
531
+ passed.response.destroy();
532
+ } catch (error) {
533
+ if (signal.aborted || (error instanceof Error && error.name === "AbortError")) throw error;
534
+ // An unsupported or refused challenge falls back to the blocked document.
535
+ }
536
+ }
537
+
538
+ return (
539
+ blocked ?? documentFromDecoded(target, response, body, signal, extractHtml, allowEmptyContent)
540
+ );
483
541
  }
484
542
 
485
543
  return documentFromResponse(target, response, signal, extractHtml, allowEmptyContent);
@@ -689,18 +747,71 @@ async function fetchDocument(
689
747
  };
690
748
  }
691
749
 
692
- return {
693
- document: await documentFromAcquisition(
694
- target,
695
- response,
696
- controller.signal,
697
- extractHtml,
698
- allowEmptyContent,
699
- requestDependencies,
700
- true,
701
- ),
702
- revalidated: false,
703
- };
750
+ const requestedFeed = redditFeedUrl(rawUrl);
751
+ const finalFeed = redditFeedUrl(target.url.href);
752
+
753
+ const eligibleFeed =
754
+ requestedFeed && finalFeed && requestedFeed.toLowerCase() === finalFeed.toLowerCase()
755
+ ? requestedFeed
756
+ : undefined;
757
+
758
+ const document = await documentFromAcquisition(
759
+ target,
760
+ response,
761
+ controller.signal,
762
+ extractHtml,
763
+ allowEmptyContent,
764
+ requestDependencies,
765
+ true,
766
+ );
767
+
768
+ const feedUrl = document.extractionDiagnostics?.botWall ? eligibleFeed : undefined;
769
+
770
+ if (feedUrl) {
771
+ try {
772
+ const feed = await requestFollowingRedirects(
773
+ feedUrl,
774
+ controller.signal,
775
+ requestDependencies,
776
+ );
777
+
778
+ const type = normalizeContentType(responseContentTypeHeader(feed.response));
779
+
780
+ if (
781
+ feed.target.url.hostname === "www.reddit.com" &&
782
+ feed.target.url.protocol === "https:" &&
783
+ feed.response.statusCode === 200 &&
784
+ type === "application/atom+xml"
785
+ ) {
786
+ const body = await decodeResponseBody(
787
+ feed.response,
788
+ controller.signal,
789
+ responseContentTypeHeader(feed.response),
790
+ type,
791
+ );
792
+
793
+ const markdown = extractRedditFeed(body.raw, feedUrl);
794
+
795
+ if (markdown)
796
+ return {
797
+ document: {
798
+ url: document.url,
799
+ contentType: type,
800
+ markdown,
801
+ extractor: "raw",
802
+ shellSuspected: false,
803
+ cachedAt: Date.now(),
804
+ },
805
+ revalidated: false,
806
+ };
807
+ } else feed.response.destroy();
808
+ } catch (error) {
809
+ if (controller.signal.aborted) throw error;
810
+ // Reddit's anonymous feed may be unavailable or rate limited.
811
+ }
812
+ }
813
+
814
+ return { document, revalidated: false };
704
815
  } catch (error) {
705
816
  if (timedOut) throw new Error(`web_fetch timed out after ${timeoutMs / 1000} seconds.`);
706
817
 
@@ -0,0 +1,71 @@
1
+ import { DOMParser } from "linkedom";
2
+ import { assertConversionDepth } from "../document/complexity.ts";
3
+ import { htmlToMarkdownFallback } from "../document/extract.ts";
4
+
5
+ /** Restrict the fallback to public Reddit post permalinks, never arbitrary hosts. */
6
+ export function redditFeedUrl(rawUrl: string): string | undefined {
7
+ const url = new URL(rawUrl);
8
+
9
+ if (
10
+ url.protocol !== "https:" ||
11
+ !["reddit.com", "www.reddit.com", "old.reddit.com"].includes(url.hostname) ||
12
+ url.username ||
13
+ url.password ||
14
+ url.port
15
+ )
16
+ return undefined;
17
+
18
+ const match = /^\/r\/([a-z0-9_]+)\/comments\/([a-z0-9]+)(?:\/[^/]+)?\/?$/i.exec(url.pathname);
19
+
20
+ if (!match) return undefined;
21
+
22
+ return `https://www.reddit.com/r/${match[1]}/comments/${match[2]}/.rss`;
23
+ }
24
+
25
+ /** Render the anonymous Atom representation; it does not preserve comment hierarchy. */
26
+ export function extractRedditFeed(raw: string, feedUrl: string): string | undefined {
27
+ assertConversionDepth(raw);
28
+ const document = new DOMParser().parseFromString(raw, "text/xml");
29
+
30
+ if (document.documentElement?.localName !== "feed") return undefined;
31
+ const id = /\/comments\/([a-z0-9]+)\//i.exec(new URL(feedUrl).pathname)?.[1];
32
+ const entries = [...document.querySelectorAll("entry")];
33
+
34
+ const post = entries.find(
35
+ (entry) => entry.querySelector("id")?.textContent?.trim() === `t3_${id}`,
36
+ );
37
+
38
+ if (!post) return undefined;
39
+
40
+ const render = (entry: Element): string => {
41
+ const author = entry.querySelector("author name")?.textContent?.trim();
42
+ const title = entry.querySelector("title")?.textContent?.trim();
43
+ const content = entry.querySelector("content")?.textContent ?? "";
44
+ const text = htmlToMarkdownFallback(content);
45
+
46
+ return [title, author ? `By ${author}` : "", text].filter(Boolean).join("\n\n");
47
+ };
48
+
49
+ const main = render(post);
50
+
51
+ if (!main) return undefined;
52
+
53
+ const comments: string[] = [];
54
+
55
+ for (const entry of entries) {
56
+ if (
57
+ entry === post ||
58
+ !/^t1_[a-z0-9]+$/i.test(entry.querySelector("id")?.textContent?.trim() ?? "")
59
+ )
60
+ continue;
61
+ const comment = render(entry);
62
+
63
+ if (comment) comments.push(comment);
64
+ }
65
+
66
+ return [
67
+ "Reddit Atom feed; comments may be incomplete and thread hierarchy is unavailable.",
68
+ main,
69
+ ...comments.map((comment) => `## Comment\n\n${comment}`),
70
+ ].join("\n\n");
71
+ }
@@ -0,0 +1,93 @@
1
+ import { parseHTML } from "linkedom";
2
+
3
+ /** Parse the observed Reddit challenge without executing server-provided JavaScript. */
4
+ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
5
+ if (
6
+ pageUrl.protocol !== "https:" ||
7
+ !["reddit.com", "www.reddit.com", "old.reddit.com"].includes(pageUrl.hostname) ||
8
+ pageUrl.username ||
9
+ pageUrl.password ||
10
+ pageUrl.port
11
+ )
12
+ return undefined;
13
+ const { document } = parseHTML(raw);
14
+ const forms = document.querySelectorAll("form");
15
+
16
+ if (forms.length !== 1) return undefined;
17
+ const form = forms[0];
18
+
19
+ if (!form.hasAttribute("hidden") || form.getAttribute("method")?.toLowerCase() !== "get")
20
+ return undefined;
21
+ const action = form.getAttribute("action");
22
+
23
+ if (!action) return undefined;
24
+ let target: URL;
25
+
26
+ try {
27
+ target = new URL(action, pageUrl);
28
+ } catch {
29
+ return undefined;
30
+ }
31
+
32
+ if (
33
+ target.origin !== pageUrl.origin ||
34
+ target.pathname !== pageUrl.pathname ||
35
+ target.search ||
36
+ target.hash
37
+ )
38
+ return undefined;
39
+ const inputs = [...form.querySelectorAll("input")];
40
+
41
+ if (inputs.length !== 4) return undefined;
42
+ const values = new Map<string, string>();
43
+
44
+ for (const input of inputs) {
45
+ const name = input.getAttribute("name");
46
+
47
+ if (!name || values.has(name) || input.getAttribute("type")?.toLowerCase() !== "hidden")
48
+ return undefined;
49
+ values.set(name, input.getAttribute("value") ?? "");
50
+ }
51
+
52
+ const token = values.get("jsc_token");
53
+
54
+ if (
55
+ values.get("solution") !== "" ||
56
+ values.get("js_challenge") !== "1" ||
57
+ !token ||
58
+ !/^[a-f0-9]{1,256}$/i.test(token) ||
59
+ values.get("jsc_orig_r") !== ""
60
+ )
61
+ return undefined;
62
+
63
+ for (const name of values.keys()) if (pageUrl.searchParams.has(name)) return undefined;
64
+
65
+ if (pageUrl.search.length > 2048) return undefined;
66
+ const scripts = [...document.querySelectorAll("script")];
67
+
68
+ if (scripts.length !== 1 || scripts[0].hasAttribute("src")) return undefined;
69
+ const script = scripts[0].textContent ?? "";
70
+
71
+ if (script.length > 16_384) return undefined;
72
+
73
+ // Match only the observed literal string-doubling expression. Never evaluate code.
74
+ const match =
75
+ /await\s*\(\s*async\s+([a-zA-Z_$][\w$]*)\s*=>\s*\1\s*\+\s*\1\s*\)\s*\(\s*(["'])([a-f0-9]{1,128})\2\s*\)/i.exec(
76
+ script,
77
+ );
78
+
79
+ if (
80
+ !match ||
81
+ !/namedItem\(["']solution["']\)\.value\s*=/.test(script) ||
82
+ !/requestSubmit\(\)/.test(script)
83
+ )
84
+ return undefined;
85
+ target.searchParams.set("solution", match[3] + match[3]);
86
+ target.searchParams.set("js_challenge", "1");
87
+ target.searchParams.set("jsc_token", token);
88
+ target.searchParams.set("jsc_orig_r", "");
89
+
90
+ for (const [key, value] of pageUrl.searchParams) target.searchParams.append(key, value);
91
+
92
+ return target;
93
+ }
@@ -27,6 +27,93 @@ const VOID_ELEMENTS = new Set([
27
27
  // in particular, linkedom parses nested elements inside <noscript>.
28
28
  const RAW_TEXT_ELEMENTS = new Set(["script", "style", "textarea"]);
29
29
 
30
+ /** Form elements that close each other in linkedom's parser, mirroring htmlparser2. */
31
+ const FORM_ELEMENTS = new Set([
32
+ "input",
33
+ "option",
34
+ "optgroup",
35
+ "select",
36
+ "button",
37
+ "datalist",
38
+ "textarea",
39
+ ]);
40
+
41
+ const P_TAG = new Set(["p"]);
42
+
43
+ /**
44
+ * Start tags that imply an end tag, mapped to the tags they close, mirroring
45
+ * htmlparser2's `openImpliesClose` table used by linkedom. A tag closes only while it
46
+ * is on top of the open-element stack; an intervening element keeps it open.
47
+ */
48
+ const IMPLIED_END_TAGS = new Map<string, ReadonlySet<string>>([
49
+ ["tr", new Set(["tr", "th", "td"])],
50
+ ["th", new Set(["th"])],
51
+ ["td", new Set(["thead", "th", "td"])],
52
+ ["body", new Set(["head", "link", "script"])],
53
+ ["li", new Set(["li"])],
54
+ ["p", P_TAG],
55
+ ["h1", P_TAG],
56
+ ["h2", P_TAG],
57
+ ["h3", P_TAG],
58
+ ["h4", P_TAG],
59
+ ["h5", P_TAG],
60
+ ["h6", P_TAG],
61
+ ["select", FORM_ELEMENTS],
62
+ ["input", FORM_ELEMENTS],
63
+ ["output", FORM_ELEMENTS],
64
+ ["button", FORM_ELEMENTS],
65
+ ["datalist", FORM_ELEMENTS],
66
+ ["textarea", FORM_ELEMENTS],
67
+ ["option", new Set(["option"])],
68
+ ["optgroup", new Set(["optgroup", "option"])],
69
+ ["dd", new Set(["dd", "dt"])],
70
+ ["dt", new Set(["dd", "dt"])],
71
+ ["address", P_TAG],
72
+ ["article", P_TAG],
73
+ ["aside", P_TAG],
74
+ ["blockquote", P_TAG],
75
+ ["details", P_TAG],
76
+ ["div", P_TAG],
77
+ ["dl", P_TAG],
78
+ ["fieldset", P_TAG],
79
+ ["figcaption", P_TAG],
80
+ ["figure", P_TAG],
81
+ ["footer", P_TAG],
82
+ ["form", P_TAG],
83
+ ["header", P_TAG],
84
+ ["hr", P_TAG],
85
+ ["main", P_TAG],
86
+ ["nav", P_TAG],
87
+ ["ol", P_TAG],
88
+ ["pre", P_TAG],
89
+ ["section", P_TAG],
90
+ ["table", P_TAG],
91
+ ["ul", P_TAG],
92
+ ["rt", new Set(["rt", "rp"])],
93
+ ["rp", new Set(["rt", "rp"])],
94
+ ["tbody", new Set(["thead", "tbody"])],
95
+ ["tfoot", new Set(["thead", "tbody"])],
96
+ ] satisfies Array<[string, ReadonlySet<string>]>);
97
+
98
+ /**
99
+ * Elements that open foreign content, where self-closing syntax is honored.
100
+ * In HTML content a trailing `/` is ignored, matching linkedom and the HTML rules.
101
+ */
102
+ const FOREIGN_ROOTS = new Set(["svg", "math"]);
103
+
104
+ /** Foreign-content elements that switch linkedom back to HTML parsing. */
105
+ const HTML_INTEGRATION_ELEMENTS = new Set([
106
+ "mi",
107
+ "mo",
108
+ "mn",
109
+ "ms",
110
+ "mtext",
111
+ "annotation-xml",
112
+ "foreignobject",
113
+ "desc",
114
+ "title",
115
+ ]);
116
+
30
117
  /**
31
118
  * Finds a raw-text end tag in lowercased HTML, starting at the supplied code-unit
32
119
  * offset, without interpreting its body as markup. Returns -1 when none is found.
@@ -49,16 +136,59 @@ function findRawTextEnd(html: string, name: string, from: number): number {
49
136
 
50
137
  /**
51
138
  * Conservatively checks lexical HTML depth in one pass, before creating a DOM.
52
- * Only a matching top-of-stack closing tag reduces depth. Self-closing syntax
53
- * on non-void HTML elements is counted as opening, just as linkedom treats it.
139
+ * Only a matching top-of-stack closing tag reduces depth, plus the implied end tags
140
+ * that linkedom itself applies for optional-end-tag elements; without those, ordinary
141
+ * documents whose `p`, `li`, or `td` end tags are omitted would be refused. An implied
142
+ * close applies only while its tag is on top of the stack, matching linkedom's parser,
143
+ * so an intervening element keeps counting toward depth. Self-closing syntax on non-void
144
+ * HTML elements is counted as opening, just as linkedom treats it, while foreign content
145
+ * (`svg`, `math`) honors it.
54
146
  * Quoted attributes, comments, and raw-text bodies cannot hide nested markup.
55
147
  */
56
148
  export function exceedsConversionDepth(html: string): boolean {
57
149
  // Preserve code-unit positions when normalizing ASCII tag names.
58
150
  const lower = html.replace(/[A-Z]+/g, (match) => match.toLowerCase());
59
151
  const stack: string[] = [];
152
+ // htmlparser2 keeps this flag in parallel with its element stack. Integration points
153
+ // push HTML mode even under SVG or MathML; this must happen before self-closing checks.
154
+ const foreignContexts = [false];
60
155
  let offset = 0;
61
156
 
157
+ const push = (name: string): void => {
158
+ const parentForeign = foreignContexts.at(-1) ?? false;
159
+
160
+ const foreign = FOREIGN_ROOTS.has(name)
161
+ ? true
162
+ : HTML_INTEGRATION_ELEMENTS.has(name)
163
+ ? false
164
+ : parentForeign;
165
+
166
+ stack.push(name);
167
+ foreignContexts.push(foreign);
168
+ };
169
+
170
+ const pop = (): void => {
171
+ if (stack.pop() === undefined) return;
172
+
173
+ foreignContexts.pop();
174
+ };
175
+
176
+ // The scan is charged to the elements it pops, so total work stays linear.
177
+ const closeImplied = (name: string): void => {
178
+ const implied = IMPLIED_END_TAGS.get(name);
179
+
180
+ if (implied === undefined) return;
181
+
182
+ // linkedom closes an implied end tag only while it is on top of its own stack.
183
+ while (stack.length > 0) {
184
+ const top = stack.at(-1);
185
+
186
+ if (top === undefined || !implied.has(top)) return;
187
+
188
+ pop();
189
+ }
190
+ };
191
+
62
192
  while (offset < html.length) {
63
193
  const start = html.indexOf("<", offset);
64
194
 
@@ -121,9 +251,20 @@ export function exceedsConversionDepth(html: string): boolean {
121
251
  if (html[cursor - 1] !== ">") break;
122
252
 
123
253
  if (closing) {
124
- if (stack.at(-1) === name) stack.pop();
254
+ if (stack.at(-1) === name) pop();
125
255
  } else if (!VOID_ELEMENTS.has(name)) {
126
- stack.push(name);
256
+ // Implied closes apply only in HTML mode, matching htmlparser2/linkedom.
257
+ if (!foreignContexts.at(-1)) closeImplied(name);
258
+ push(name);
259
+
260
+ // Self-closing syntax is honored only in foreign mode. An unquoted attribute value
261
+ // can itself end in `/`, so it is not a self-closing marker. Check after push so an
262
+ // HTML integration point such as `<foreignObject/>` remains open as linkedom does.
263
+ if (html[cursor - 2] === "/" && !unquotedValue && foreignContexts.at(-1)) {
264
+ pop();
265
+ offset = cursor;
266
+ continue;
267
+ }
127
268
 
128
269
  if (stack.length > MAX_CONVERSION_DEPTH) return true;
129
270
 
@@ -83,7 +83,14 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
83
83
  const { document } = parseHTML(raw);
84
84
  const anubisText = [...document.childNodes].map((node) => node.textContent ?? "").join(" ");
85
85
 
86
+ const redditChallenge =
87
+ markdown.trim().length < CAPTCHA_CHALLENGE_MAX_MARKDOWN_CHARACTERS &&
88
+ /<input\b[^>]*\bname\s*=\s*["']js_challenge["']/i.test(raw) &&
89
+ /<input\b[^>]*\bname\s*=\s*["']jsc_token["']/i.test(raw) &&
90
+ /<input\b[^>]*\bname\s*=\s*["']solution["']/i.test(raw);
91
+
86
92
  const captchaChallenge =
93
+ redditChallenge ||
87
94
  CAPTCHA_LOADER_MARKERS.some((marker) => marker.test(raw)) ||
88
95
  (markdown.trim().length < CAPTCHA_CHALLENGE_MAX_MARKDOWN_CHARACTERS &&
89
96
  CAPTCHA_WIDGET_MARKERS.some((marker) => marker.test(raw)));
@@ -147,6 +147,29 @@ export function htmlToMarkdownFallback(html: string): string {
147
147
  element.remove();
148
148
  }
149
149
 
150
+ for (const element of document.querySelectorAll("[hidden], [aria-hidden], [style]")) {
151
+ const style = element.getAttribute("style") ?? "";
152
+
153
+ const hiddenStyle =
154
+ /(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(
155
+ style,
156
+ );
157
+
158
+ if (
159
+ element.hasAttribute("hidden") ||
160
+ element.getAttribute("aria-hidden")?.trim().toLowerCase() === "true" ||
161
+ hiddenStyle
162
+ ) {
163
+ element.remove();
164
+ }
165
+ }
166
+
167
+ for (const element of document.body.querySelectorAll(
168
+ "p, div, section, article, li, blockquote, pre, h1, h2, h3, h4, h5, h6, br, tr",
169
+ )) {
170
+ element.after(document.createTextNode("\n\n"));
171
+ }
172
+
150
173
  return document.body.textContent
151
174
  .replace(/[ \t]+\n/g, "\n")
152
175
  .replace(/\n[ \t]+/g, "\n")
@@ -242,6 +265,24 @@ function stripChromeWrappers(document: Document, baseUrl: URL): void {
242
265
  }
243
266
  }
244
267
 
268
+ /** Restricts GitHub repository roots to their rendered README, when available. */
269
+ function isolateGitHubReadme(document: Document, baseUrl: URL): boolean {
270
+ if (baseUrl.hostname !== "github.com" || baseUrl.pathname.split("/").filter(Boolean).length !== 2)
271
+ return false;
272
+
273
+ const readme = document.querySelector(
274
+ "main article.markdown-body.entry-content[itemprop='text']",
275
+ );
276
+
277
+ if (!readme || !readme.textContent?.trim()) return false;
278
+
279
+ const main = document.createElement("main");
280
+ main.appendChild(readme);
281
+ document.body.replaceChildren(main);
282
+
283
+ return true;
284
+ }
285
+
245
286
  /**
246
287
  * Collapses consecutive duplicate markdown link lines (e.g. duplicated [Latest] on GitHub releases).
247
288
  *
@@ -409,10 +450,13 @@ export async function extractHtmlToMarkdown(
409
450
  fragmentOffsets?: Record<string, number>;
410
451
  describedByLink?: string;
411
452
  markdownAlternateLink?: string;
453
+ githubReadme?: boolean;
412
454
  }> {
413
455
  // Keep refusal outside the catch: the fallback also constructs a DOM.
414
456
  assertConversionDepth(html);
415
457
  let advertised: AdvertisedLinks = {};
458
+ let fallbackHtml = html;
459
+ let githubReadme = false;
416
460
 
417
461
  try {
418
462
  assertAbsoluteHttpUrl(baseUrl);
@@ -429,9 +473,13 @@ export async function extractHtmlToMarkdown(
429
473
  originalIds.set(element, element.id);
430
474
  }
431
475
 
432
- normalizeSelectorUnsafeIds(document);
433
476
  stripChromeWrappers(document, baseUrl);
434
477
  advertised = readAdvertisedLinks(document, baseUrl);
478
+
479
+ githubReadme = isolateGitHubReadme(document, baseUrl);
480
+
481
+ if (githubReadme) fallbackHtml = document.documentElement.outerHTML;
482
+ normalizeSelectorUnsafeIds(document);
435
483
  // Pass the full absolute URL so Defuddle resolves relative links (e.g.
436
484
  // `/owner/repo/releases`) and metadata against the real origin instead of
437
485
  // dropping the scheme and host and constructing `new URL(pathname)`.
@@ -448,6 +496,7 @@ export async function extractHtmlToMarkdown(
448
496
  markdown,
449
497
  title: trimmedTitle || undefined,
450
498
  extractor: "defuddle",
499
+ githubReadme,
451
500
  fragmentOffsets: buildFragmentOffsets(document, markdown, originalIds),
452
501
  ...advertised,
453
502
  };
@@ -456,11 +505,11 @@ export async function extractHtmlToMarkdown(
456
505
  // Fall through to the basic converter for malformed or unsupported pages.
457
506
  }
458
507
 
459
- const fallbackMarkdown = stripExtractedCssCruft(htmlToMarkdownFallback(html));
508
+ const fallbackMarkdown = stripExtractedCssCruft(htmlToMarkdownFallback(fallbackHtml));
460
509
  let fragmentOffsets: Record<string, number> = {};
461
510
 
462
511
  try {
463
- fragmentOffsets = buildFragmentOffsets(parseHTML(html).document, fallbackMarkdown);
512
+ fragmentOffsets = buildFragmentOffsets(parseHTML(fallbackHtml).document, fallbackMarkdown);
464
513
  } catch {
465
514
  // Malformed HTML has already been reduced to plain text; no anchors are available.
466
515
  }
@@ -468,6 +517,7 @@ export async function extractHtmlToMarkdown(
468
517
  return {
469
518
  markdown: fallbackMarkdown,
470
519
  extractor: "basic",
520
+ githubReadme,
471
521
  fragmentOffsets,
472
522
  ...advertised,
473
523
  };
package/src/index.ts CHANGED
@@ -79,14 +79,14 @@ export const webFetchParameters = Type.Object({
79
79
  Type.String({
80
80
  minLength: 1,
81
81
  maxLength: FETCH_MAX_QUERY_CHARACTERS,
82
- description: "Find sections matching this text.",
82
+ description: "Select page sections matching this text.",
83
83
  }),
84
84
  ),
85
85
  offset: Type.Optional(
86
86
  Type.Integer({
87
87
  minimum: 0,
88
88
  maximum: FETCH_MAX_OFFSET_CHARACTERS,
89
- description: "Start at this character offset.",
89
+ description: "Continue at this character offset in the selected view.",
90
90
  }),
91
91
  ),
92
92
  });
@@ -99,6 +99,7 @@ export const webFetchParameters = Type.Object({
99
99
  export default function (pi: ExtensionAPI) {
100
100
  pi.registerTool<typeof webFetchParameters, Partial<WebFetchDetails>>({
101
101
  name: "web_fetch",
102
+ exposure: "model-only",
102
103
  label: "Web Fetch",
103
104
  description: "Read content from a public URL.",
104
105
  parameters: webFetchParameters,