@zeldrisho/pi-web-fetch 0.17.0 → 0.17.1

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,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.17.1] - 2026-11-18
11
+
12
+ ### Changed
13
+
14
+ - Restore codemode access to structured fetch results with Pi 0.99.0 or newer.
15
+ - Return Packit Copr API data without a verbose substitution notice, while preserving the source URL and structured provenance.
16
+
17
+ ### Fixed
18
+
19
+ - Preserve selected documentation surfaces in HTML fragments and when tab controls use multiple supported attribute mappings.
20
+ - Recognize standard Swagger UI initializers and retain index notices when a visible link points to a different index.
21
+ - Honor explicitly selected documentation surfaces when supported by the page, rather than mixing unrelated surface instructions.
22
+ - Extract plain-text GitHub repository READMEs without the file-listing table.
23
+ - Avoid redundant discovered index notices when the visible page already links to a same-site documentation index.
24
+ - Retrieve Packit Copr job data without an API key and advertised Swagger specifications from otherwise empty app pages.
25
+ - Explain when an empty page requires JavaScript instead of reporting a generic extraction error.
26
+ - Solve supported Anubis challenges that declare no extensions as `null`.
27
+ - Fetch slash-sensitive pages when a trailing slash returns 404 but the page exists without it.
28
+ - Report page errors after a solved Anubis challenge instead of incorrectly reporting a bot block.
29
+
10
30
  ## [0.17.0] - 2026-11-12
11
31
 
12
32
  ### Changed
@@ -345,7 +365,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
345
365
 
346
366
  - Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
347
367
 
348
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...HEAD
368
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...HEAD
369
+ [0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
349
370
  [0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
350
371
  [0.16.5]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...pi-web-fetch-v0.16.5
351
372
  [0.16.4]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.3...pi-web-fetch-v0.16.4
package/README.md CHANGED
@@ -15,8 +15,6 @@ 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
-
20
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.
21
19
 
22
20
  | Parameter | Description |
@@ -25,6 +23,8 @@ The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markd
25
23
  | `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
26
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. |
27
25
 
26
+ When a documentation page exposes a supported tab selector and the URL explicitly selects one (for example, `?tab=cli`), output shows that tab and shared content, with a notice that other tabs were omitted. Remove the parameter to see the full extracted page. Continuation offsets apply to the selected view.
27
+
28
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.
29
29
 
30
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.
@@ -33,12 +33,16 @@ For example, a URL such as `https://github.com/zeldrisho/pi-packages/blob/main/p
33
33
 
34
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
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.
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. Packit Copr job pages can return their public API data without an API key, and empty Swagger UI pages can return an advertised same-origin specification; result metadata identifies the substitute and its URL. Unsupported challenges and JavaScript CAPTCHAs return a blocked result; there is no browser fallback.
37
37
 
38
38
  ### Caching
39
39
 
40
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.
41
41
 
42
+ ### Programmatic results
43
+
44
+ Structured codemode results require Pi 0.99.0 or newer. 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.
45
+
42
46
  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
47
 
44
48
  ## Uninstall
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-fetch",
3
- "version": "0.17.0",
3
+ "version": "0.17.1",
4
4
  "description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
5
5
  "keywords": [
6
6
  "pi",
@@ -55,12 +55,6 @@
55
55
  ]
56
56
  },
57
57
  "scripts": {
58
- "check": "vp check",
59
- "test": "vp test",
60
- "test:watch": "vp test --watch",
61
- "lint": "vp lint",
62
- "lint:fix": "vp lint --fix",
63
- "format": "vp fmt --write",
64
- "typecheck": "vp check --no-fmt --no-lint"
58
+ "test": "vp test"
65
59
  }
66
60
  }
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage } from "node:http";
2
+ import { parseHTML } from "linkedom";
2
3
  import { acquisitionAdmission } from "./admission.ts";
3
4
  import {
4
5
  lineFragmentOffsets,
@@ -291,6 +292,7 @@ async function documentFromDecoded(
291
292
  let markdown: string;
292
293
  let title: string | undefined;
293
294
  let fragmentOffsets: Record<string, number> | undefined;
295
+ let surfaceView: CompleteDocument["surfaceView"];
294
296
  let extractor: CompleteDocument["extractor"] = "raw";
295
297
  let describedBy: string | undefined = linkHints.describedBy;
296
298
  let markdownAlternateUrl: string | undefined = linkHints.markdownAlternate;
@@ -303,6 +305,7 @@ async function documentFromDecoded(
303
305
  markdown = extracted.markdown;
304
306
  title = extracted.title;
305
307
  fragmentOffsets = extracted.fragmentOffsets;
308
+ surfaceView = extracted.surfaceView;
306
309
  extractor = extracted.extractor;
307
310
  githubReadme = extracted.githubReadme === true;
308
311
  describedBy = describedBy ?? extracted.describedByLink;
@@ -342,12 +345,48 @@ async function documentFromDecoded(
342
345
  const links = isHtml ? extractDocumentLinks(raw, target.url) : undefined;
343
346
 
344
347
  const extractionDiagnostics = isHtml ? diagnoseExtraction(raw, markdown) : undefined;
348
+ let swaggerSpecUrl: string | undefined;
349
+
350
+ if (isHtml && !markdown.trim()) {
351
+ const { document } = parseHTML(raw);
352
+
353
+ for (const script of document.querySelectorAll("script:not([src])")) {
354
+ const text = script.textContent ?? "";
355
+
356
+ const options = /\bSwaggerUIBundle\s*\(\s*\{([^{}]{0,8192})\}/.exec(text)?.[1];
357
+
358
+ const match =
359
+ options === undefined
360
+ ? undefined
361
+ : /(?:^|,)\s*url\s*:\s*["']([^"'\\\r\n]+)["']/.exec(options);
362
+
363
+ if (!match) continue;
364
+
365
+ try {
366
+ const candidate = new URL(match[1], target.url);
367
+
368
+ if (
369
+ candidate.origin === target.url.origin &&
370
+ !candidate.username &&
371
+ !candidate.password &&
372
+ !candidate.hash
373
+ )
374
+ swaggerSpecUrl = candidate.href;
375
+ } catch {
376
+ // Ignore malformed advertisements.
377
+ }
378
+
379
+ break;
380
+ }
381
+ }
345
382
 
346
383
  if (
347
384
  !markdown.trim() &&
348
385
  (!links || (links.internal.length === 0 && links.external.length === 0)) &&
349
386
  !allowEmptyContent &&
350
- !extractionDiagnostics?.botWall
387
+ !extractionDiagnostics?.botWall &&
388
+ !extractionDiagnostics?.javascriptRequired &&
389
+ !swaggerSpecUrl
351
390
  ) {
352
391
  throw new Error("web_fetch: Page has no extractable content.");
353
392
  }
@@ -369,6 +408,7 @@ async function documentFromDecoded(
369
408
  contentType,
370
409
  markdown,
371
410
  fragmentOffsets,
411
+ surfaceView,
372
412
  title,
373
413
  extractor,
374
414
  shellSuspected,
@@ -380,6 +420,7 @@ async function documentFromDecoded(
380
420
  markdownAlternateUrl,
381
421
  sourceLanguage,
382
422
  openapiSpec,
423
+ swaggerSpecUrl,
383
424
  };
384
425
  }
385
426
 
@@ -477,29 +518,39 @@ async function documentFromAcquisition(
477
518
  const challenge = parseAnubisChallenge(body.raw, target.url);
478
519
 
479
520
  if (challenge) {
521
+ let passed: Awaited<ReturnType<typeof solveAnubisChallenge>>;
522
+
480
523
  try {
481
- const passed = await solveAnubisChallenge({
524
+ passed = await solveAnubisChallenge({
482
525
  challenge,
483
526
  pageUrl: target.url,
484
527
  raw: body.raw,
485
528
  dependencies,
486
529
  signal,
487
530
  });
531
+ } catch (error) {
532
+ if (signal.aborted || (error instanceof Error && error.name === "AbortError"))
533
+ throw error;
488
534
 
489
- return await documentFromAcquisition(
490
- passed.target,
491
- passed.response,
535
+ return documentFromDecoded(
536
+ target,
537
+ response,
538
+ body,
492
539
  signal,
493
540
  extractHtml,
494
541
  allowEmptyContent,
495
- dependencies,
496
- false,
497
542
  );
498
- } catch (error) {
499
- if (signal.aborted || (error instanceof Error && error.name === "AbortError"))
500
- throw error;
501
- // Any other failure degrades to the standard blocked output below.
502
543
  }
544
+
545
+ return documentFromAcquisition(
546
+ passed.target,
547
+ passed.response,
548
+ signal,
549
+ extractHtml,
550
+ allowEmptyContent,
551
+ dependencies,
552
+ false,
553
+ );
503
554
  }
504
555
 
505
556
  // An unsolvable challenge, denial, or error page is returned as blocked.
@@ -672,6 +723,25 @@ async function fetchDocument(
672
723
  ));
673
724
  }
674
725
 
726
+ // Some sites distinguish a documentation page from the same path with a
727
+ // trailing slash. Retry only once, after representation negotiation fails.
728
+ if (
729
+ retryRepresentationMiss &&
730
+ response.statusCode === 404 &&
731
+ target.url.pathname !== "/" &&
732
+ target.url.pathname.endsWith("/")
733
+ ) {
734
+ const alternate = new URL(target.url);
735
+ alternate.pathname = alternate.pathname.slice(0, -1);
736
+ response.destroy();
737
+ ({ target, response } = await requestFollowingRedirects(
738
+ alternate,
739
+ controller.signal,
740
+ requestDependencies,
741
+ { Accept: "text/html, text/plain;q=0.9, */*;q=0.1" },
742
+ ));
743
+ }
744
+
675
745
  if (
676
746
  response.statusCode !== undefined &&
677
747
  responseHeader(response, "cf-mitigated")?.trim().toLowerCase() === "challenge"
@@ -6,6 +6,28 @@ import {
6
6
  type FetchRemoteDependencies,
7
7
  } from "./fetch.ts";
8
8
  import { InflightCoalescer } from "../inflight";
9
+ import { validateRemoteUrl } from "../network/network-policy.ts";
10
+
11
+ function restrictOrigin(
12
+ dependencies: FetchRemoteDependencies,
13
+ origin: string,
14
+ ): FetchRemoteDependencies {
15
+ const validate = dependencies.validateUrl ?? validateRemoteUrl;
16
+
17
+ return {
18
+ ...dependencies,
19
+ solveAnubisChallenges: false,
20
+ solveAwsWafChallenges: false,
21
+ validateUrl: async (value) => {
22
+ const url = value instanceof URL ? value : new URL(value);
23
+
24
+ if (url.origin !== origin || url.username || url.password)
25
+ throw new Error("Cross-origin fallback redirect refused.");
26
+
27
+ return validate(value);
28
+ },
29
+ };
30
+ }
9
31
 
10
32
  const CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
11
33
 
@@ -149,7 +171,7 @@ async function ensureLlmsTxtIndex(
149
171
  candidates: URL[],
150
172
  signal: AbortSignal | undefined,
151
173
  dependencies: FetchRemoteDependencies,
152
- ): Promise<{ url: string; document: CompleteDocument } | undefined> {
174
+ ): Promise<{ url: string; document: CompleteDocument; aliases?: string[] } | undefined> {
153
175
  const documents = await Promise.all(
154
176
  candidates.map((candidate) => probeUsableRawText(candidate, signal, dependencies)),
155
177
  );
@@ -159,7 +181,13 @@ async function ensureLlmsTxtIndex(
159
181
  for (let depth = documents.length - 1; depth >= 0; depth -= 1) {
160
182
  const document = documents[depth];
161
183
 
162
- if (document) return { url: candidates[depth].href, document };
184
+ if (document) {
185
+ const aliases = documents.flatMap((other, i) =>
186
+ i !== depth && other && other.markdown === document.markdown ? [candidates[i].href] : [],
187
+ );
188
+
189
+ return { url: candidates[depth].href, document, aliases };
190
+ }
163
191
  }
164
192
 
165
193
  return undefined;
@@ -253,10 +281,41 @@ export async function fetchDocumentWithLlmsTxtSupport(
253
281
  dependencies: FetchRemoteDependencies,
254
282
  ): Promise<CompleteDocument> {
255
283
  try {
256
- if (isGitHubLikeHost(new URL(rawUrl).hostname)) {
284
+ const url = new URL(rawUrl);
285
+ const match = /^\/jobs\/copr\/(\d+)\/?$/.exec(url.pathname);
286
+
287
+ if (
288
+ url.protocol === "https:" &&
289
+ url.host === "dashboard.packit.dev" &&
290
+ !url.username &&
291
+ !url.password &&
292
+ !url.search &&
293
+ match
294
+ ) {
295
+ const apiUrl = `https://prod.packit.dev/api/copr-builds/${match[1]}`;
296
+
297
+ try {
298
+ const document = await fetchCompleteDocument(
299
+ apiUrl,
300
+ signal,
301
+ restrictOrigin(dependencies, "https://prod.packit.dev"),
302
+ );
303
+
304
+ if (
305
+ new URL(document.url).origin === "https://prod.packit.dev" &&
306
+ document.contentType === "application/json"
307
+ )
308
+ return { ...document, representationFallback: "packit-api" };
309
+ } catch (error) {
310
+ if (signal?.aborted) throw error;
311
+ }
312
+ }
313
+
314
+ if (isGitHubLikeHost(url.hostname)) {
257
315
  return fetchCompleteDocument(rawUrl, signal, dependencies);
258
316
  }
259
- } catch {
317
+ } catch (error) {
318
+ if (signal?.aborted) throw error;
260
319
  // Invalid URL falls through to fetchCompleteDocument which will throw.
261
320
  }
262
321
 
@@ -297,7 +356,29 @@ export async function fetchDocumentWithLlmsTxtSupport(
297
356
  ? await probeUsableRawText(describedBy, signal, dependencies)
298
357
  : undefined;
299
358
 
300
- if (described && describedBy) index = { url: describedBy.href, document: described };
359
+ if (described && describedBy && index?.url !== describedBy.href)
360
+ index = { url: describedBy.href, document: described };
361
+ }
362
+
363
+ if (
364
+ !primary.markdown.trim() &&
365
+ primary.swaggerSpecUrl &&
366
+ isSafeToProbe(toAbsoluteUrl(primary.swaggerSpecUrl), primary.url)
367
+ ) {
368
+ try {
369
+ const spec = await fetchCompleteDocument(
370
+ primary.swaggerSpecUrl,
371
+ signal,
372
+ restrictOrigin(dependencies, new URL(primary.url).origin),
373
+ false,
374
+ false,
375
+ );
376
+
377
+ if (isSafeToProbe(toAbsoluteUrl(spec.url), primary.url) && spec.openapiSpec)
378
+ return { ...spec, representationFallback: "swagger-spec" };
379
+ } catch (error) {
380
+ if (signal?.aborted) throw error;
381
+ }
301
382
  }
302
383
 
303
384
  if (isLowQualityDocument(primary) || !primary.markdown.trim()) {
@@ -317,16 +398,16 @@ export async function fetchDocumentWithLlmsTxtSupport(
317
398
 
318
399
  if (index) return { ...index.document, llmsTxtFallback: true };
319
400
  } else if (index) {
320
- return { ...primary, llmsTxtIndexUrl: index.url };
401
+ return { ...primary, llmsTxtIndexUrl: index.url, llmsTxtIndexAliases: index.aliases };
321
402
  }
322
403
 
323
404
  if (
324
405
  !primary.markdown.trim() &&
325
406
  (!primary.links || (primary.links.internal.length === 0 && primary.links.external.length === 0))
326
407
  ) {
327
- // A JavaScript CAPTCHA or bot wall can be text-empty. Surface it as the standard
328
- // blocked document rather than a misleading "no content" error.
329
- if (primary.extractionDiagnostics?.botWall) return primary;
408
+ // Preserve diagnostics for empty challenge pages and JavaScript app shells.
409
+ if (primary.extractionDiagnostics?.botWall || primary.extractionDiagnostics?.javascriptRequired)
410
+ return primary;
330
411
 
331
412
  throw new Error("web_fetch: Page has no extractable content.");
332
413
  }
@@ -283,7 +283,7 @@ export function parseAnubisChallenge(raw: string, pageUrl: URL): AnubisChallenge
283
283
  return undefined;
284
284
  }
285
285
 
286
- const extensions = rawExtensions === undefined ? [] : rawExtensions;
286
+ const extensions = rawExtensions ?? [];
287
287
 
288
288
  if (!isStringArray(extensions) || extensions.length > MAX_EXTENSIONS) return undefined;
289
289
 
@@ -19,6 +19,13 @@ export interface CompleteDocument {
19
19
  /** Character offsets for document fragments, derived from HTML anchors/headings. */
20
20
  fragmentOffsets?: Record<string, number>;
21
21
  markdown: string;
22
+ /** A URL-selected surface derived from the complete extracted page. */
23
+ surfaceView?: {
24
+ selected: string;
25
+ omitted: number;
26
+ markdown: string;
27
+ fragmentOffsets?: Record<string, number>;
28
+ };
22
29
  title?: string;
23
30
  extractor: "defuddle" | "basic" | "raw";
24
31
  /** @deprecated Use extractionDiagnostics for the individual quality signals. */
@@ -39,12 +46,18 @@ export interface CompleteDocument {
39
46
  openapiSpec?: boolean;
40
47
  /** Set when the site publishes a usable /llms.txt index and this document is not that index. */
41
48
  llmsTxtIndexUrl?: string;
49
+ /** Probed index URLs with identical complete content. */
50
+ llmsTxtIndexAliases?: string[];
42
51
  /** Absolute URL advertised via `rel="describedby"` (header or HTML link) for this page. */
43
52
  llmsTxtDescribedBy?: string;
44
53
  /** Absolute URL advertised for a Markdown version of this page (`rel="alternate" type="text/markdown"`). */
45
54
  markdownAlternateUrl?: string;
46
55
  /** True when this document is the advertised Markdown version served instead of a low-quality page. */
47
56
  markdownAlternateFallback?: boolean;
57
+ /** Same-origin OpenAPI document advertised by an otherwise empty Swagger UI. */
58
+ swaggerSpecUrl?: string;
59
+ /** The returned content is an API or specification substituted for the page. */
60
+ representationFallback?: "packit-api" | "swagger-spec";
48
61
  }
49
62
 
50
63
  /**
@@ -270,9 +270,22 @@ function isolateGitHubReadme(document: Document, baseUrl: URL): boolean {
270
270
  if (baseUrl.hostname !== "github.com" || baseUrl.pathname.split("/").filter(Boolean).length !== 2)
271
271
  return false;
272
272
 
273
- const readme = document.querySelector(
274
- "main article.markdown-body.entry-content[itemprop='text']",
275
- );
273
+ let readme = document.querySelector("main article.markdown-body.entry-content[itemprop='text']");
274
+
275
+ if (!readme) {
276
+ // GitHub renders plain-text READMEs outside the markdown article. Require
277
+ // the active README tab immediately beside the plain content, not just a pre.
278
+ for (const nav of document.querySelectorAll('main nav[aria-label="Repository files"]')) {
279
+ const activeTab = nav.querySelector('a[aria-current="page"] [data-content="README"]');
280
+ const content = nav.parentElement?.nextElementSibling;
281
+ const plain = content?.querySelector("div.plain > pre");
282
+
283
+ if (activeTab && plain?.textContent?.trim()) {
284
+ readme = plain;
285
+ break;
286
+ }
287
+ }
288
+ }
276
289
 
277
290
  if (!readme || !readme.textContent?.trim()) return false;
278
291
 
@@ -440,7 +453,7 @@ function readAdvertisedLinks(
440
453
  * @returns The extracted Markdown, optional title, extractor used, and advertised discovery links
441
454
  * @throws When markup exceeds the safe conversion depth
442
455
  */
443
- export async function extractHtmlToMarkdown(
456
+ async function extractHtmlDocument(
444
457
  html: string,
445
458
  baseUrl: URL,
446
459
  ): Promise<{
@@ -522,3 +535,137 @@ export async function extractHtmlToMarkdown(
522
535
  ...advertised,
523
536
  };
524
537
  }
538
+
539
+ /** Select only an explicitly requested, unambiguous surface control and sibling panes. */
540
+ function selectSurfaceHtml(
541
+ html: string,
542
+ url: URL,
543
+ ): { html: string; selected: string; omitted: number } | undefined {
544
+ const values = url.searchParams.getAll("tab");
545
+
546
+ if (values.length !== 1 || !/^[a-z0-9-]{1,40}$/u.test(values[0])) return undefined;
547
+ const selected = values[0];
548
+ const { document } = parseHTML(html);
549
+ normalizeFragmentDocument(document);
550
+ const candidates: Array<{ panes: Element[]; chosen: Element }> = [];
551
+
552
+ // Standard ARIA controls identify their panels by ID. The query value must
553
+ // match a control ID or panel ID exactly; labels are not URL identifiers.
554
+ for (const group of document.querySelectorAll('[role="tablist"]')) {
555
+ const controls = [...group.querySelectorAll('[role="tab"]')].filter(
556
+ (control) => control.closest('[role="tablist"]') === group,
557
+ );
558
+
559
+ if (controls.length < 2 || controls.length > 20) continue;
560
+ const ids = controls.map((control) => control.getAttribute("aria-controls") ?? "");
561
+
562
+ if (ids.some((id) => !id || /\s/u.test(id)) || new Set(ids).size !== ids.length) continue;
563
+
564
+ const panes = ids.map((id) => {
565
+ const matches = [...document.querySelectorAll('[role="tabpanel"][id]')].filter(
566
+ (pane) => pane.getAttribute("id") === id,
567
+ );
568
+
569
+ return matches.length === 1 ? matches[0] : undefined;
570
+ });
571
+
572
+ if (panes.some((pane) => !pane)) continue;
573
+
574
+ const matched = controls.flatMap((control, i) =>
575
+ control.id === selected || ids[i] === selected ? [i] : [],
576
+ );
577
+
578
+ if (matched.length !== 1) continue;
579
+ const resolved = panes.filter((pane): pane is Element => pane !== undefined);
580
+
581
+ if (resolved.some((pane) => pane.parentElement !== resolved[0].parentElement)) continue;
582
+ candidates.push({ panes: resolved, chosen: resolved[matched[0]] });
583
+ }
584
+
585
+ // Some sites use their own explicit surface IDs instead of ARIA references.
586
+ const groups = [...document.querySelectorAll("[data-surface-filter-pills]")];
587
+ const surfacePanes = [...document.querySelectorAll("[data-surface-pane]")];
588
+
589
+ if (groups.length === 1 && surfacePanes.length >= 2 && surfacePanes.length <= 20) {
590
+ const controls = [...groups[0].querySelectorAll('[role="tab"][data-surface-id]')];
591
+ const ids = controls.map((control) => control.getAttribute("data-surface-id"));
592
+ const paneIds = surfacePanes.map((pane) => pane.getAttribute("data-surface-pane"));
593
+ const chosen = surfacePanes.find((pane) => pane.getAttribute("data-surface-pane") === selected);
594
+
595
+ if (
596
+ controls.length === surfacePanes.length &&
597
+ new Set(ids).size === ids.length &&
598
+ new Set(paneIds).size === paneIds.length &&
599
+ ids.includes(selected) &&
600
+ chosen &&
601
+ ids.every((id) => id && paneIds.includes(id)) &&
602
+ surfacePanes.every((pane) => pane.parentElement === surfacePanes[0].parentElement)
603
+ )
604
+ candidates.push({ panes: surfacePanes, chosen });
605
+ }
606
+
607
+ const unique = candidates.filter(
608
+ (candidate, index) =>
609
+ !candidates
610
+ .slice(0, index)
611
+ .some(
612
+ (previous) =>
613
+ previous.chosen === candidate.chosen &&
614
+ previous.panes.length === candidate.panes.length &&
615
+ previous.panes.every((pane) => candidate.panes.includes(pane)),
616
+ ),
617
+ );
618
+
619
+ if (unique.length !== 1) return undefined;
620
+ const { panes, chosen } = unique[0];
621
+
622
+ if (!chosen?.textContent?.trim()) return undefined;
623
+
624
+ for (const pane of panes) if (pane !== chosen) pane.remove();
625
+ // The selected pane may be hidden by the server's default inline state.
626
+ chosen.removeAttribute("hidden");
627
+ chosen.removeAttribute("aria-hidden");
628
+ chosen.removeAttribute("style");
629
+
630
+ return { html: document.documentElement.outerHTML, selected, omitted: panes.length - 1 };
631
+ }
632
+
633
+ /** Extract the complete page and, when explicitly requested, a separate surface view. */
634
+ export async function extractHtmlToMarkdown(
635
+ html: string,
636
+ baseUrl: URL,
637
+ ): Promise<
638
+ Awaited<ReturnType<typeof extractHtmlDocument>> & {
639
+ surfaceView?: {
640
+ selected: string;
641
+ omitted: number;
642
+ markdown: string;
643
+ fragmentOffsets?: Record<string, number>;
644
+ };
645
+ }
646
+ > {
647
+ assertConversionDepth(html);
648
+ const complete = await extractHtmlDocument(html, baseUrl);
649
+
650
+ try {
651
+ const surface = selectSurfaceHtml(html, baseUrl);
652
+
653
+ if (!surface) return complete;
654
+ const view = await extractHtmlDocument(surface.html, baseUrl);
655
+
656
+ if (!view.markdown.trim()) return complete;
657
+
658
+ return {
659
+ ...complete,
660
+ surfaceView: {
661
+ selected: surface.selected,
662
+ omitted: surface.omitted,
663
+ markdown: view.markdown,
664
+ fragmentOffsets: view.fragmentOffsets,
665
+ },
666
+ };
667
+ } catch {
668
+ // A derived view must never make an otherwise readable page unavailable.
669
+ return complete;
670
+ }
671
+ }
package/src/index.ts CHANGED
@@ -99,7 +99,6 @@ 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",
103
102
  label: "Web Fetch",
104
103
  description: "Read content from a public URL.",
105
104
  parameters: webFetchParameters,
package/src/service.ts CHANGED
@@ -66,6 +66,25 @@ function safeUrl(value: string): URL | undefined {
66
66
  }
67
67
  }
68
68
 
69
+ /** Recognizes visible Markdown links to the discovered index or verified aliases. */
70
+ function hasVisibleIndexLink(text: string, pageUrl: string, indexes: readonly string[]): boolean {
71
+ const page = safeUrl(pageUrl);
72
+
73
+ if (!page) return false;
74
+
75
+ for (const match of text.matchAll(/\[[^\]\n]*\]\(([^\s)]+)\)/gu)) {
76
+ try {
77
+ const target = new URL(match[1], page);
78
+
79
+ if (target.origin === page.origin && indexes.includes(target.href)) return true;
80
+ } catch {
81
+ // Ignore malformed page links.
82
+ }
83
+ }
84
+
85
+ return false;
86
+ }
87
+
69
88
  /**
70
89
  * Classify the kind of content returned by a fetch operation.
71
90
  *
@@ -188,10 +207,13 @@ export interface WebFetchDetails {
188
207
  outline: DocumentOutline;
189
208
  /** Deterministic focused-extraction evidence when a query was supplied. */
190
209
  focus?: FocusDetails;
210
+ surface?: { selected: string; omitted: number };
191
211
  /** True when the returned content is the site's /llms.txt served instead of the requested page. */
192
212
  llmsTxtFallback: boolean;
193
213
  /** True when the returned content is the page's advertised Markdown version served instead of a low-quality page. */
194
214
  markdownAlternateFallback: boolean;
215
+ /** Identifies an API or specification used instead of the page. */
216
+ representationFallback?: CompleteDocument["representationFallback"];
195
217
  /** The site's /llms.txt index URL when one exists and the returned content is not that index itself. */
196
218
  llmsTxtUrl?: string;
197
219
  /** True for a fresh cache hit or a successful 304 revalidation. */
@@ -230,8 +252,10 @@ export interface WebFetchStructuredOutput {
230
252
  characterCount: number;
231
253
  llmsTxtFallback: boolean;
232
254
  markdownAlternateFallback: boolean;
255
+ representationFallback?: CompleteDocument["representationFallback"];
233
256
  extraction?: CompleteDocument["extractionDiagnostics"];
234
257
  focus?: FocusDetails;
258
+ surface?: { selected: string; omitted: number };
235
259
  outline: { totalWords: number; totalHeadings: number; omittedHeadings: number };
236
260
  fragment?: { requested: string; matched: boolean; offset?: number };
237
261
  }
@@ -255,6 +279,9 @@ export const webFetchOutputSchema = Type.Object({
255
279
  characterCount: Type.Integer(),
256
280
  llmsTxtFallback: Type.Boolean(),
257
281
  markdownAlternateFallback: Type.Boolean(),
282
+ representationFallback: Type.Optional(
283
+ Type.Union([Type.Literal("packit-api"), Type.Literal("swagger-spec")]),
284
+ ),
258
285
  extraction: Type.Optional(
259
286
  Type.Object({
260
287
  javascriptRequired: Type.Boolean(),
@@ -275,6 +302,7 @@ export const webFetchOutputSchema = Type.Object({
275
302
  focusedCharacters: Type.Integer(),
276
303
  }),
277
304
  ),
305
+ surface: Type.Optional(Type.Object({ selected: Type.String(), omitted: Type.Integer() })),
278
306
  outline: Type.Object({
279
307
  totalWords: Type.Integer(),
280
308
  totalHeadings: Type.Integer(),
@@ -294,6 +322,14 @@ const completeDocumentCacheSchema = Type.Object(
294
322
  url: Type.String(),
295
323
  contentType: Type.String(),
296
324
  markdown: Type.String(),
325
+ surfaceView: Type.Optional(
326
+ Type.Object({
327
+ selected: Type.String({ maxLength: 40 }),
328
+ omitted: Type.Integer({ minimum: 1, maximum: 19 }),
329
+ markdown: Type.String(),
330
+ fragmentOffsets: Type.Optional(Type.Record(Type.String(), Type.Number())),
331
+ }),
332
+ ),
297
333
  fragmentOffsets: Type.Optional(Type.Record(Type.String(), Type.Number())),
298
334
  extractor: Type.Union([Type.Literal("raw"), Type.Literal("basic"), Type.Literal("defuddle")]),
299
335
  shellSuspected: Type.Boolean(),
@@ -358,7 +394,9 @@ const fetchCachePersistence: CachePersistence<string, CompleteDocument> = {
358
394
  const fetchCache = new ExpiringLruCache<string, CompleteDocument>(
359
395
  CACHE_MAX_ENTRIES,
360
396
  CACHE_MAX_MARKDOWN_BYTES,
361
- (document) => encoder.encode(document.markdown).byteLength,
397
+ (document) =>
398
+ encoder.encode(document.markdown).byteLength +
399
+ encoder.encode(document.surfaceView?.markdown ?? "").byteLength,
362
400
  undefined,
363
401
  fetchCachePersistence,
364
402
  );
@@ -431,7 +469,12 @@ export async function executeWebFetch(
431
469
 
432
470
  const displayRequestedUrl = redactUrlForDisplay(params.url);
433
471
  const sourceUrl = urlWithoutFragment(params.url);
434
- const cacheKey = canonicalKey({ url: sourceUrl });
472
+
473
+ // Older persisted entries predate surface views and must not mask explicit selections.
474
+ const cacheKey = safeUrl(sourceUrl)?.searchParams.has("tab")
475
+ ? canonicalKey({ url: sourceUrl, surfaceExtraction: 1 })
476
+ : canonicalKey({ url: sourceUrl });
477
+
435
478
  let document = fetchCache.get(cacheKey);
436
479
  const now = Date.now();
437
480
 
@@ -466,7 +509,12 @@ export async function executeWebFetch(
466
509
  let fetched: CompleteDocument;
467
510
  let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
468
511
 
469
- if (stale?.validators && !stale.llmsTxtFallback && !stale.markdownAlternateFallback) {
512
+ if (
513
+ stale?.validators &&
514
+ !stale.llmsTxtFallback &&
515
+ !stale.markdownAlternateFallback &&
516
+ !stale.representationFallback
517
+ ) {
470
518
  const outcome = await revalidateCompleteDocument(
471
519
  sourceUrl,
472
520
  stale,
@@ -506,6 +554,21 @@ export async function executeWebFetch(
506
554
  links: undefined,
507
555
  fragmentOffsets: undefined,
508
556
  };
557
+ const canonicalMarkdown = document.markdown;
558
+
559
+ const surface =
560
+ !blocked && document.surfaceView
561
+ ? { selected: document.surfaceView.selected, omitted: document.surfaceView.omitted }
562
+ : undefined;
563
+
564
+ if (surface && document.surfaceView) {
565
+ document = {
566
+ ...document,
567
+ markdown: document.surfaceView.markdown,
568
+ fragmentOffsets: document.surfaceView.fragmentOffsets,
569
+ };
570
+ }
571
+
509
572
  const resolvedFragment = resolveFragmentOffset(document, params.url);
510
573
  const fragmentOffset = resolvedFragment.offset;
511
574
  const fragmentMatched = resolvedFragment.fragment !== undefined && fragmentOffset !== undefined;
@@ -613,6 +676,12 @@ export async function executeWebFetch(
613
676
  const output = blocked
614
677
  ? "Blocked by an anti-bot challenge. Requested page content is unavailable."
615
678
  : [
679
+ ...(result.representationFallback === "swagger-spec"
680
+ ? [
681
+ `[Showing the advertised Swagger specification from ${finalUrl} instead of the requested page.]`,
682
+ "",
683
+ ]
684
+ : []),
616
685
  ...(result.markdownAlternateFallback
617
686
  ? [
618
687
  "[Page content was sparse; showing the site's advertised Markdown version instead.]",
@@ -637,6 +706,12 @@ export async function executeWebFetch(
637
706
  "",
638
707
  ]
639
708
  : []),
709
+ ...(surface
710
+ ? [
711
+ `[Showing tab "${surface.selected}"; ${surface.omitted} other tabs omitted. Continuation offsets apply to this view.]`,
712
+ "",
713
+ ]
714
+ : []),
640
715
  ...(fragmentMatched ? ["[Starting at the requested URL fragment.]", ""] : []),
641
716
  ...(focused
642
717
  ? [
@@ -646,16 +721,44 @@ export async function executeWebFetch(
646
721
  "",
647
722
  ]
648
723
  : []),
649
- result.markdown || (focused ? "" : "[The page contained no readable text.]"),
724
+ result.markdown ||
725
+ (focused
726
+ ? ""
727
+ : result.extractionDiagnostics?.javascriptRequired
728
+ ? "[This page requires JavaScript; its content could not be retrieved.]"
729
+ : "[The page contained no readable text.]"),
650
730
  ].join("\n");
651
731
 
652
- const outputTruncation = truncateHead(output, {
732
+ let outputTruncation = truncateHead(output, {
653
733
  maxLines: DEFAULT_MAX_LINES,
654
734
  maxBytes: DEFAULT_MAX_BYTES,
655
735
  });
656
736
 
737
+ if (showLlmsNotice && result.llmsTxtIndexUrl) {
738
+ const indexUrl = redactUrlForDisplay(result.llmsTxtIndexUrl);
739
+ const notice = `Index: ${indexUrl}\n\n`;
740
+ const noticePosition = outputTruncation.content.indexOf(notice);
741
+
742
+ if (
743
+ noticePosition !== -1 &&
744
+ ([indexUrl, ...(result.llmsTxtIndexAliases ?? []).map(redactUrlForDisplay)].some((url) =>
745
+ outputTruncation.content.slice(noticePosition + notice.length).includes(url),
746
+ ) ||
747
+ hasVisibleIndexLink(
748
+ outputTruncation.content.slice(noticePosition + notice.length),
749
+ rawFinalUrl,
750
+ [result.llmsTxtIndexUrl, ...(result.llmsTxtIndexAliases ?? [])],
751
+ ))
752
+ ) {
753
+ outputTruncation = truncateHead(output.replace(notice, ""), {
754
+ maxLines: DEFAULT_MAX_LINES,
755
+ maxBytes: DEFAULT_MAX_BYTES,
756
+ });
757
+ }
758
+ }
759
+
657
760
  const truncated = result.truncated || outputTruncation.truncated;
658
- const outline = createDocumentOutline(document.markdown);
761
+ const outline = createDocumentOutline(canonicalMarkdown);
659
762
 
660
763
  const structured: WebFetchStructuredOutput = {
661
764
  requestedUrl,
@@ -675,8 +778,10 @@ export async function executeWebFetch(
675
778
  characterCount: 0,
676
779
  llmsTxtFallback: Boolean(result.llmsTxtFallback),
677
780
  markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
781
+ representationFallback: result.representationFallback,
678
782
  extraction: result.extractionDiagnostics,
679
783
  focus: focused?.details,
784
+ surface,
680
785
  outline: {
681
786
  totalWords: outline.totalWords,
682
787
  totalHeadings: outline.totalHeadings,
@@ -733,8 +838,10 @@ export async function executeWebFetch(
733
838
  confidence,
734
839
  outline,
735
840
  focus: focused?.details,
841
+ surface,
736
842
  llmsTxtFallback: Boolean(result.llmsTxtFallback),
737
843
  markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
844
+ representationFallback: result.representationFallback,
738
845
  llmsTxtUrl:
739
846
  result.llmsTxtIndexUrl === undefined
740
847
  ? undefined