reasonally 0.4.0 → 0.6.0

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.
@@ -6,8 +6,10 @@ import { createHash, randomBytes } from "node:crypto";
6
6
  import { access, appendFile, chmod, mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile, } from "node:fs/promises";
7
7
  import { hostname } from "node:os";
8
8
  import { basename, join } from "node:path";
9
+ import { contentText } from "./compact.js";
9
10
  import { CONTINUE_PROMPT, HELPER_PLAN_ON_NOTE, INTERRUPTED_NOTE, PLAN_OFF_NOTE, PLAN_ON_NOTE, } from "./loop-constants.js";
10
11
  import { PLAN_TOOL } from "./tools/plan.js";
12
+ import { commandLabel } from "./command-template.js";
11
13
  /** A new session's id, which is also its file name: when it started, plus a few random characters. */
12
14
  export function newSessionId(now = new Date()) {
13
15
  const stamp = now.toISOString().replace(/[:.]/g, "-");
@@ -270,11 +272,69 @@ function planArgument(args) {
270
272
  }
271
273
  /** Notes the agent adds in front of a message, never shown as what the user wrote. */
272
274
  const LEADING_NOTES = [INTERRUPTED_NOTE, PLAN_ON_NOTE, HELPER_PLAN_ON_NOTE, PLAN_OFF_NOTE];
275
+ /**
276
+ * A message as it's saved: images become a placeholder, so session files stay small and their
277
+ * content stays text. The conversation in memory keeps them. Other messages are returned as is.
278
+ */
279
+ export function savedMessage(message) {
280
+ if (message.role !== "user" || typeof message.content === "string")
281
+ return message;
282
+ return { ...message, content: contentText(message.content) };
283
+ }
284
+ /**
285
+ * The record a host saves for a change to the conversation. Every kind of change has its own
286
+ * record (a change saved as the wrong kind would rewrite the conversation on the next load).
287
+ * Images become `[image]` (see `savedMessage`): files stay small and hold no screenshots, while the
288
+ * conversation in memory keeps them. A slash command goes beside its message, never in it: older
289
+ * versions read only `message`, so they never send it on.
290
+ */
291
+ export function changeRecord(change) {
292
+ switch (change.type) {
293
+ case "usage":
294
+ return {
295
+ type: "usage",
296
+ promptTokens: change.usage.promptTokens,
297
+ completionTokens: change.usage.completionTokens,
298
+ costMicros: change.costMicros.toString(),
299
+ };
300
+ case "append": {
301
+ const message = savedMessage(change.message);
302
+ if (message.role !== "user" || !message.command)
303
+ return { type: "append", message };
304
+ const { command, ...rest } = message;
305
+ return { type: "append", message: rest, command };
306
+ }
307
+ case "replace":
308
+ return {
309
+ type: "replace",
310
+ reason: change.reason,
311
+ messages: change.messages.map((m) => savedMessage(withoutCommand(m))),
312
+ };
313
+ default: {
314
+ const unknown = change;
315
+ throw new Error(`No session record for ${JSON.stringify(unknown)}`);
316
+ }
317
+ }
318
+ }
319
+ function withoutCommand(message) {
320
+ if (message.role !== "user" || !message.command)
321
+ return message;
322
+ const copy = { ...message };
323
+ delete copy.command;
324
+ return copy;
325
+ }
326
+ /** A saved `command`, if it has the right shape (a file edited by hand may not). */
327
+ function commandOf(value) {
328
+ const c = value;
329
+ return c && typeof c.name === "string" && c.name && typeof c.args === "string"
330
+ ? { name: c.name, args: c.args }
331
+ : null;
332
+ }
273
333
  /** Strips our own markers from a user message, for showing it. */
274
334
  export function userText(content) {
275
335
  if (content === CONTINUE_PROMPT)
276
336
  return null;
277
- let text = content;
337
+ let text = typeof content === "string" ? content : contentText(content);
278
338
  for (let found = true; found;) {
279
339
  const note = LEADING_NOTES.find((n) => text.startsWith(n));
280
340
  found = Boolean(note);
@@ -331,12 +391,14 @@ export async function loadSession(path) {
331
391
  display.push({ kind: "compacted" });
332
392
  break;
333
393
  case "append": {
334
- const m = r.message;
394
+ const command = r.message.role === "user" ? commandOf(r.command) : null;
395
+ const m = command && r.message.role === "user" ? { ...r.message, command } : r.message;
335
396
  messages.push(m);
336
397
  if (m.role === "user") {
337
- const shown = userText(m.content);
398
+ // A tool call's images, added by the agent: not something the user wrote.
399
+ const shown = m.synthetic ? null : userText(m.content);
338
400
  if (shown)
339
- display.push({ kind: "user", text: shown });
401
+ display.push({ kind: "user", text: shown, ...(command ? { command } : {}) });
340
402
  }
341
403
  else if (m.role === "assistant") {
342
404
  if (m.content)
@@ -389,18 +451,25 @@ export async function listSessions(dir) {
389
451
  return [];
390
452
  }
391
453
  const loaded = await Promise.all(names.map((n) => loadSession(join(dir, n))));
454
+ // Ties (changed in the same millisecond) go to the newer conversation: ids start with its start.
392
455
  return loaded
393
456
  .filter((s) => s !== null && s.display.some((d) => d.kind === "user"))
394
457
  .map((s) => ({
395
458
  id: s.meta.id,
396
459
  path: s.path,
397
460
  surface: s.meta.surface ?? "terminal",
398
- firstMessage: s.display.find((d) => d.kind === "user").text,
461
+ firstMessage: shownText(s.display.find((d) => d.kind === "user")),
399
462
  model: s.model,
400
463
  costMicros: s.costMicros,
401
464
  updatedAt: s.updatedAt,
402
465
  }))
403
- .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
466
+ .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime() || b.id.localeCompare(a.id));
467
+ }
468
+ /** How a user message reads in a list: what was typed (`/review auth` for a command). */
469
+ function shownText(entry) {
470
+ if (entry.kind !== "user")
471
+ return "";
472
+ return entry.command ? commandLabel(entry.command) : entry.text;
404
473
  }
405
474
  /** "just now", "5m ago", "3h ago", "2d ago", or the date. */
406
475
  export function timeAgo(date, now = new Date()) {
@@ -4,6 +4,8 @@ import { planTool } from "./plan.js";
4
4
  import { findTool, grepTool } from "./search.js";
5
5
  import { taskTool } from "./task.js";
6
6
  import { todoTool } from "./todo.js";
7
+ import { webFetchTool } from "./web-fetch.js";
8
+ import { webSearchTool } from "./web-search.js";
7
9
  /** The built-in tools, in the order the model sees them. */
8
10
  export const BUILTIN_TOOLS = [
9
11
  readTool,
@@ -16,6 +18,13 @@ export const BUILTIN_TOOLS = [
16
18
  taskTool,
17
19
  planTool,
18
20
  ];
21
+ /** The web tools the user hasn't turned off, after the built-ins. */
22
+ export function webTools(policy) {
23
+ return [
24
+ ...(policy.search === "off" ? [] : [webSearchTool]),
25
+ ...(policy.fetch === "off" ? [] : [webFetchTool]),
26
+ ];
27
+ }
19
28
  /** The `tools` array for a chat request. */
20
29
  export const toolSchemas = (tools) => tools.map((t) => ({
21
30
  type: "function",
@@ -4,7 +4,7 @@ export const MAX_PARALLEL_HELPERS = 4;
4
4
  export const HELPER_NOTE = `# You are a helper
5
5
  Another agent handed you the task below and will act on your report; the user sees only a one-line
6
6
  status for you. Work on your own: you can't ask the user questions. You can read and search freely;
7
- edits and commands need the user's approval, so only make changes the task asks for.
7
+ edits, commands and some web pages need the user's approval, so only make changes the task asks for.
8
8
  Finish with a concise report: what you found (with path:line references), anything you changed,
9
9
  and anything you couldn't do. Don't paste whole files.`;
10
10
  export const taskTool = {
@@ -0,0 +1,131 @@
1
+ import { parseDocument } from "./dom.js";
2
+ const ENDPOINT = "https://html.duckduckgo.com/html/";
3
+ /** A search from this computer gets this long before the fallback takes over. */
4
+ export const DEVICE_TIMEOUT_MS = 5_000;
5
+ /** After a block (or a page we can't read), searches skip this computer for this long. */
6
+ export const BACKOFF_MS = 10 * 60_000;
7
+ /** At most one search a second from this computer. */
8
+ const MIN_INTERVAL_MS = 1_000;
9
+ const MAX_RESULTS = 10;
10
+ const RECENCY_PARAM = { day: "d", week: "w", month: "m", year: "y" };
11
+ /** Back-off and pacing, shared by every search in this process. */
12
+ export const deviceState = { blockedUntil: 0, lastAt: 0 };
13
+ /** DuckDuckGo's region for a locale ("en-US" → "us-en"); "wt-wt" means no region. */
14
+ export function regionFor(locale) {
15
+ const [language, country] = locale.toLowerCase().replace("_", "-").split("-");
16
+ if (!language || !country || !/^[a-z]{2}$/.test(country))
17
+ return "wt-wt";
18
+ return `${country === "gb" ? "uk" : country}-${language}`;
19
+ }
20
+ /** The result's real address: DuckDuckGo wraps links as `//duckduckgo.com/l/?uddg=<url>`. */
21
+ export function unwrapLink(href) {
22
+ try {
23
+ const url = new URL(href, "https://duckduckgo.com");
24
+ if (url.hostname.endsWith("duckduckgo.com")) {
25
+ if (url.pathname === "/y.js")
26
+ return null; // an ad
27
+ const target = url.searchParams.get("uddg");
28
+ return target && /^https?:\/\//i.test(target) ? target : null;
29
+ }
30
+ return /^https?:$/.test(url.protocol) ? url.href : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /** Reads a results page. `null`: not a results page we recognize (a block, or a changed layout). */
37
+ export async function parseResults(html) {
38
+ const document = await parseDocument(html);
39
+ const items = [...document.querySelectorAll(".result")];
40
+ if (!items.length)
41
+ return document.querySelector(".no-results") ? [] : null;
42
+ const seen = new Set();
43
+ const results = [];
44
+ for (const item of items) {
45
+ if (item.classList.contains("result--ad"))
46
+ continue;
47
+ const link = item.querySelector("a.result__a");
48
+ const url = link ? unwrapLink(link.getAttribute("href") ?? "") : null;
49
+ if (!link || !url || seen.has(url))
50
+ continue;
51
+ seen.add(url);
52
+ results.push({
53
+ title: (link.textContent ?? "").replace(/\s+/g, " ").trim() || url,
54
+ url,
55
+ snippet: (item.querySelector(".result__snippet")?.textContent ?? "")
56
+ .replace(/\s+/g, " ")
57
+ .trim(),
58
+ published: null,
59
+ });
60
+ if (results.length === MAX_RESULTS)
61
+ break;
62
+ }
63
+ // Results that are all ads, or none we could read, mean the layout isn't what we know.
64
+ return results.length ? results : null;
65
+ }
66
+ function wait(ms, signal) {
67
+ return new Promise((resolve, reject) => {
68
+ if (signal.aborted)
69
+ return reject(signal.reason);
70
+ const timer = setTimeout(done, ms);
71
+ function done() {
72
+ signal.removeEventListener("abort", onAbort);
73
+ resolve();
74
+ }
75
+ function onAbort() {
76
+ clearTimeout(timer);
77
+ reject(signal.reason);
78
+ }
79
+ signal.addEventListener("abort", onAbort, { once: true });
80
+ });
81
+ }
82
+ /** Searches from this computer. The user's `signal` aborting is thrown; anything else is a result. */
83
+ export async function searchFromDevice(query, options) {
84
+ const now = options.now ?? Date.now;
85
+ if (now() < deviceState.blockedUntil)
86
+ return { ok: false, why: "backoff" };
87
+ const gap = deviceState.lastAt + MIN_INTERVAL_MS - now();
88
+ if (gap > 0)
89
+ await wait(gap, options.signal);
90
+ deviceState.lastAt = now();
91
+ const locale = options.locale ?? Intl.DateTimeFormat().resolvedOptions().locale;
92
+ const form = new URLSearchParams({
93
+ q: query.site ? `${query.query} site:${query.site}` : query.query,
94
+ kl: regionFor(locale),
95
+ });
96
+ if (query.recency)
97
+ form.set("df", RECENCY_PARAM[query.recency]);
98
+ const timeout = AbortSignal.timeout(DEVICE_TIMEOUT_MS);
99
+ let html;
100
+ try {
101
+ const res = await options.fetch(ENDPOINT, {
102
+ method: "POST",
103
+ headers: {
104
+ "content-type": "application/x-www-form-urlencoded",
105
+ accept: "text/html",
106
+ "accept-language": `${locale}, en;q=0.8`,
107
+ "user-agent": options.userAgent,
108
+ },
109
+ body: form.toString(),
110
+ signal: AbortSignal.any([options.signal, timeout]),
111
+ });
112
+ // DuckDuckGo answers automated-looking traffic with 202 and a challenge instead of results.
113
+ if (res.status !== 200) {
114
+ res.body?.cancel().catch(() => { });
115
+ deviceState.blockedUntil = now() + BACKOFF_MS;
116
+ return { ok: false, why: "blocked" };
117
+ }
118
+ html = await res.text();
119
+ }
120
+ catch {
121
+ if (options.signal.aborted)
122
+ throw options.signal.reason;
123
+ return { ok: false, why: timeout.aborted ? "timeout" : "network" };
124
+ }
125
+ const results = await parseResults(html);
126
+ if (results === null) {
127
+ deviceState.blockedUntil = now() + BACKOFF_MS;
128
+ return { ok: false, why: "unreadable" };
129
+ }
130
+ return results.length ? { ok: true, results } : { ok: false, why: "empty" };
131
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The few DOM calls the web tools make, typed here so they compile the same with or without the
3
+ * DOM's own types (the CLI builds without them; the desktop's builds have them).
4
+ */
5
+ /** Parses HTML into a document (linkedom, loaded on first use). */
6
+ export async function parseDocument(html) {
7
+ const { parseHTML } = await import("linkedom");
8
+ return parseHTML(html).document;
9
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * A web page as markdown for the model: the main content (Readability), with links made absolute,
3
+ * images reduced to their descriptions and page furniture dropped. The libraries load on first use,
4
+ * so starting the agent doesn't pay for them.
5
+ */
6
+ import { parseDocument } from "./dom.js";
7
+ /** Elements that are never content. */
8
+ const NOISE = ["script", "style", "noscript", "template", "iframe", "svg", "canvas", "object"];
9
+ /** Page furniture, dropped when Readability can't find an article and the whole body is used. */
10
+ const FURNITURE = ["nav", "header", "footer", "aside", "form", "button", "dialog"];
11
+ const tidy = (text) => text
12
+ .replace(/[ \t]+\n/g, "\n")
13
+ .replace(/\n{3,}/g, "\n\n")
14
+ .trim();
15
+ export async function htmlToMarkdown(html, pageUrl) {
16
+ const [document, { Readability }, { default: TurndownService }] = await Promise.all([
17
+ parseDocument(html),
18
+ import("@mozilla/readability"),
19
+ import("turndown"),
20
+ ]);
21
+ // Absolute links, so the model can read them with web_fetch.
22
+ for (const a of document.querySelectorAll("a[href]")) {
23
+ try {
24
+ a.setAttribute("href", new URL(a.getAttribute("href") ?? "", pageUrl).href);
25
+ }
26
+ catch {
27
+ a.removeAttribute("href");
28
+ }
29
+ }
30
+ for (const el of document.querySelectorAll(NOISE.join(",")))
31
+ el.remove();
32
+ const title = (document.title || "").trim();
33
+ let content = null;
34
+ try {
35
+ // Readability changes the document it reads, so it gets a copy.
36
+ const copy = document.cloneNode(true);
37
+ const article = new Readability(copy, {
38
+ charThreshold: 200,
39
+ }).parse();
40
+ if (article?.content && (article.textContent ?? "").trim().length >= 200) {
41
+ content = article.content;
42
+ }
43
+ }
44
+ catch {
45
+ // fall back to the whole body
46
+ }
47
+ if (content === null) {
48
+ for (const el of document.querySelectorAll(FURNITURE.join(",")))
49
+ el.remove();
50
+ content = document.body?.innerHTML ?? html;
51
+ }
52
+ const turndown = new TurndownService({
53
+ headingStyle: "atx",
54
+ codeBlockStyle: "fenced",
55
+ bulletListMarker: "-",
56
+ emDelimiter: "*",
57
+ });
58
+ turndown.remove(NOISE);
59
+ turndown.addRule("images", {
60
+ filter: "img",
61
+ replacement: (_content, node) => {
62
+ const alt = (node.getAttribute("alt") ?? "").trim();
63
+ return alt ? `[image: ${alt}]` : "";
64
+ },
65
+ });
66
+ // The model reads this text, so markdown escapes would only get in its way.
67
+ turndown.escape = (text) => text;
68
+ // Heading anchors ("#", "¶", or an invisible character linking to the heading itself).
69
+ turndown.addRule("anchors", {
70
+ filter: (node) => {
71
+ const el = node;
72
+ const text = (el.textContent ?? "").replace(/[\u200b\u00a0\s]/g, "");
73
+ return el.nodeName === "A" && ["", "#", "¶", "§", "🔗"].includes(text);
74
+ },
75
+ replacement: () => "",
76
+ });
77
+ // Links whose text is the address itself read better bare.
78
+ turndown.addRule("plainLinks", {
79
+ filter: (node) => {
80
+ const el = node;
81
+ const href = el.getAttribute("href");
82
+ return el.nodeName === "A" && !!href && (el.textContent ?? "").trim() === href;
83
+ },
84
+ replacement: (content) => content,
85
+ });
86
+ const fragment = await parseDocument(`<!doctype html><html><body>${content}</body></html>`);
87
+ const body = fragment.body;
88
+ const markdown = tidy(turndown.turndown(body));
89
+ return { title, markdown };
90
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Reads one public web page for `web_fetch`: http(s) only, never this computer or the local network
3
+ * (checked on the hostname and again on every address it resolves to, at connect time), redirects
4
+ * followed only within the same site, a time limit, a size cap and text content only.
5
+ */
6
+ import { lookup as dnsLookup } from "node:dns";
7
+ import http from "node:http";
8
+ import https from "node:https";
9
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
10
+ import { isLocalHostname, isNonPublicAddress } from "../../../browser/guards.js";
11
+ import { siteOf } from "../../permissions.js";
12
+ /** A page has this long, redirects included. */
13
+ export const PAGE_TIMEOUT_MS = 20_000;
14
+ /** Bigger bodies are refused (read as they arrive, so a huge page never fills memory). */
15
+ export const MAX_PAGE_BYTES = 5 * 1024 * 1024;
16
+ const MAX_REDIRECTS = 5;
17
+ /** A host that resolved to this computer or the local network. */
18
+ export class NonPublicAddressError extends Error {
19
+ hostname;
20
+ constructor(hostname) {
21
+ super(`${hostname} is on this computer or the local network.`);
22
+ this.hostname = hostname;
23
+ }
24
+ }
25
+ /**
26
+ * A `lookup` for sockets that refuses non-public addresses, so a name can't be pointed at the
27
+ * local network between our check and the connection (DNS rebinding): the check is the connection's
28
+ * own resolution.
29
+ */
30
+ export function guardedLookup(resolve = dnsLookup) {
31
+ return (hostname, options, callback) => {
32
+ resolve(hostname, { ...options, all: true }, (error, addresses) => {
33
+ if (error)
34
+ return callback(error, []);
35
+ const list = addresses;
36
+ if (!list.length || list.some((a) => isNonPublicAddress(a.address))) {
37
+ return callback(new NonPublicAddressError(hostname), []);
38
+ }
39
+ if (options.all)
40
+ callback(null, list);
41
+ else
42
+ callback(null, list[0].address, list[0].family);
43
+ });
44
+ };
45
+ }
46
+ function headerMap(headers) {
47
+ return Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : v]));
48
+ }
49
+ /** The real transport: Node's http(s) with the guarded lookup and decompression. */
50
+ export const nodeTransport = (url, { headers, signal }) => new Promise((resolve, reject) => {
51
+ const request = (url.protocol === "http:" ? http : https).request(url, { method: "GET", headers, signal, lookup: guardedLookup() }, (res) => {
52
+ const encoding = (res.headers["content-encoding"] ?? "").toLowerCase().trim();
53
+ let body = res;
54
+ if (encoding === "gzip" || encoding === "x-gzip")
55
+ body = res.pipe(createGunzip());
56
+ else if (encoding === "br")
57
+ body = res.pipe(createBrotliDecompress());
58
+ else if (encoding === "deflate")
59
+ body = res.pipe(createInflate());
60
+ if (body !== res)
61
+ res.on("error", (error) => body.destroy(error));
62
+ resolve({
63
+ status: res.statusCode ?? 0,
64
+ headers: headerMap(res.headers),
65
+ body,
66
+ cancel: () => {
67
+ body.destroy();
68
+ res.destroy();
69
+ },
70
+ });
71
+ });
72
+ request.on("error", reject);
73
+ request.end();
74
+ });
75
+ const HTML_TYPES = new Set(["text/html", "application/xhtml+xml"]);
76
+ const isTextType = (type) => type.startsWith("text/") ||
77
+ type === "application/json" ||
78
+ type.endsWith("+json") ||
79
+ type === "application/xml" ||
80
+ type.endsWith("+xml") ||
81
+ type === "application/javascript" ||
82
+ type === "application/x-ndjson";
83
+ /** Plain-language reason for an HTTP error status. */
84
+ export function statusReason(status) {
85
+ if (status === 401 || status === 407)
86
+ return `it needs a sign-in (${status})`;
87
+ if (status === 403)
88
+ return "the site refused (403)";
89
+ if (status === 404 || status === 410)
90
+ return `page not found (${status})`;
91
+ if (status === 429)
92
+ return "the site is limiting requests (429)";
93
+ if (status >= 500)
94
+ return `the site had an error (${status})`;
95
+ return `the site answered ${status}`;
96
+ }
97
+ function networkReason(error) {
98
+ const code = error?.code ?? "";
99
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN")
100
+ return "the site couldn't be found";
101
+ if (code.startsWith("CERT_") || code.includes("SELF_SIGNED") || code.startsWith("ERR_TLS")) {
102
+ return "its security certificate isn't valid";
103
+ }
104
+ if (code === "ECONNREFUSED")
105
+ return "the site refused the connection";
106
+ if (code === "ECONNRESET" || code === "EPIPE")
107
+ return "the connection dropped";
108
+ // zlib (Z_DATA_ERROR…) and brotli (ERR__ERROR_FORMAT_…) decoding errors
109
+ if (code.startsWith("Z_") || code.startsWith("ERR__ERROR_FORMAT")) {
110
+ return "its content couldn't be decoded";
111
+ }
112
+ return code ? `couldn't connect (${code})` : "couldn't connect";
113
+ }
114
+ function decode(bytes, contentType) {
115
+ const charset = /charset="?([^";\s]+)/i.exec(contentType)?.[1];
116
+ try {
117
+ return new TextDecoder(charset ?? "utf-8").decode(bytes);
118
+ }
119
+ catch {
120
+ return new TextDecoder("utf-8").decode(bytes);
121
+ }
122
+ }
123
+ /**
124
+ * Fetches `url` (already checked: http(s), not a local hostname). The user's `signal` aborting is
125
+ * thrown as its reason; everything else comes back as an outcome.
126
+ */
127
+ export async function readPage(url, options) {
128
+ const transport = options.transport ?? nodeTransport;
129
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? PAGE_TIMEOUT_MS);
130
+ const signal = AbortSignal.any([options.signal, timeout]);
131
+ const site = siteOf(url);
132
+ const headers = {
133
+ "user-agent": options.userAgent,
134
+ accept: "text/html,application/xhtml+xml,text/markdown;q=0.9,text/plain;q=0.8,*/*;q=0.5",
135
+ "accept-encoding": "gzip, deflate, br",
136
+ "accept-language": "en;q=0.9, *;q=0.5",
137
+ };
138
+ const fail = (error) => {
139
+ if (options.signal.aborted)
140
+ throw options.signal.reason;
141
+ if (timeout.aborted)
142
+ return { kind: "error", reason: "it took too long" };
143
+ if (error instanceof NonPublicAddressError) {
144
+ return { kind: "error", reason: "local network addresses are off limits", local: true };
145
+ }
146
+ return { kind: "error", reason: networkReason(error) };
147
+ };
148
+ let current = new URL(url);
149
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
150
+ let res;
151
+ try {
152
+ res = await transport(current, { headers, signal });
153
+ }
154
+ catch (error) {
155
+ return fail(error);
156
+ }
157
+ const location = res.headers.location;
158
+ if (res.status >= 300 && res.status < 400 && location) {
159
+ res.cancel();
160
+ let next;
161
+ try {
162
+ next = new URL(location, current);
163
+ }
164
+ catch {
165
+ return { kind: "error", reason: "it redirects to an invalid address" };
166
+ }
167
+ if (next.protocol !== "http:" && next.protocol !== "https:") {
168
+ return { kind: "error", reason: "it redirects to something that isn't a web page" };
169
+ }
170
+ if (isLocalHostname(next.hostname)) {
171
+ return { kind: "error", reason: "local network addresses are off limits", local: true };
172
+ }
173
+ if (siteOf(next) !== site)
174
+ return { kind: "redirect", to: next.href };
175
+ current = next;
176
+ continue;
177
+ }
178
+ if (res.status < 200 || res.status >= 300) {
179
+ res.cancel();
180
+ return { kind: "error", reason: statusReason(res.status) };
181
+ }
182
+ const contentType = (res.headers["content-type"] ?? "").toLowerCase();
183
+ const type = contentType.split(";")[0].trim();
184
+ if (type === "application/pdf") {
185
+ res.cancel();
186
+ return { kind: "error", reason: "PDFs aren't supported yet" };
187
+ }
188
+ if (type && !HTML_TYPES.has(type) && !isTextType(type)) {
189
+ res.cancel();
190
+ return { kind: "error", reason: `it isn't a web page (${type})` };
191
+ }
192
+ const chunks = [];
193
+ let size = 0;
194
+ try {
195
+ for await (const chunk of res.body) {
196
+ size += chunk.byteLength;
197
+ if (size > MAX_PAGE_BYTES) {
198
+ res.cancel();
199
+ return { kind: "error", reason: "the page is too large" };
200
+ }
201
+ chunks.push(chunk);
202
+ }
203
+ }
204
+ catch (error) {
205
+ return fail(error);
206
+ }
207
+ const bytes = new Uint8Array(size);
208
+ let offset = 0;
209
+ for (const chunk of chunks) {
210
+ bytes.set(chunk, offset);
211
+ offset += chunk.byteLength;
212
+ }
213
+ const body = decode(bytes, contentType);
214
+ const html = HTML_TYPES.has(type) || (!type && /^\s*</.test(body));
215
+ return { kind: "page", url: current.href, body, html };
216
+ }
217
+ return { kind: "error", reason: "it redirects too many times" };
218
+ }