@zeldrisho/pi-web-fetch 0.18.1 → 0.18.2
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 +15 -1
- package/README.md +7 -7
- package/package.json +7 -10
- package/src/abort.ts +1 -1
- package/src/acquisition/admission.ts +1 -1
- package/src/acquisition/fetch-metadata.ts +9 -9
- package/src/acquisition/fetch.ts +18 -9
- package/src/acquisition/llms.ts +28 -10
- package/src/acquisition/reddit.ts +4 -2
- package/src/cache.ts +33 -20
- package/src/challenges/anubis-solver.ts +27 -15
- package/src/challenges/anubis.ts +19 -10
- package/src/challenges/aws-waf-resolver.ts +0 -4
- package/src/challenges/aws-waf-solver.ts +7 -5
- package/src/challenges/reddit.ts +12 -6
- package/src/document/complexity.ts +4 -3
- package/src/document/content.ts +7 -1
- package/src/document/evidence.ts +5 -4
- package/src/document/extract.ts +221 -63
- package/src/document/focus.ts +22 -9
- package/src/document/fragment-index.ts +4 -4
- package/src/document/fragments.ts +34 -18
- package/src/document/markdown-cleanup.ts +2 -2
- package/src/document/openapi.ts +2 -1
- package/src/document/source-format.ts +4 -3
- package/src/limits.ts +3 -3
- package/src/network/cookies.ts +2 -2
- package/src/network/network-policy.ts +5 -3
- package/src/network/network-redirects.ts +5 -3
- package/src/network/network-transport.ts +6 -4
- package/src/render.ts +1 -1
- package/src/service.ts +108 -40
- package/workers/anubis-solver.js +6 -6
- package/workers/aws-waf-solver.js +7 -19
- package/workers/aws-waf-worker.js +0 -2
package/src/document/openapi.ts
CHANGED
|
@@ -56,8 +56,9 @@ export function isOpenapiSource(raw: string, contentType: string): boolean {
|
|
|
56
56
|
let paths = false;
|
|
57
57
|
|
|
58
58
|
for (const property of node.properties) {
|
|
59
|
-
if (property.type !== "Property" || property.computed || property.kind !== "init")
|
|
59
|
+
if (property.type !== "Property" || property.computed || property.kind !== "init") {
|
|
60
60
|
continue;
|
|
61
|
+
}
|
|
61
62
|
|
|
62
63
|
const key =
|
|
63
64
|
property.key.type === "Identifier"
|
|
@@ -16,13 +16,13 @@ function isSourceContentType(value: string): value is SourceContentType {
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
/** Shortest body reformatted; below this a page is returned verbatim. */
|
|
19
|
-
const MINIFIED_MIN_CHARACTERS =
|
|
19
|
+
const MINIFIED_MIN_CHARACTERS = 2000;
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
22
|
* Largest body reformatted. Reformatting triples transient memory for a document too
|
|
23
23
|
* large to cache, so bigger bodies keep their original single-line layout.
|
|
24
24
|
*/
|
|
25
|
-
const MINIFIED_MAX_CHARACTERS = 2 *
|
|
25
|
+
const MINIFIED_MAX_CHARACTERS = 2 * 1024 * 1024;
|
|
26
26
|
|
|
27
27
|
/**
|
|
28
28
|
* Shortest average line that still counts as machine-generated. Bundled source is
|
|
@@ -51,8 +51,9 @@ const LINE_ENDING_CHARACTERS = new Set([",", ";"]);
|
|
|
51
51
|
* author's line structure, which is more useful than any generated layout.
|
|
52
52
|
*/
|
|
53
53
|
function isMinified(value: string): boolean {
|
|
54
|
-
if (value.length < MINIFIED_MIN_CHARACTERS || value.length > MINIFIED_MAX_CHARACTERS)
|
|
54
|
+
if (value.length < MINIFIED_MIN_CHARACTERS || value.length > MINIFIED_MAX_CHARACTERS) {
|
|
55
55
|
return false;
|
|
56
|
+
}
|
|
56
57
|
|
|
57
58
|
let lineBreaks = 0;
|
|
58
59
|
|
package/src/limits.ts
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
export const FETCH_DEFAULT_OFFSET = 0;
|
|
3
3
|
|
|
4
4
|
/** Minimum allowed value for maxCharacters parameter. */
|
|
5
|
-
export const FETCH_MIN_MAX_CHARACTERS =
|
|
5
|
+
export const FETCH_MIN_MAX_CHARACTERS = 1000;
|
|
6
6
|
|
|
7
7
|
/** Default maximum characters to return per fetch. */
|
|
8
|
-
export const FETCH_DEFAULT_MAX_CHARACTERS =
|
|
8
|
+
export const FETCH_DEFAULT_MAX_CHARACTERS = 6000;
|
|
9
9
|
|
|
10
10
|
/** Maximum allowed characters to return per fetch. */
|
|
11
11
|
export const FETCH_MAX_CHARACTERS = 30_000;
|
|
@@ -17,4 +17,4 @@ export const FETCH_MAX_OFFSET_CHARACTERS = 20_000_000;
|
|
|
17
17
|
export const FETCH_MAX_QUERY_CHARACTERS = 400;
|
|
18
18
|
|
|
19
19
|
/** Maximum allowed length for input URLs (characters). */
|
|
20
|
-
export const FETCH_MAX_URL_CHARACTERS =
|
|
20
|
+
export const FETCH_MAX_URL_CHARACTERS = 2048;
|
package/src/network/cookies.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { IncomingHttpHeaders, IncomingMessage } from "node:http";
|
|
|
4
4
|
const MAX_COOKIES = 128;
|
|
5
5
|
|
|
6
6
|
/** Maximum accepted cookie value length in characters. */
|
|
7
|
-
const MAX_COOKIE_VALUE_CHARACTERS =
|
|
7
|
+
const MAX_COOKIE_VALUE_CHARACTERS = 4096;
|
|
8
8
|
|
|
9
9
|
/** Maximum accepted cookie name length in characters. */
|
|
10
10
|
const MAX_COOKIE_NAME_CHARACTERS = 256;
|
|
@@ -148,7 +148,7 @@ function parseSetCookie(raw: string, url: URL, now: number): ParsedCookie | unde
|
|
|
148
148
|
? expires
|
|
149
149
|
: maxAge <= 0
|
|
150
150
|
? now - 1
|
|
151
|
-
: now + Math.min(maxAge, 31_536_000) *
|
|
151
|
+
: now + Math.min(maxAge, 31_536_000) * 1000;
|
|
152
152
|
|
|
153
153
|
return { name, value, path, secure, expiresAt };
|
|
154
154
|
}
|
|
@@ -145,15 +145,17 @@ export async function validateRemoteUrl(
|
|
|
145
145
|
): Promise<ValidatedTarget> {
|
|
146
146
|
const url = value instanceof URL ? value : new URL(value);
|
|
147
147
|
|
|
148
|
-
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
148
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
149
149
|
throw new Error("web_fetch only supports HTTP and HTTPS URLs.");
|
|
150
|
+
}
|
|
150
151
|
|
|
151
|
-
if (url.username || url.password)
|
|
152
|
+
if (url.username || url.password) {
|
|
152
153
|
throw new Error("web_fetch blocks URLs containing credentials.");
|
|
154
|
+
}
|
|
153
155
|
|
|
154
156
|
const hostname = url.hostname
|
|
155
157
|
.toLowerCase()
|
|
156
|
-
.
|
|
158
|
+
.replaceAll(/^\[|\]$/g, "")
|
|
157
159
|
.replace(/\.$/, "");
|
|
158
160
|
|
|
159
161
|
if (!hostname || hostname === "localhost" || hostname.endsWith(".localhost")) {
|
|
@@ -17,7 +17,7 @@ const BASE_RETRY_DELAY_MS = 250;
|
|
|
17
17
|
|
|
18
18
|
interface OriginState {
|
|
19
19
|
active: number;
|
|
20
|
-
waiting:
|
|
20
|
+
waiting: (() => void)[];
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
const origins = new Map<string, OriginState>();
|
|
@@ -121,7 +121,7 @@ function retryAfterMilliseconds(value: string | undefined, now = Date.now()): nu
|
|
|
121
121
|
if (!value) return undefined;
|
|
122
122
|
const trimmed = value.trim();
|
|
123
123
|
|
|
124
|
-
if (/^\d+(?:\.\d+)?$/u.test(trimmed)) return Number(trimmed) *
|
|
124
|
+
if (/^\d+(?:\.\d+)?$/u.test(trimmed)) return Number(trimmed) * 1000;
|
|
125
125
|
const date = Date.parse(value);
|
|
126
126
|
|
|
127
127
|
if (!Number.isFinite(date)) return undefined;
|
|
@@ -144,6 +144,7 @@ async function coordinatedRequest(
|
|
|
144
144
|
const random = dependencies.random ?? Math.random;
|
|
145
145
|
const sleep = dependencies.sleep ?? defaultSleep;
|
|
146
146
|
|
|
147
|
+
// oxlint-disable-next-line no-useless-assignment -- the update feeds the next retry iteration
|
|
147
148
|
for (let attempt = 0; ; attempt += 1) {
|
|
148
149
|
const release = await acquireOrigin(target.url.origin, signal);
|
|
149
150
|
let response: IncomingMessage;
|
|
@@ -211,8 +212,9 @@ export async function requestFollowingRedirects(
|
|
|
211
212
|
|
|
212
213
|
if (!location) throw new Error("web_fetch received a redirect without a Location header.");
|
|
213
214
|
|
|
214
|
-
if (redirects === FETCH_MAX_REDIRECTS)
|
|
215
|
+
if (redirects === FETCH_MAX_REDIRECTS) {
|
|
215
216
|
throw new Error("web_fetch followed too many redirects.");
|
|
217
|
+
}
|
|
216
218
|
target = await awaitWithAbort(validateUrl(new URL(location, target.url)), signal);
|
|
217
219
|
// Validators describe the originally cached resource and must not leak to a redirect target.
|
|
218
220
|
// Representation preferences and challenge identities are safe to retain.
|
|
@@ -6,7 +6,7 @@ import { formatSize } from "@earendil-works/pi-coding-agent";
|
|
|
6
6
|
import type { ValidatedTarget } from "./network-policy.ts";
|
|
7
7
|
|
|
8
8
|
/** Maximum size in bytes for raw HTTP response bodies. */
|
|
9
|
-
export const FETCH_MAX_BYTES = 5 *
|
|
9
|
+
export const FETCH_MAX_BYTES = 5 * 1024 * 1024;
|
|
10
10
|
|
|
11
11
|
/** Fixed User-Agent used for page requests and challenge solvers. */
|
|
12
12
|
export const WEB_FETCH_USER_AGENT = "Mozilla/5.0 (compatible; PiWebFetch/1.0; +https://pi.dev)";
|
|
@@ -16,7 +16,7 @@ export const WEB_FETCH_USER_AGENT = "Mozilla/5.0 (compatible; PiWebFetch/1.0; +h
|
|
|
16
16
|
* budget so the next validated address can be tried inside the overall
|
|
17
17
|
* request timeout.
|
|
18
18
|
*/
|
|
19
|
-
export const CONNECT_ATTEMPT_TIMEOUT_MS =
|
|
19
|
+
export const CONNECT_ATTEMPT_TIMEOUT_MS = 4000;
|
|
20
20
|
|
|
21
21
|
const encoder = new TextEncoder();
|
|
22
22
|
|
|
@@ -195,6 +195,7 @@ export async function requestPinned(
|
|
|
195
195
|
}
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
+
// oxlint-disable-next-line typescript/only-throw-error -- propagate the last connection rejection unchanged
|
|
198
199
|
throw lastError ?? new Error("web_fetch could not connect.");
|
|
199
200
|
}
|
|
200
201
|
|
|
@@ -327,8 +328,9 @@ export function decompressResponse(
|
|
|
327
328
|
else if (encoding === "br") bytes = brotliDecompressSync(bytes, options);
|
|
328
329
|
else throw new Error(`unsupported content encoding: ${encoding}`);
|
|
329
330
|
} catch (error) {
|
|
330
|
-
if (error instanceof Error && error.message.startsWith("unsupported content encoding:"))
|
|
331
|
+
if (error instanceof Error && error.message.startsWith("unsupported content encoding:")) {
|
|
331
332
|
throw error;
|
|
333
|
+
}
|
|
332
334
|
|
|
333
335
|
if (error instanceof Error && "code" in error && error.code === "ERR_BUFFER_TOO_LARGE") {
|
|
334
336
|
throw new Error(
|
|
@@ -347,7 +349,7 @@ export function decodeResponse(bytes: Uint8Array, contentTypeHeader: string): st
|
|
|
347
349
|
const charset = contentTypeHeader.match(/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i)?.[1];
|
|
348
350
|
|
|
349
351
|
try {
|
|
350
|
-
return new TextDecoder(charset || "
|
|
352
|
+
return new TextDecoder(charset || "utf8").decode(bytes);
|
|
351
353
|
} catch {
|
|
352
354
|
return new TextDecoder("utf-8").decode(bytes);
|
|
353
355
|
}
|
package/src/render.ts
CHANGED
|
@@ -12,7 +12,7 @@ export function renderCollapsibleOutput(
|
|
|
12
12
|
warning?: string,
|
|
13
13
|
expandHint = "Ctrl+O to expand",
|
|
14
14
|
): Container {
|
|
15
|
-
const lines = output.
|
|
15
|
+
const lines = output.replaceAll("\r\n", "\n").split("\n");
|
|
16
16
|
|
|
17
17
|
while (lines.at(-1) === "") lines.pop();
|
|
18
18
|
const visible = expanded ? lines : lines.slice(0, COLLAPSED_LINES);
|
package/src/service.ts
CHANGED
|
@@ -9,13 +9,17 @@ import {
|
|
|
9
9
|
type AgentToolResult,
|
|
10
10
|
} from "@earendil-works/pi-coding-agent";
|
|
11
11
|
import { ExpiringLruCache, stableKeyHash, canonicalKey, type CachePersistence } from "./cache";
|
|
12
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
MAX_CACHED_FRAGMENT_TABS,
|
|
14
|
+
sliceCompleteDocument,
|
|
15
|
+
type CompleteDocument,
|
|
16
|
+
} from "./document/content.ts";
|
|
13
17
|
import { revalidateCompleteDocument, type FetchRemoteDependencies } from "./acquisition/fetch.ts";
|
|
14
18
|
import { fetchDocumentWithLlmsTxtSupport } from "./acquisition/llms.ts";
|
|
15
19
|
import { extractHtmlToMarkdown, filterAndroidBomHtml } from "./document/extract.ts";
|
|
16
20
|
import { focusMarkdown, type FocusDetails } from "./document/focus.ts";
|
|
17
21
|
import { isCachedOpenapi } from "./document/openapi.ts";
|
|
18
|
-
import { resolveFragmentOffset, urlWithoutFragment } from "./document/fragments.ts";
|
|
22
|
+
import { fragmentTabId, resolveFragmentOffset, urlWithoutFragment } from "./document/fragments.ts";
|
|
19
23
|
import { InflightCoalescer } from "./inflight";
|
|
20
24
|
import { createDocumentOutline, type DocumentOutline } from "./document/outline.ts";
|
|
21
25
|
import { redactUrlForDisplay } from "./redact";
|
|
@@ -28,13 +32,16 @@ import {
|
|
|
28
32
|
FETCH_MIN_MAX_CHARACTERS,
|
|
29
33
|
} from "./limits";
|
|
30
34
|
|
|
31
|
-
const CACHE_TTL_MS = 24 * 60 * 60 *
|
|
35
|
+
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
32
36
|
|
|
33
37
|
const CACHE_STALE_RETENTION_MS = 7 * CACHE_TTL_MS;
|
|
34
38
|
|
|
39
|
+
// Bump when HTML extraction changes must invalidate persisted results, even fresh ones.
|
|
40
|
+
const HTML_EXTRACTION_CACHE_VERSION = 2;
|
|
41
|
+
|
|
35
42
|
const CACHE_MAX_ENTRIES = 100;
|
|
36
43
|
|
|
37
|
-
const CACHE_MAX_MARKDOWN_BYTES = 20 *
|
|
44
|
+
const CACHE_MAX_MARKDOWN_BYTES = 20 * 1024 * 1024;
|
|
38
45
|
|
|
39
46
|
const MAX_INFLIGHT_REQUESTS = 100;
|
|
40
47
|
|
|
@@ -142,8 +149,9 @@ export function classifyContentKind(
|
|
|
142
149
|
|
|
143
150
|
if (path === "/llms.txt" || path.endsWith("/llms.txt")) return "llms-index";
|
|
144
151
|
|
|
145
|
-
if (host === "raw.githubusercontent.com" || host === "gist.githubusercontent.com")
|
|
152
|
+
if (host === "raw.githubusercontent.com" || host === "gist.githubusercontent.com") {
|
|
146
153
|
return "code-file";
|
|
154
|
+
}
|
|
147
155
|
|
|
148
156
|
if (host === "github.com") {
|
|
149
157
|
const segments = path.split("/").filter(Boolean);
|
|
@@ -253,7 +261,7 @@ export interface WebFetchDetails {
|
|
|
253
261
|
}
|
|
254
262
|
|
|
255
263
|
interface WebFetchUpdate {
|
|
256
|
-
content:
|
|
264
|
+
content: { type: "text"; text: string }[];
|
|
257
265
|
details: Record<string, never>;
|
|
258
266
|
}
|
|
259
267
|
|
|
@@ -348,10 +356,14 @@ const completeDocumentCacheSchema = Type.Object(
|
|
|
348
356
|
url: Type.String(),
|
|
349
357
|
contentType: Type.String(),
|
|
350
358
|
markdown: Type.String(),
|
|
359
|
+
fragmentTabs: Type.Optional(
|
|
360
|
+
Type.Array(Type.String({ maxLength: 80 }), { maxItems: MAX_CACHED_FRAGMENT_TABS }),
|
|
361
|
+
),
|
|
351
362
|
surfaceView: Type.Optional(
|
|
352
363
|
Type.Object({
|
|
353
|
-
selected: Type.String({ maxLength:
|
|
364
|
+
selected: Type.String({ maxLength: 80 }),
|
|
354
365
|
omitted: Type.Integer({ minimum: 1, maximum: 19 }),
|
|
366
|
+
fragmentSelected: Type.Optional(Type.Literal(true)),
|
|
355
367
|
markdown: Type.String(),
|
|
356
368
|
fragmentOffsets: Type.Optional(Type.Record(Type.String(), Type.Number())),
|
|
357
369
|
}),
|
|
@@ -406,13 +418,27 @@ const completeDocumentCacheSchema = Type.Object(
|
|
|
406
418
|
{ additionalProperties: true },
|
|
407
419
|
);
|
|
408
420
|
|
|
421
|
+
const htmlExtractionCacheMarker = Type.Object({
|
|
422
|
+
htmlExtractionCacheVersion: Type.Literal(HTML_EXTRACTION_CACHE_VERSION),
|
|
423
|
+
});
|
|
424
|
+
|
|
409
425
|
function isCompleteDocument(value: CompleteDocument): boolean {
|
|
410
|
-
return
|
|
426
|
+
return (
|
|
427
|
+
Check(completeDocumentCacheSchema, value) &&
|
|
428
|
+
(value.extractor === "raw" || Check(htmlExtractionCacheMarker, value))
|
|
429
|
+
);
|
|
411
430
|
}
|
|
412
431
|
|
|
413
432
|
const fetchCachePersistence: CachePersistence<string, CompleteDocument> = {
|
|
414
433
|
directory: resolveCacheDirectory("pi-web-fetch"),
|
|
415
|
-
serialize: (document) =>
|
|
434
|
+
serialize: (document) =>
|
|
435
|
+
encoder.encode(
|
|
436
|
+
JSON.stringify(
|
|
437
|
+
document.extractor === "raw"
|
|
438
|
+
? document
|
|
439
|
+
: { ...document, htmlExtractionCacheVersion: HTML_EXTRACTION_CACHE_VERSION },
|
|
440
|
+
),
|
|
441
|
+
),
|
|
416
442
|
// SAFETY: JSON is validated immediately below before entering the cache.
|
|
417
443
|
deserialize: (bytes) => JSON.parse(new TextDecoder().decode(bytes)) as CompleteDocument,
|
|
418
444
|
validate: isCompleteDocument,
|
|
@@ -424,7 +450,8 @@ const fetchCache = new ExpiringLruCache<string, CompleteDocument>(
|
|
|
424
450
|
CACHE_MAX_MARKDOWN_BYTES,
|
|
425
451
|
(document) =>
|
|
426
452
|
encoder.encode(document.markdown).byteLength +
|
|
427
|
-
encoder.encode(document.surfaceView?.markdown ?? "").byteLength
|
|
453
|
+
encoder.encode(document.surfaceView?.markdown ?? "").byteLength +
|
|
454
|
+
(document.fragmentTabs?.reduce((length, id) => length + id.length, 0) ?? 0),
|
|
428
455
|
undefined,
|
|
429
456
|
fetchCachePersistence,
|
|
430
457
|
);
|
|
@@ -502,12 +529,13 @@ export async function executeWebFetch(
|
|
|
502
529
|
);
|
|
503
530
|
}
|
|
504
531
|
|
|
505
|
-
if (params.url.length < 1 || params.url.length >
|
|
532
|
+
if (params.url.length < 1 || params.url.length > 2048) {
|
|
506
533
|
throw new Error("web_fetch url must contain between 1 and 2048 characters.");
|
|
507
534
|
}
|
|
508
535
|
|
|
509
536
|
const displayRequestedUrl = redactUrlForDisplay(params.url);
|
|
510
537
|
const sourceUrl = urlWithoutFragment(params.url);
|
|
538
|
+
const fragmentTab = fragmentTabId(params.url);
|
|
511
539
|
const bomVersion = androidBomVersionQuery(sourceUrl, params.query);
|
|
512
540
|
|
|
513
541
|
// Older persisted entries predate surface views and must not mask explicit selections.
|
|
@@ -518,16 +546,37 @@ export async function executeWebFetch(
|
|
|
518
546
|
if (bomVersion) cacheDimensions.androidBomVersion = bomVersion;
|
|
519
547
|
|
|
520
548
|
const cacheKey = canonicalKey({ url: sourceUrl, ...cacheDimensions });
|
|
521
|
-
|
|
522
|
-
|
|
549
|
+
const tabKey = fragmentTab
|
|
550
|
+
? canonicalKey({ url: sourceUrl, ...cacheDimensions, fragmentTab })
|
|
551
|
+
: undefined;
|
|
552
|
+
const canonical = fetchCache.get(cacheKey);
|
|
523
553
|
const now = Date.now();
|
|
554
|
+
const isFresh = (entry: CompleteDocument | undefined): boolean =>
|
|
555
|
+
Boolean(
|
|
556
|
+
entry &&
|
|
557
|
+
!entry.llmsTxtFallback &&
|
|
558
|
+
!entry.extractionDiagnostics?.botWall &&
|
|
559
|
+
(entry.cachedAt === undefined || now - entry.cachedAt < CACHE_TTL_MS),
|
|
560
|
+
);
|
|
561
|
+
const canonicalMatches =
|
|
562
|
+
!fragmentTab ||
|
|
563
|
+
(canonical?.fragmentTabs
|
|
564
|
+
? !canonical.fragmentTabs.includes(fragmentTab)
|
|
565
|
+
: canonical?.extractor === "raw" &&
|
|
566
|
+
!canonical.markdownAlternateFallback &&
|
|
567
|
+
!canonical.representationFallback &&
|
|
568
|
+
!canonical.llmsTxtFallback);
|
|
569
|
+
let document = canonicalMatches ? canonical : undefined;
|
|
570
|
+
|
|
571
|
+
if (fragmentTab && tabKey && !isFresh(document)) {
|
|
572
|
+
const tab = fetchCache.get(tabKey);
|
|
573
|
+
|
|
574
|
+
if (tab?.surfaceView?.fragmentSelected && tab.surfaceView.selected === fragmentTab) {
|
|
575
|
+
document = tab;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
524
578
|
|
|
525
|
-
const fresh =
|
|
526
|
-
document &&
|
|
527
|
-
!document.llmsTxtFallback &&
|
|
528
|
-
!document.extractionDiagnostics?.botWall &&
|
|
529
|
-
(document.cachedAt === undefined || now - document.cachedAt < CACHE_TTL_MS),
|
|
530
|
-
);
|
|
579
|
+
const fresh = isFresh(document);
|
|
531
580
|
|
|
532
581
|
let cacheStatus: CacheStatus = fresh ? "hit" : "miss";
|
|
533
582
|
onUpdate?.({
|
|
@@ -546,9 +595,29 @@ export async function executeWebFetch(
|
|
|
546
595
|
|
|
547
596
|
if (!fresh) {
|
|
548
597
|
const stale = document;
|
|
598
|
+
const acquisitionDependencies: FetchRemoteDependencies =
|
|
599
|
+
bomVersion || fragmentTab
|
|
600
|
+
? {
|
|
601
|
+
...dependencies,
|
|
602
|
+
extractHtml: async (html, url) => {
|
|
603
|
+
if (!bomVersion) {
|
|
604
|
+
return (dependencies.extractHtml ?? extractHtmlToMarkdown)(html, url, fragmentTab);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const filtered = filterAndroidBomHtml(html, bomVersion);
|
|
608
|
+
|
|
609
|
+
if (filtered === undefined) {
|
|
610
|
+
throw new Error(`web_fetch: Android BOM version ${bomVersion} was not found.`);
|
|
611
|
+
}
|
|
549
612
|
|
|
613
|
+
return extractHtmlToMarkdown(filtered, url, fragmentTab);
|
|
614
|
+
},
|
|
615
|
+
}
|
|
616
|
+
: dependencies;
|
|
617
|
+
|
|
618
|
+
// Keep pending fragment selections separate until extraction identifies the view.
|
|
550
619
|
const acquisition = await inflightFetches.run(
|
|
551
|
-
cacheKey,
|
|
620
|
+
tabKey ?? cacheKey,
|
|
552
621
|
async (sharedSignal) => {
|
|
553
622
|
let fetched: CompleteDocument;
|
|
554
623
|
let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
|
|
@@ -568,26 +637,12 @@ export async function executeWebFetch(
|
|
|
568
637
|
sourceUrl,
|
|
569
638
|
stale,
|
|
570
639
|
sharedSignal,
|
|
571
|
-
|
|
640
|
+
acquisitionDependencies,
|
|
572
641
|
);
|
|
573
642
|
|
|
574
643
|
fetched = outcome.document;
|
|
575
644
|
acquisitionStatus = outcome.revalidated ? "revalidated" : "miss";
|
|
576
645
|
} else {
|
|
577
|
-
const acquisitionDependencies = bomVersion
|
|
578
|
-
? {
|
|
579
|
-
...dependencies,
|
|
580
|
-
extractHtml: async (html: string, url: URL) => {
|
|
581
|
-
const filtered = filterAndroidBomHtml(html, bomVersion);
|
|
582
|
-
|
|
583
|
-
if (filtered === undefined)
|
|
584
|
-
throw new Error(`web_fetch: Android BOM version ${bomVersion} was not found.`);
|
|
585
|
-
|
|
586
|
-
return extractHtmlToMarkdown(filtered, url);
|
|
587
|
-
},
|
|
588
|
-
}
|
|
589
|
-
: dependencies;
|
|
590
|
-
|
|
591
646
|
fetched = await fetchDocumentWithLlmsTxtSupport(
|
|
592
647
|
sourceUrl,
|
|
593
648
|
sharedSignal,
|
|
@@ -598,7 +653,11 @@ export async function executeWebFetch(
|
|
|
598
653
|
}
|
|
599
654
|
|
|
600
655
|
if (!fetched.extractionDiagnostics?.botWall) {
|
|
601
|
-
|
|
656
|
+
const storageKey = fetched.surfaceView?.fragmentSelected ? tabKey : cacheKey;
|
|
657
|
+
|
|
658
|
+
if (storageKey) {
|
|
659
|
+
fetchCache.set(storageKey, fetched, Date.now() + CACHE_STALE_RETENTION_MS);
|
|
660
|
+
}
|
|
602
661
|
}
|
|
603
662
|
|
|
604
663
|
return { document: fetched, cacheStatus: acquisitionStatus };
|
|
@@ -615,7 +674,7 @@ export async function executeWebFetch(
|
|
|
615
674
|
const blocked = Boolean(document.extractionDiagnostics?.botWall);
|
|
616
675
|
|
|
617
676
|
// Keep acquisition diagnostics, but never expose challenge prose, links, or continuation.
|
|
618
|
-
if (blocked)
|
|
677
|
+
if (blocked) {
|
|
619
678
|
document = {
|
|
620
679
|
...document,
|
|
621
680
|
markdown: "",
|
|
@@ -623,6 +682,7 @@ export async function executeWebFetch(
|
|
|
623
682
|
links: undefined,
|
|
624
683
|
fragmentOffsets: undefined,
|
|
625
684
|
};
|
|
685
|
+
}
|
|
626
686
|
const canonicalMarkdown = document.markdown;
|
|
627
687
|
|
|
628
688
|
const surface =
|
|
@@ -638,7 +698,10 @@ export async function executeWebFetch(
|
|
|
638
698
|
};
|
|
639
699
|
}
|
|
640
700
|
|
|
641
|
-
const
|
|
701
|
+
const fragmentSurface = surface && document.surfaceView?.fragmentSelected ? surface : undefined;
|
|
702
|
+
const resolvedFragment = fragmentSurface
|
|
703
|
+
? { fragment: fragmentSurface.selected, offset: 0, endOffset: undefined }
|
|
704
|
+
: resolveFragmentOffset(document, params.url);
|
|
642
705
|
const fragmentOffset = resolvedFragment.offset;
|
|
643
706
|
const fragmentMatched = resolvedFragment.fragment !== undefined && fragmentOffset !== undefined;
|
|
644
707
|
|
|
@@ -673,7 +736,9 @@ export async function executeWebFetch(
|
|
|
673
736
|
const startingOffset = explicitOffset ?? fragmentOffset ?? FETCH_DEFAULT_OFFSET;
|
|
674
737
|
|
|
675
738
|
const useFragment =
|
|
676
|
-
|
|
739
|
+
!fragmentSurface &&
|
|
740
|
+
fragmentOffset !== undefined &&
|
|
741
|
+
(explicitOffset === undefined || params.query !== undefined);
|
|
677
742
|
|
|
678
743
|
const hasFragmentRange = useFragment && resolvedFragment.endOffset !== undefined;
|
|
679
744
|
|
|
@@ -791,7 +856,9 @@ export async function executeWebFetch(
|
|
|
791
856
|
"",
|
|
792
857
|
]
|
|
793
858
|
: []),
|
|
794
|
-
...(fragmentMatched
|
|
859
|
+
...(fragmentMatched && !fragmentSurface
|
|
860
|
+
? ["[Starting at the requested URL fragment.]", ""]
|
|
861
|
+
: []),
|
|
795
862
|
...(focused
|
|
796
863
|
? [
|
|
797
864
|
focused.details.matchedSections > 0
|
|
@@ -897,6 +964,7 @@ export async function executeWebFetch(
|
|
|
897
964
|
|
|
898
965
|
// SAFETY: this DTO contains only bounded JSON data; serialization omits optional
|
|
899
966
|
// undefined properties so the emitted value matches the declared output schema.
|
|
967
|
+
// oxlint-disable-next-line unicorn/prefer-structured-clone -- preserve output's JSON representation
|
|
900
968
|
const structuredContent = JSON.parse(JSON.stringify(structured)) as NonNullable<
|
|
901
969
|
AgentToolResult["structuredContent"]
|
|
902
970
|
>;
|
package/workers/anubis-solver.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
/** Maximum length in bytes of the server-provided random challenge data. */
|
|
3
|
-
export const ANUBIS_MAX_RANDOM_DATA_BYTES =
|
|
3
|
+
export const ANUBIS_MAX_RANDOM_DATA_BYTES = 4096;
|
|
4
4
|
/** Maximum size in bytes of a server-provided WebAssembly challenge module. */
|
|
5
|
-
export const ANUBIS_MAX_WASM_BYTES = 4 *
|
|
5
|
+
export const ANUBIS_MAX_WASM_BYTES = 4 * 1024 * 1024;
|
|
6
6
|
/** The host function Anubis baseline WebAssembly modules import. */
|
|
7
7
|
const ANUBIS_WASM_IMPORT = { module: "anubis", name: "anubis_update_nonce" };
|
|
8
8
|
/** Exports required from an Anubis baseline WebAssembly module. */
|
|
@@ -95,8 +95,8 @@ export function solveAnubisSha256Hex(randomData, difficulty, deadline) {
|
|
|
95
95
|
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 64)
|
|
96
96
|
throw new Error("Anubis challenge requested an unsupported difficulty.");
|
|
97
97
|
const prefix = "0".repeat(difficulty);
|
|
98
|
-
for (let nonce = 0; nonce <=
|
|
99
|
-
if ((nonce &
|
|
98
|
+
for (let nonce = 0; nonce <= 0xff_ff_ff_ff; nonce += 1) {
|
|
99
|
+
if ((nonce & 0xf_ff) === 0 && Date.now() > deadline)
|
|
100
100
|
throw new Error("Anubis proof of work exceeded the time budget.");
|
|
101
101
|
const hash = createHash("sha256").update(randomData).update(String(nonce)).digest("hex");
|
|
102
102
|
if (hash.startsWith(prefix))
|
|
@@ -122,7 +122,7 @@ export function solveAnubisSha256Hex(randomData, difficulty, deadline) {
|
|
|
122
122
|
export function solveAnubisWasm(moduleBytes, randomData, difficulty, deadline) {
|
|
123
123
|
if (moduleBytes.byteLength === 0 || moduleBytes.byteLength > ANUBIS_MAX_WASM_BYTES)
|
|
124
124
|
throw new Error("Anubis challenge module exceeded the size limit.");
|
|
125
|
-
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty >
|
|
125
|
+
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 0xff_ff_ff_ff)
|
|
126
126
|
throw new Error("Anubis challenge requested an unsupported difficulty.");
|
|
127
127
|
const data = decodeHex(randomData);
|
|
128
128
|
if (!data || data.byteLength > ANUBIS_MAX_RANDOM_DATA_BYTES)
|
|
@@ -146,7 +146,7 @@ export function solveAnubisWasm(moduleBytes, randomData, difficulty, deadline) {
|
|
|
146
146
|
setDataLength(data.byteLength);
|
|
147
147
|
const nonce = work(difficulty, 0, 1);
|
|
148
148
|
const hashSize = resultHashSize() >>> 0;
|
|
149
|
-
if (hashSize < 1 || hashSize >
|
|
149
|
+
if (hashSize < 1 || hashSize > 4096)
|
|
150
150
|
throw new Error("Anubis challenge module returned an invalid hash size.");
|
|
151
151
|
const hashBytes = readMemory(memory, resultHashPtr(), hashSize);
|
|
152
152
|
if (Date.now() > deadline)
|
|
@@ -1,56 +1,44 @@
|
|
|
1
1
|
import { createHash, scryptSync } from "node:crypto";
|
|
2
|
-
|
|
3
2
|
/** Returns whether the first `difficulty` bits of a hash are zero. */
|
|
4
3
|
export function hasLeadingZeroBits(hash, difficulty) {
|
|
5
4
|
for (let bit = 0; bit < difficulty; bit += 1) {
|
|
6
5
|
const byte = hash[Math.floor(bit / 8)];
|
|
7
|
-
|
|
8
6
|
if (byte === undefined || (byte & (1 << (7 - (bit % 8)))) !== 0) return false;
|
|
9
7
|
}
|
|
10
|
-
|
|
11
8
|
return true;
|
|
12
9
|
}
|
|
13
|
-
|
|
14
10
|
/** Solves the bandwidth challenge using a bounded zero-filled buffer. */
|
|
15
11
|
export function solveAwsWafBandwidth(difficulty) {
|
|
16
|
-
const sizes = [
|
|
17
|
-
|
|
18
|
-
return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1_024).toString("base64");
|
|
12
|
+
const sizes = [1024, 1024, 10_240, 102_400, 1_048_576, 10_485_760];
|
|
13
|
+
return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1024).toString("base64");
|
|
19
14
|
}
|
|
20
|
-
|
|
21
15
|
/** Computes bounded proof-of-work inside a disposable worker. */
|
|
22
16
|
export function solveAwsWafWork(work) {
|
|
23
|
-
if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32)
|
|
17
|
+
if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32) {
|
|
24
18
|
return undefined;
|
|
25
|
-
|
|
19
|
+
}
|
|
26
20
|
if (work.type === "NetworkBandwidth") return solveAwsWafBandwidth(work.difficulty);
|
|
27
|
-
|
|
28
21
|
if (work.type === "SHA256") {
|
|
29
22
|
for (let nonce = 0; nonce < 2_000_000; nonce += 1) {
|
|
30
23
|
const digest = createHash("sha256").update(`${work.input}${work.checksum}${nonce}`).digest();
|
|
31
|
-
|
|
32
24
|
if (hasLeadingZeroBits(digest, work.difficulty)) return String(nonce);
|
|
33
25
|
}
|
|
34
26
|
}
|
|
35
|
-
|
|
36
27
|
if (work.type === "HashcashScrypt") {
|
|
37
28
|
const cost = work.memory > 0 ? work.memory : 128;
|
|
38
|
-
|
|
39
29
|
// Reject large or invalid costs before invoking OpenSSL.
|
|
40
|
-
if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0)
|
|
30
|
+
if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0) {
|
|
41
31
|
return undefined;
|
|
42
|
-
|
|
32
|
+
}
|
|
43
33
|
for (let nonce = 0; nonce < 100_000; nonce += 1) {
|
|
44
34
|
const digest = scryptSync(`${work.input}${work.checksum}${nonce}`, work.checksum, 32, {
|
|
45
35
|
N: cost,
|
|
46
36
|
r: 8,
|
|
47
37
|
p: 1,
|
|
48
|
-
maxmem: 64 *
|
|
38
|
+
maxmem: 64 * 1024 * 1024,
|
|
49
39
|
});
|
|
50
|
-
|
|
51
40
|
if (hasLeadingZeroBits(digest, work.difficulty)) return String(nonce);
|
|
52
41
|
}
|
|
53
42
|
}
|
|
54
|
-
|
|
55
43
|
return undefined;
|
|
56
44
|
}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/* v8 ignore file -- exercised through worker integration tests. */
|
|
2
2
|
import { parentPort, workerData } from "node:worker_threads";
|
|
3
3
|
import { solveAwsWafWork } from "./aws-waf-solver.js";
|
|
4
|
-
|
|
5
4
|
const work = workerData;
|
|
6
|
-
|
|
7
5
|
try {
|
|
8
6
|
parentPort?.postMessage({ kind: "solved", solution: solveAwsWafWork(work) });
|
|
9
7
|
} catch (error) {
|