@zeldrisho/pi-web-fetch 0.17.1 → 0.18.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,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.18.0] - 2026-11-20
11
+
12
+ ### Added
13
+
14
+ - Fetch GitLab.com file links as raw source, and prefer available Markdown versions of documentation pages.
15
+
16
+ ### Changed
17
+
18
+ - Use Pi's configured expand-key hint when displaying collapsed fetch output.
19
+ - Preserve selected tab views when a Markdown representation is unavailable for tab-scoped pages, and use accurate notices for derived Markdown substitutions.
20
+
21
+ ### Fixed
22
+
23
+ - Preserve section headings when a query selects a later passage from a long section.
24
+ - Match dotted API identifiers literally within longer queries, and clarify that focused results can omit relevant content.
25
+ - Preserve nested `/-/blob/` path segments when normalizing GitLab file URLs.
26
+ - Match hyphenated dotted filenames such as `package-lock.json` in focused queries.
27
+
10
28
  ## [0.17.1] - 2026-11-18
11
29
 
12
30
  ### Changed
@@ -365,7 +383,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
365
383
 
366
384
  - Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
367
385
 
368
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...HEAD
386
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.0...HEAD
387
+ [0.18.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...pi-web-fetch-v0.18.0
369
388
  [0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
370
389
  [0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
371
390
  [0.16.5]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...pi-web-fetch-v0.16.5
package/README.md CHANGED
@@ -25,13 +25,13 @@ The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markd
25
25
 
26
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
27
 
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.
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 identifiers in longer queries, and standalone 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
- 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.
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, GitLab.com file links, and bare gists are converted to raw source URLs; GitHub repository roots use their README. GitHub directory listings are not supported.
31
31
 
32
32
  ### Page alternatives and bot challenges
33
33
 
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.
34
+ The tool prefers Markdown when sites offer it, including advertised alternatives and documented Next.js and Vercel documentation endpoints, and can discover `/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
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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-fetch",
3
- "version": "0.17.1",
3
+ "version": "0.18.0",
4
4
  "description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
5
5
  "keywords": [
6
6
  "pi",
@@ -37,7 +37,7 @@
37
37
  "yaml": "^2.9.1"
38
38
  },
39
39
  "devDependencies": {
40
- "@earendil-works/pi-coding-agent": "^1.4.0",
40
+ "@earendil-works/pi-coding-agent": "^1.5.0",
41
41
  "@earendil-works/pi-tui": "^1.4.0",
42
42
  "typebox": "^1.4.3",
43
43
  "typescript": "^7.0.2",
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Rewrites GitHub source URLs to their raw counterparts so file contents are fetched as
3
- * clean plain text instead of Defuddle's noisy rendered view:
2
+ * Rewrites GitHub and GitLab source URLs to their raw counterparts so file contents are
3
+ * fetched as clean plain text instead of Defuddle's noisy rendered view:
4
4
  *
5
5
  * - `github.com` `blob` URLs become their `raw.githubusercontent.com` counterpart.
6
6
  * - Bare gist pages (`gist.github.com/<user>/<id>`) get `/raw` appended; the redirect to
@@ -15,6 +15,20 @@ export function normalizeGitHubRawUrl(rawUrl: string): string {
15
15
 
16
16
  if (url.protocol !== "https:") return rawUrl;
17
17
 
18
+ if (url.hostname === "gitlab.com" && !url.username && !url.password && !url.port) {
19
+ const delimiter = url.pathname.indexOf("/-/blob/");
20
+ const repository = delimiter > 0 ? url.pathname.slice(0, delimiter) : "";
21
+ const file = delimiter > 0 ? url.pathname.slice(delimiter + "/-/blob/".length) : "";
22
+
23
+ if (repository.split("/").filter(Boolean).length >= 2 && file.includes("/")) {
24
+ url.pathname = `${repository}/-/raw/${file}`;
25
+
26
+ return url.href;
27
+ }
28
+
29
+ return rawUrl;
30
+ }
31
+
18
32
  if (url.hostname === "github.com") {
19
33
  if (url.pathname.includes("/blob/")) {
20
34
  return `https://raw.githubusercontent.com${url.pathname.replace("/blob/", "/")}${url.search}`;
@@ -104,6 +104,27 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
104
104
  }
105
105
  }
106
106
 
107
+ /** Returns documented Markdown endpoints only for known documentation routes. */
108
+ export function documentationMarkdownUrl(value: string): URL | undefined {
109
+ const url = safeUrl(value);
110
+
111
+ if (!url || url.protocol !== "https:" || url.username || url.password || url.port) return;
112
+
113
+ if (
114
+ !(
115
+ (url.hostname === "nextjs.org" || url.hostname === "vercel.com") &&
116
+ (url.pathname === "/docs" || url.pathname.startsWith("/docs/"))
117
+ )
118
+ )
119
+ return;
120
+
121
+ if (url.pathname.endsWith(".md")) return;
122
+ url.pathname = `${url.pathname.replace(/\/$/, "")}.md`;
123
+ url.hash = "";
124
+
125
+ return url;
126
+ }
127
+
107
128
  function isLowQualityDocument(document: CompleteDocument): boolean {
108
129
  // Sparse extraction alone is not proof of an empty app shell: server-rendered pages
109
130
  // may include useful content in streaming/framework markup that article extraction
@@ -381,6 +402,48 @@ export async function fetchDocumentWithLlmsTxtSupport(
381
402
  }
382
403
  }
383
404
 
405
+ // Prefer a page-specific Markdown representation even when HTML extraction succeeded.
406
+ // Restrict the entire redirect chain, and never substitute HTML or arbitrary text.
407
+ if (
408
+ !primary.surfaceView &&
409
+ primary.extractor !== "raw" &&
410
+ (!primary.markdownAlternateUrl || (!isLowQualityDocument(primary) && primary.markdown.trim()))
411
+ ) {
412
+ const advertised = primary.markdownAlternateUrl
413
+ ? toAbsoluteUrl(primary.markdownAlternateUrl)
414
+ : undefined;
415
+
416
+ const candidate = advertised ?? documentationMarkdownUrl(primary.url);
417
+
418
+ if (candidate && isSafeToProbe(candidate, primary.url) && candidate.href !== primary.url) {
419
+ try {
420
+ const alternate = await fetchCompleteDocument(
421
+ candidate.href,
422
+ signal,
423
+ restrictOrigin(dependencies, new URL(primary.url).origin),
424
+ false,
425
+ false,
426
+ );
427
+
428
+ if (
429
+ alternate.extractor === "raw" &&
430
+ /^(text\/markdown|text\/x-markdown)(?:;|$)/i.test(alternate.contentType) &&
431
+ alternate.markdown.trim().length >= LLMS_TXT_MIN_MARKDOWN_CHARACTERS &&
432
+ !alternate.shellSuspected
433
+ )
434
+ return {
435
+ ...alternate,
436
+ markdownAlternateFallback: true,
437
+ markdownAlternateReason: advertised ? "advertised" : "preferred",
438
+ llmsTxtIndexUrl: index?.url,
439
+ llmsTxtIndexAliases: index?.aliases,
440
+ };
441
+ } catch (error) {
442
+ if (signal?.aborted) throw error;
443
+ }
444
+ }
445
+ }
446
+
384
447
  if (isLowQualityDocument(primary) || !primary.markdown.trim()) {
385
448
  // The page's own advertised Markdown version is strictly better than an index.
386
449
  const markdownAlternate = primary.markdownAlternateUrl
@@ -388,12 +451,16 @@ export async function fetchDocumentWithLlmsTxtSupport(
388
451
  : undefined;
389
452
 
390
453
  const alternate =
391
- markdownAlternate && isSafeToProbe(markdownAlternate, primary.url)
454
+ !primary.surfaceView && markdownAlternate && isSafeToProbe(markdownAlternate, primary.url)
392
455
  ? await probeUsableRawText(markdownAlternate, signal, dependencies)
393
456
  : undefined;
394
457
 
395
458
  if (alternate && markdownAlternate) {
396
- return { ...alternate, markdownAlternateFallback: true };
459
+ return {
460
+ ...alternate,
461
+ markdownAlternateFallback: true,
462
+ markdownAlternateReason: "advertised",
463
+ };
397
464
  }
398
465
 
399
466
  if (index) return { ...index.document, llmsTxtFallback: true };
@@ -52,8 +52,10 @@ export interface CompleteDocument {
52
52
  llmsTxtDescribedBy?: string;
53
53
  /** Absolute URL advertised for a Markdown version of this page (`rel="alternate" type="text/markdown"`). */
54
54
  markdownAlternateUrl?: string;
55
- /** True when this document is the advertised Markdown version served instead of a low-quality page. */
55
+ /** True when this document is a Markdown representation substituted for the requested page. */
56
56
  markdownAlternateFallback?: boolean;
57
+ /** Why the Markdown representation was selected. */
58
+ markdownAlternateReason?: "advertised" | "preferred";
57
59
  /** Same-origin OpenAPI document advertised by an otherwise empty Swagger UI. */
58
60
  swaggerSpecUrl?: string;
59
61
  /** The returned content is an API or specification substituted for the page. */
@@ -20,6 +20,8 @@ export interface FocusResult {
20
20
  interface Section {
21
21
  markdown: string;
22
22
  tokens: string[];
23
+ /** Original heading for a continuation chunk of an oversized section. */
24
+ context?: { group: number; heading: string; continuation: boolean };
23
25
  }
24
26
 
25
27
  interface SplitSections {
@@ -284,8 +286,9 @@ function splitSections(markdown: string): SplitSections {
284
286
 
285
287
  // Split oversized sections at blank lines outside fences, so matches do not pull
286
288
  // in an entire chapter. Keep the heading with its first content block.
287
- const bounded = sections.flatMap((section) => {
288
- if (section.length <= WINDOW_MIN_CHARACTERS) return [section];
289
+ const bounded = sections.flatMap((section, group) => {
290
+ if (section.length <= WINDOW_MIN_CHARACTERS)
291
+ return [{ markdown: section, tokens: tokens(section) }];
289
292
  const chunks: string[] = [];
290
293
  let current: string[] = [];
291
294
  let size = 0;
@@ -326,13 +329,19 @@ function splitSections(markdown: string): SplitSections {
326
329
 
327
330
  if (chunk) chunks.push(chunk);
328
331
 
329
- return chunks;
332
+ const heading = section.split("\n", 1)[0];
333
+
334
+ return chunks.map((chunk, index) => {
335
+ const result: Section = { markdown: chunk, tokens: tokens(chunk) };
336
+
337
+ if (heading.length <= 500 && HEADING_PATTERN.test(heading))
338
+ result.context = { group, heading, continuation: index > 0 };
339
+
340
+ return result;
341
+ });
330
342
  });
331
343
 
332
- return {
333
- sections: bounded.map((section) => ({ markdown: section, tokens: tokens(section) })),
334
- separator: "\n\n",
335
- };
344
+ return { sections: bounded, separator: "\n\n" };
336
345
  }
337
346
 
338
347
  /**
@@ -380,8 +389,23 @@ export function focusMarkdown(markdown: string, query: string): FocusResult {
380
389
  ? normalizedQuery.toLowerCase()
381
390
  : undefined;
382
391
 
392
+ // A dotted API name inside a natural-language query must still match as one
393
+ // identifier; otherwise its common components can select unrelated sections.
394
+ const embeddedIdentifiers = literalIdentifier
395
+ ? []
396
+ : [
397
+ ...new Set(
398
+ (
399
+ normalizedQuery.toLowerCase().match(/\b[a-z_$][\w$-]*(?:\.[a-z_$][\w$-]*)+\b/g) ?? []
400
+ ).filter((identifier) => identifier.split(".").some((part) => part.length > 1)),
401
+ ),
402
+ ];
403
+
383
404
  const scores = sections.map((section) => {
384
405
  if (literalIdentifier) return containsIdentifier(section.markdown, literalIdentifier) ? 1 : 0;
406
+
407
+ if (embeddedIdentifiers.some((identifier) => !containsIdentifier(section.markdown, identifier)))
408
+ return 0;
385
409
  const frequencies = new Map<string, number>();
386
410
 
387
411
  for (const token of section.tokens) frequencies.set(token, (frequencies.get(token) ?? 0) + 1);
@@ -412,7 +436,18 @@ export function focusMarkdown(markdown: string, query: string): FocusResult {
412
436
  (_, index) => scores[index] > 0 && scores[index] >= highestScore * 0.5,
413
437
  );
414
438
 
415
- const focused = selected.map((section) => section.markdown).join(separator);
439
+ const seenGroups = new Set<number>();
440
+
441
+ const focused = selected
442
+ .map((section) => {
443
+ const context = section.context;
444
+ const needsHeading = context?.continuation && !seenGroups.has(context.group);
445
+
446
+ if (context) seenGroups.add(context.group);
447
+
448
+ return needsHeading ? `${context.heading}\n\n${section.markdown}` : section.markdown;
449
+ })
450
+ .join(separator);
416
451
 
417
452
  return {
418
453
  markdown: focused,
package/src/index.ts CHANGED
@@ -150,6 +150,7 @@ export default function (pi: ExtensionAPI) {
150
150
  result.details?.truncated && result.details.nextOffset !== undefined
151
151
  ? `[Content truncated. Continue with offset=${result.details.nextOffset} to read the next chunk.]`
152
152
  : undefined,
153
+ context?.keyHint?.("app.tools.expand", "to expand") ?? "Ctrl+O to expand",
153
154
  )
154
155
  : new Text(theme.fg("dim", "No content"), 0, 0);
155
156
  },
package/src/render.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { getMarkdownTheme, keyHint } from "@earendil-works/pi-coding-agent";
1
+ import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
2
2
  import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
3
3
 
4
4
  const COLLAPSED_LINES = 10;
@@ -10,6 +10,7 @@ export function renderCollapsibleOutput(
10
10
  theme: { fg(color: "toolOutput" | "muted" | "warning", text: string): string },
11
11
  isError = false,
12
12
  warning?: string,
13
+ expandHint = "Ctrl+O to expand",
13
14
  ): Container {
14
15
  const lines = output.replace(/\r\n/g, "\n").split("\n");
15
16
 
@@ -30,7 +31,7 @@ export function renderCollapsibleOutput(
30
31
  if (remaining > 0) {
31
32
  component.addChild(
32
33
  new Text(
33
- `${theme.fg("muted", `... (${remaining} more lines, ${lines.length} total,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`,
34
+ `${theme.fg("muted", `... (${remaining} more lines, ${lines.length} total,`)} ${expandHint}${theme.fg("muted", ")")}`,
34
35
  0,
35
36
  0,
36
37
  ),
package/src/service.ts CHANGED
@@ -509,8 +509,16 @@ export async function executeWebFetch(
509
509
  let fetched: CompleteDocument;
510
510
  let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
511
511
 
512
+ const staleCanUseMarkdownPolicy =
513
+ stale !== undefined &&
514
+ stale.extractor !== "raw" &&
515
+ !stale.surfaceView &&
516
+ !stale.llmsTxtFallback &&
517
+ !stale.representationFallback;
518
+
512
519
  if (
513
520
  stale?.validators &&
521
+ !staleCanUseMarkdownPolicy &&
514
522
  !stale.llmsTxtFallback &&
515
523
  !stale.markdownAlternateFallback &&
516
524
  !stale.representationFallback
@@ -684,7 +692,11 @@ export async function executeWebFetch(
684
692
  : []),
685
693
  ...(result.markdownAlternateFallback
686
694
  ? [
687
- "[Page content was sparse; showing the site's advertised Markdown version instead.]",
695
+ result.markdownAlternateReason === "advertised"
696
+ ? "[Showing the site's advertised Markdown version instead.]"
697
+ : result.markdownAlternateReason === "preferred"
698
+ ? "[Showing the site's preferred Markdown representation instead.]"
699
+ : "[Showing a Markdown representation instead of the requested page.]",
688
700
  "",
689
701
  ]
690
702
  : []),
@@ -716,8 +728,8 @@ export async function executeWebFetch(
716
728
  ...(focused
717
729
  ? [
718
730
  focused.details.matchedSections > 0
719
- ? `[Query matched ${focused.details.matchedSections}/${focused.details.totalSections} sections. Offsets apply to this view; omit query for the full page.]`
720
- : "[No sections matched. Omit query for the full page.]",
731
+ ? `[Query selected ${focused.details.matchedSections}/${focused.details.totalSections} sections; relevant content may be omitted. Offsets apply to this view; omit query for the full page.]`
732
+ : "[No sections selected. The query may miss relevant content; omit query for the full page.]",
721
733
  "",
722
734
  ]
723
735
  : []),