@zeldrisho/pi-web-fetch 0.17.0 → 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 +41 -1
- package/README.md +10 -6
- package/package.json +3 -9
- package/src/acquisition/fetch-metadata.ts +16 -2
- package/src/acquisition/fetch.ts +81 -11
- package/src/acquisition/llms.ts +159 -11
- package/src/challenges/anubis.ts +1 -1
- package/src/document/content.ts +16 -1
- package/src/document/extract.ts +151 -4
- package/src/document/focus.ts +43 -8
- package/src/index.ts +1 -1
- package/src/render.ts +3 -2
- package/src/service.ts +128 -9
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,44 @@ 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
|
+
|
|
28
|
+
## [0.17.1] - 2026-11-18
|
|
29
|
+
|
|
30
|
+
### Changed
|
|
31
|
+
|
|
32
|
+
- Restore codemode access to structured fetch results with Pi 0.99.0 or newer.
|
|
33
|
+
- Return Packit Copr API data without a verbose substitution notice, while preserving the source URL and structured provenance.
|
|
34
|
+
|
|
35
|
+
### Fixed
|
|
36
|
+
|
|
37
|
+
- Preserve selected documentation surfaces in HTML fragments and when tab controls use multiple supported attribute mappings.
|
|
38
|
+
- Recognize standard Swagger UI initializers and retain index notices when a visible link points to a different index.
|
|
39
|
+
- Honor explicitly selected documentation surfaces when supported by the page, rather than mixing unrelated surface instructions.
|
|
40
|
+
- Extract plain-text GitHub repository READMEs without the file-listing table.
|
|
41
|
+
- Avoid redundant discovered index notices when the visible page already links to a same-site documentation index.
|
|
42
|
+
- Retrieve Packit Copr job data without an API key and advertised Swagger specifications from otherwise empty app pages.
|
|
43
|
+
- Explain when an empty page requires JavaScript instead of reporting a generic extraction error.
|
|
44
|
+
- Solve supported Anubis challenges that declare no extensions as `null`.
|
|
45
|
+
- Fetch slash-sensitive pages when a trailing slash returns 404 but the page exists without it.
|
|
46
|
+
- Report page errors after a solved Anubis challenge instead of incorrectly reporting a bot block.
|
|
47
|
+
|
|
10
48
|
## [0.17.0] - 2026-11-12
|
|
11
49
|
|
|
12
50
|
### Changed
|
|
@@ -345,7 +383,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
345
383
|
|
|
346
384
|
- Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
|
|
347
385
|
|
|
348
|
-
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.
|
|
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
|
|
388
|
+
[0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
|
|
349
389
|
[0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
|
|
350
390
|
[0.16.5]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...pi-web-fetch-v0.16.5
|
|
351
391
|
[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,20 +23,26 @@ 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
|
|
|
28
|
-
|
|
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
|
+
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
|
|
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
|
-
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.
|
|
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.
|
|
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",
|
|
@@ -55,12 +55,6 @@
|
|
|
55
55
|
]
|
|
56
56
|
},
|
|
57
57
|
"scripts": {
|
|
58
|
-
"
|
|
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,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Rewrites GitHub source URLs to their raw counterparts so file contents are
|
|
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}`;
|
package/src/acquisition/fetch.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
490
|
-
|
|
491
|
-
|
|
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"
|
package/src/acquisition/llms.ts
CHANGED
|
@@ -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
|
|
|
@@ -82,6 +104,27 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
|
|
|
82
104
|
}
|
|
83
105
|
}
|
|
84
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
|
+
|
|
85
128
|
function isLowQualityDocument(document: CompleteDocument): boolean {
|
|
86
129
|
// Sparse extraction alone is not proof of an empty app shell: server-rendered pages
|
|
87
130
|
// may include useful content in streaming/framework markup that article extraction
|
|
@@ -149,7 +192,7 @@ async function ensureLlmsTxtIndex(
|
|
|
149
192
|
candidates: URL[],
|
|
150
193
|
signal: AbortSignal | undefined,
|
|
151
194
|
dependencies: FetchRemoteDependencies,
|
|
152
|
-
): Promise<{ url: string; document: CompleteDocument } | undefined> {
|
|
195
|
+
): Promise<{ url: string; document: CompleteDocument; aliases?: string[] } | undefined> {
|
|
153
196
|
const documents = await Promise.all(
|
|
154
197
|
candidates.map((candidate) => probeUsableRawText(candidate, signal, dependencies)),
|
|
155
198
|
);
|
|
@@ -159,7 +202,13 @@ async function ensureLlmsTxtIndex(
|
|
|
159
202
|
for (let depth = documents.length - 1; depth >= 0; depth -= 1) {
|
|
160
203
|
const document = documents[depth];
|
|
161
204
|
|
|
162
|
-
if (document)
|
|
205
|
+
if (document) {
|
|
206
|
+
const aliases = documents.flatMap((other, i) =>
|
|
207
|
+
i !== depth && other && other.markdown === document.markdown ? [candidates[i].href] : [],
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
return { url: candidates[depth].href, document, aliases };
|
|
211
|
+
}
|
|
163
212
|
}
|
|
164
213
|
|
|
165
214
|
return undefined;
|
|
@@ -253,10 +302,41 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
253
302
|
dependencies: FetchRemoteDependencies,
|
|
254
303
|
): Promise<CompleteDocument> {
|
|
255
304
|
try {
|
|
256
|
-
|
|
305
|
+
const url = new URL(rawUrl);
|
|
306
|
+
const match = /^\/jobs\/copr\/(\d+)\/?$/.exec(url.pathname);
|
|
307
|
+
|
|
308
|
+
if (
|
|
309
|
+
url.protocol === "https:" &&
|
|
310
|
+
url.host === "dashboard.packit.dev" &&
|
|
311
|
+
!url.username &&
|
|
312
|
+
!url.password &&
|
|
313
|
+
!url.search &&
|
|
314
|
+
match
|
|
315
|
+
) {
|
|
316
|
+
const apiUrl = `https://prod.packit.dev/api/copr-builds/${match[1]}`;
|
|
317
|
+
|
|
318
|
+
try {
|
|
319
|
+
const document = await fetchCompleteDocument(
|
|
320
|
+
apiUrl,
|
|
321
|
+
signal,
|
|
322
|
+
restrictOrigin(dependencies, "https://prod.packit.dev"),
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
if (
|
|
326
|
+
new URL(document.url).origin === "https://prod.packit.dev" &&
|
|
327
|
+
document.contentType === "application/json"
|
|
328
|
+
)
|
|
329
|
+
return { ...document, representationFallback: "packit-api" };
|
|
330
|
+
} catch (error) {
|
|
331
|
+
if (signal?.aborted) throw error;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (isGitHubLikeHost(url.hostname)) {
|
|
257
336
|
return fetchCompleteDocument(rawUrl, signal, dependencies);
|
|
258
337
|
}
|
|
259
|
-
} catch {
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if (signal?.aborted) throw error;
|
|
260
340
|
// Invalid URL falls through to fetchCompleteDocument which will throw.
|
|
261
341
|
}
|
|
262
342
|
|
|
@@ -297,7 +377,71 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
297
377
|
? await probeUsableRawText(describedBy, signal, dependencies)
|
|
298
378
|
: undefined;
|
|
299
379
|
|
|
300
|
-
if (described && describedBy
|
|
380
|
+
if (described && describedBy && index?.url !== describedBy.href)
|
|
381
|
+
index = { url: describedBy.href, document: described };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
if (
|
|
385
|
+
!primary.markdown.trim() &&
|
|
386
|
+
primary.swaggerSpecUrl &&
|
|
387
|
+
isSafeToProbe(toAbsoluteUrl(primary.swaggerSpecUrl), primary.url)
|
|
388
|
+
) {
|
|
389
|
+
try {
|
|
390
|
+
const spec = await fetchCompleteDocument(
|
|
391
|
+
primary.swaggerSpecUrl,
|
|
392
|
+
signal,
|
|
393
|
+
restrictOrigin(dependencies, new URL(primary.url).origin),
|
|
394
|
+
false,
|
|
395
|
+
false,
|
|
396
|
+
);
|
|
397
|
+
|
|
398
|
+
if (isSafeToProbe(toAbsoluteUrl(spec.url), primary.url) && spec.openapiSpec)
|
|
399
|
+
return { ...spec, representationFallback: "swagger-spec" };
|
|
400
|
+
} catch (error) {
|
|
401
|
+
if (signal?.aborted) throw error;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
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
|
+
}
|
|
301
445
|
}
|
|
302
446
|
|
|
303
447
|
if (isLowQualityDocument(primary) || !primary.markdown.trim()) {
|
|
@@ -307,26 +451,30 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
307
451
|
: undefined;
|
|
308
452
|
|
|
309
453
|
const alternate =
|
|
310
|
-
markdownAlternate && isSafeToProbe(markdownAlternate, primary.url)
|
|
454
|
+
!primary.surfaceView && markdownAlternate && isSafeToProbe(markdownAlternate, primary.url)
|
|
311
455
|
? await probeUsableRawText(markdownAlternate, signal, dependencies)
|
|
312
456
|
: undefined;
|
|
313
457
|
|
|
314
458
|
if (alternate && markdownAlternate) {
|
|
315
|
-
return {
|
|
459
|
+
return {
|
|
460
|
+
...alternate,
|
|
461
|
+
markdownAlternateFallback: true,
|
|
462
|
+
markdownAlternateReason: "advertised",
|
|
463
|
+
};
|
|
316
464
|
}
|
|
317
465
|
|
|
318
466
|
if (index) return { ...index.document, llmsTxtFallback: true };
|
|
319
467
|
} else if (index) {
|
|
320
|
-
return { ...primary, llmsTxtIndexUrl: index.url };
|
|
468
|
+
return { ...primary, llmsTxtIndexUrl: index.url, llmsTxtIndexAliases: index.aliases };
|
|
321
469
|
}
|
|
322
470
|
|
|
323
471
|
if (
|
|
324
472
|
!primary.markdown.trim() &&
|
|
325
473
|
(!primary.links || (primary.links.internal.length === 0 && primary.links.external.length === 0))
|
|
326
474
|
) {
|
|
327
|
-
//
|
|
328
|
-
|
|
329
|
-
|
|
475
|
+
// Preserve diagnostics for empty challenge pages and JavaScript app shells.
|
|
476
|
+
if (primary.extractionDiagnostics?.botWall || primary.extractionDiagnostics?.javascriptRequired)
|
|
477
|
+
return primary;
|
|
330
478
|
|
|
331
479
|
throw new Error("web_fetch: Page has no extractable content.");
|
|
332
480
|
}
|
package/src/challenges/anubis.ts
CHANGED
|
@@ -283,7 +283,7 @@ export function parseAnubisChallenge(raw: string, pageUrl: URL): AnubisChallenge
|
|
|
283
283
|
return undefined;
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
-
const extensions = rawExtensions
|
|
286
|
+
const extensions = rawExtensions ?? [];
|
|
287
287
|
|
|
288
288
|
if (!isStringArray(extensions) || extensions.length > MAX_EXTENSIONS) return undefined;
|
|
289
289
|
|
package/src/document/content.ts
CHANGED
|
@@ -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,20 @@ 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
|
-
/** True when this document is
|
|
55
|
+
/** True when this document is a Markdown representation substituted for the requested page. */
|
|
47
56
|
markdownAlternateFallback?: boolean;
|
|
57
|
+
/** Why the Markdown representation was selected. */
|
|
58
|
+
markdownAlternateReason?: "advertised" | "preferred";
|
|
59
|
+
/** Same-origin OpenAPI document advertised by an otherwise empty Swagger UI. */
|
|
60
|
+
swaggerSpecUrl?: string;
|
|
61
|
+
/** The returned content is an API or specification substituted for the page. */
|
|
62
|
+
representationFallback?: "packit-api" | "swagger-spec";
|
|
48
63
|
}
|
|
49
64
|
|
|
50
65
|
/**
|
package/src/document/extract.ts
CHANGED
|
@@ -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
|
-
|
|
274
|
-
|
|
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
|
-
|
|
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/document/focus.ts
CHANGED
|
@@ -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)
|
|
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
|
-
|
|
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
|
|
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
|
@@ -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,
|
|
@@ -151,6 +150,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
151
150
|
result.details?.truncated && result.details.nextOffset !== undefined
|
|
152
151
|
? `[Content truncated. Continue with offset=${result.details.nextOffset} to read the next chunk.]`
|
|
153
152
|
: undefined,
|
|
153
|
+
context?.keyHint?.("app.tools.expand", "to expand") ?? "Ctrl+O to expand",
|
|
154
154
|
)
|
|
155
155
|
: new Text(theme.fg("dim", "No content"), 0, 0);
|
|
156
156
|
},
|
package/src/render.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getMarkdownTheme
|
|
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,`)} ${
|
|
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
|
@@ -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) =>
|
|
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
|
-
|
|
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,20 @@ export async function executeWebFetch(
|
|
|
466
509
|
let fetched: CompleteDocument;
|
|
467
510
|
let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
|
|
468
511
|
|
|
469
|
-
|
|
512
|
+
const staleCanUseMarkdownPolicy =
|
|
513
|
+
stale !== undefined &&
|
|
514
|
+
stale.extractor !== "raw" &&
|
|
515
|
+
!stale.surfaceView &&
|
|
516
|
+
!stale.llmsTxtFallback &&
|
|
517
|
+
!stale.representationFallback;
|
|
518
|
+
|
|
519
|
+
if (
|
|
520
|
+
stale?.validators &&
|
|
521
|
+
!staleCanUseMarkdownPolicy &&
|
|
522
|
+
!stale.llmsTxtFallback &&
|
|
523
|
+
!stale.markdownAlternateFallback &&
|
|
524
|
+
!stale.representationFallback
|
|
525
|
+
) {
|
|
470
526
|
const outcome = await revalidateCompleteDocument(
|
|
471
527
|
sourceUrl,
|
|
472
528
|
stale,
|
|
@@ -506,6 +562,21 @@ export async function executeWebFetch(
|
|
|
506
562
|
links: undefined,
|
|
507
563
|
fragmentOffsets: undefined,
|
|
508
564
|
};
|
|
565
|
+
const canonicalMarkdown = document.markdown;
|
|
566
|
+
|
|
567
|
+
const surface =
|
|
568
|
+
!blocked && document.surfaceView
|
|
569
|
+
? { selected: document.surfaceView.selected, omitted: document.surfaceView.omitted }
|
|
570
|
+
: undefined;
|
|
571
|
+
|
|
572
|
+
if (surface && document.surfaceView) {
|
|
573
|
+
document = {
|
|
574
|
+
...document,
|
|
575
|
+
markdown: document.surfaceView.markdown,
|
|
576
|
+
fragmentOffsets: document.surfaceView.fragmentOffsets,
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
|
|
509
580
|
const resolvedFragment = resolveFragmentOffset(document, params.url);
|
|
510
581
|
const fragmentOffset = resolvedFragment.offset;
|
|
511
582
|
const fragmentMatched = resolvedFragment.fragment !== undefined && fragmentOffset !== undefined;
|
|
@@ -613,9 +684,19 @@ export async function executeWebFetch(
|
|
|
613
684
|
const output = blocked
|
|
614
685
|
? "Blocked by an anti-bot challenge. Requested page content is unavailable."
|
|
615
686
|
: [
|
|
687
|
+
...(result.representationFallback === "swagger-spec"
|
|
688
|
+
? [
|
|
689
|
+
`[Showing the advertised Swagger specification from ${finalUrl} instead of the requested page.]`,
|
|
690
|
+
"",
|
|
691
|
+
]
|
|
692
|
+
: []),
|
|
616
693
|
...(result.markdownAlternateFallback
|
|
617
694
|
? [
|
|
618
|
-
|
|
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.]",
|
|
619
700
|
"",
|
|
620
701
|
]
|
|
621
702
|
: []),
|
|
@@ -637,25 +718,59 @@ export async function executeWebFetch(
|
|
|
637
718
|
"",
|
|
638
719
|
]
|
|
639
720
|
: []),
|
|
721
|
+
...(surface
|
|
722
|
+
? [
|
|
723
|
+
`[Showing tab "${surface.selected}"; ${surface.omitted} other tabs omitted. Continuation offsets apply to this view.]`,
|
|
724
|
+
"",
|
|
725
|
+
]
|
|
726
|
+
: []),
|
|
640
727
|
...(fragmentMatched ? ["[Starting at the requested URL fragment.]", ""] : []),
|
|
641
728
|
...(focused
|
|
642
729
|
? [
|
|
643
730
|
focused.details.matchedSections > 0
|
|
644
|
-
? `[Query
|
|
645
|
-
: "[No sections
|
|
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.]",
|
|
646
733
|
"",
|
|
647
734
|
]
|
|
648
735
|
: []),
|
|
649
|
-
result.markdown ||
|
|
736
|
+
result.markdown ||
|
|
737
|
+
(focused
|
|
738
|
+
? ""
|
|
739
|
+
: result.extractionDiagnostics?.javascriptRequired
|
|
740
|
+
? "[This page requires JavaScript; its content could not be retrieved.]"
|
|
741
|
+
: "[The page contained no readable text.]"),
|
|
650
742
|
].join("\n");
|
|
651
743
|
|
|
652
|
-
|
|
744
|
+
let outputTruncation = truncateHead(output, {
|
|
653
745
|
maxLines: DEFAULT_MAX_LINES,
|
|
654
746
|
maxBytes: DEFAULT_MAX_BYTES,
|
|
655
747
|
});
|
|
656
748
|
|
|
749
|
+
if (showLlmsNotice && result.llmsTxtIndexUrl) {
|
|
750
|
+
const indexUrl = redactUrlForDisplay(result.llmsTxtIndexUrl);
|
|
751
|
+
const notice = `Index: ${indexUrl}\n\n`;
|
|
752
|
+
const noticePosition = outputTruncation.content.indexOf(notice);
|
|
753
|
+
|
|
754
|
+
if (
|
|
755
|
+
noticePosition !== -1 &&
|
|
756
|
+
([indexUrl, ...(result.llmsTxtIndexAliases ?? []).map(redactUrlForDisplay)].some((url) =>
|
|
757
|
+
outputTruncation.content.slice(noticePosition + notice.length).includes(url),
|
|
758
|
+
) ||
|
|
759
|
+
hasVisibleIndexLink(
|
|
760
|
+
outputTruncation.content.slice(noticePosition + notice.length),
|
|
761
|
+
rawFinalUrl,
|
|
762
|
+
[result.llmsTxtIndexUrl, ...(result.llmsTxtIndexAliases ?? [])],
|
|
763
|
+
))
|
|
764
|
+
) {
|
|
765
|
+
outputTruncation = truncateHead(output.replace(notice, ""), {
|
|
766
|
+
maxLines: DEFAULT_MAX_LINES,
|
|
767
|
+
maxBytes: DEFAULT_MAX_BYTES,
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
657
772
|
const truncated = result.truncated || outputTruncation.truncated;
|
|
658
|
-
const outline = createDocumentOutline(
|
|
773
|
+
const outline = createDocumentOutline(canonicalMarkdown);
|
|
659
774
|
|
|
660
775
|
const structured: WebFetchStructuredOutput = {
|
|
661
776
|
requestedUrl,
|
|
@@ -675,8 +790,10 @@ export async function executeWebFetch(
|
|
|
675
790
|
characterCount: 0,
|
|
676
791
|
llmsTxtFallback: Boolean(result.llmsTxtFallback),
|
|
677
792
|
markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
|
|
793
|
+
representationFallback: result.representationFallback,
|
|
678
794
|
extraction: result.extractionDiagnostics,
|
|
679
795
|
focus: focused?.details,
|
|
796
|
+
surface,
|
|
680
797
|
outline: {
|
|
681
798
|
totalWords: outline.totalWords,
|
|
682
799
|
totalHeadings: outline.totalHeadings,
|
|
@@ -733,8 +850,10 @@ export async function executeWebFetch(
|
|
|
733
850
|
confidence,
|
|
734
851
|
outline,
|
|
735
852
|
focus: focused?.details,
|
|
853
|
+
surface,
|
|
736
854
|
llmsTxtFallback: Boolean(result.llmsTxtFallback),
|
|
737
855
|
markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
|
|
856
|
+
representationFallback: result.representationFallback,
|
|
738
857
|
llmsTxtUrl:
|
|
739
858
|
result.llmsTxtIndexUrl === undefined
|
|
740
859
|
? undefined
|