import { isIP } from "node:net"; import { sanitize } from "../hub/envelope.ts"; import { OUTPUT_CAP } from "./sandbox.ts"; import { allowed } from "./web-fetch-config.ts"; export { MAX_WEB_HOSTS, webFetchAllow, webHostProblem } from "./web-fetch-config.ts"; // agent-hub #515 (hub task #332): the local worker's `web_fetch`. Spec: "On-prem web reading (#515)", the owner decision of 2026-10-22. // It is refused for the whole turn of a PII task, whatever the host: the URL or a query string could carry PII to the web, and `pii.paths` and `sanitize()` cover // what comes back, not what goes out. Outside a PII turn it runs only through the egress proxy, to hosts the person listed for this project, and returns bounded, // sanitized text only. Off by default. /** The refusal for a PII turn. It is the same text for every URL, so it says nothing about the request. */ export const WEB_FETCH_PII = "error: web_fetch is not available in a PII task turn, whatever the host: the URL or a query could carry PII to the web. Use doc_read or read for what the project already holds"; /** What the daemon hands the worker when a project opts in (`local.web_fetch.allow` names at least one host). Getters, so a policy reload applies to the next call. */ export interface WebFetchPort { /** `local.web_fetch.allow`: hosts (`host` or `host:port`, subdomains included for a name) the model may read. */ allow: () => readonly string[]; /** The loopback URL of the egress proxy that opens tunnels to `allow` and nothing else; undefined while it is not running. */ proxyUrl: () => string | undefined; /** Test seam: the fetch to use. Production leaves it unset (the global `fetch`). */ fetch?: (url: string, init: { proxy: string; redirect: "manual"; signal: AbortSignal; headers: Record; method: "GET" }) => Promise; } /** The port as a tool call sees it: with whether this turn is a PII task turn. */ export interface WebFetchContext extends WebFetchPort { pii: boolean } export const WEB_FETCH_TIMEOUT_MS = 15_000; /** Bytes read from a response, however large it says it is. Text past it is cut, never buffered. */ export const WEB_FETCH_MAX_BYTES = 512 * 1024; export const WEB_FETCH_MAX_URL = 2000; /** Redirects followed, each one re-checked against the allowlist before it is requested. */ export const WEB_FETCH_MAX_REDIRECTS = 3; export const DEFAULT_WEB_LINES = 2000; const TEXT_TYPE = /^(?:text\/[a-z0-9.+-]+|application\/(?:json|xml|xhtml\+xml|[a-z0-9.+-]+\+(?:json|xml)))(?:\s*;.*)?$/i; /** * Whether a URL may be requested at all: https, a host the list names, port 443 unless the entry says otherwise, no userinfo, no address literal, no fragment-only tricks. * A reason string, never a throw. The reason names the host (the model already wrote it) and never anything the person configured beyond "not in the list". */ export function checkWebUrl(raw: string, allow: readonly string[]): { ok: true; url: URL } | { ok: false; reason: string } { if (typeof raw !== "string" || !raw.trim() || raw.length > WEB_FETCH_MAX_URL || /[\x00-\x20\x7f]/.test(raw)) return { ok: false, reason: "url must be one https URL of at most 2000 characters with no spaces or control characters" }; let url: URL; try { url = new URL(raw); } catch { return { ok: false, reason: "url is not a valid URL" }; } if (url.protocol !== "https:") return { ok: false, reason: "only https URLs are fetched" }; if (url.username || url.password) return { ok: false, reason: "a URL with a user name or password is not fetched" }; const host = url.hostname.replace(/^\[|\]$/g, ""); if (isIP(host)) return { ok: false, reason: "an address is not a host: name the site, and the person lists it in local.web_fetch.allow" }; const port = url.port ? Number(url.port) : 443; if (!allowed([...allow], host, port)) return { ok: false, reason: `${host}:${port} is not in local.web_fetch.allow` }; url.hash = ""; return { ok: true, url }; } /** The decoded text of a response body, read at most `WEB_FETCH_MAX_BYTES` bytes deep. */ async function readBounded(res: Response): Promise<{ text: string; cut: boolean }> { const reader = res.body?.getReader(); if (!reader) return { text: "", cut: false }; const chunks: Uint8Array[] = []; let total = 0, cut = false; for (;;) { const { done, value } = await reader.read(); if (done) break; if (total + value.length > WEB_FETCH_MAX_BYTES) { chunks.push(value.subarray(0, WEB_FETCH_MAX_BYTES - total)); total = WEB_FETCH_MAX_BYTES; cut = true; void reader.cancel().catch(() => undefined); break; } chunks.push(value); total += value.length; } return { text: new TextDecoder("utf-8", { fatal: false }).decode(Buffer.concat(chunks)), cut }; } const SKIPPED_ELEMENTS = new Set(["script", "style", "noscript", "template", "svg", "head"]); /** Their content is never markup, so an unclosed one swallows the rest of the page (what a browser does); the others lose only their tag. */ const RAW_TEXT_ELEMENTS = new Set(["script", "style"]); const BLOCK_CLOSERS = new Set(["p", "div", "li", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "section", "article", "br", "pre", "blockquote", "table"]); const isAsciiLetter = (code: number) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122); const isNameCode = (code: number) => isAsciiLetter(code) || (code >= 48 && code <= 57) || code === 45; /** * Markup reduced to its text, enough to read a page: scripts and styles go, tags go, entities are decoded for the few that matter, runs of blank lines collapse. * One forward pass over a body that a hostile page controls: every index only moves ahead, and a search that finds nothing is never repeated for the same * target, so the work is linear in the body whatever is left unclosed (a repeated `