@zeldrisho/pi-web-fetch 0.16.5 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -1
- package/README.md +6 -2
- package/package.json +7 -13
- package/src/acquisition/fetch.ts +210 -29
- package/src/acquisition/llms.ts +90 -9
- package/src/acquisition/reddit.ts +71 -0
- package/src/challenges/anubis.ts +1 -1
- package/src/challenges/reddit.ts +93 -0
- package/src/document/content.ts +13 -0
- package/src/document/evidence.ts +7 -0
- package/src/document/extract.ts +184 -4
- package/src/index.ts +2 -2
- package/src/service.ts +113 -6
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.17.1] - 2026-11-18
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- Restore codemode access to structured fetch results with Pi 0.99.0 or newer.
|
|
15
|
+
- Return Packit Copr API data without a verbose substitution notice, while preserving the source URL and structured provenance.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- Preserve selected documentation surfaces in HTML fragments and when tab controls use multiple supported attribute mappings.
|
|
20
|
+
- Recognize standard Swagger UI initializers and retain index notices when a visible link points to a different index.
|
|
21
|
+
- Honor explicitly selected documentation surfaces when supported by the page, rather than mixing unrelated surface instructions.
|
|
22
|
+
- Extract plain-text GitHub repository READMEs without the file-listing table.
|
|
23
|
+
- Avoid redundant discovered index notices when the visible page already links to a same-site documentation index.
|
|
24
|
+
- Retrieve Packit Copr job data without an API key and advertised Swagger specifications from otherwise empty app pages.
|
|
25
|
+
- Explain when an empty page requires JavaScript instead of reporting a generic extraction error.
|
|
26
|
+
- Solve supported Anubis challenges that declare no extensions as `null`.
|
|
27
|
+
- Fetch slash-sensitive pages when a trailing slash returns 404 but the page exists without it.
|
|
28
|
+
- Report page errors after a solved Anubis challenge instead of incorrectly reporting a bot block.
|
|
29
|
+
|
|
30
|
+
## [0.17.0] - 2026-11-12
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- **Breaking:** `web_fetch` requires Pi 0.99.0 or newer and can no longer be called by other tools, including codemode; use direct model calls instead.
|
|
35
|
+
|
|
36
|
+
### Fixed
|
|
37
|
+
|
|
38
|
+
- Solve supported Reddit JavaScript challenges and try the public post feed when a challenge remains blocked.
|
|
39
|
+
- Return the rendered README instead of repository file listings on GitHub repository pages when a README is available, without misclassifying short READMEs as sparse pages.
|
|
40
|
+
|
|
10
41
|
## [0.16.5] - 2026-11-10
|
|
11
42
|
|
|
12
43
|
### Fixed
|
|
@@ -334,7 +365,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
334
365
|
|
|
335
366
|
- Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
|
|
336
367
|
|
|
337
|
-
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.
|
|
368
|
+
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...HEAD
|
|
369
|
+
[0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
|
|
370
|
+
[0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
|
|
338
371
|
[0.16.5]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...pi-web-fetch-v0.16.5
|
|
339
372
|
[0.16.4]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.3...pi-web-fetch-v0.16.4
|
|
340
373
|
[0.16.3]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.2...pi-web-fetch-v0.16.3
|
package/README.md
CHANGED
|
@@ -23,13 +23,17 @@ The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markd
|
|
|
23
23
|
| `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
|
|
24
24
|
| `offset` | Optional character offset for continuing through extracted content. With a query and a fragment, offsets apply to the focused view; otherwise an offset takes precedence over the fragment. |
|
|
25
25
|
|
|
26
|
+
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
|
+
|
|
26
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.
|
|
27
29
|
|
|
28
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.
|
|
29
31
|
|
|
30
32
|
### Page alternatives and bot challenges
|
|
31
33
|
|
|
32
|
-
The tool can discover advertised Markdown versions and `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index.
|
|
34
|
+
The tool can discover advertised Markdown versions and `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index.
|
|
35
|
+
|
|
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.
|
|
33
37
|
|
|
34
38
|
### Caching
|
|
35
39
|
|
|
@@ -37,7 +41,7 @@ Fetched pages are cached in private local storage across sessions. Cached conten
|
|
|
37
41
|
|
|
38
42
|
### Programmatic results
|
|
39
43
|
|
|
40
|
-
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.
|
|
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.
|
|
41
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
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zeldrisho/pi-web-fetch",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.1",
|
|
4
4
|
"description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi",
|
|
@@ -33,19 +33,19 @@
|
|
|
33
33
|
"acorn": "^8.19.0",
|
|
34
34
|
"acorn-walk": "^8.3.5",
|
|
35
35
|
"defuddle": "^0.19.6",
|
|
36
|
-
"linkedom": "^0.18.
|
|
36
|
+
"linkedom": "^0.18.15",
|
|
37
37
|
"yaml": "^2.9.1"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@earendil-works/pi-coding-agent": "^1.4.0",
|
|
41
41
|
"@earendil-works/pi-tui": "^1.4.0",
|
|
42
|
-
"typebox": "^1.4.
|
|
42
|
+
"typebox": "^1.4.3",
|
|
43
43
|
"typescript": "^7.0.2",
|
|
44
|
-
"vite": "npm:@voidzero-dev/vite-plus-core@1.
|
|
45
|
-
"vite-plus": "1.
|
|
44
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@1.5.0",
|
|
45
|
+
"vite-plus": "1.5.0"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
|
-
"@earendil-works/pi-coding-agent": "
|
|
48
|
+
"@earendil-works/pi-coding-agent": ">=0.99.0",
|
|
49
49
|
"@earendil-works/pi-tui": "*",
|
|
50
50
|
"typebox": "*"
|
|
51
51
|
},
|
|
@@ -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
|
}
|
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,
|
|
@@ -22,6 +23,7 @@ import {
|
|
|
22
23
|
type AwsWafSolution,
|
|
23
24
|
} from "../challenges/aws-waf.ts";
|
|
24
25
|
import { nativeAwsWafResolver } from "../challenges/aws-waf-resolver.ts";
|
|
26
|
+
import { redditChallengeUrl } from "../challenges/reddit.ts";
|
|
25
27
|
import {
|
|
26
28
|
sliceCompleteDocument,
|
|
27
29
|
type CompleteDocument,
|
|
@@ -34,6 +36,7 @@ import {
|
|
|
34
36
|
hasExtractionWarning,
|
|
35
37
|
} from "../document/evidence.ts";
|
|
36
38
|
import { extractHtmlToMarkdown } from "../document/extract.ts";
|
|
39
|
+
import { redditFeedUrl, extractRedditFeed } from "./reddit.ts";
|
|
37
40
|
import { assertConversionDepth } from "../document/complexity.ts";
|
|
38
41
|
import { formatMinifiedSource } from "../document/source-format.ts";
|
|
39
42
|
import { isOpenapiSource } from "../document/openapi.ts";
|
|
@@ -289,10 +292,12 @@ async function documentFromDecoded(
|
|
|
289
292
|
let markdown: string;
|
|
290
293
|
let title: string | undefined;
|
|
291
294
|
let fragmentOffsets: Record<string, number> | undefined;
|
|
295
|
+
let surfaceView: CompleteDocument["surfaceView"];
|
|
292
296
|
let extractor: CompleteDocument["extractor"] = "raw";
|
|
293
297
|
let describedBy: string | undefined = linkHints.describedBy;
|
|
294
298
|
let markdownAlternateUrl: string | undefined = linkHints.markdownAlternate;
|
|
295
299
|
let sourceLanguage: string | undefined;
|
|
300
|
+
let githubReadme = false;
|
|
296
301
|
const openapiSpec = isOpenapiSource(raw, contentType);
|
|
297
302
|
|
|
298
303
|
if (isHtmlContentType(contentType)) {
|
|
@@ -300,7 +305,9 @@ async function documentFromDecoded(
|
|
|
300
305
|
markdown = extracted.markdown;
|
|
301
306
|
title = extracted.title;
|
|
302
307
|
fragmentOffsets = extracted.fragmentOffsets;
|
|
308
|
+
surfaceView = extracted.surfaceView;
|
|
303
309
|
extractor = extracted.extractor;
|
|
310
|
+
githubReadme = extracted.githubReadme === true;
|
|
304
311
|
describedBy = describedBy ?? extracted.describedByLink;
|
|
305
312
|
markdownAlternateUrl = markdownAlternateUrl ?? extracted.markdownAlternateLink;
|
|
306
313
|
} else if (contentType === "application/json") {
|
|
@@ -337,15 +344,57 @@ async function documentFromDecoded(
|
|
|
337
344
|
const isHtml = isHtmlContentType(contentType);
|
|
338
345
|
const links = isHtml ? extractDocumentLinks(raw, target.url) : undefined;
|
|
339
346
|
|
|
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
|
+
}
|
|
382
|
+
|
|
340
383
|
if (
|
|
341
384
|
!markdown.trim() &&
|
|
342
385
|
(!links || (links.internal.length === 0 && links.external.length === 0)) &&
|
|
343
|
-
!allowEmptyContent
|
|
386
|
+
!allowEmptyContent &&
|
|
387
|
+
!extractionDiagnostics?.botWall &&
|
|
388
|
+
!extractionDiagnostics?.javascriptRequired &&
|
|
389
|
+
!swaggerSpecUrl
|
|
344
390
|
) {
|
|
345
391
|
throw new Error("web_fetch: Page has no extractable content.");
|
|
346
392
|
}
|
|
347
393
|
|
|
348
|
-
|
|
394
|
+
// Repository chrome can dwarf a complete, intentionally short README.
|
|
395
|
+
if (extractionDiagnostics && githubReadme && markdown.trim()) {
|
|
396
|
+
extractionDiagnostics.sparseExtraction = false;
|
|
397
|
+
}
|
|
349
398
|
|
|
350
399
|
const shellSuspected = extractionDiagnostics
|
|
351
400
|
? hasExtractionWarning(extractionDiagnostics)
|
|
@@ -359,6 +408,7 @@ async function documentFromDecoded(
|
|
|
359
408
|
contentType,
|
|
360
409
|
markdown,
|
|
361
410
|
fragmentOffsets,
|
|
411
|
+
surfaceView,
|
|
362
412
|
title,
|
|
363
413
|
extractor,
|
|
364
414
|
shellSuspected,
|
|
@@ -370,6 +420,7 @@ async function documentFromDecoded(
|
|
|
370
420
|
markdownAlternateUrl,
|
|
371
421
|
sourceLanguage,
|
|
372
422
|
openapiSpec,
|
|
423
|
+
swaggerSpecUrl,
|
|
373
424
|
};
|
|
374
425
|
}
|
|
375
426
|
|
|
@@ -432,35 +483,93 @@ async function documentFromAcquisition(
|
|
|
432
483
|
dependencies: FetchRemoteDependencies,
|
|
433
484
|
allowSolve: boolean,
|
|
434
485
|
): Promise<CompleteDocument> {
|
|
435
|
-
assertSuccessfulResponse(response);
|
|
436
486
|
const status = response.statusCode ?? 0;
|
|
437
487
|
const contentTypeHeader = responseContentTypeHeader(response);
|
|
438
488
|
const contentType = normalizeContentType(contentTypeHeader);
|
|
439
489
|
|
|
490
|
+
const reddit403 =
|
|
491
|
+
allowSolve &&
|
|
492
|
+
status === 403 &&
|
|
493
|
+
target.url.protocol === "https:" &&
|
|
494
|
+
["reddit.com", "www.reddit.com", "old.reddit.com"].includes(target.url.hostname) &&
|
|
495
|
+
!target.url.username &&
|
|
496
|
+
!target.url.password &&
|
|
497
|
+
!target.url.port &&
|
|
498
|
+
isHtmlContentType(contentType);
|
|
499
|
+
|
|
500
|
+
if (!reddit403) assertSuccessfulResponse(response);
|
|
501
|
+
|
|
440
502
|
if (
|
|
441
503
|
allowSolve &&
|
|
442
|
-
|
|
443
|
-
status >= 200 &&
|
|
444
|
-
status < 300 &&
|
|
504
|
+
((status >= 200 && status < 300) || reddit403) &&
|
|
445
505
|
isHtmlContentType(contentType)
|
|
446
506
|
) {
|
|
447
507
|
const body = await decodeResponseBody(response, signal, contentTypeHeader, contentType);
|
|
448
508
|
|
|
449
|
-
if (
|
|
509
|
+
if (reddit403 && !diagnoseExtraction(body.raw, "").botWall) assertSuccessfulResponse(response);
|
|
510
|
+
|
|
511
|
+
const blocked = reddit403
|
|
512
|
+
? await documentFromDecoded(target, response, body, signal, extractHtml, allowEmptyContent)
|
|
513
|
+
: undefined;
|
|
514
|
+
|
|
515
|
+
if (reddit403 && !blocked?.extractionDiagnostics?.botWall) assertSuccessfulResponse(response);
|
|
516
|
+
|
|
517
|
+
if (!reddit403 && dependencies.solveAnubisChallenges !== false && hasAnubisMarkers(body.raw)) {
|
|
450
518
|
const challenge = parseAnubisChallenge(body.raw, target.url);
|
|
451
519
|
|
|
452
520
|
if (challenge) {
|
|
521
|
+
let passed: Awaited<ReturnType<typeof solveAnubisChallenge>>;
|
|
522
|
+
|
|
453
523
|
try {
|
|
454
|
-
|
|
524
|
+
passed = await solveAnubisChallenge({
|
|
455
525
|
challenge,
|
|
456
526
|
pageUrl: target.url,
|
|
457
527
|
raw: body.raw,
|
|
458
528
|
dependencies,
|
|
459
529
|
signal,
|
|
460
530
|
});
|
|
531
|
+
} catch (error) {
|
|
532
|
+
if (signal.aborted || (error instanceof Error && error.name === "AbortError"))
|
|
533
|
+
throw error;
|
|
534
|
+
|
|
535
|
+
return documentFromDecoded(
|
|
536
|
+
target,
|
|
537
|
+
response,
|
|
538
|
+
body,
|
|
539
|
+
signal,
|
|
540
|
+
extractHtml,
|
|
541
|
+
allowEmptyContent,
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
return documentFromAcquisition(
|
|
546
|
+
passed.target,
|
|
547
|
+
passed.response,
|
|
548
|
+
signal,
|
|
549
|
+
extractHtml,
|
|
550
|
+
allowEmptyContent,
|
|
551
|
+
dependencies,
|
|
552
|
+
false,
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// An unsolvable challenge, denial, or error page is returned as blocked.
|
|
557
|
+
return documentFromDecoded(target, response, body, signal, extractHtml, allowEmptyContent);
|
|
558
|
+
}
|
|
461
559
|
|
|
560
|
+
const redditPass = redditChallengeUrl(body.raw, target.url);
|
|
561
|
+
|
|
562
|
+
if (redditPass) {
|
|
563
|
+
try {
|
|
564
|
+
const passed = await requestFollowingRedirects(redditPass, signal, dependencies);
|
|
565
|
+
|
|
566
|
+
if (
|
|
567
|
+
passed.target.url.origin === target.url.origin &&
|
|
568
|
+
passed.target.url.pathname === target.url.pathname
|
|
569
|
+
) {
|
|
570
|
+
// The handshake query contains a token; never expose or cache it as the document URL.
|
|
462
571
|
return await documentFromAcquisition(
|
|
463
|
-
passed.target,
|
|
572
|
+
{ ...passed.target, url: target.url },
|
|
464
573
|
passed.response,
|
|
465
574
|
signal,
|
|
466
575
|
extractHtml,
|
|
@@ -468,18 +577,18 @@ async function documentFromAcquisition(
|
|
|
468
577
|
dependencies,
|
|
469
578
|
false,
|
|
470
579
|
);
|
|
471
|
-
} catch (error) {
|
|
472
|
-
if (signal.aborted || (error instanceof Error && error.name === "AbortError"))
|
|
473
|
-
throw error;
|
|
474
|
-
// Any other failure degrades to the standard blocked output below.
|
|
475
580
|
}
|
|
476
|
-
}
|
|
477
581
|
|
|
478
|
-
|
|
479
|
-
|
|
582
|
+
passed.response.destroy();
|
|
583
|
+
} catch (error) {
|
|
584
|
+
if (signal.aborted || (error instanceof Error && error.name === "AbortError")) throw error;
|
|
585
|
+
// An unsupported or refused challenge falls back to the blocked document.
|
|
586
|
+
}
|
|
480
587
|
}
|
|
481
588
|
|
|
482
|
-
return
|
|
589
|
+
return (
|
|
590
|
+
blocked ?? documentFromDecoded(target, response, body, signal, extractHtml, allowEmptyContent)
|
|
591
|
+
);
|
|
483
592
|
}
|
|
484
593
|
|
|
485
594
|
return documentFromResponse(target, response, signal, extractHtml, allowEmptyContent);
|
|
@@ -614,6 +723,25 @@ async function fetchDocument(
|
|
|
614
723
|
));
|
|
615
724
|
}
|
|
616
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
|
+
|
|
617
745
|
if (
|
|
618
746
|
response.statusCode !== undefined &&
|
|
619
747
|
responseHeader(response, "cf-mitigated")?.trim().toLowerCase() === "challenge"
|
|
@@ -689,18 +817,71 @@ async function fetchDocument(
|
|
|
689
817
|
};
|
|
690
818
|
}
|
|
691
819
|
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
820
|
+
const requestedFeed = redditFeedUrl(rawUrl);
|
|
821
|
+
const finalFeed = redditFeedUrl(target.url.href);
|
|
822
|
+
|
|
823
|
+
const eligibleFeed =
|
|
824
|
+
requestedFeed && finalFeed && requestedFeed.toLowerCase() === finalFeed.toLowerCase()
|
|
825
|
+
? requestedFeed
|
|
826
|
+
: undefined;
|
|
827
|
+
|
|
828
|
+
const document = await documentFromAcquisition(
|
|
829
|
+
target,
|
|
830
|
+
response,
|
|
831
|
+
controller.signal,
|
|
832
|
+
extractHtml,
|
|
833
|
+
allowEmptyContent,
|
|
834
|
+
requestDependencies,
|
|
835
|
+
true,
|
|
836
|
+
);
|
|
837
|
+
|
|
838
|
+
const feedUrl = document.extractionDiagnostics?.botWall ? eligibleFeed : undefined;
|
|
839
|
+
|
|
840
|
+
if (feedUrl) {
|
|
841
|
+
try {
|
|
842
|
+
const feed = await requestFollowingRedirects(
|
|
843
|
+
feedUrl,
|
|
844
|
+
controller.signal,
|
|
845
|
+
requestDependencies,
|
|
846
|
+
);
|
|
847
|
+
|
|
848
|
+
const type = normalizeContentType(responseContentTypeHeader(feed.response));
|
|
849
|
+
|
|
850
|
+
if (
|
|
851
|
+
feed.target.url.hostname === "www.reddit.com" &&
|
|
852
|
+
feed.target.url.protocol === "https:" &&
|
|
853
|
+
feed.response.statusCode === 200 &&
|
|
854
|
+
type === "application/atom+xml"
|
|
855
|
+
) {
|
|
856
|
+
const body = await decodeResponseBody(
|
|
857
|
+
feed.response,
|
|
858
|
+
controller.signal,
|
|
859
|
+
responseContentTypeHeader(feed.response),
|
|
860
|
+
type,
|
|
861
|
+
);
|
|
862
|
+
|
|
863
|
+
const markdown = extractRedditFeed(body.raw, feedUrl);
|
|
864
|
+
|
|
865
|
+
if (markdown)
|
|
866
|
+
return {
|
|
867
|
+
document: {
|
|
868
|
+
url: document.url,
|
|
869
|
+
contentType: type,
|
|
870
|
+
markdown,
|
|
871
|
+
extractor: "raw",
|
|
872
|
+
shellSuspected: false,
|
|
873
|
+
cachedAt: Date.now(),
|
|
874
|
+
},
|
|
875
|
+
revalidated: false,
|
|
876
|
+
};
|
|
877
|
+
} else feed.response.destroy();
|
|
878
|
+
} catch (error) {
|
|
879
|
+
if (controller.signal.aborted) throw error;
|
|
880
|
+
// Reddit's anonymous feed may be unavailable or rate limited.
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
return { document, revalidated: false };
|
|
704
885
|
} catch (error) {
|
|
705
886
|
if (timedOut) throw new Error(`web_fetch timed out after ${timeoutMs / 1000} seconds.`);
|
|
706
887
|
|
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
|
|
|
@@ -149,7 +171,7 @@ async function ensureLlmsTxtIndex(
|
|
|
149
171
|
candidates: URL[],
|
|
150
172
|
signal: AbortSignal | undefined,
|
|
151
173
|
dependencies: FetchRemoteDependencies,
|
|
152
|
-
): Promise<{ url: string; document: CompleteDocument } | undefined> {
|
|
174
|
+
): Promise<{ url: string; document: CompleteDocument; aliases?: string[] } | undefined> {
|
|
153
175
|
const documents = await Promise.all(
|
|
154
176
|
candidates.map((candidate) => probeUsableRawText(candidate, signal, dependencies)),
|
|
155
177
|
);
|
|
@@ -159,7 +181,13 @@ async function ensureLlmsTxtIndex(
|
|
|
159
181
|
for (let depth = documents.length - 1; depth >= 0; depth -= 1) {
|
|
160
182
|
const document = documents[depth];
|
|
161
183
|
|
|
162
|
-
if (document)
|
|
184
|
+
if (document) {
|
|
185
|
+
const aliases = documents.flatMap((other, i) =>
|
|
186
|
+
i !== depth && other && other.markdown === document.markdown ? [candidates[i].href] : [],
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
return { url: candidates[depth].href, document, aliases };
|
|
190
|
+
}
|
|
163
191
|
}
|
|
164
192
|
|
|
165
193
|
return undefined;
|
|
@@ -253,10 +281,41 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
253
281
|
dependencies: FetchRemoteDependencies,
|
|
254
282
|
): Promise<CompleteDocument> {
|
|
255
283
|
try {
|
|
256
|
-
|
|
284
|
+
const url = new URL(rawUrl);
|
|
285
|
+
const match = /^\/jobs\/copr\/(\d+)\/?$/.exec(url.pathname);
|
|
286
|
+
|
|
287
|
+
if (
|
|
288
|
+
url.protocol === "https:" &&
|
|
289
|
+
url.host === "dashboard.packit.dev" &&
|
|
290
|
+
!url.username &&
|
|
291
|
+
!url.password &&
|
|
292
|
+
!url.search &&
|
|
293
|
+
match
|
|
294
|
+
) {
|
|
295
|
+
const apiUrl = `https://prod.packit.dev/api/copr-builds/${match[1]}`;
|
|
296
|
+
|
|
297
|
+
try {
|
|
298
|
+
const document = await fetchCompleteDocument(
|
|
299
|
+
apiUrl,
|
|
300
|
+
signal,
|
|
301
|
+
restrictOrigin(dependencies, "https://prod.packit.dev"),
|
|
302
|
+
);
|
|
303
|
+
|
|
304
|
+
if (
|
|
305
|
+
new URL(document.url).origin === "https://prod.packit.dev" &&
|
|
306
|
+
document.contentType === "application/json"
|
|
307
|
+
)
|
|
308
|
+
return { ...document, representationFallback: "packit-api" };
|
|
309
|
+
} catch (error) {
|
|
310
|
+
if (signal?.aborted) throw error;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (isGitHubLikeHost(url.hostname)) {
|
|
257
315
|
return fetchCompleteDocument(rawUrl, signal, dependencies);
|
|
258
316
|
}
|
|
259
|
-
} catch {
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (signal?.aborted) throw error;
|
|
260
319
|
// Invalid URL falls through to fetchCompleteDocument which will throw.
|
|
261
320
|
}
|
|
262
321
|
|
|
@@ -297,7 +356,29 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
297
356
|
? await probeUsableRawText(describedBy, signal, dependencies)
|
|
298
357
|
: undefined;
|
|
299
358
|
|
|
300
|
-
if (described && describedBy
|
|
359
|
+
if (described && describedBy && index?.url !== describedBy.href)
|
|
360
|
+
index = { url: describedBy.href, document: described };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (
|
|
364
|
+
!primary.markdown.trim() &&
|
|
365
|
+
primary.swaggerSpecUrl &&
|
|
366
|
+
isSafeToProbe(toAbsoluteUrl(primary.swaggerSpecUrl), primary.url)
|
|
367
|
+
) {
|
|
368
|
+
try {
|
|
369
|
+
const spec = await fetchCompleteDocument(
|
|
370
|
+
primary.swaggerSpecUrl,
|
|
371
|
+
signal,
|
|
372
|
+
restrictOrigin(dependencies, new URL(primary.url).origin),
|
|
373
|
+
false,
|
|
374
|
+
false,
|
|
375
|
+
);
|
|
376
|
+
|
|
377
|
+
if (isSafeToProbe(toAbsoluteUrl(spec.url), primary.url) && spec.openapiSpec)
|
|
378
|
+
return { ...spec, representationFallback: "swagger-spec" };
|
|
379
|
+
} catch (error) {
|
|
380
|
+
if (signal?.aborted) throw error;
|
|
381
|
+
}
|
|
301
382
|
}
|
|
302
383
|
|
|
303
384
|
if (isLowQualityDocument(primary) || !primary.markdown.trim()) {
|
|
@@ -317,16 +398,16 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
317
398
|
|
|
318
399
|
if (index) return { ...index.document, llmsTxtFallback: true };
|
|
319
400
|
} else if (index) {
|
|
320
|
-
return { ...primary, llmsTxtIndexUrl: index.url };
|
|
401
|
+
return { ...primary, llmsTxtIndexUrl: index.url, llmsTxtIndexAliases: index.aliases };
|
|
321
402
|
}
|
|
322
403
|
|
|
323
404
|
if (
|
|
324
405
|
!primary.markdown.trim() &&
|
|
325
406
|
(!primary.links || (primary.links.internal.length === 0 && primary.links.external.length === 0))
|
|
326
407
|
) {
|
|
327
|
-
//
|
|
328
|
-
|
|
329
|
-
|
|
408
|
+
// Preserve diagnostics for empty challenge pages and JavaScript app shells.
|
|
409
|
+
if (primary.extractionDiagnostics?.botWall || primary.extractionDiagnostics?.javascriptRequired)
|
|
410
|
+
return primary;
|
|
330
411
|
|
|
331
412
|
throw new Error("web_fetch: Page has no extractable content.");
|
|
332
413
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { DOMParser } from "linkedom";
|
|
2
|
+
import { assertConversionDepth } from "../document/complexity.ts";
|
|
3
|
+
import { htmlToMarkdownFallback } from "../document/extract.ts";
|
|
4
|
+
|
|
5
|
+
/** Restrict the fallback to public Reddit post permalinks, never arbitrary hosts. */
|
|
6
|
+
export function redditFeedUrl(rawUrl: string): string | undefined {
|
|
7
|
+
const url = new URL(rawUrl);
|
|
8
|
+
|
|
9
|
+
if (
|
|
10
|
+
url.protocol !== "https:" ||
|
|
11
|
+
!["reddit.com", "www.reddit.com", "old.reddit.com"].includes(url.hostname) ||
|
|
12
|
+
url.username ||
|
|
13
|
+
url.password ||
|
|
14
|
+
url.port
|
|
15
|
+
)
|
|
16
|
+
return undefined;
|
|
17
|
+
|
|
18
|
+
const match = /^\/r\/([a-z0-9_]+)\/comments\/([a-z0-9]+)(?:\/[^/]+)?\/?$/i.exec(url.pathname);
|
|
19
|
+
|
|
20
|
+
if (!match) return undefined;
|
|
21
|
+
|
|
22
|
+
return `https://www.reddit.com/r/${match[1]}/comments/${match[2]}/.rss`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Render the anonymous Atom representation; it does not preserve comment hierarchy. */
|
|
26
|
+
export function extractRedditFeed(raw: string, feedUrl: string): string | undefined {
|
|
27
|
+
assertConversionDepth(raw);
|
|
28
|
+
const document = new DOMParser().parseFromString(raw, "text/xml");
|
|
29
|
+
|
|
30
|
+
if (document.documentElement?.localName !== "feed") return undefined;
|
|
31
|
+
const id = /\/comments\/([a-z0-9]+)\//i.exec(new URL(feedUrl).pathname)?.[1];
|
|
32
|
+
const entries = [...document.querySelectorAll("entry")];
|
|
33
|
+
|
|
34
|
+
const post = entries.find(
|
|
35
|
+
(entry) => entry.querySelector("id")?.textContent?.trim() === `t3_${id}`,
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
if (!post) return undefined;
|
|
39
|
+
|
|
40
|
+
const render = (entry: Element): string => {
|
|
41
|
+
const author = entry.querySelector("author name")?.textContent?.trim();
|
|
42
|
+
const title = entry.querySelector("title")?.textContent?.trim();
|
|
43
|
+
const content = entry.querySelector("content")?.textContent ?? "";
|
|
44
|
+
const text = htmlToMarkdownFallback(content);
|
|
45
|
+
|
|
46
|
+
return [title, author ? `By ${author}` : "", text].filter(Boolean).join("\n\n");
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const main = render(post);
|
|
50
|
+
|
|
51
|
+
if (!main) return undefined;
|
|
52
|
+
|
|
53
|
+
const comments: string[] = [];
|
|
54
|
+
|
|
55
|
+
for (const entry of entries) {
|
|
56
|
+
if (
|
|
57
|
+
entry === post ||
|
|
58
|
+
!/^t1_[a-z0-9]+$/i.test(entry.querySelector("id")?.textContent?.trim() ?? "")
|
|
59
|
+
)
|
|
60
|
+
continue;
|
|
61
|
+
const comment = render(entry);
|
|
62
|
+
|
|
63
|
+
if (comment) comments.push(comment);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return [
|
|
67
|
+
"Reddit Atom feed; comments may be incomplete and thread hierarchy is unavailable.",
|
|
68
|
+
main,
|
|
69
|
+
...comments.map((comment) => `## Comment\n\n${comment}`),
|
|
70
|
+
].join("\n\n");
|
|
71
|
+
}
|
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
|
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { parseHTML } from "linkedom";
|
|
2
|
+
|
|
3
|
+
/** Parse the observed Reddit challenge without executing server-provided JavaScript. */
|
|
4
|
+
export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
|
|
5
|
+
if (
|
|
6
|
+
pageUrl.protocol !== "https:" ||
|
|
7
|
+
!["reddit.com", "www.reddit.com", "old.reddit.com"].includes(pageUrl.hostname) ||
|
|
8
|
+
pageUrl.username ||
|
|
9
|
+
pageUrl.password ||
|
|
10
|
+
pageUrl.port
|
|
11
|
+
)
|
|
12
|
+
return undefined;
|
|
13
|
+
const { document } = parseHTML(raw);
|
|
14
|
+
const forms = document.querySelectorAll("form");
|
|
15
|
+
|
|
16
|
+
if (forms.length !== 1) return undefined;
|
|
17
|
+
const form = forms[0];
|
|
18
|
+
|
|
19
|
+
if (!form.hasAttribute("hidden") || form.getAttribute("method")?.toLowerCase() !== "get")
|
|
20
|
+
return undefined;
|
|
21
|
+
const action = form.getAttribute("action");
|
|
22
|
+
|
|
23
|
+
if (!action) return undefined;
|
|
24
|
+
let target: URL;
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
target = new URL(action, pageUrl);
|
|
28
|
+
} catch {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (
|
|
33
|
+
target.origin !== pageUrl.origin ||
|
|
34
|
+
target.pathname !== pageUrl.pathname ||
|
|
35
|
+
target.search ||
|
|
36
|
+
target.hash
|
|
37
|
+
)
|
|
38
|
+
return undefined;
|
|
39
|
+
const inputs = [...form.querySelectorAll("input")];
|
|
40
|
+
|
|
41
|
+
if (inputs.length !== 4) return undefined;
|
|
42
|
+
const values = new Map<string, string>();
|
|
43
|
+
|
|
44
|
+
for (const input of inputs) {
|
|
45
|
+
const name = input.getAttribute("name");
|
|
46
|
+
|
|
47
|
+
if (!name || values.has(name) || input.getAttribute("type")?.toLowerCase() !== "hidden")
|
|
48
|
+
return undefined;
|
|
49
|
+
values.set(name, input.getAttribute("value") ?? "");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const token = values.get("jsc_token");
|
|
53
|
+
|
|
54
|
+
if (
|
|
55
|
+
values.get("solution") !== "" ||
|
|
56
|
+
values.get("js_challenge") !== "1" ||
|
|
57
|
+
!token ||
|
|
58
|
+
!/^[a-f0-9]{1,256}$/i.test(token) ||
|
|
59
|
+
values.get("jsc_orig_r") !== ""
|
|
60
|
+
)
|
|
61
|
+
return undefined;
|
|
62
|
+
|
|
63
|
+
for (const name of values.keys()) if (pageUrl.searchParams.has(name)) return undefined;
|
|
64
|
+
|
|
65
|
+
if (pageUrl.search.length > 2048) return undefined;
|
|
66
|
+
const scripts = [...document.querySelectorAll("script")];
|
|
67
|
+
|
|
68
|
+
if (scripts.length !== 1 || scripts[0].hasAttribute("src")) return undefined;
|
|
69
|
+
const script = scripts[0].textContent ?? "";
|
|
70
|
+
|
|
71
|
+
if (script.length > 16_384) return undefined;
|
|
72
|
+
|
|
73
|
+
// Match only the observed literal string-doubling expression. Never evaluate code.
|
|
74
|
+
const match =
|
|
75
|
+
/await\s*\(\s*async\s+([a-zA-Z_$][\w$]*)\s*=>\s*\1\s*\+\s*\1\s*\)\s*\(\s*(["'])([a-f0-9]{1,128})\2\s*\)/i.exec(
|
|
76
|
+
script,
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
if (
|
|
80
|
+
!match ||
|
|
81
|
+
!/namedItem\(["']solution["']\)\.value\s*=/.test(script) ||
|
|
82
|
+
!/requestSubmit\(\)/.test(script)
|
|
83
|
+
)
|
|
84
|
+
return undefined;
|
|
85
|
+
target.searchParams.set("solution", match[3] + match[3]);
|
|
86
|
+
target.searchParams.set("js_challenge", "1");
|
|
87
|
+
target.searchParams.set("jsc_token", token);
|
|
88
|
+
target.searchParams.set("jsc_orig_r", "");
|
|
89
|
+
|
|
90
|
+
for (const [key, value] of pageUrl.searchParams) target.searchParams.append(key, value);
|
|
91
|
+
|
|
92
|
+
return target;
|
|
93
|
+
}
|
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,18 @@ export interface CompleteDocument {
|
|
|
39
46
|
openapiSpec?: boolean;
|
|
40
47
|
/** Set when the site publishes a usable /llms.txt index and this document is not that index. */
|
|
41
48
|
llmsTxtIndexUrl?: string;
|
|
49
|
+
/** Probed index URLs with identical complete content. */
|
|
50
|
+
llmsTxtIndexAliases?: string[];
|
|
42
51
|
/** Absolute URL advertised via `rel="describedby"` (header or HTML link) for this page. */
|
|
43
52
|
llmsTxtDescribedBy?: string;
|
|
44
53
|
/** Absolute URL advertised for a Markdown version of this page (`rel="alternate" type="text/markdown"`). */
|
|
45
54
|
markdownAlternateUrl?: string;
|
|
46
55
|
/** True when this document is the advertised Markdown version served instead of a low-quality page. */
|
|
47
56
|
markdownAlternateFallback?: boolean;
|
|
57
|
+
/** Same-origin OpenAPI document advertised by an otherwise empty Swagger UI. */
|
|
58
|
+
swaggerSpecUrl?: string;
|
|
59
|
+
/** The returned content is an API or specification substituted for the page. */
|
|
60
|
+
representationFallback?: "packit-api" | "swagger-spec";
|
|
48
61
|
}
|
|
49
62
|
|
|
50
63
|
/**
|
package/src/document/evidence.ts
CHANGED
|
@@ -83,7 +83,14 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
|
|
|
83
83
|
const { document } = parseHTML(raw);
|
|
84
84
|
const anubisText = [...document.childNodes].map((node) => node.textContent ?? "").join(" ");
|
|
85
85
|
|
|
86
|
+
const redditChallenge =
|
|
87
|
+
markdown.trim().length < CAPTCHA_CHALLENGE_MAX_MARKDOWN_CHARACTERS &&
|
|
88
|
+
/<input\b[^>]*\bname\s*=\s*["']js_challenge["']/i.test(raw) &&
|
|
89
|
+
/<input\b[^>]*\bname\s*=\s*["']jsc_token["']/i.test(raw) &&
|
|
90
|
+
/<input\b[^>]*\bname\s*=\s*["']solution["']/i.test(raw);
|
|
91
|
+
|
|
86
92
|
const captchaChallenge =
|
|
93
|
+
redditChallenge ||
|
|
87
94
|
CAPTCHA_LOADER_MARKERS.some((marker) => marker.test(raw)) ||
|
|
88
95
|
(markdown.trim().length < CAPTCHA_CHALLENGE_MAX_MARKDOWN_CHARACTERS &&
|
|
89
96
|
CAPTCHA_WIDGET_MARKERS.some((marker) => marker.test(raw)));
|
package/src/document/extract.ts
CHANGED
|
@@ -164,6 +164,12 @@ export function htmlToMarkdownFallback(html: string): string {
|
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
+
for (const element of document.body.querySelectorAll(
|
|
168
|
+
"p, div, section, article, li, blockquote, pre, h1, h2, h3, h4, h5, h6, br, tr",
|
|
169
|
+
)) {
|
|
170
|
+
element.after(document.createTextNode("\n\n"));
|
|
171
|
+
}
|
|
172
|
+
|
|
167
173
|
return document.body.textContent
|
|
168
174
|
.replace(/[ \t]+\n/g, "\n")
|
|
169
175
|
.replace(/\n[ \t]+/g, "\n")
|
|
@@ -259,6 +265,37 @@ function stripChromeWrappers(document: Document, baseUrl: URL): void {
|
|
|
259
265
|
}
|
|
260
266
|
}
|
|
261
267
|
|
|
268
|
+
/** Restricts GitHub repository roots to their rendered README, when available. */
|
|
269
|
+
function isolateGitHubReadme(document: Document, baseUrl: URL): boolean {
|
|
270
|
+
if (baseUrl.hostname !== "github.com" || baseUrl.pathname.split("/").filter(Boolean).length !== 2)
|
|
271
|
+
return false;
|
|
272
|
+
|
|
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
|
+
}
|
|
289
|
+
|
|
290
|
+
if (!readme || !readme.textContent?.trim()) return false;
|
|
291
|
+
|
|
292
|
+
const main = document.createElement("main");
|
|
293
|
+
main.appendChild(readme);
|
|
294
|
+
document.body.replaceChildren(main);
|
|
295
|
+
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
|
|
262
299
|
/**
|
|
263
300
|
* Collapses consecutive duplicate markdown link lines (e.g. duplicated [Latest] on GitHub releases).
|
|
264
301
|
*
|
|
@@ -416,7 +453,7 @@ function readAdvertisedLinks(
|
|
|
416
453
|
* @returns The extracted Markdown, optional title, extractor used, and advertised discovery links
|
|
417
454
|
* @throws When markup exceeds the safe conversion depth
|
|
418
455
|
*/
|
|
419
|
-
|
|
456
|
+
async function extractHtmlDocument(
|
|
420
457
|
html: string,
|
|
421
458
|
baseUrl: URL,
|
|
422
459
|
): Promise<{
|
|
@@ -426,10 +463,13 @@ export async function extractHtmlToMarkdown(
|
|
|
426
463
|
fragmentOffsets?: Record<string, number>;
|
|
427
464
|
describedByLink?: string;
|
|
428
465
|
markdownAlternateLink?: string;
|
|
466
|
+
githubReadme?: boolean;
|
|
429
467
|
}> {
|
|
430
468
|
// Keep refusal outside the catch: the fallback also constructs a DOM.
|
|
431
469
|
assertConversionDepth(html);
|
|
432
470
|
let advertised: AdvertisedLinks = {};
|
|
471
|
+
let fallbackHtml = html;
|
|
472
|
+
let githubReadme = false;
|
|
433
473
|
|
|
434
474
|
try {
|
|
435
475
|
assertAbsoluteHttpUrl(baseUrl);
|
|
@@ -446,9 +486,13 @@ export async function extractHtmlToMarkdown(
|
|
|
446
486
|
originalIds.set(element, element.id);
|
|
447
487
|
}
|
|
448
488
|
|
|
449
|
-
normalizeSelectorUnsafeIds(document);
|
|
450
489
|
stripChromeWrappers(document, baseUrl);
|
|
451
490
|
advertised = readAdvertisedLinks(document, baseUrl);
|
|
491
|
+
|
|
492
|
+
githubReadme = isolateGitHubReadme(document, baseUrl);
|
|
493
|
+
|
|
494
|
+
if (githubReadme) fallbackHtml = document.documentElement.outerHTML;
|
|
495
|
+
normalizeSelectorUnsafeIds(document);
|
|
452
496
|
// Pass the full absolute URL so Defuddle resolves relative links (e.g.
|
|
453
497
|
// `/owner/repo/releases`) and metadata against the real origin instead of
|
|
454
498
|
// dropping the scheme and host and constructing `new URL(pathname)`.
|
|
@@ -465,6 +509,7 @@ export async function extractHtmlToMarkdown(
|
|
|
465
509
|
markdown,
|
|
466
510
|
title: trimmedTitle || undefined,
|
|
467
511
|
extractor: "defuddle",
|
|
512
|
+
githubReadme,
|
|
468
513
|
fragmentOffsets: buildFragmentOffsets(document, markdown, originalIds),
|
|
469
514
|
...advertised,
|
|
470
515
|
};
|
|
@@ -473,11 +518,11 @@ export async function extractHtmlToMarkdown(
|
|
|
473
518
|
// Fall through to the basic converter for malformed or unsupported pages.
|
|
474
519
|
}
|
|
475
520
|
|
|
476
|
-
const fallbackMarkdown = stripExtractedCssCruft(htmlToMarkdownFallback(
|
|
521
|
+
const fallbackMarkdown = stripExtractedCssCruft(htmlToMarkdownFallback(fallbackHtml));
|
|
477
522
|
let fragmentOffsets: Record<string, number> = {};
|
|
478
523
|
|
|
479
524
|
try {
|
|
480
|
-
fragmentOffsets = buildFragmentOffsets(parseHTML(
|
|
525
|
+
fragmentOffsets = buildFragmentOffsets(parseHTML(fallbackHtml).document, fallbackMarkdown);
|
|
481
526
|
} catch {
|
|
482
527
|
// Malformed HTML has already been reduced to plain text; no anchors are available.
|
|
483
528
|
}
|
|
@@ -485,7 +530,142 @@ export async function extractHtmlToMarkdown(
|
|
|
485
530
|
return {
|
|
486
531
|
markdown: fallbackMarkdown,
|
|
487
532
|
extractor: "basic",
|
|
533
|
+
githubReadme,
|
|
488
534
|
fragmentOffsets,
|
|
489
535
|
...advertised,
|
|
490
536
|
};
|
|
491
537
|
}
|
|
538
|
+
|
|
539
|
+
/** Select only an explicitly requested, unambiguous surface control and sibling panes. */
|
|
540
|
+
function selectSurfaceHtml(
|
|
541
|
+
html: string,
|
|
542
|
+
url: URL,
|
|
543
|
+
): { html: string; selected: string; omitted: number } | undefined {
|
|
544
|
+
const values = url.searchParams.getAll("tab");
|
|
545
|
+
|
|
546
|
+
if (values.length !== 1 || !/^[a-z0-9-]{1,40}$/u.test(values[0])) return undefined;
|
|
547
|
+
const selected = values[0];
|
|
548
|
+
const { document } = parseHTML(html);
|
|
549
|
+
normalizeFragmentDocument(document);
|
|
550
|
+
const candidates: Array<{ panes: Element[]; chosen: Element }> = [];
|
|
551
|
+
|
|
552
|
+
// Standard ARIA controls identify their panels by ID. The query value must
|
|
553
|
+
// match a control ID or panel ID exactly; labels are not URL identifiers.
|
|
554
|
+
for (const group of document.querySelectorAll('[role="tablist"]')) {
|
|
555
|
+
const controls = [...group.querySelectorAll('[role="tab"]')].filter(
|
|
556
|
+
(control) => control.closest('[role="tablist"]') === group,
|
|
557
|
+
);
|
|
558
|
+
|
|
559
|
+
if (controls.length < 2 || controls.length > 20) continue;
|
|
560
|
+
const ids = controls.map((control) => control.getAttribute("aria-controls") ?? "");
|
|
561
|
+
|
|
562
|
+
if (ids.some((id) => !id || /\s/u.test(id)) || new Set(ids).size !== ids.length) continue;
|
|
563
|
+
|
|
564
|
+
const panes = ids.map((id) => {
|
|
565
|
+
const matches = [...document.querySelectorAll('[role="tabpanel"][id]')].filter(
|
|
566
|
+
(pane) => pane.getAttribute("id") === id,
|
|
567
|
+
);
|
|
568
|
+
|
|
569
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
if (panes.some((pane) => !pane)) continue;
|
|
573
|
+
|
|
574
|
+
const matched = controls.flatMap((control, i) =>
|
|
575
|
+
control.id === selected || ids[i] === selected ? [i] : [],
|
|
576
|
+
);
|
|
577
|
+
|
|
578
|
+
if (matched.length !== 1) continue;
|
|
579
|
+
const resolved = panes.filter((pane): pane is Element => pane !== undefined);
|
|
580
|
+
|
|
581
|
+
if (resolved.some((pane) => pane.parentElement !== resolved[0].parentElement)) continue;
|
|
582
|
+
candidates.push({ panes: resolved, chosen: resolved[matched[0]] });
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// Some sites use their own explicit surface IDs instead of ARIA references.
|
|
586
|
+
const groups = [...document.querySelectorAll("[data-surface-filter-pills]")];
|
|
587
|
+
const surfacePanes = [...document.querySelectorAll("[data-surface-pane]")];
|
|
588
|
+
|
|
589
|
+
if (groups.length === 1 && surfacePanes.length >= 2 && surfacePanes.length <= 20) {
|
|
590
|
+
const controls = [...groups[0].querySelectorAll('[role="tab"][data-surface-id]')];
|
|
591
|
+
const ids = controls.map((control) => control.getAttribute("data-surface-id"));
|
|
592
|
+
const paneIds = surfacePanes.map((pane) => pane.getAttribute("data-surface-pane"));
|
|
593
|
+
const chosen = surfacePanes.find((pane) => pane.getAttribute("data-surface-pane") === selected);
|
|
594
|
+
|
|
595
|
+
if (
|
|
596
|
+
controls.length === surfacePanes.length &&
|
|
597
|
+
new Set(ids).size === ids.length &&
|
|
598
|
+
new Set(paneIds).size === paneIds.length &&
|
|
599
|
+
ids.includes(selected) &&
|
|
600
|
+
chosen &&
|
|
601
|
+
ids.every((id) => id && paneIds.includes(id)) &&
|
|
602
|
+
surfacePanes.every((pane) => pane.parentElement === surfacePanes[0].parentElement)
|
|
603
|
+
)
|
|
604
|
+
candidates.push({ panes: surfacePanes, chosen });
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const unique = candidates.filter(
|
|
608
|
+
(candidate, index) =>
|
|
609
|
+
!candidates
|
|
610
|
+
.slice(0, index)
|
|
611
|
+
.some(
|
|
612
|
+
(previous) =>
|
|
613
|
+
previous.chosen === candidate.chosen &&
|
|
614
|
+
previous.panes.length === candidate.panes.length &&
|
|
615
|
+
previous.panes.every((pane) => candidate.panes.includes(pane)),
|
|
616
|
+
),
|
|
617
|
+
);
|
|
618
|
+
|
|
619
|
+
if (unique.length !== 1) return undefined;
|
|
620
|
+
const { panes, chosen } = unique[0];
|
|
621
|
+
|
|
622
|
+
if (!chosen?.textContent?.trim()) return undefined;
|
|
623
|
+
|
|
624
|
+
for (const pane of panes) if (pane !== chosen) pane.remove();
|
|
625
|
+
// The selected pane may be hidden by the server's default inline state.
|
|
626
|
+
chosen.removeAttribute("hidden");
|
|
627
|
+
chosen.removeAttribute("aria-hidden");
|
|
628
|
+
chosen.removeAttribute("style");
|
|
629
|
+
|
|
630
|
+
return { html: document.documentElement.outerHTML, selected, omitted: panes.length - 1 };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** Extract the complete page and, when explicitly requested, a separate surface view. */
|
|
634
|
+
export async function extractHtmlToMarkdown(
|
|
635
|
+
html: string,
|
|
636
|
+
baseUrl: URL,
|
|
637
|
+
): Promise<
|
|
638
|
+
Awaited<ReturnType<typeof extractHtmlDocument>> & {
|
|
639
|
+
surfaceView?: {
|
|
640
|
+
selected: string;
|
|
641
|
+
omitted: number;
|
|
642
|
+
markdown: string;
|
|
643
|
+
fragmentOffsets?: Record<string, number>;
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
> {
|
|
647
|
+
assertConversionDepth(html);
|
|
648
|
+
const complete = await extractHtmlDocument(html, baseUrl);
|
|
649
|
+
|
|
650
|
+
try {
|
|
651
|
+
const surface = selectSurfaceHtml(html, baseUrl);
|
|
652
|
+
|
|
653
|
+
if (!surface) return complete;
|
|
654
|
+
const view = await extractHtmlDocument(surface.html, baseUrl);
|
|
655
|
+
|
|
656
|
+
if (!view.markdown.trim()) return complete;
|
|
657
|
+
|
|
658
|
+
return {
|
|
659
|
+
...complete,
|
|
660
|
+
surfaceView: {
|
|
661
|
+
selected: surface.selected,
|
|
662
|
+
omitted: surface.omitted,
|
|
663
|
+
markdown: view.markdown,
|
|
664
|
+
fragmentOffsets: view.fragmentOffsets,
|
|
665
|
+
},
|
|
666
|
+
};
|
|
667
|
+
} catch {
|
|
668
|
+
// A derived view must never make an otherwise readable page unavailable.
|
|
669
|
+
return complete;
|
|
670
|
+
}
|
|
671
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -79,14 +79,14 @@ export const webFetchParameters = Type.Object({
|
|
|
79
79
|
Type.String({
|
|
80
80
|
minLength: 1,
|
|
81
81
|
maxLength: FETCH_MAX_QUERY_CHARACTERS,
|
|
82
|
-
description: "
|
|
82
|
+
description: "Select page sections matching this text.",
|
|
83
83
|
}),
|
|
84
84
|
),
|
|
85
85
|
offset: Type.Optional(
|
|
86
86
|
Type.Integer({
|
|
87
87
|
minimum: 0,
|
|
88
88
|
maximum: FETCH_MAX_OFFSET_CHARACTERS,
|
|
89
|
-
description: "
|
|
89
|
+
description: "Continue at this character offset in the selected view.",
|
|
90
90
|
}),
|
|
91
91
|
),
|
|
92
92
|
});
|
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,12 @@ export async function executeWebFetch(
|
|
|
466
509
|
let fetched: CompleteDocument;
|
|
467
510
|
let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
|
|
468
511
|
|
|
469
|
-
if (
|
|
512
|
+
if (
|
|
513
|
+
stale?.validators &&
|
|
514
|
+
!stale.llmsTxtFallback &&
|
|
515
|
+
!stale.markdownAlternateFallback &&
|
|
516
|
+
!stale.representationFallback
|
|
517
|
+
) {
|
|
470
518
|
const outcome = await revalidateCompleteDocument(
|
|
471
519
|
sourceUrl,
|
|
472
520
|
stale,
|
|
@@ -506,6 +554,21 @@ export async function executeWebFetch(
|
|
|
506
554
|
links: undefined,
|
|
507
555
|
fragmentOffsets: undefined,
|
|
508
556
|
};
|
|
557
|
+
const canonicalMarkdown = document.markdown;
|
|
558
|
+
|
|
559
|
+
const surface =
|
|
560
|
+
!blocked && document.surfaceView
|
|
561
|
+
? { selected: document.surfaceView.selected, omitted: document.surfaceView.omitted }
|
|
562
|
+
: undefined;
|
|
563
|
+
|
|
564
|
+
if (surface && document.surfaceView) {
|
|
565
|
+
document = {
|
|
566
|
+
...document,
|
|
567
|
+
markdown: document.surfaceView.markdown,
|
|
568
|
+
fragmentOffsets: document.surfaceView.fragmentOffsets,
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
|
|
509
572
|
const resolvedFragment = resolveFragmentOffset(document, params.url);
|
|
510
573
|
const fragmentOffset = resolvedFragment.offset;
|
|
511
574
|
const fragmentMatched = resolvedFragment.fragment !== undefined && fragmentOffset !== undefined;
|
|
@@ -613,6 +676,12 @@ export async function executeWebFetch(
|
|
|
613
676
|
const output = blocked
|
|
614
677
|
? "Blocked by an anti-bot challenge. Requested page content is unavailable."
|
|
615
678
|
: [
|
|
679
|
+
...(result.representationFallback === "swagger-spec"
|
|
680
|
+
? [
|
|
681
|
+
`[Showing the advertised Swagger specification from ${finalUrl} instead of the requested page.]`,
|
|
682
|
+
"",
|
|
683
|
+
]
|
|
684
|
+
: []),
|
|
616
685
|
...(result.markdownAlternateFallback
|
|
617
686
|
? [
|
|
618
687
|
"[Page content was sparse; showing the site's advertised Markdown version instead.]",
|
|
@@ -637,6 +706,12 @@ export async function executeWebFetch(
|
|
|
637
706
|
"",
|
|
638
707
|
]
|
|
639
708
|
: []),
|
|
709
|
+
...(surface
|
|
710
|
+
? [
|
|
711
|
+
`[Showing tab "${surface.selected}"; ${surface.omitted} other tabs omitted. Continuation offsets apply to this view.]`,
|
|
712
|
+
"",
|
|
713
|
+
]
|
|
714
|
+
: []),
|
|
640
715
|
...(fragmentMatched ? ["[Starting at the requested URL fragment.]", ""] : []),
|
|
641
716
|
...(focused
|
|
642
717
|
? [
|
|
@@ -646,16 +721,44 @@ export async function executeWebFetch(
|
|
|
646
721
|
"",
|
|
647
722
|
]
|
|
648
723
|
: []),
|
|
649
|
-
result.markdown ||
|
|
724
|
+
result.markdown ||
|
|
725
|
+
(focused
|
|
726
|
+
? ""
|
|
727
|
+
: result.extractionDiagnostics?.javascriptRequired
|
|
728
|
+
? "[This page requires JavaScript; its content could not be retrieved.]"
|
|
729
|
+
: "[The page contained no readable text.]"),
|
|
650
730
|
].join("\n");
|
|
651
731
|
|
|
652
|
-
|
|
732
|
+
let outputTruncation = truncateHead(output, {
|
|
653
733
|
maxLines: DEFAULT_MAX_LINES,
|
|
654
734
|
maxBytes: DEFAULT_MAX_BYTES,
|
|
655
735
|
});
|
|
656
736
|
|
|
737
|
+
if (showLlmsNotice && result.llmsTxtIndexUrl) {
|
|
738
|
+
const indexUrl = redactUrlForDisplay(result.llmsTxtIndexUrl);
|
|
739
|
+
const notice = `Index: ${indexUrl}\n\n`;
|
|
740
|
+
const noticePosition = outputTruncation.content.indexOf(notice);
|
|
741
|
+
|
|
742
|
+
if (
|
|
743
|
+
noticePosition !== -1 &&
|
|
744
|
+
([indexUrl, ...(result.llmsTxtIndexAliases ?? []).map(redactUrlForDisplay)].some((url) =>
|
|
745
|
+
outputTruncation.content.slice(noticePosition + notice.length).includes(url),
|
|
746
|
+
) ||
|
|
747
|
+
hasVisibleIndexLink(
|
|
748
|
+
outputTruncation.content.slice(noticePosition + notice.length),
|
|
749
|
+
rawFinalUrl,
|
|
750
|
+
[result.llmsTxtIndexUrl, ...(result.llmsTxtIndexAliases ?? [])],
|
|
751
|
+
))
|
|
752
|
+
) {
|
|
753
|
+
outputTruncation = truncateHead(output.replace(notice, ""), {
|
|
754
|
+
maxLines: DEFAULT_MAX_LINES,
|
|
755
|
+
maxBytes: DEFAULT_MAX_BYTES,
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
657
760
|
const truncated = result.truncated || outputTruncation.truncated;
|
|
658
|
-
const outline = createDocumentOutline(
|
|
761
|
+
const outline = createDocumentOutline(canonicalMarkdown);
|
|
659
762
|
|
|
660
763
|
const structured: WebFetchStructuredOutput = {
|
|
661
764
|
requestedUrl,
|
|
@@ -675,8 +778,10 @@ export async function executeWebFetch(
|
|
|
675
778
|
characterCount: 0,
|
|
676
779
|
llmsTxtFallback: Boolean(result.llmsTxtFallback),
|
|
677
780
|
markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
|
|
781
|
+
representationFallback: result.representationFallback,
|
|
678
782
|
extraction: result.extractionDiagnostics,
|
|
679
783
|
focus: focused?.details,
|
|
784
|
+
surface,
|
|
680
785
|
outline: {
|
|
681
786
|
totalWords: outline.totalWords,
|
|
682
787
|
totalHeadings: outline.totalHeadings,
|
|
@@ -733,8 +838,10 @@ export async function executeWebFetch(
|
|
|
733
838
|
confidence,
|
|
734
839
|
outline,
|
|
735
840
|
focus: focused?.details,
|
|
841
|
+
surface,
|
|
736
842
|
llmsTxtFallback: Boolean(result.llmsTxtFallback),
|
|
737
843
|
markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
|
|
844
|
+
representationFallback: result.representationFallback,
|
|
738
845
|
llmsTxtUrl:
|
|
739
846
|
result.llmsTxtIndexUrl === undefined
|
|
740
847
|
? undefined
|