@zeldrisho/pi-web-fetch 0.17.1 → 0.18.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 +30 -1
- package/README.md +3 -3
- package/package.json +2 -2
- package/src/acquisition/fetch-metadata.ts +16 -2
- package/src/acquisition/fetch.ts +27 -2
- package/src/acquisition/llms.ts +115 -33
- package/src/document/content.ts +7 -1
- package/src/document/evidence.ts +29 -3
- package/src/document/extract.ts +107 -1
- package/src/document/focus.ts +43 -8
- package/src/document/openapi.ts +21 -4
- package/src/index.ts +1 -0
- package/src/network/network-redirects.ts +1 -1
- package/src/render.ts +3 -2
- package/src/service.ts +90 -9
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.18.1] - 2026-11-23
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Read a page's authored no-JavaScript fallback when script-only markup leaves the extraction empty or sparse, instead of returning stray interface text.
|
|
15
|
+
- Preserve conditional revalidation for stale pages cached under the current Markdown-preference policy while migrating older entries once.
|
|
16
|
+
- Discover documentation indexes from deeper URL ancestors and filter Android BOM pages to the requested version.
|
|
17
|
+
- Preserve HTML representation preferences across redirects, keep Android BOM selections isolated in the cache, and avoid treating readable fallback content as a markup shell.
|
|
18
|
+
|
|
19
|
+
## [0.18.0] - 2026-11-20
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- Fetch GitLab.com file links as raw source, and prefer available Markdown versions of documentation pages.
|
|
24
|
+
|
|
25
|
+
### Changed
|
|
26
|
+
|
|
27
|
+
- Use Pi's configured expand-key hint when displaying collapsed fetch output.
|
|
28
|
+
- Preserve selected tab views when a Markdown representation is unavailable for tab-scoped pages, and use accurate notices for derived Markdown substitutions.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- Preserve section headings when a query selects a later passage from a long section.
|
|
33
|
+
- Match dotted API identifiers literally within longer queries, and clarify that focused results can omit relevant content.
|
|
34
|
+
- Preserve nested `/-/blob/` path segments when normalizing GitLab file URLs.
|
|
35
|
+
- Match hyphenated dotted filenames such as `package-lock.json` in focused queries.
|
|
36
|
+
|
|
10
37
|
## [0.17.1] - 2026-11-18
|
|
11
38
|
|
|
12
39
|
### Changed
|
|
@@ -365,7 +392,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
365
392
|
|
|
366
393
|
- Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
|
|
367
394
|
|
|
368
|
-
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.
|
|
395
|
+
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.1...HEAD
|
|
396
|
+
[0.18.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.0...pi-web-fetch-v0.18.1
|
|
397
|
+
[0.18.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...pi-web-fetch-v0.18.0
|
|
369
398
|
[0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
|
|
370
399
|
[0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
|
|
371
400
|
[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
|
|
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. Pages that render entirely with JavaScript can return their authored no-JavaScript overview when one exists; the result says so, and script-rendered content remains unavailable. 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.
|
|
3
|
+
"version": "0.18.1",
|
|
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",
|
|
@@ -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
|
@@ -298,6 +298,7 @@ async function documentFromDecoded(
|
|
|
298
298
|
let markdownAlternateUrl: string | undefined = linkHints.markdownAlternate;
|
|
299
299
|
let sourceLanguage: string | undefined;
|
|
300
300
|
let githubReadme = false;
|
|
301
|
+
let noscriptFallback = false;
|
|
301
302
|
const openapiSpec = isOpenapiSource(raw, contentType);
|
|
302
303
|
|
|
303
304
|
if (isHtmlContentType(contentType)) {
|
|
@@ -308,6 +309,7 @@ async function documentFromDecoded(
|
|
|
308
309
|
surfaceView = extracted.surfaceView;
|
|
309
310
|
extractor = extracted.extractor;
|
|
310
311
|
githubReadme = extracted.githubReadme === true;
|
|
312
|
+
noscriptFallback = extracted.noscriptFallback === true;
|
|
311
313
|
describedBy = describedBy ?? extracted.describedByLink;
|
|
312
314
|
markdownAlternateUrl = markdownAlternateUrl ?? extracted.markdownAlternateLink;
|
|
313
315
|
} else if (contentType === "application/json") {
|
|
@@ -396,8 +398,17 @@ async function documentFromDecoded(
|
|
|
396
398
|
extractionDiagnostics.sparseExtraction = false;
|
|
397
399
|
}
|
|
398
400
|
|
|
401
|
+
// An authored no-JavaScript fallback is readable content, not a shell artifact.
|
|
402
|
+
if (extractionDiagnostics && noscriptFallback && markdown.trim()) {
|
|
403
|
+
extractionDiagnostics.sparseExtraction = false;
|
|
404
|
+
}
|
|
405
|
+
|
|
399
406
|
const shellSuspected = extractionDiagnostics
|
|
400
|
-
? hasExtractionWarning(
|
|
407
|
+
? hasExtractionWarning(
|
|
408
|
+
noscriptFallback
|
|
409
|
+
? { ...extractionDiagnostics, javascriptRequired: false }
|
|
410
|
+
: extractionDiagnostics,
|
|
411
|
+
)
|
|
401
412
|
: false;
|
|
402
413
|
|
|
403
414
|
const etag = responseHeader(response, "etag");
|
|
@@ -415,9 +426,11 @@ async function documentFromDecoded(
|
|
|
415
426
|
extractionDiagnostics,
|
|
416
427
|
links,
|
|
417
428
|
validators: etag || lastModified ? { etag, lastModified } : undefined,
|
|
429
|
+
markdownPolicyVersion: 2,
|
|
418
430
|
cachedAt: Date.now(),
|
|
419
431
|
llmsTxtDescribedBy: describedBy,
|
|
420
432
|
markdownAlternateUrl,
|
|
433
|
+
noscriptFallback,
|
|
421
434
|
sourceLanguage,
|
|
422
435
|
openapiSpec,
|
|
423
436
|
swaggerSpecUrl,
|
|
@@ -664,6 +677,7 @@ async function fetchDocument(
|
|
|
664
677
|
cached?: CompleteDocument,
|
|
665
678
|
allowEmptyContent = false,
|
|
666
679
|
retryRepresentationMiss = true,
|
|
680
|
+
preferHtml = false,
|
|
667
681
|
): Promise<{ document: CompleteDocument; revalidated: boolean }> {
|
|
668
682
|
assertAbsoluteHttpUrlForFetch(normalizeGitHubRawUrl(rawUrl));
|
|
669
683
|
const controller = new AbortController();
|
|
@@ -694,6 +708,12 @@ async function fetchDocument(
|
|
|
694
708
|
const requestDependencies: FetchRemoteDependencies = {
|
|
695
709
|
...dependencies,
|
|
696
710
|
cookies: dependencies.cookies ?? new CookieJar(),
|
|
711
|
+
persistentHeaders: preferHtml
|
|
712
|
+
? {
|
|
713
|
+
...dependencies.persistentHeaders,
|
|
714
|
+
Accept: "text/html, text/plain;q=0.9, */*;q=0.1",
|
|
715
|
+
}
|
|
716
|
+
: dependencies.persistentHeaders,
|
|
697
717
|
};
|
|
698
718
|
|
|
699
719
|
try {
|
|
@@ -704,7 +724,9 @@ async function fetchDocument(
|
|
|
704
724
|
requestUrl,
|
|
705
725
|
controller.signal,
|
|
706
726
|
requestDependencies,
|
|
707
|
-
|
|
727
|
+
preferHtml
|
|
728
|
+
? { ...conditionalHeaders, Accept: "text/html, text/plain;q=0.9, */*;q=0.1" }
|
|
729
|
+
: conditionalHeaders,
|
|
708
730
|
);
|
|
709
731
|
|
|
710
732
|
// Some servers route Markdown negotiation to a missing representation even
|
|
@@ -794,6 +816,7 @@ async function fetchDocument(
|
|
|
794
816
|
target.url,
|
|
795
817
|
controller.signal,
|
|
796
818
|
retryDependencies,
|
|
819
|
+
preferHtml ? { Accept: "text/html, text/plain;q=0.9, */*;q=0.1" } : {},
|
|
797
820
|
));
|
|
798
821
|
}
|
|
799
822
|
}
|
|
@@ -907,6 +930,7 @@ export async function fetchCompleteDocument(
|
|
|
907
930
|
dependencies: FetchRemoteDependencies,
|
|
908
931
|
allowEmptyContent = false,
|
|
909
932
|
retryRepresentationMiss = true,
|
|
933
|
+
preferHtml = false,
|
|
910
934
|
): Promise<CompleteDocument> {
|
|
911
935
|
return (
|
|
912
936
|
await fetchDocument(
|
|
@@ -916,6 +940,7 @@ export async function fetchCompleteDocument(
|
|
|
916
940
|
undefined,
|
|
917
941
|
allowEmptyContent,
|
|
918
942
|
retryRepresentationMiss,
|
|
943
|
+
preferHtml,
|
|
919
944
|
)
|
|
920
945
|
).document;
|
|
921
946
|
}
|
package/src/acquisition/llms.ts
CHANGED
|
@@ -31,6 +31,9 @@ function restrictOrigin(
|
|
|
31
31
|
|
|
32
32
|
const CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
|
|
33
33
|
|
|
34
|
+
/** Bounds parallel index probes while allowing substantially deeper paths than two levels. */
|
|
35
|
+
const MAX_LLMS_TXT_CANDIDATES = 16;
|
|
36
|
+
|
|
34
37
|
const LLMS_TXT_MIN_MARKDOWN_CHARACTERS = 200;
|
|
35
38
|
|
|
36
39
|
const encoder = new TextEncoder();
|
|
@@ -44,11 +47,10 @@ function safeUrl(value: string): URL | undefined {
|
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
/**
|
|
47
|
-
* Builds candidate `/llms.txt` URLs for a page: the site-root index plus
|
|
48
|
-
* directory index
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* the page itself is already a `llms.txt` path, so a fallback never retries itself.
|
|
50
|
+
* Builds candidate `/llms.txt` URLs for a page: the site-root index plus every ancestor
|
|
51
|
+
* directory index, mirroring sites that publish per-section indexes. Returns them ordered
|
|
52
|
+
* shallow → deep, and an empty list for non-HTTP(S) targets or when the page itself is
|
|
53
|
+
* already a `llms.txt` path, so a fallback never retries itself.
|
|
52
54
|
*/
|
|
53
55
|
function isGitHubLikeHost(hostname: string): boolean {
|
|
54
56
|
return (
|
|
@@ -79,9 +81,8 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
|
|
|
79
81
|
|
|
80
82
|
if (url.pathname === "/llms.txt" || url.pathname.endsWith("/llms.txt")) return [];
|
|
81
83
|
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
// segment as a directory itself, so `/r2/` still probes `/r2/llms.txt`.
|
|
84
|
+
// A trailing slash marks the final segment as a directory itself, so `/r2/`
|
|
85
|
+
// probes `/r2/llms.txt`.
|
|
85
86
|
const trimmedDirectory = url.pathname.endsWith("/")
|
|
86
87
|
? url.pathname
|
|
87
88
|
: url.pathname.replace(/\/[^/]*$/, "/");
|
|
@@ -89,11 +90,16 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
|
|
|
89
90
|
const directories = ["/"];
|
|
90
91
|
const parts = trimmedDirectory.split("/").filter(Boolean);
|
|
91
92
|
|
|
92
|
-
for (let depth = 1; depth <=
|
|
93
|
+
for (let depth = 1; depth <= parts.length; depth += 1) {
|
|
93
94
|
directories.push(`/${parts.slice(0, depth).join("/")}/`);
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
|
|
97
|
+
const selectedDirectories =
|
|
98
|
+
directories.length <= MAX_LLMS_TXT_CANDIDATES
|
|
99
|
+
? directories
|
|
100
|
+
: [directories[0], ...directories.slice(-(MAX_LLMS_TXT_CANDIDATES - 1))];
|
|
101
|
+
|
|
102
|
+
return selectedDirectories.map((pathname) => {
|
|
97
103
|
const candidate = new URL(url.origin);
|
|
98
104
|
candidate.pathname = `${pathname}llms.txt`;
|
|
99
105
|
|
|
@@ -104,7 +110,31 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
|
|
|
104
110
|
}
|
|
105
111
|
}
|
|
106
112
|
|
|
113
|
+
/** Returns documented Markdown endpoints only for known documentation routes. */
|
|
114
|
+
export function documentationMarkdownUrl(value: string): URL | undefined {
|
|
115
|
+
const url = safeUrl(value);
|
|
116
|
+
|
|
117
|
+
if (!url || url.protocol !== "https:" || url.username || url.password || url.port) return;
|
|
118
|
+
|
|
119
|
+
if (
|
|
120
|
+
!(
|
|
121
|
+
(url.hostname === "nextjs.org" || url.hostname === "vercel.com") &&
|
|
122
|
+
(url.pathname === "/docs" || url.pathname.startsWith("/docs/"))
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
return;
|
|
126
|
+
|
|
127
|
+
if (url.pathname.endsWith(".md")) return;
|
|
128
|
+
url.pathname = `${url.pathname.replace(/\/$/, "")}.md`;
|
|
129
|
+
url.hash = "";
|
|
130
|
+
|
|
131
|
+
return url;
|
|
132
|
+
}
|
|
133
|
+
|
|
107
134
|
function isLowQualityDocument(document: CompleteDocument): boolean {
|
|
135
|
+
// An authored fallback is readable content, so a site index would be a downgrade.
|
|
136
|
+
if (document.noscriptFallback && !document.extractionDiagnostics?.botWall) return false;
|
|
137
|
+
|
|
108
138
|
// Sparse extraction alone is not proof of an empty app shell: server-rendered pages
|
|
109
139
|
// may include useful content in streaming/framework markup that article extraction
|
|
110
140
|
// does not fully recognize. Keep that page rather than replacing it with a site index.
|
|
@@ -123,14 +153,6 @@ interface LlmsTxtProbe {
|
|
|
123
153
|
|
|
124
154
|
const MAX_LLMS_TXT_PROBE_ENTRIES = 512;
|
|
125
155
|
|
|
126
|
-
/**
|
|
127
|
-
* Deepest ancestor-directory `/llms.txt` probed, e.g. `/a/b/c` also probes
|
|
128
|
-
* `/a/b/llms.txt`. Locale-prefixed documentation sites publish their section index
|
|
129
|
-
* one level below the locale root, so two levels are needed to reach
|
|
130
|
-
* `/en/docs/llms.txt` from `/en/docs/catalog/...`.
|
|
131
|
-
*/
|
|
132
|
-
const MAX_LLMS_TXT_DIRECTORY_DEPTH = 2;
|
|
133
|
-
|
|
134
156
|
const llmsTxtProbes = new ExpiringLruCache<string, LlmsTxtProbe>(
|
|
135
157
|
MAX_LLMS_TXT_PROBE_ENTRIES,
|
|
136
158
|
8 * 1024 * 1024,
|
|
@@ -172,21 +194,29 @@ async function ensureLlmsTxtIndex(
|
|
|
172
194
|
signal: AbortSignal | undefined,
|
|
173
195
|
dependencies: FetchRemoteDependencies,
|
|
174
196
|
): Promise<{ url: string; document: CompleteDocument; aliases?: string[] } | undefined> {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
197
|
+
// Candidates are ordered shallow → deep. Probe from the page upward in small batches:
|
|
198
|
+
// this preserves a preference for the deepest usable index without issuing every
|
|
199
|
+
// ancestor request when a nearby section index already exists.
|
|
200
|
+
const batchSize = 4;
|
|
178
201
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const document = documents[depth];
|
|
202
|
+
for (let end = candidates.length; end > 0; end -= batchSize) {
|
|
203
|
+
const start = Math.max(0, end - batchSize);
|
|
204
|
+
const batch = candidates.slice(start, end);
|
|
183
205
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
);
|
|
206
|
+
const documents = await Promise.all(
|
|
207
|
+
batch.map((candidate) => probeUsableRawText(candidate, signal, dependencies)),
|
|
208
|
+
);
|
|
188
209
|
|
|
189
|
-
|
|
210
|
+
for (let index = documents.length - 1; index >= 0; index -= 1) {
|
|
211
|
+
const document = documents[index];
|
|
212
|
+
|
|
213
|
+
if (document) {
|
|
214
|
+
const aliases = documents.flatMap((other, i) =>
|
|
215
|
+
i !== index && other && other.markdown === document.markdown ? [batch[i].href] : [],
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
return { url: batch[index].href, document, aliases };
|
|
219
|
+
}
|
|
190
220
|
}
|
|
191
221
|
}
|
|
192
222
|
|
|
@@ -279,6 +309,8 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
279
309
|
rawUrl: string,
|
|
280
310
|
signal: AbortSignal | undefined,
|
|
281
311
|
dependencies: FetchRemoteDependencies,
|
|
312
|
+
preferHtml = false,
|
|
313
|
+
allowMarkdownAlternates = true,
|
|
282
314
|
): Promise<CompleteDocument> {
|
|
283
315
|
try {
|
|
284
316
|
const url = new URL(rawUrl);
|
|
@@ -324,7 +356,7 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
324
356
|
// A withheld page must not discard an index that is still usable, so the pair is
|
|
325
357
|
// settled instead of rejected together.
|
|
326
358
|
const [primarySettled, indexSettled] = await Promise.allSettled([
|
|
327
|
-
fetchCompleteDocument(rawUrl, signal, dependencies, true),
|
|
359
|
+
fetchCompleteDocument(rawUrl, signal, dependencies, true, true, preferHtml),
|
|
328
360
|
candidates.length > 0
|
|
329
361
|
? ensureLlmsTxtIndex(candidates, signal, dependencies)
|
|
330
362
|
: Promise.resolve(undefined),
|
|
@@ -381,6 +413,49 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
381
413
|
}
|
|
382
414
|
}
|
|
383
415
|
|
|
416
|
+
// Prefer a page-specific Markdown representation even when HTML extraction succeeded.
|
|
417
|
+
// Restrict the entire redirect chain, and never substitute HTML or arbitrary text.
|
|
418
|
+
if (
|
|
419
|
+
allowMarkdownAlternates &&
|
|
420
|
+
!primary.surfaceView &&
|
|
421
|
+
primary.extractor !== "raw" &&
|
|
422
|
+
(!primary.markdownAlternateUrl || (!isLowQualityDocument(primary) && primary.markdown.trim()))
|
|
423
|
+
) {
|
|
424
|
+
const advertised = primary.markdownAlternateUrl
|
|
425
|
+
? toAbsoluteUrl(primary.markdownAlternateUrl)
|
|
426
|
+
: undefined;
|
|
427
|
+
|
|
428
|
+
const candidate = advertised ?? documentationMarkdownUrl(primary.url);
|
|
429
|
+
|
|
430
|
+
if (candidate && isSafeToProbe(candidate, primary.url) && candidate.href !== primary.url) {
|
|
431
|
+
try {
|
|
432
|
+
const alternate = await fetchCompleteDocument(
|
|
433
|
+
candidate.href,
|
|
434
|
+
signal,
|
|
435
|
+
restrictOrigin(dependencies, new URL(primary.url).origin),
|
|
436
|
+
false,
|
|
437
|
+
false,
|
|
438
|
+
);
|
|
439
|
+
|
|
440
|
+
if (
|
|
441
|
+
alternate.extractor === "raw" &&
|
|
442
|
+
/^(text\/markdown|text\/x-markdown)(?:;|$)/i.test(alternate.contentType) &&
|
|
443
|
+
alternate.markdown.trim().length >= LLMS_TXT_MIN_MARKDOWN_CHARACTERS &&
|
|
444
|
+
!alternate.shellSuspected
|
|
445
|
+
)
|
|
446
|
+
return {
|
|
447
|
+
...alternate,
|
|
448
|
+
markdownAlternateFallback: true,
|
|
449
|
+
markdownAlternateReason: advertised ? "advertised" : "preferred",
|
|
450
|
+
llmsTxtIndexUrl: index?.url,
|
|
451
|
+
llmsTxtIndexAliases: index?.aliases,
|
|
452
|
+
};
|
|
453
|
+
} catch (error) {
|
|
454
|
+
if (signal?.aborted) throw error;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
384
459
|
if (isLowQualityDocument(primary) || !primary.markdown.trim()) {
|
|
385
460
|
// The page's own advertised Markdown version is strictly better than an index.
|
|
386
461
|
const markdownAlternate = primary.markdownAlternateUrl
|
|
@@ -388,12 +463,19 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
388
463
|
: undefined;
|
|
389
464
|
|
|
390
465
|
const alternate =
|
|
391
|
-
|
|
466
|
+
allowMarkdownAlternates &&
|
|
467
|
+
!primary.surfaceView &&
|
|
468
|
+
markdownAlternate &&
|
|
469
|
+
isSafeToProbe(markdownAlternate, primary.url)
|
|
392
470
|
? await probeUsableRawText(markdownAlternate, signal, dependencies)
|
|
393
471
|
: undefined;
|
|
394
472
|
|
|
395
473
|
if (alternate && markdownAlternate) {
|
|
396
|
-
return {
|
|
474
|
+
return {
|
|
475
|
+
...alternate,
|
|
476
|
+
markdownAlternateFallback: true,
|
|
477
|
+
markdownAlternateReason: "advertised",
|
|
478
|
+
};
|
|
397
479
|
}
|
|
398
480
|
|
|
399
481
|
if (index) return { ...index.document, llmsTxtFallback: true };
|
package/src/document/content.ts
CHANGED
|
@@ -36,6 +36,8 @@ export interface CompleteDocument {
|
|
|
36
36
|
links?: ExtractedLinks;
|
|
37
37
|
/** HTTP validators retained for stale-cache revalidation. */
|
|
38
38
|
validators?: { etag?: string; lastModified?: string };
|
|
39
|
+
/** Version of the Markdown-preference cache policy that produced this entry. */
|
|
40
|
+
markdownPolicyVersion?: 2;
|
|
39
41
|
/** Time at which this representation was fetched or successfully revalidated. */
|
|
40
42
|
cachedAt?: number;
|
|
41
43
|
/** True when this document is the site's /llms.txt served instead of a low-quality page. */
|
|
@@ -52,8 +54,12 @@ export interface CompleteDocument {
|
|
|
52
54
|
llmsTxtDescribedBy?: string;
|
|
53
55
|
/** Absolute URL advertised for a Markdown version of this page (`rel="alternate" type="text/markdown"`). */
|
|
54
56
|
markdownAlternateUrl?: string;
|
|
55
|
-
/** True when this document is
|
|
57
|
+
/** True when this document is a Markdown representation substituted for the requested page. */
|
|
56
58
|
markdownAlternateFallback?: boolean;
|
|
59
|
+
/** True when this document is the page's authored no-JavaScript fallback content. */
|
|
60
|
+
noscriptFallback?: boolean;
|
|
61
|
+
/** Why the Markdown representation was selected. */
|
|
62
|
+
markdownAlternateReason?: "advertised" | "preferred";
|
|
57
63
|
/** Same-origin OpenAPI document advertised by an otherwise empty Swagger UI. */
|
|
58
64
|
swaggerSpecUrl?: string;
|
|
59
65
|
/** The returned content is an API or specification substituted for the page. */
|
package/src/document/evidence.ts
CHANGED
|
@@ -5,6 +5,13 @@ const MAX_LINKS = 16;
|
|
|
5
5
|
|
|
6
6
|
const MAX_ANCHOR_CHARACTERS = 120;
|
|
7
7
|
|
|
8
|
+
/** Raw and extracted sizes below which an HTML page counts as sparsely extracted. */
|
|
9
|
+
const SPARSE_MIN_RAW_CHARACTERS = 4_000;
|
|
10
|
+
|
|
11
|
+
const SPARSE_MAX_MARKDOWN_CHARACTERS = 1_024;
|
|
12
|
+
|
|
13
|
+
const SPARSE_MAX_MARKDOWN_RATIO = 0.008;
|
|
14
|
+
|
|
8
15
|
/** Bounded, machine-readable reasons that an HTML extraction may be incomplete. */
|
|
9
16
|
export interface ExtractionDiagnostics {
|
|
10
17
|
javascriptRequired: boolean;
|
|
@@ -78,6 +85,26 @@ const CONSENT_MARKERS = [
|
|
|
78
85
|
/we\s+use\s+cookies/i,
|
|
79
86
|
];
|
|
80
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Reports whether an extraction is too small for the markup it came from.
|
|
90
|
+
*
|
|
91
|
+
* @param rawCharacters - UTF-16 length of the fetched HTML
|
|
92
|
+
* @param markdownCharacters - UTF-16 length of the extracted Markdown
|
|
93
|
+
* @returns True when the extraction looks sparse for a page of this size
|
|
94
|
+
*/
|
|
95
|
+
export function isSparseExtraction(rawCharacters: number, markdownCharacters: number): boolean {
|
|
96
|
+
return (
|
|
97
|
+
rawCharacters > SPARSE_MIN_RAW_CHARACTERS &&
|
|
98
|
+
markdownCharacters < SPARSE_MAX_MARKDOWN_CHARACTERS &&
|
|
99
|
+
markdownCharacters < rawCharacters * SPARSE_MAX_MARKDOWN_RATIO
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Reports whether the HTML advertises that JavaScript is required to render the page. */
|
|
104
|
+
export function hasJavaScriptMarkers(raw: string): boolean {
|
|
105
|
+
return JAVASCRIPT_MARKERS.some((marker) => marker.test(raw));
|
|
106
|
+
}
|
|
107
|
+
|
|
81
108
|
/** Produces explicit, bounded extraction-quality signals instead of one opaque shell flag. */
|
|
82
109
|
export function diagnoseExtraction(raw: string, markdown: string): ExtractionDiagnostics {
|
|
83
110
|
const { document } = parseHTML(raw);
|
|
@@ -96,7 +123,7 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
|
|
|
96
123
|
CAPTCHA_WIDGET_MARKERS.some((marker) => marker.test(raw)));
|
|
97
124
|
|
|
98
125
|
return {
|
|
99
|
-
javascriptRequired:
|
|
126
|
+
javascriptRequired: hasJavaScriptMarkers(raw),
|
|
100
127
|
botWall:
|
|
101
128
|
hasAnubisMarkers(raw) ||
|
|
102
129
|
BOT_MARKERS.some((marker) => marker.test(raw)) ||
|
|
@@ -105,8 +132,7 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
|
|
|
105
132
|
ANUBIS_PROTECTION_MARKERS.some((marker) => marker.test(anubisText)) &&
|
|
106
133
|
PROOF_OF_WORK_MARKER.test(anubisText)),
|
|
107
134
|
consentInterstitial: CONSENT_MARKERS.some((marker) => marker.test(raw)),
|
|
108
|
-
sparseExtraction:
|
|
109
|
-
raw.length > 4_000 && markdown.length < 1_024 && markdown.length < raw.length * 0.008,
|
|
135
|
+
sparseExtraction: isSparseExtraction(raw.length, markdown.length),
|
|
110
136
|
rawCharacters: raw.length,
|
|
111
137
|
extractedCharacters: markdown.length,
|
|
112
138
|
};
|
package/src/document/extract.ts
CHANGED
|
@@ -3,11 +3,18 @@ import type { DefuddleResponse } from "defuddle/node";
|
|
|
3
3
|
import { stripExtractedCssCruft } from "./markdown-cleanup.ts";
|
|
4
4
|
import { buildFragmentOffsets } from "./fragment-index.ts";
|
|
5
5
|
import { assertConversionDepth } from "./complexity.ts";
|
|
6
|
+
import { hasJavaScriptMarkers, isSparseExtraction } from "./evidence.ts";
|
|
6
7
|
|
|
7
8
|
export { stripExtractedCssCruft } from "./markdown-cleanup.ts";
|
|
8
9
|
|
|
9
10
|
const RAW_ID_SELECTOR_SAFE = /^-?[_a-zA-Z][-_a-zA-Z0-9]*$/;
|
|
10
11
|
|
|
12
|
+
/** Minimum authored no-JavaScript fallback length worth showing instead of a shell. */
|
|
13
|
+
const NOSCRIPT_FALLBACK_MIN_CHARACTERS = 200;
|
|
14
|
+
|
|
15
|
+
/** Primary extraction length below which a JavaScript-required page counts as a shell. */
|
|
16
|
+
const NOSCRIPT_PRIMARY_MAX_CHARACTERS = 1_024;
|
|
17
|
+
|
|
11
18
|
/** Removes schema.org scripts that Defuddle would report directly to the process console. */
|
|
12
19
|
function removeMalformedSchemaOrgData(document: Document): void {
|
|
13
20
|
for (const script of document.querySelectorAll<HTMLScriptElement>(
|
|
@@ -464,6 +471,7 @@ async function extractHtmlDocument(
|
|
|
464
471
|
describedByLink?: string;
|
|
465
472
|
markdownAlternateLink?: string;
|
|
466
473
|
githubReadme?: boolean;
|
|
474
|
+
noscriptFallback?: boolean;
|
|
467
475
|
}> {
|
|
468
476
|
// Keep refusal outside the catch: the fallback also constructs a DOM.
|
|
469
477
|
assertConversionDepth(html);
|
|
@@ -630,6 +638,103 @@ function selectSurfaceHtml(
|
|
|
630
638
|
return { html: document.documentElement.outerHTML, selected, omitted: panes.length - 1 };
|
|
631
639
|
}
|
|
632
640
|
|
|
641
|
+
/** Removes non-selected Android Compose BOM rows from the HTML table. */
|
|
642
|
+
export function filterAndroidBomHtml(html: string, version: string): string | undefined {
|
|
643
|
+
const { document } = parseHTML(html);
|
|
644
|
+
const rows = [...document.querySelectorAll<HTMLElement>("tr[filter-value]")];
|
|
645
|
+
const matching = rows.filter((row) => row.getAttribute("filter-value") === version);
|
|
646
|
+
|
|
647
|
+
if (matching.length === 0) return undefined;
|
|
648
|
+
|
|
649
|
+
for (const row of rows) {
|
|
650
|
+
if (row.getAttribute("filter-value") !== version) row.remove();
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
return document.documentElement.outerHTML;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* Builds a standalone document from the page's no-JavaScript fallback blocks, or
|
|
658
|
+
* returns undefined when the page has none. The recovering document is reparsed
|
|
659
|
+
* through the same depth preflight when it is extracted.
|
|
660
|
+
*/
|
|
661
|
+
function noscriptFallbackHtml(html: string): string | undefined {
|
|
662
|
+
if (!/<noscript[\s>]/i.test(html)) return undefined;
|
|
663
|
+
|
|
664
|
+
let sections: string[];
|
|
665
|
+
|
|
666
|
+
try {
|
|
667
|
+
const { document } = parseHTML(html);
|
|
668
|
+
|
|
669
|
+
sections = [...document.querySelectorAll("noscript")].flatMap((block) => {
|
|
670
|
+
const inner = block.innerHTML.trim();
|
|
671
|
+
|
|
672
|
+
return inner.length > 0 ? [inner] : [];
|
|
673
|
+
});
|
|
674
|
+
} catch {
|
|
675
|
+
return undefined;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
return sections.length === 0
|
|
679
|
+
? undefined
|
|
680
|
+
: `<html><head></head><body>${sections.join("\n")}</body></html>`;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* Reports whether the primary extraction is too weak to represent the page: empty,
|
|
685
|
+
* sparse for its markup, or no more than a JavaScript-required notice.
|
|
686
|
+
*/
|
|
687
|
+
function isWeakExtraction(html: string, markdown: string): boolean {
|
|
688
|
+
const length = markdown.trim().length;
|
|
689
|
+
const substantive = length >= NOSCRIPT_FALLBACK_MIN_CHARACTERS;
|
|
690
|
+
|
|
691
|
+
if (length === 0) return true;
|
|
692
|
+
|
|
693
|
+
if (isSparseExtraction(html.length, length) && !substantive) return true;
|
|
694
|
+
|
|
695
|
+
return length < NOSCRIPT_PRIMARY_MAX_CHARACTERS && hasJavaScriptMarkers(html) && !substantive;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* Reads the page's authored no-JavaScript fallback when the primary extraction is
|
|
700
|
+
* empty, sparse, or only a JavaScript-required notice. Readable pages keep their
|
|
701
|
+
* primary content, so fallback navigation or notices never replace real content.
|
|
702
|
+
*/
|
|
703
|
+
async function extractNoscriptFallback(
|
|
704
|
+
html: string,
|
|
705
|
+
baseUrl: URL,
|
|
706
|
+
primary: Awaited<ReturnType<typeof extractHtmlDocument>>,
|
|
707
|
+
): Promise<Awaited<ReturnType<typeof extractHtmlDocument>> | undefined> {
|
|
708
|
+
if (!isWeakExtraction(html, primary.markdown)) return undefined;
|
|
709
|
+
|
|
710
|
+
const fallbackHtml = noscriptFallbackHtml(html);
|
|
711
|
+
|
|
712
|
+
if (!fallbackHtml) return undefined;
|
|
713
|
+
|
|
714
|
+
try {
|
|
715
|
+
const fallback = await extractHtmlDocument(fallbackHtml, baseUrl);
|
|
716
|
+
|
|
717
|
+
if (
|
|
718
|
+
fallback.markdown.length < NOSCRIPT_FALLBACK_MIN_CHARACTERS ||
|
|
719
|
+
fallback.markdown.length <= primary.markdown.length
|
|
720
|
+
)
|
|
721
|
+
return undefined;
|
|
722
|
+
|
|
723
|
+
return {
|
|
724
|
+
...fallback,
|
|
725
|
+
// The synthesized document has no head metadata of its own.
|
|
726
|
+
title: primary.title ?? fallback.title,
|
|
727
|
+
githubReadme: primary.githubReadme,
|
|
728
|
+
describedByLink: primary.describedByLink ?? fallback.describedByLink,
|
|
729
|
+
markdownAlternateLink: primary.markdownAlternateLink ?? fallback.markdownAlternateLink,
|
|
730
|
+
noscriptFallback: true,
|
|
731
|
+
};
|
|
732
|
+
} catch {
|
|
733
|
+
// A fallback must never make an otherwise readable page unavailable.
|
|
734
|
+
return undefined;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
633
738
|
/** Extract the complete page and, when explicitly requested, a separate surface view. */
|
|
634
739
|
export async function extractHtmlToMarkdown(
|
|
635
740
|
html: string,
|
|
@@ -645,7 +750,8 @@ export async function extractHtmlToMarkdown(
|
|
|
645
750
|
}
|
|
646
751
|
> {
|
|
647
752
|
assertConversionDepth(html);
|
|
648
|
-
const
|
|
753
|
+
const primary = await extractHtmlDocument(html, baseUrl);
|
|
754
|
+
const complete = (await extractNoscriptFallback(html, baseUrl, primary)) ?? primary;
|
|
649
755
|
|
|
650
756
|
try {
|
|
651
757
|
const surface = selectSurfaceHtml(html, baseUrl);
|
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/document/openapi.ts
CHANGED
|
@@ -1,9 +1,25 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { simple } from "acorn-walk";
|
|
3
|
-
import { parseDocument } from "yaml";
|
|
1
|
+
import { createRequire } from "node:module";
|
|
4
2
|
import { Type } from "typebox";
|
|
5
3
|
import { Check } from "typebox/value";
|
|
6
4
|
|
|
5
|
+
const require = createRequire(import.meta.url);
|
|
6
|
+
|
|
7
|
+
let parserModules:
|
|
8
|
+
| {
|
|
9
|
+
parse: typeof import("acorn").parse;
|
|
10
|
+
simple: typeof import("acorn-walk").simple;
|
|
11
|
+
parseDocument: typeof import("yaml").parseDocument;
|
|
12
|
+
}
|
|
13
|
+
| undefined;
|
|
14
|
+
|
|
15
|
+
function getParserModules(): NonNullable<typeof parserModules> {
|
|
16
|
+
return (parserModules ??= {
|
|
17
|
+
parse: require("acorn").parse,
|
|
18
|
+
simple: require("acorn-walk").simple,
|
|
19
|
+
parseDocument: require("yaml").parseDocument,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
7
23
|
const schema = Type.Union([
|
|
8
24
|
Type.Object({
|
|
9
25
|
openapi: Type.String({ pattern: "^3\\.\\d+\\.\\d+$" }),
|
|
@@ -24,12 +40,13 @@ export function isOpenapiSource(raw: string, contentType: string): boolean {
|
|
|
24
40
|
if (contentType === "application/json") return Check(schema, JSON.parse(raw));
|
|
25
41
|
|
|
26
42
|
if (contentType === "text/yaml") {
|
|
27
|
-
const document = parseDocument(raw, { uniqueKeys: true });
|
|
43
|
+
const document = getParserModules().parseDocument(raw, { uniqueKeys: true });
|
|
28
44
|
|
|
29
45
|
return document.errors.length === 0 && Check(schema, document.toJS({ maxAliasCount: 0 }));
|
|
30
46
|
}
|
|
31
47
|
|
|
32
48
|
if (contentType !== "text/javascript") return false;
|
|
49
|
+
const { parse, simple } = getParserModules();
|
|
33
50
|
const ast = parse(raw, { ecmaVersion: "latest", sourceType: "module" });
|
|
34
51
|
let found = false;
|
|
35
52
|
simple(ast, {
|
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
|
},
|
|
@@ -215,7 +215,7 @@ export async function requestFollowingRedirects(
|
|
|
215
215
|
throw new Error("web_fetch followed too many redirects.");
|
|
216
216
|
target = await awaitWithAbort(validateUrl(new URL(location, target.url)), signal);
|
|
217
217
|
// Validators describe the originally cached resource and must not leak to a redirect target.
|
|
218
|
-
//
|
|
218
|
+
// Representation preferences and challenge identities are safe to retain.
|
|
219
219
|
requestHeaders = dependencies.persistentHeaders ?? {};
|
|
220
220
|
}
|
|
221
221
|
|
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
|
@@ -12,6 +12,7 @@ import { ExpiringLruCache, stableKeyHash, canonicalKey, type CachePersistence }
|
|
|
12
12
|
import { sliceCompleteDocument, type CompleteDocument } from "./document/content.ts";
|
|
13
13
|
import { revalidateCompleteDocument, type FetchRemoteDependencies } from "./acquisition/fetch.ts";
|
|
14
14
|
import { fetchDocumentWithLlmsTxtSupport } from "./acquisition/llms.ts";
|
|
15
|
+
import { extractHtmlToMarkdown, filterAndroidBomHtml } from "./document/extract.ts";
|
|
15
16
|
import { focusMarkdown, type FocusDetails } from "./document/focus.ts";
|
|
16
17
|
import { isCachedOpenapi } from "./document/openapi.ts";
|
|
17
18
|
import { resolveFragmentOffset, urlWithoutFragment } from "./document/fragments.ts";
|
|
@@ -37,6 +38,27 @@ const CACHE_MAX_MARKDOWN_BYTES = 20 * 1_024 * 1_024;
|
|
|
37
38
|
|
|
38
39
|
const MAX_INFLIGHT_REQUESTS = 100;
|
|
39
40
|
|
|
41
|
+
interface CacheDimensions {
|
|
42
|
+
surfaceExtraction?: number;
|
|
43
|
+
androidBomVersion?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function androidBomVersionQuery(url: string, query: string | undefined): string | undefined {
|
|
47
|
+
if (query === undefined || !/^\d{4}\.\d{2}\.\d{2}$/.test(query.trim())) return undefined;
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const parsed = new URL(url);
|
|
51
|
+
|
|
52
|
+
return parsed.protocol === "https:" &&
|
|
53
|
+
parsed.hostname === "developer.android.com" &&
|
|
54
|
+
parsed.pathname === "/develop/ui/compose/bom/bom-mapping"
|
|
55
|
+
? query.trim()
|
|
56
|
+
: undefined;
|
|
57
|
+
} catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
40
62
|
/** Minimum extracted length for both the low-quality trigger and llms.txt acceptance. */
|
|
41
63
|
const encoder = new TextEncoder();
|
|
42
64
|
|
|
@@ -212,6 +234,8 @@ export interface WebFetchDetails {
|
|
|
212
234
|
llmsTxtFallback: boolean;
|
|
213
235
|
/** True when the returned content is the page's advertised Markdown version served instead of a low-quality page. */
|
|
214
236
|
markdownAlternateFallback: boolean;
|
|
237
|
+
/** True when the returned content is the page's authored no-JavaScript fallback. */
|
|
238
|
+
noscriptFallback: boolean;
|
|
215
239
|
/** Identifies an API or specification used instead of the page. */
|
|
216
240
|
representationFallback?: CompleteDocument["representationFallback"];
|
|
217
241
|
/** The site's /llms.txt index URL when one exists and the returned content is not that index itself. */
|
|
@@ -252,6 +276,7 @@ export interface WebFetchStructuredOutput {
|
|
|
252
276
|
characterCount: number;
|
|
253
277
|
llmsTxtFallback: boolean;
|
|
254
278
|
markdownAlternateFallback: boolean;
|
|
279
|
+
noscriptFallback: boolean;
|
|
255
280
|
representationFallback?: CompleteDocument["representationFallback"];
|
|
256
281
|
extraction?: CompleteDocument["extractionDiagnostics"];
|
|
257
282
|
focus?: FocusDetails;
|
|
@@ -279,6 +304,7 @@ export const webFetchOutputSchema = Type.Object({
|
|
|
279
304
|
characterCount: Type.Integer(),
|
|
280
305
|
llmsTxtFallback: Type.Boolean(),
|
|
281
306
|
markdownAlternateFallback: Type.Boolean(),
|
|
307
|
+
noscriptFallback: Type.Boolean(),
|
|
282
308
|
representationFallback: Type.Optional(
|
|
283
309
|
Type.Union([Type.Literal("packit-api"), Type.Literal("swagger-spec")]),
|
|
284
310
|
),
|
|
@@ -369,6 +395,8 @@ const completeDocumentCacheSchema = Type.Object(
|
|
|
369
395
|
lastModified: Type.Optional(Type.String()),
|
|
370
396
|
}),
|
|
371
397
|
),
|
|
398
|
+
markdownPolicyVersion: Type.Optional(Type.Literal(2)),
|
|
399
|
+
noscriptFallback: Type.Optional(Type.Boolean()),
|
|
372
400
|
llmsTxtFallback: Type.Optional(Type.Boolean()),
|
|
373
401
|
llmsTxtIndexUrl: Type.Optional(Type.String()),
|
|
374
402
|
llmsTxtDescribedBy: Type.Optional(Type.String()),
|
|
@@ -408,6 +436,17 @@ interface FetchAcquisition {
|
|
|
408
436
|
|
|
409
437
|
const inflightFetches = new InflightCoalescer<string, FetchAcquisition>(MAX_INFLIGHT_REQUESTS);
|
|
410
438
|
|
|
439
|
+
/** Returns whether a stale entry predates the Markdown-preference cache policy. */
|
|
440
|
+
export function staleCacheNeedsMarkdownPolicy(document: CompleteDocument): boolean {
|
|
441
|
+
return (
|
|
442
|
+
document.markdownPolicyVersion !== 2 &&
|
|
443
|
+
document.extractor !== "raw" &&
|
|
444
|
+
!document.surfaceView &&
|
|
445
|
+
!document.llmsTxtFallback &&
|
|
446
|
+
!document.representationFallback
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
|
|
411
450
|
/**
|
|
412
451
|
* Executes a validated web fetch, including caching, focusing, and bounded pagination.
|
|
413
452
|
*
|
|
@@ -469,11 +508,16 @@ export async function executeWebFetch(
|
|
|
469
508
|
|
|
470
509
|
const displayRequestedUrl = redactUrlForDisplay(params.url);
|
|
471
510
|
const sourceUrl = urlWithoutFragment(params.url);
|
|
511
|
+
const bomVersion = androidBomVersionQuery(sourceUrl, params.query);
|
|
472
512
|
|
|
473
513
|
// Older persisted entries predate surface views and must not mask explicit selections.
|
|
474
|
-
const
|
|
475
|
-
|
|
476
|
-
|
|
514
|
+
const cacheDimensions: CacheDimensions = {};
|
|
515
|
+
|
|
516
|
+
if (safeUrl(sourceUrl)?.searchParams.has("tab")) cacheDimensions.surfaceExtraction = 1;
|
|
517
|
+
|
|
518
|
+
if (bomVersion) cacheDimensions.androidBomVersion = bomVersion;
|
|
519
|
+
|
|
520
|
+
const cacheKey = canonicalKey({ url: sourceUrl, ...cacheDimensions });
|
|
477
521
|
|
|
478
522
|
let document = fetchCache.get(cacheKey);
|
|
479
523
|
const now = Date.now();
|
|
@@ -509,11 +553,16 @@ export async function executeWebFetch(
|
|
|
509
553
|
let fetched: CompleteDocument;
|
|
510
554
|
let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
|
|
511
555
|
|
|
556
|
+
const staleNeedsMarkdownPolicy =
|
|
557
|
+
stale !== undefined && staleCacheNeedsMarkdownPolicy(stale);
|
|
558
|
+
|
|
512
559
|
if (
|
|
513
560
|
stale?.validators &&
|
|
561
|
+
!staleNeedsMarkdownPolicy &&
|
|
514
562
|
!stale.llmsTxtFallback &&
|
|
515
563
|
!stale.markdownAlternateFallback &&
|
|
516
|
-
!stale.representationFallback
|
|
564
|
+
!stale.representationFallback &&
|
|
565
|
+
!bomVersion
|
|
517
566
|
) {
|
|
518
567
|
const outcome = await revalidateCompleteDocument(
|
|
519
568
|
sourceUrl,
|
|
@@ -525,7 +574,27 @@ export async function executeWebFetch(
|
|
|
525
574
|
fetched = outcome.document;
|
|
526
575
|
acquisitionStatus = outcome.revalidated ? "revalidated" : "miss";
|
|
527
576
|
} else {
|
|
528
|
-
|
|
577
|
+
const acquisitionDependencies = bomVersion
|
|
578
|
+
? {
|
|
579
|
+
...dependencies,
|
|
580
|
+
extractHtml: async (html: string, url: URL) => {
|
|
581
|
+
const filtered = filterAndroidBomHtml(html, bomVersion);
|
|
582
|
+
|
|
583
|
+
if (filtered === undefined)
|
|
584
|
+
throw new Error(`web_fetch: Android BOM version ${bomVersion} was not found.`);
|
|
585
|
+
|
|
586
|
+
return extractHtmlToMarkdown(filtered, url);
|
|
587
|
+
},
|
|
588
|
+
}
|
|
589
|
+
: dependencies;
|
|
590
|
+
|
|
591
|
+
fetched = await fetchDocumentWithLlmsTxtSupport(
|
|
592
|
+
sourceUrl,
|
|
593
|
+
sharedSignal,
|
|
594
|
+
acquisitionDependencies,
|
|
595
|
+
Boolean(bomVersion),
|
|
596
|
+
!bomVersion,
|
|
597
|
+
);
|
|
529
598
|
}
|
|
530
599
|
|
|
531
600
|
if (!fetched.extractionDiagnostics?.botWall) {
|
|
@@ -619,7 +688,7 @@ export async function executeWebFetch(
|
|
|
619
688
|
: document;
|
|
620
689
|
|
|
621
690
|
const focused =
|
|
622
|
-
blocked || params.query === undefined
|
|
691
|
+
blocked || params.query === undefined || bomVersion
|
|
623
692
|
? undefined
|
|
624
693
|
: focusMarkdown(fragmentDocument.markdown, params.query);
|
|
625
694
|
|
|
@@ -684,7 +753,17 @@ export async function executeWebFetch(
|
|
|
684
753
|
: []),
|
|
685
754
|
...(result.markdownAlternateFallback
|
|
686
755
|
? [
|
|
687
|
-
|
|
756
|
+
result.markdownAlternateReason === "advertised"
|
|
757
|
+
? "[Showing the site's advertised Markdown version instead.]"
|
|
758
|
+
: result.markdownAlternateReason === "preferred"
|
|
759
|
+
? "[Showing the site's preferred Markdown representation instead.]"
|
|
760
|
+
: "[Showing a Markdown representation instead of the requested page.]",
|
|
761
|
+
"",
|
|
762
|
+
]
|
|
763
|
+
: []),
|
|
764
|
+
...(result.noscriptFallback
|
|
765
|
+
? [
|
|
766
|
+
"[Showing the page's no-JavaScript fallback; script-rendered content is unavailable.]",
|
|
688
767
|
"",
|
|
689
768
|
]
|
|
690
769
|
: []),
|
|
@@ -716,8 +795,8 @@ export async function executeWebFetch(
|
|
|
716
795
|
...(focused
|
|
717
796
|
? [
|
|
718
797
|
focused.details.matchedSections > 0
|
|
719
|
-
? `[Query
|
|
720
|
-
: "[No sections
|
|
798
|
+
? `[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.]`
|
|
799
|
+
: "[No sections selected. The query may miss relevant content; omit query for the full page.]",
|
|
721
800
|
"",
|
|
722
801
|
]
|
|
723
802
|
: []),
|
|
@@ -778,6 +857,7 @@ export async function executeWebFetch(
|
|
|
778
857
|
characterCount: 0,
|
|
779
858
|
llmsTxtFallback: Boolean(result.llmsTxtFallback),
|
|
780
859
|
markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
|
|
860
|
+
noscriptFallback: Boolean(result.noscriptFallback),
|
|
781
861
|
representationFallback: result.representationFallback,
|
|
782
862
|
extraction: result.extractionDiagnostics,
|
|
783
863
|
focus: focused?.details,
|
|
@@ -841,6 +921,7 @@ export async function executeWebFetch(
|
|
|
841
921
|
surface,
|
|
842
922
|
llmsTxtFallback: Boolean(result.llmsTxtFallback),
|
|
843
923
|
markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
|
|
924
|
+
noscriptFallback: Boolean(result.noscriptFallback),
|
|
844
925
|
representationFallback: result.representationFallback,
|
|
845
926
|
llmsTxtUrl:
|
|
846
927
|
result.llmsTxtIndexUrl === undefined
|