@zeldrisho/pi-web-fetch 0.16.2 → 0.16.4
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 +19 -1
- package/README.md +6 -6
- package/package.json +3 -3
- package/src/acquisition/admission.ts +61 -0
- package/src/acquisition/fetch.ts +19 -10
- package/src/challenges/anubis.ts +1 -1
- package/src/document/content.ts +1 -1
- package/src/document/focus.ts +195 -15
- package/src/index.ts +15 -1
- package/src/network/network-redirects.ts +15 -9
- package/src/render.ts +1 -1
- package/src/service.ts +12 -11
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.16.4] - 2026-11-09
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Close unused redirect and error responses promptly, including stalled responses.
|
|
15
|
+
- Avoid retrying before a server's longer requested delay.
|
|
16
|
+
- Bound concurrent page acquisitions, including slow downloads, and reject requests when the waiting queue is full.
|
|
17
|
+
|
|
18
|
+
## [0.16.3] - 2026-11-01
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- Improve focus queries for identifiers, common words, word variants, HTML headings, and oversized content.
|
|
23
|
+
- Keep fragment-focused continuation offsets on the same view.
|
|
24
|
+
- Shorten focus, error, fallback, and end-of-results notices.
|
|
25
|
+
|
|
10
26
|
## [0.16.2] - 2026-10-30
|
|
11
27
|
|
|
12
28
|
### Changed
|
|
@@ -308,7 +324,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
308
324
|
|
|
309
325
|
- Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
|
|
310
326
|
|
|
311
|
-
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.
|
|
327
|
+
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...HEAD
|
|
328
|
+
[0.16.4]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.3...pi-web-fetch-v0.16.4
|
|
329
|
+
[0.16.3]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.2...pi-web-fetch-v0.16.3
|
|
312
330
|
[0.16.2]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.1...pi-web-fetch-v0.16.2
|
|
313
331
|
[0.16.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.0...pi-web-fetch-v0.16.1
|
|
314
332
|
[0.16.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.15.0...pi-web-fetch-v0.16.0
|
package/README.md
CHANGED
|
@@ -17,13 +17,13 @@ Use `pi config` to enable or disable the extension, and `pi list` to see configu
|
|
|
17
17
|
|
|
18
18
|
The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markdown, plain text, JSON, and XML. HTML is converted to Markdown; images are omitted. Minified JavaScript, JSON, and YAML are returned as indented code blocks so long single-line payloads stay readable. URLs with credentials, local or private network targets, unsafe redirects, downloads over 5 MiB, and unsupported content types are rejected.
|
|
19
19
|
|
|
20
|
-
| Parameter | Description
|
|
21
|
-
| --------- |
|
|
22
|
-
| `url` | Required page URL. URL fragments can start output at a matching heading or anchor.
|
|
23
|
-
| `query` | Optional; selects matching sections from a long page. Sections remain in source order.
|
|
24
|
-
| `offset` | Optional character offset for continuing through extracted content; takes precedence over
|
|
20
|
+
| Parameter | Description |
|
|
21
|
+
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| `url` | Required page URL. URL fragments can start output at a matching heading or anchor. |
|
|
23
|
+
| `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
|
|
24
|
+
| `offset` | Optional character offset for continuing through extracted content. With a query and fragment, offsets apply to the fragment-focused view; otherwise, an offset takes precedence over the fragment. |
|
|
25
25
|
|
|
26
|
-
Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` to continue. Use `query` to focus on matching sections, or omit it to read the complete document. Pi's preview is collapsed by default; press `Ctrl+O` to expand it.
|
|
26
|
+
Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` to continue with the same URL and query. Use `query` to focus on matching sections, or omit it to read the complete document. 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
27
|
|
|
28
28
|
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
29
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zeldrisho/pi-web-fetch",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.4",
|
|
4
4
|
"description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi",
|
|
@@ -41,8 +41,8 @@
|
|
|
41
41
|
"@earendil-works/pi-tui": "^1.4.0",
|
|
42
42
|
"typebox": "^1.4.2",
|
|
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.4.0",
|
|
45
|
+
"vite-plus": "1.4.0"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
48
|
"@earendil-works/pi-coding-agent": "*",
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Limits complete acquisitions, including slow response bodies and extraction. */
|
|
2
|
+
export class AcquisitionAdmission {
|
|
3
|
+
#active = 0;
|
|
4
|
+
readonly #waiting: Array<() => void> = [];
|
|
5
|
+
|
|
6
|
+
constructor(
|
|
7
|
+
readonly maxActive: number,
|
|
8
|
+
readonly maxWaiting: number,
|
|
9
|
+
) {}
|
|
10
|
+
|
|
11
|
+
async acquire(signal: AbortSignal): Promise<() => void> {
|
|
12
|
+
signal.throwIfAborted();
|
|
13
|
+
|
|
14
|
+
if (this.#active >= this.maxActive) {
|
|
15
|
+
if (this.#waiting.length >= this.maxWaiting) {
|
|
16
|
+
throw new Error("web_fetch is busy; too many requests are waiting.");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
await new Promise<void>((resolve, reject) => {
|
|
20
|
+
const enter = () => {
|
|
21
|
+
signal.removeEventListener("abort", cancel);
|
|
22
|
+
this.#active += 1;
|
|
23
|
+
resolve();
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const cancel = () => {
|
|
27
|
+
const index = this.#waiting.indexOf(enter);
|
|
28
|
+
|
|
29
|
+
if (index >= 0) this.#waiting.splice(index, 1);
|
|
30
|
+
reject(signal.reason);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
this.#waiting.push(enter);
|
|
34
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
35
|
+
|
|
36
|
+
if (signal.aborted) cancel();
|
|
37
|
+
});
|
|
38
|
+
} else {
|
|
39
|
+
this.#active += 1;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let released = false;
|
|
43
|
+
|
|
44
|
+
const release = () => {
|
|
45
|
+
if (released) return;
|
|
46
|
+
released = true;
|
|
47
|
+
this.#active -= 1;
|
|
48
|
+
this.#waiting.shift()?.();
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
if (signal.aborted) {
|
|
52
|
+
release();
|
|
53
|
+
signal.throwIfAborted();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return release;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Bound worst-case concurrent downloads without serializing normal subagent use. */
|
|
61
|
+
export const acquisitionAdmission = new AcquisitionAdmission(16, 128);
|
package/src/acquisition/fetch.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import { acquisitionAdmission } from "./admission.ts";
|
|
2
3
|
import {
|
|
3
4
|
lineFragmentOffsets,
|
|
4
5
|
markdownFragmentOffsets,
|
|
@@ -202,7 +203,7 @@ function assertSuccessfulResponse(response: IncomingMessage): void {
|
|
|
202
203
|
const status = response.statusCode ?? 0;
|
|
203
204
|
|
|
204
205
|
if (isAwsWafChallengeResponse(response)) {
|
|
205
|
-
response.
|
|
206
|
+
response.destroy();
|
|
206
207
|
throw new ChallengeBlockedError(
|
|
207
208
|
`web_fetch was blocked by an AWS WAF anti-bot challenge (HTTP ${status}).`,
|
|
208
209
|
);
|
|
@@ -213,7 +214,7 @@ function assertSuccessfulResponse(response: IncomingMessage): void {
|
|
|
213
214
|
const cloudflareChallenge =
|
|
214
215
|
responseHeader(response, "cf-mitigated")?.trim().toLowerCase() === "challenge";
|
|
215
216
|
|
|
216
|
-
response.
|
|
217
|
+
response.destroy();
|
|
217
218
|
|
|
218
219
|
if (cloudflareChallenge) {
|
|
219
220
|
throw new ChallengeBlockedError(
|
|
@@ -221,11 +222,14 @@ function assertSuccessfulResponse(response: IncomingMessage): void {
|
|
|
221
222
|
);
|
|
222
223
|
}
|
|
223
224
|
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
225
|
+
const hint =
|
|
226
|
+
status === 404
|
|
227
|
+
? " Page not found or inaccessible."
|
|
228
|
+
: status === 401 || status === 403
|
|
229
|
+
? " Access denied or authentication required."
|
|
230
|
+
: "";
|
|
227
231
|
|
|
228
|
-
throw new Error(`
|
|
232
|
+
throw new Error(`HTTP ${status}.${hint}`);
|
|
229
233
|
}
|
|
230
234
|
|
|
231
235
|
/**
|
|
@@ -566,6 +570,9 @@ async function fetchDocument(
|
|
|
566
570
|
|
|
567
571
|
const cancel = () => controller.abort();
|
|
568
572
|
signal?.addEventListener("abort", cancel, { once: true });
|
|
573
|
+
|
|
574
|
+
if (signal?.aborted) cancel();
|
|
575
|
+
let release: (() => void) | undefined;
|
|
569
576
|
const conditionalHeaders: Record<string, string> = {};
|
|
570
577
|
|
|
571
578
|
if (cached?.validators?.etag) conditionalHeaders["If-None-Match"] = cached.validators.etag;
|
|
@@ -581,6 +588,7 @@ async function fetchDocument(
|
|
|
581
588
|
};
|
|
582
589
|
|
|
583
590
|
try {
|
|
591
|
+
release = await acquisitionAdmission.acquire(controller.signal);
|
|
584
592
|
const requestUrl = normalizeGitHubRawUrl(rawUrl);
|
|
585
593
|
|
|
586
594
|
let { target, response } = await requestFollowingRedirects(
|
|
@@ -597,7 +605,7 @@ async function fetchDocument(
|
|
|
597
605
|
// for one exact representation opt out: HTML from that URL is never the
|
|
598
606
|
// representation they are looking for.
|
|
599
607
|
if (retryRepresentationMiss && [404, 406].includes(response.statusCode ?? 0)) {
|
|
600
|
-
response.
|
|
608
|
+
response.destroy();
|
|
601
609
|
({ target, response } = await requestFollowingRedirects(
|
|
602
610
|
target.url,
|
|
603
611
|
controller.signal,
|
|
@@ -613,7 +621,7 @@ async function fetchDocument(
|
|
|
613
621
|
const fallbackUrl = npmRegistryFallbackUrl(rawUrl);
|
|
614
622
|
|
|
615
623
|
if (fallbackUrl) {
|
|
616
|
-
response.
|
|
624
|
+
response.destroy();
|
|
617
625
|
({ target, response } = await requestFollowingRedirects(
|
|
618
626
|
fallbackUrl,
|
|
619
627
|
controller.signal,
|
|
@@ -629,7 +637,7 @@ async function fetchDocument(
|
|
|
629
637
|
const resolver = requestDependencies.awsWafResolver ?? nativeAwsWafResolver;
|
|
630
638
|
|
|
631
639
|
if (resolver) {
|
|
632
|
-
response.
|
|
640
|
+
response.destroy();
|
|
633
641
|
|
|
634
642
|
const solution = await resolveAwsWafToken(
|
|
635
643
|
resolver,
|
|
@@ -665,7 +673,7 @@ async function fetchDocument(
|
|
|
665
673
|
}
|
|
666
674
|
|
|
667
675
|
if (response.statusCode === 304 && cached) {
|
|
668
|
-
response.
|
|
676
|
+
response.destroy();
|
|
669
677
|
const etag = responseHeader(response, "etag") ?? cached.validators?.etag;
|
|
670
678
|
|
|
671
679
|
const lastModified =
|
|
@@ -699,6 +707,7 @@ async function fetchDocument(
|
|
|
699
707
|
if (signal?.aborted) throw new Error("web_fetch was cancelled.");
|
|
700
708
|
throw error;
|
|
701
709
|
} finally {
|
|
710
|
+
release?.();
|
|
702
711
|
clearTimeout(timeout);
|
|
703
712
|
signal?.removeEventListener("abort", cancel);
|
|
704
713
|
}
|
package/src/challenges/anubis.ts
CHANGED
|
@@ -394,7 +394,7 @@ async function fetchWasmModule(
|
|
|
394
394
|
const status = response.statusCode ?? 0;
|
|
395
395
|
|
|
396
396
|
if (status < 200 || status >= 300) {
|
|
397
|
-
response.
|
|
397
|
+
response.destroy();
|
|
398
398
|
throw new Error(`web_fetch could not download the Anubis challenge module (HTTP ${status}).`);
|
|
399
399
|
}
|
|
400
400
|
|
package/src/document/content.ts
CHANGED
|
@@ -119,7 +119,7 @@ export function sliceCompleteDocument(
|
|
|
119
119
|
if (truncated) {
|
|
120
120
|
markdown += `\n\n[Content truncated. Continue with offset=${end} to read the next chunk.]`;
|
|
121
121
|
} else if (offset > 0) {
|
|
122
|
-
markdown += "\n\n[End of
|
|
122
|
+
markdown += "\n\n[End of results.]";
|
|
123
123
|
}
|
|
124
124
|
|
|
125
125
|
return {
|
package/src/document/focus.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const WORD_PATTERN = /[\p{L}\p{N}_+#]+/gu;
|
|
2
2
|
|
|
3
|
-
const HEADING_PATTERN =
|
|
3
|
+
const HEADING_PATTERN = /^(?:#{1,6}\s+\S| {0,3}<h[1-6](?:\s[^>]*|)>)/i;
|
|
4
4
|
|
|
5
5
|
/** Metadata describing deterministic query-focused extraction. */
|
|
6
6
|
export interface FocusDetails {
|
|
@@ -35,18 +35,95 @@ const WINDOW_TARGET_CHARACTERS = 8_000;
|
|
|
35
35
|
const WINDOW_MIN_LINES = 80;
|
|
36
36
|
|
|
37
37
|
/** Fewest characters a headingless block needs before it is split into windows. */
|
|
38
|
-
const WINDOW_MIN_CHARACTERS =
|
|
38
|
+
const WINDOW_MIN_CHARACTERS = 6_000;
|
|
39
|
+
|
|
40
|
+
const STOP_WORDS = new Set([
|
|
41
|
+
"a",
|
|
42
|
+
"an",
|
|
43
|
+
"and",
|
|
44
|
+
"are",
|
|
45
|
+
"for",
|
|
46
|
+
"how",
|
|
47
|
+
"in",
|
|
48
|
+
"is",
|
|
49
|
+
"of",
|
|
50
|
+
"on",
|
|
51
|
+
"the",
|
|
52
|
+
"to",
|
|
53
|
+
"with",
|
|
54
|
+
]);
|
|
39
55
|
|
|
40
56
|
function tokens(value: string): string[] {
|
|
41
|
-
return (value.toLowerCase().match(WORD_PATTERN) ?? []).
|
|
57
|
+
return (value.toLowerCase().match(WORD_PATTERN) ?? []).map((token) => {
|
|
58
|
+
let word = token;
|
|
59
|
+
|
|
60
|
+
if (word.length > 5 && /(?:ss|ch|sh|x|z)es$/.test(word)) word = word.slice(0, -2);
|
|
61
|
+
else if (word.length > 4 && word.endsWith("s") && !word.endsWith("ss"))
|
|
62
|
+
word = word.slice(0, -1);
|
|
63
|
+
|
|
64
|
+
if (word.length > 6 && word.endsWith("ion")) return word.slice(0, -3);
|
|
65
|
+
|
|
66
|
+
if (word.length > 4 && /(?:ing|ed)$/.test(word)) return word.replace(/(?:ing|ed)$/, "");
|
|
67
|
+
|
|
68
|
+
if (word.length > 4 && /(?:ch|sh|v)e$/.test(word)) return word.slice(0, -1);
|
|
69
|
+
|
|
70
|
+
return word;
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function containsIdentifier(markdown: string, identifier: string): boolean {
|
|
75
|
+
const text = markdown.toLowerCase();
|
|
76
|
+
let index = text.indexOf(identifier);
|
|
77
|
+
|
|
78
|
+
while (index !== -1) {
|
|
79
|
+
const before = text[index - 1] ?? "";
|
|
80
|
+
const after = text[index + identifier.length] ?? "";
|
|
81
|
+
|
|
82
|
+
const beforeWord =
|
|
83
|
+
/[\p{L}\p{N}_+#-]/u.test(before) ||
|
|
84
|
+
(before === "." && /[\p{L}\p{N}]/u.test(text[index - 2] ?? ""));
|
|
85
|
+
|
|
86
|
+
const afterWord =
|
|
87
|
+
/[\p{L}\p{N}_+#-]/u.test(after) ||
|
|
88
|
+
(after === "." && /[\p{L}\p{N}]/u.test(text[index + identifier.length + 1] ?? ""));
|
|
89
|
+
|
|
90
|
+
if (!beforeWord && !afterWord) return true;
|
|
91
|
+
index = text.indexOf(identifier, index + 1);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Split long lines at whitespace without breaking identifiers or surrogate pairs. */
|
|
98
|
+
function splitLongLine(line: string): string[] {
|
|
99
|
+
const parts: string[] = [];
|
|
100
|
+
let start = 0;
|
|
101
|
+
const target = WINDOW_TARGET_CHARACTERS / 2;
|
|
102
|
+
|
|
103
|
+
while (line.length - start > target) {
|
|
104
|
+
let end = start + target;
|
|
105
|
+
|
|
106
|
+
while (end > start && !/\s/u.test(line[end])) end -= 1;
|
|
107
|
+
|
|
108
|
+
if (end === start) {
|
|
109
|
+
end = start + target;
|
|
110
|
+
|
|
111
|
+
while (end < line.length && !/\s/u.test(line[end])) end += 1;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (end >= line.length) break;
|
|
115
|
+
parts.push(line.slice(start, end));
|
|
116
|
+
start = end;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (start < line.length) parts.push(line.slice(start));
|
|
120
|
+
|
|
121
|
+
return parts;
|
|
42
122
|
}
|
|
43
123
|
|
|
44
124
|
/**
|
|
45
|
-
* Splits
|
|
46
|
-
*
|
|
47
|
-
* Formatted source and log files have neither headings nor blank lines, so treating the
|
|
48
|
-
* whole body as a single section would make focus select everything. Windows are bounded
|
|
49
|
-
* by characters but never cut a line, and short blocks keep their single section.
|
|
125
|
+
* Splits headingless blocks into line-aligned windows, splitting long lines at
|
|
126
|
+
* whitespace when possible. Unbroken tokens stay intact even if oversized.
|
|
50
127
|
*/
|
|
51
128
|
function splitIntoWindows(block: string): string[] {
|
|
52
129
|
const lines = block.split(/\r?\n/);
|
|
@@ -58,6 +135,15 @@ function splitIntoWindows(block: string): string[] {
|
|
|
58
135
|
let size = 0;
|
|
59
136
|
|
|
60
137
|
for (const line of lines) {
|
|
138
|
+
if (line.length > WINDOW_TARGET_CHARACTERS / 2) {
|
|
139
|
+
if (current.length) windows.push(current.join("\n"));
|
|
140
|
+
current = [];
|
|
141
|
+
size = 0;
|
|
142
|
+
|
|
143
|
+
windows.push(...splitLongLine(line));
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
|
|
61
147
|
if (size > 0 && size + line.length + 1 > WINDOW_TARGET_CHARACTERS) {
|
|
62
148
|
windows.push(current.join("\n"));
|
|
63
149
|
current = [];
|
|
@@ -134,9 +220,41 @@ function splitSections(markdown: string): SplitSections {
|
|
|
134
220
|
const hasHeadings = headingLines.some(Boolean);
|
|
135
221
|
|
|
136
222
|
if (!hasHeadings) {
|
|
137
|
-
//
|
|
223
|
+
// Split mixed prose and fenced blocks only at blank lines outside fences.
|
|
138
224
|
if (lines.some((line) => /^[ \t]{0,3}(`{3,}|~{3,})/.test(line))) {
|
|
139
|
-
|
|
225
|
+
const parts: string[] = [];
|
|
226
|
+
let current: string[] = [];
|
|
227
|
+
let fence: { marker: string; length: number } | undefined;
|
|
228
|
+
|
|
229
|
+
for (const line of lines) {
|
|
230
|
+
const match = /^[ \t]{0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
|
231
|
+
|
|
232
|
+
if (match) {
|
|
233
|
+
if (!fence) fence = { marker: match[1][0], length: match[1].length };
|
|
234
|
+
else if (
|
|
235
|
+
match[1][0] === fence.marker &&
|
|
236
|
+
match[1].length >= fence.length &&
|
|
237
|
+
!match[2].trim()
|
|
238
|
+
)
|
|
239
|
+
fence = undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (!fence && !line.trim()) {
|
|
243
|
+
const part = current.join("\n").trim();
|
|
244
|
+
|
|
245
|
+
if (part) parts.push(part);
|
|
246
|
+
current = [];
|
|
247
|
+
} else current.push(line);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const part = current.join("\n").trim();
|
|
251
|
+
|
|
252
|
+
if (part) parts.push(part);
|
|
253
|
+
|
|
254
|
+
return {
|
|
255
|
+
sections: parts.map((part) => ({ markdown: part, tokens: tokens(part) })),
|
|
256
|
+
separator: "\n\n",
|
|
257
|
+
};
|
|
140
258
|
}
|
|
141
259
|
|
|
142
260
|
const windowed = blocks.flatMap(splitIntoWindows);
|
|
@@ -164,8 +282,55 @@ function splitSections(markdown: string): SplitSections {
|
|
|
164
282
|
|
|
165
283
|
flush();
|
|
166
284
|
|
|
285
|
+
// Split oversized sections at blank lines outside fences, so matches do not pull
|
|
286
|
+
// in an entire chapter. Keep the heading with its first content block.
|
|
287
|
+
const bounded = sections.flatMap((section) => {
|
|
288
|
+
if (section.length <= WINDOW_MIN_CHARACTERS) return [section];
|
|
289
|
+
const chunks: string[] = [];
|
|
290
|
+
let current: string[] = [];
|
|
291
|
+
let size = 0;
|
|
292
|
+
let inFence: { marker: string; length: number } | undefined;
|
|
293
|
+
|
|
294
|
+
for (const line of section.split("\n")) {
|
|
295
|
+
const match = /^[ \t]{0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
|
296
|
+
|
|
297
|
+
if (match) {
|
|
298
|
+
if (!inFence) inFence = { marker: match[1][0], length: match[1].length };
|
|
299
|
+
else if (
|
|
300
|
+
match[1][0] === inFence.marker &&
|
|
301
|
+
match[1].length >= inFence.length &&
|
|
302
|
+
!match[2].trim()
|
|
303
|
+
)
|
|
304
|
+
inFence = undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (!inFence && line.length > WINDOW_TARGET_CHARACTERS / 2) {
|
|
308
|
+
if (current.length) chunks.push(current.join("\n").trim());
|
|
309
|
+
current = [];
|
|
310
|
+
size = 0;
|
|
311
|
+
|
|
312
|
+
chunks.push(...splitLongLine(line));
|
|
313
|
+
} else if (!inFence && !line.trim() && size >= WINDOW_TARGET_CHARACTERS / 2) {
|
|
314
|
+
const chunk = current.join("\n").trim();
|
|
315
|
+
|
|
316
|
+
if (chunk) chunks.push(chunk);
|
|
317
|
+
current = [];
|
|
318
|
+
size = 0;
|
|
319
|
+
} else {
|
|
320
|
+
current.push(line);
|
|
321
|
+
size += line.length + 1;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const chunk = current.join("\n").trim();
|
|
326
|
+
|
|
327
|
+
if (chunk) chunks.push(chunk);
|
|
328
|
+
|
|
329
|
+
return chunks;
|
|
330
|
+
});
|
|
331
|
+
|
|
167
332
|
return {
|
|
168
|
-
sections:
|
|
333
|
+
sections: bounded.map((section) => ({ markdown: section, tokens: tokens(section) })),
|
|
169
334
|
separator: "\n\n",
|
|
170
335
|
};
|
|
171
336
|
}
|
|
@@ -177,11 +342,13 @@ function splitSections(markdown: string): SplitSections {
|
|
|
177
342
|
*/
|
|
178
343
|
export function focusMarkdown(markdown: string, query: string): FocusResult {
|
|
179
344
|
const normalizedQuery = query.trim();
|
|
180
|
-
const
|
|
345
|
+
const allTerms = [...new Set(tokens(normalizedQuery))];
|
|
346
|
+
const meaningfulTerms = allTerms.filter((term) => !STOP_WORDS.has(term));
|
|
347
|
+
const queryTerms = meaningfulTerms.length ? meaningfulTerms : allTerms;
|
|
181
348
|
const { sections, separator } = splitSections(markdown);
|
|
182
349
|
const originalCharacters = markdown.length;
|
|
183
350
|
|
|
184
|
-
if (
|
|
351
|
+
if (!normalizedQuery || sections.length === 0) {
|
|
185
352
|
return {
|
|
186
353
|
markdown: "",
|
|
187
354
|
details: {
|
|
@@ -207,7 +374,14 @@ export function focusMarkdown(markdown: string, query: string): FocusResult {
|
|
|
207
374
|
);
|
|
208
375
|
}
|
|
209
376
|
|
|
210
|
-
|
|
377
|
+
// Punctuated identifiers and flags are literal, never broad component searches.
|
|
378
|
+
const literalIdentifier =
|
|
379
|
+
!/\s/u.test(normalizedQuery) && /[.\-/]/u.test(normalizedQuery)
|
|
380
|
+
? normalizedQuery.toLowerCase()
|
|
381
|
+
: undefined;
|
|
382
|
+
|
|
383
|
+
const scores = sections.map((section) => {
|
|
384
|
+
if (literalIdentifier) return containsIdentifier(section.markdown, literalIdentifier) ? 1 : 0;
|
|
211
385
|
const frequencies = new Map<string, number>();
|
|
212
386
|
|
|
213
387
|
for (const token of section.tokens) frequencies.set(token, (frequencies.get(token) ?? 0) + 1);
|
|
@@ -229,9 +403,15 @@ export function focusMarkdown(markdown: string, query: string): FocusResult {
|
|
|
229
403
|
((frequency * (1.2 + 1)) / (frequency + 1.2 * lengthNormalization));
|
|
230
404
|
}
|
|
231
405
|
|
|
232
|
-
return score
|
|
406
|
+
return score;
|
|
233
407
|
});
|
|
234
408
|
|
|
409
|
+
const highestScore = scores.reduce((highest, score) => Math.max(highest, score), 0);
|
|
410
|
+
|
|
411
|
+
const selected = sections.filter(
|
|
412
|
+
(_, index) => scores[index] > 0 && scores[index] >= highestScore * 0.5,
|
|
413
|
+
);
|
|
414
|
+
|
|
235
415
|
const focused = selected.map((section) => section.markdown).join(separator);
|
|
236
416
|
|
|
237
417
|
return {
|
package/src/index.ts
CHANGED
|
@@ -115,7 +115,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
115
115
|
},
|
|
116
116
|
|
|
117
117
|
async execute(_toolCallId, params, signal, onUpdate) {
|
|
118
|
-
|
|
118
|
+
try {
|
|
119
|
+
return await executeWebFetch(params, signal, onUpdate);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error instanceof Error && /^web_fetch(?:: | )/.test(error.message)) {
|
|
122
|
+
const message = error.message.replace(/^web_fetch(?:: | )/, "");
|
|
123
|
+
throw new Error(
|
|
124
|
+
message === "was cancelled."
|
|
125
|
+
? "Cancelled."
|
|
126
|
+
: message.charAt(0).toUpperCase() + message.slice(1),
|
|
127
|
+
{ cause: error },
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
119
133
|
},
|
|
120
134
|
|
|
121
135
|
/**
|
|
@@ -116,18 +116,17 @@ async function defaultSleep(milliseconds: number, signal: AbortSignal): Promise<
|
|
|
116
116
|
});
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
-
/** Parses a Retry-After header into a
|
|
119
|
+
/** Parses a Retry-After header into a delay in milliseconds. */
|
|
120
120
|
function retryAfterMilliseconds(value: string | undefined, now = Date.now()): number | undefined {
|
|
121
121
|
if (!value) return undefined;
|
|
122
|
-
const
|
|
122
|
+
const trimmed = value.trim();
|
|
123
123
|
|
|
124
|
-
if (
|
|
125
|
-
return Math.min(seconds * 1_000, MAX_RETRY_DELAY_MS);
|
|
124
|
+
if (/^\d+(?:\.\d+)?$/u.test(trimmed)) return Number(trimmed) * 1_000;
|
|
126
125
|
const date = Date.parse(value);
|
|
127
126
|
|
|
128
127
|
if (!Number.isFinite(date)) return undefined;
|
|
129
128
|
|
|
130
|
-
return Math.
|
|
129
|
+
return Math.max(0, date - now);
|
|
131
130
|
}
|
|
132
131
|
|
|
133
132
|
/** Sends one origin-limited request and retries transient rate-limit responses. */
|
|
@@ -170,10 +169,14 @@ async function coordinatedRequest(
|
|
|
170
169
|
const status = response.statusCode ?? 0;
|
|
171
170
|
|
|
172
171
|
if (![429, 503].includes(status) || attempt >= MAX_RETRIES) return response;
|
|
173
|
-
// The retry decision uses headers only. Drop an untrusted error body so it cannot
|
|
174
|
-
// consume unbounded bandwidth while the caller is backing off.
|
|
175
|
-
response.destroy();
|
|
176
172
|
const advertised = retryAfterMilliseconds(responseHeader(response, "retry-after"));
|
|
173
|
+
|
|
174
|
+
// Do not retry earlier than the server requested. Return the response so the
|
|
175
|
+
// caller can report its status rather than waiting beyond our retry budget.
|
|
176
|
+
if (advertised !== undefined && advertised > MAX_RETRY_DELAY_MS) return response;
|
|
177
|
+
|
|
178
|
+
// The retry decision uses headers only. Drop the untrusted error body.
|
|
179
|
+
response.destroy();
|
|
177
180
|
const exponential = BASE_RETRY_DELAY_MS * 2 ** attempt;
|
|
178
181
|
const jittered = Math.round(exponential * (0.75 + Math.min(1, Math.max(0, random())) * 0.5));
|
|
179
182
|
await sleep(advertised ?? Math.min(jittered, MAX_RETRY_DELAY_MS), signal);
|
|
@@ -202,11 +205,14 @@ export async function requestFollowingRedirects(
|
|
|
202
205
|
|
|
203
206
|
const location = responseHeader(response, "location");
|
|
204
207
|
|
|
208
|
+
// Redirect bodies are unused and may never finish. Close before validation
|
|
209
|
+
// or error handling so no discarded response survives the acquisition.
|
|
210
|
+
response.destroy();
|
|
211
|
+
|
|
205
212
|
if (!location) throw new Error("web_fetch received a redirect without a Location header.");
|
|
206
213
|
|
|
207
214
|
if (redirects === FETCH_MAX_REDIRECTS)
|
|
208
215
|
throw new Error("web_fetch followed too many redirects.");
|
|
209
|
-
response.resume();
|
|
210
216
|
target = await awaitWithAbort(validateUrl(new URL(location, target.url)), signal);
|
|
211
217
|
// Validators describe the originally cached resource and must not leak to a redirect target.
|
|
212
218
|
// Challenge handshakes opt into a fixed browser identity instead.
|
package/src/render.ts
CHANGED
package/src/service.ts
CHANGED
|
@@ -374,7 +374,8 @@ const inflightFetches = new InflightCoalescer<string, FetchAcquisition>(MAX_INFL
|
|
|
374
374
|
* Executes a validated web fetch, including caching, focusing, and bounded pagination.
|
|
375
375
|
*
|
|
376
376
|
* A URL fragment selects the starting heading, anchor, or source range unless
|
|
377
|
-
* an explicit offset is supplied. A query selects sections before pagination
|
|
377
|
+
* an explicit offset is supplied without a query. A query selects sections before pagination;
|
|
378
|
+
* its continuation offsets retain the fragment-selected view.
|
|
378
379
|
* Missing fragments may suggest up to three links to other pages with that
|
|
379
380
|
* fragment. Discovered llms.txt index URLs appear on every unblocked result,
|
|
380
381
|
* including cache hits. Detected bot-wall documents return a blocked result
|
|
@@ -539,13 +540,13 @@ export async function executeWebFetch(
|
|
|
539
540
|
|
|
540
541
|
const startingOffset = explicitOffset ?? fragmentOffset ?? FETCH_DEFAULT_OFFSET;
|
|
541
542
|
|
|
542
|
-
const
|
|
543
|
-
explicitOffset === undefined
|
|
544
|
-
|
|
545
|
-
|
|
543
|
+
const useFragment =
|
|
544
|
+
fragmentOffset !== undefined && (explicitOffset === undefined || params.query !== undefined);
|
|
545
|
+
|
|
546
|
+
const hasFragmentRange = useFragment && resolvedFragment.endOffset !== undefined;
|
|
546
547
|
|
|
547
548
|
const fragmentDocument =
|
|
548
|
-
|
|
549
|
+
useFragment && fragmentOffset !== undefined
|
|
549
550
|
? {
|
|
550
551
|
...document,
|
|
551
552
|
markdown: hasFragmentRange
|
|
@@ -614,13 +615,13 @@ export async function executeWebFetch(
|
|
|
614
615
|
: [
|
|
615
616
|
...(result.markdownAlternateFallback
|
|
616
617
|
? [
|
|
617
|
-
"[
|
|
618
|
+
"[Page content was sparse; showing the site's advertised Markdown version instead.]",
|
|
618
619
|
"",
|
|
619
620
|
]
|
|
620
621
|
: []),
|
|
621
622
|
...(result.llmsTxtFallback
|
|
622
623
|
? [
|
|
623
|
-
"[Showing the site
|
|
624
|
+
"[Showing the site index instead of the requested page. Follow a link for details.]",
|
|
624
625
|
"",
|
|
625
626
|
]
|
|
626
627
|
: []),
|
|
@@ -629,7 +630,7 @@ export async function executeWebFetch(
|
|
|
629
630
|
: []),
|
|
630
631
|
...(resolvedFragment.fragment !== undefined && !fragmentMatched
|
|
631
632
|
? [
|
|
632
|
-
"[
|
|
633
|
+
"[Fragment not found; showing the page from the beginning.]",
|
|
633
634
|
...(fragmentSuggestions.length
|
|
634
635
|
? [`[This page links to the requested fragment: ${fragmentSuggestions.join(", ")}]`]
|
|
635
636
|
: []),
|
|
@@ -640,8 +641,8 @@ export async function executeWebFetch(
|
|
|
640
641
|
...(focused
|
|
641
642
|
? [
|
|
642
643
|
focused.details.matchedSections > 0
|
|
643
|
-
? `[
|
|
644
|
-
: "[No
|
|
644
|
+
? `[Query matched ${focused.details.matchedSections}/${focused.details.totalSections} sections. Offsets apply to this view; omit query for the full page.]`
|
|
645
|
+
: "[No sections matched. Omit query for the full page.]",
|
|
645
646
|
"",
|
|
646
647
|
]
|
|
647
648
|
: []),
|