@zeldrisho/pi-web-fetch 0.16.3 → 0.16.5

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,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.16.5] - 2026-11-10
11
+
12
+ ### Fixed
13
+
14
+ - Exclude explicitly hidden elements from the basic HTML extraction fallback.
15
+ - Sanitize unsafe links and event handlers in HTML retained in extracted Markdown.
16
+ - 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.
17
+ - 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.
18
+ - Reject deeply nested SVG and MathML markup that uses HTML integration points or slashes in unquoted attribute values to bypass the depth preflight.
19
+
20
+ ## [0.16.4] - 2026-11-09
21
+
22
+ ### Fixed
23
+
24
+ - Close unused redirect and error responses promptly, including stalled responses.
25
+ - Avoid retrying before a server's longer requested delay.
26
+ - Bound concurrent page acquisitions, including slow downloads, and reject requests when the waiting queue is full.
27
+
10
28
  ## [0.16.3] - 2026-11-01
11
29
 
12
30
  ### Fixed
@@ -316,7 +334,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
316
334
 
317
335
  - Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
318
336
 
319
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.3...HEAD
337
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...HEAD
338
+ [0.16.5]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...pi-web-fetch-v0.16.5
339
+ [0.16.4]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.3...pi-web-fetch-v0.16.4
320
340
  [0.16.3]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.2...pi-web-fetch-v0.16.3
321
341
  [0.16.2]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.1...pi-web-fetch-v0.16.2
322
342
  [0.16.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.0...pi-web-fetch-v0.16.1
package/README.md CHANGED
@@ -17,13 +17,13 @@ Use `pi config` to enable or disable the extension, and `pi list` to see configu
17
17
 
18
18
  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
19
 
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. |
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 a fragment, offsets apply to the focused view; otherwise an offset takes precedence over the fragment. |
25
25
 
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.
26
+ 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
27
 
28
28
  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
29
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-fetch",
3
- "version": "0.16.3",
3
+ "version": "0.16.5",
4
4
  "description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
5
5
  "keywords": [
6
6
  "pi",
@@ -32,7 +32,7 @@
32
32
  "dependencies": {
33
33
  "acorn": "^8.19.0",
34
34
  "acorn-walk": "^8.3.5",
35
- "defuddle": "^0.19.5",
35
+ "defuddle": "^0.19.6",
36
36
  "linkedom": "^0.18.13",
37
37
  "yaml": "^2.9.1"
38
38
  },
@@ -0,0 +1,64 @@
1
+ /** Limits complete acquisitions, including slow response bodies and extraction. */
2
+ export class AcquisitionAdmission {
3
+ #active = 0;
4
+ readonly #waiting: Array<() => void> = [];
5
+
6
+ readonly maxActive: number;
7
+ readonly maxWaiting: number;
8
+
9
+ constructor(maxActive: number, maxWaiting: number) {
10
+ this.maxActive = maxActive;
11
+ this.maxWaiting = maxWaiting;
12
+ }
13
+
14
+ async acquire(signal: AbortSignal): Promise<() => void> {
15
+ signal.throwIfAborted();
16
+
17
+ if (this.#active >= this.maxActive) {
18
+ if (this.#waiting.length >= this.maxWaiting) {
19
+ throw new Error("web_fetch is busy; too many requests are waiting.");
20
+ }
21
+
22
+ await new Promise<void>((resolve, reject) => {
23
+ const enter = () => {
24
+ signal.removeEventListener("abort", cancel);
25
+ this.#active += 1;
26
+ resolve();
27
+ };
28
+
29
+ const cancel = () => {
30
+ const index = this.#waiting.indexOf(enter);
31
+
32
+ if (index >= 0) this.#waiting.splice(index, 1);
33
+ reject(signal.reason);
34
+ };
35
+
36
+ this.#waiting.push(enter);
37
+ signal.addEventListener("abort", cancel, { once: true });
38
+
39
+ if (signal.aborted) cancel();
40
+ });
41
+ } else {
42
+ this.#active += 1;
43
+ }
44
+
45
+ let released = false;
46
+
47
+ const release = () => {
48
+ if (released) return;
49
+ released = true;
50
+ this.#active -= 1;
51
+ this.#waiting.shift()?.();
52
+ };
53
+
54
+ if (signal.aborted) {
55
+ release();
56
+ signal.throwIfAborted();
57
+ }
58
+
59
+ return release;
60
+ }
61
+ }
62
+
63
+ /** Bound worst-case concurrent downloads without serializing normal subagent use. */
64
+ export const acquisitionAdmission = new AcquisitionAdmission(16, 128);
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage } from "node:http";
2
+ import { acquisitionAdmission } from "./admission.ts";
2
3
  import {
3
4
  lineFragmentOffsets,
4
5
  markdownFragmentOffsets,
@@ -202,7 +203,7 @@ function assertSuccessfulResponse(response: IncomingMessage): void {
202
203
  const status = response.statusCode ?? 0;
203
204
 
204
205
  if (isAwsWafChallengeResponse(response)) {
205
- response.resume();
206
+ response.destroy();
206
207
  throw new ChallengeBlockedError(
207
208
  `web_fetch was blocked by an AWS WAF anti-bot challenge (HTTP ${status}).`,
208
209
  );
@@ -213,7 +214,7 @@ function assertSuccessfulResponse(response: IncomingMessage): void {
213
214
  const cloudflareChallenge =
214
215
  responseHeader(response, "cf-mitigated")?.trim().toLowerCase() === "challenge";
215
216
 
216
- response.resume();
217
+ response.destroy();
217
218
 
218
219
  if (cloudflareChallenge) {
219
220
  throw new ChallengeBlockedError(
@@ -569,6 +570,9 @@ async function fetchDocument(
569
570
 
570
571
  const cancel = () => controller.abort();
571
572
  signal?.addEventListener("abort", cancel, { once: true });
573
+
574
+ if (signal?.aborted) cancel();
575
+ let release: (() => void) | undefined;
572
576
  const conditionalHeaders: Record<string, string> = {};
573
577
 
574
578
  if (cached?.validators?.etag) conditionalHeaders["If-None-Match"] = cached.validators.etag;
@@ -584,6 +588,7 @@ async function fetchDocument(
584
588
  };
585
589
 
586
590
  try {
591
+ release = await acquisitionAdmission.acquire(controller.signal);
587
592
  const requestUrl = normalizeGitHubRawUrl(rawUrl);
588
593
 
589
594
  let { target, response } = await requestFollowingRedirects(
@@ -600,7 +605,7 @@ async function fetchDocument(
600
605
  // for one exact representation opt out: HTML from that URL is never the
601
606
  // representation they are looking for.
602
607
  if (retryRepresentationMiss && [404, 406].includes(response.statusCode ?? 0)) {
603
- response.resume();
608
+ response.destroy();
604
609
  ({ target, response } = await requestFollowingRedirects(
605
610
  target.url,
606
611
  controller.signal,
@@ -616,7 +621,7 @@ async function fetchDocument(
616
621
  const fallbackUrl = npmRegistryFallbackUrl(rawUrl);
617
622
 
618
623
  if (fallbackUrl) {
619
- response.resume();
624
+ response.destroy();
620
625
  ({ target, response } = await requestFollowingRedirects(
621
626
  fallbackUrl,
622
627
  controller.signal,
@@ -632,7 +637,7 @@ async function fetchDocument(
632
637
  const resolver = requestDependencies.awsWafResolver ?? nativeAwsWafResolver;
633
638
 
634
639
  if (resolver) {
635
- response.resume();
640
+ response.destroy();
636
641
 
637
642
  const solution = await resolveAwsWafToken(
638
643
  resolver,
@@ -668,7 +673,7 @@ async function fetchDocument(
668
673
  }
669
674
 
670
675
  if (response.statusCode === 304 && cached) {
671
- response.resume();
676
+ response.destroy();
672
677
  const etag = responseHeader(response, "etag") ?? cached.validators?.etag;
673
678
 
674
679
  const lastModified =
@@ -702,6 +707,7 @@ async function fetchDocument(
702
707
  if (signal?.aborted) throw new Error("web_fetch was cancelled.");
703
708
  throw error;
704
709
  } finally {
710
+ release?.();
705
711
  clearTimeout(timeout);
706
712
  signal?.removeEventListener("abort", cancel);
707
713
  }
@@ -394,7 +394,7 @@ async function fetchWasmModule(
394
394
  const status = response.statusCode ?? 0;
395
395
 
396
396
  if (status < 200 || status >= 300) {
397
- response.resume();
397
+ response.destroy();
398
398
  throw new Error(`web_fetch could not download the Anubis challenge module (HTTP ${status}).`);
399
399
  }
400
400
 
@@ -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
 
@@ -147,6 +147,23 @@ 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
+
150
167
  return document.body.textContent
151
168
  .replace(/[ \t]+\n/g, "\n")
152
169
  .replace(/\n[ \t]+/g, "\n")
@@ -116,18 +116,17 @@ async function defaultSleep(milliseconds: number, signal: AbortSignal): Promise<
116
116
  });
117
117
  }
118
118
 
119
- /** Parses a Retry-After header into a bounded delay in milliseconds. */
119
+ /** Parses a Retry-After header into a delay in milliseconds. */
120
120
  function retryAfterMilliseconds(value: string | undefined, now = Date.now()): number | undefined {
121
121
  if (!value) return undefined;
122
- const seconds = Number(value.trim());
122
+ const trimmed = value.trim();
123
123
 
124
- if (Number.isFinite(seconds) && seconds >= 0)
125
- return Math.min(seconds * 1_000, MAX_RETRY_DELAY_MS);
124
+ if (/^\d+(?:\.\d+)?$/u.test(trimmed)) return Number(trimmed) * 1_000;
126
125
  const date = Date.parse(value);
127
126
 
128
127
  if (!Number.isFinite(date)) return undefined;
129
128
 
130
- return Math.min(Math.max(0, date - now), MAX_RETRY_DELAY_MS);
129
+ return Math.max(0, date - now);
131
130
  }
132
131
 
133
132
  /** Sends one origin-limited request and retries transient rate-limit responses. */
@@ -170,10 +169,14 @@ async function coordinatedRequest(
170
169
  const status = response.statusCode ?? 0;
171
170
 
172
171
  if (![429, 503].includes(status) || attempt >= MAX_RETRIES) return response;
173
- // The retry decision uses headers only. Drop an untrusted error body so it cannot
174
- // consume unbounded bandwidth while the caller is backing off.
175
- response.destroy();
176
172
  const advertised = retryAfterMilliseconds(responseHeader(response, "retry-after"));
173
+
174
+ // Do not retry earlier than the server requested. Return the response so the
175
+ // caller can report its status rather than waiting beyond our retry budget.
176
+ if (advertised !== undefined && advertised > MAX_RETRY_DELAY_MS) return response;
177
+
178
+ // The retry decision uses headers only. Drop the untrusted error body.
179
+ response.destroy();
177
180
  const exponential = BASE_RETRY_DELAY_MS * 2 ** attempt;
178
181
  const jittered = Math.round(exponential * (0.75 + Math.min(1, Math.max(0, random())) * 0.5));
179
182
  await sleep(advertised ?? Math.min(jittered, MAX_RETRY_DELAY_MS), signal);
@@ -202,11 +205,14 @@ export async function requestFollowingRedirects(
202
205
 
203
206
  const location = responseHeader(response, "location");
204
207
 
208
+ // Redirect bodies are unused and may never finish. Close before validation
209
+ // or error handling so no discarded response survives the acquisition.
210
+ response.destroy();
211
+
205
212
  if (!location) throw new Error("web_fetch received a redirect without a Location header.");
206
213
 
207
214
  if (redirects === FETCH_MAX_REDIRECTS)
208
215
  throw new Error("web_fetch followed too many redirects.");
209
- response.resume();
210
216
  target = await awaitWithAbort(validateUrl(new URL(location, target.url)), signal);
211
217
  // Validators describe the originally cached resource and must not leak to a redirect target.
212
218
  // Challenge handshakes opt into a fixed browser identity instead.