@parcha/agentrun-web 0.0.0-stage → 0.1.0-beta.57

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.
@@ -0,0 +1,46 @@
1
+ /** The guard's resolver and fetch (a test's fake network), and a signal that ends the fetch. */
2
+ export type GuardOptions = {
3
+ /** Every address a name resolves to; default the guard's own (the system resolver). */
4
+ lookup?: (host: string) => Promise<string[]>;
5
+ /** The fetch the guard dials through; default the guard's own. */
6
+ fetchImpl?: (url: URL, init: Record<string, unknown>) => Promise<Response>;
7
+ signal?: AbortSignal;
8
+ };
9
+ /** The answer that ended the redirects: its URL, status and type, and its body when it is a 2xx text answer. */
10
+ export type PublicAnswer = {
11
+ url: string;
12
+ status: number;
13
+ contentType: string;
14
+ body: string | null;
15
+ };
16
+ /** The guarded fetch: `maxBytes` its byte cap (the guard's default when not given). */
17
+ export type PublicFetch = (url: string, options: GuardOptions & {
18
+ maxBytes?: number;
19
+ }) => Promise<PublicAnswer>;
20
+ /** An HTML page read as text: its title, its text (markdown), its links; `truncated` with `html_chars` (the page's whole
21
+ * length) when its HTML was cut before it was read (HTML_READ_CHARS), `converted: "text"` when its conversion to
22
+ * markdown ran out of time and the text is the page's plain text. */
23
+ export type HtmlRead = {
24
+ title: string;
25
+ text: string;
26
+ links: string[];
27
+ converted?: "markdown" | "text";
28
+ truncated?: true;
29
+ html_chars?: number;
30
+ };
31
+ /** The HTML reader the direct fetch hands an HTML page to; `signal` ends the read. */
32
+ export type HtmlReader = (html: string, url: string, options: {
33
+ signal?: AbortSignal;
34
+ }) => Promise<HtmlRead>;
35
+ /** The guard's check of a URL's first hop with nothing sent: resolves when the guarded fetch would dial it, throws its
36
+ * refusal when not. A URL goes to a provider only once this passes. */
37
+ export type PublicCheck = (url: string, options: Pick<GuardOptions, "lookup" | "signal">) => Promise<void>;
38
+ /** The guarded fetch, its check, and for an HTML page its reader (none: an HTML page's body is read as plain text). */
39
+ export type Guard = {
40
+ fetch: PublicFetch;
41
+ check: PublicCheck;
42
+ html?: HtmlReader;
43
+ };
44
+ /** Whether `error` is the guard's refusal (a private, loopback, link-local or intranet address, a scheme other than
45
+ * http(s), a redirect to one): an error whose `failure.code` is "refused". */
46
+ export declare const isRefused: (error: unknown) => boolean;
package/dist/guard.js ADDED
@@ -0,0 +1,3 @@
1
+ /** Whether `error` is the guard's refusal (a private, loopback, link-local or intranet address, a scheme other than
2
+ * http(s), a redirect to one): an error whose `failure.code` is "refused". */
3
+ export const isRefused = (error) => error?.failure?.code === "refused";
@@ -0,0 +1,12 @@
1
+ export { type FetchOptions, type NativeSearch, type ProviderId, type Receipt, type SearchOptions, type SearchProvider, type Web, type WebConfig, createWeb } from "./web.js";
2
+ export { type Guard, type GuardOptions, type HtmlRead, type HtmlReader, type PublicAnswer, type PublicCheck, type PublicFetch } from "./guard.js";
3
+ export { type Fee, type ParallelSearchMode, type Pay, PARALLEL_EXTRACT_USD, PARALLEL_SEARCH_INCLUDED, PARALLEL_SEARCH_MODE_USD, PARALLEL_SEARCH_RESULT_USD, PARALLEL_SEARCH_USD, PaidRefused, parallelExtractFee, parallelFeeOf, parallelSearchFee, unmetered, } from "./fees.js";
4
+ export { type Backend, type Breaker, type Hit, type Limit, type Search, type SearchBounds, type Searched, type Try, ANSWER_MAX, breakers, CITE, fitSearch, QUERY_MAX, RESULTS_DEFAULT, RESULTS_MAX, SEARCH_MAX_CHARS, SNIPPET_MAX, searchArgs, searchInTurn, searchText, snippetOf, } from "./search.js";
5
+ export { type FetchProvider, type FetchTry, type Pages, type WebFetchOptions, type WebLog, type WebPage, type WebRead, type WebUnread, FETCH_ORDER, PAGES_HELD, webFetch, webFetchText } from "./fetch.js";
6
+ export { type Page, type Part, type Read, type Unread, askedUrl, clip, HTML_READ_CHARS, LINKS_CAP, LINKS_CHARS, MAX_CHARS_MIN, PAGE_CHARS, PAGE_MAX_BYTES, PAGE_READ_MAX_CHARS, partEnd, partProblem, TEXT_CAP, TITLE_CAP, URL_MAX, } from "./page.js";
7
+ export { fetchPage, readDirect } from "./providers/direct.js";
8
+ export { type ExaLimited, exaSearch } from "./providers/exa-keyless.js";
9
+ export { type FirecrawlFailed, type FirecrawlOptions, type KeylessFetch, firecrawlFetch, firecrawlScrape, firecrawlSearch } from "./providers/firecrawl-keyless.js";
10
+ export type { Words } from "./providers/mcp.js";
11
+ export { type Extract, PARALLEL_EXTRACT_URL, PARALLEL_SEARCH_URL, parallelExtract, parallelSearched } from "./providers/parallel.js";
12
+ export { type WrittenLink, linksOf, linksWritten, TRAILING, trimmed, wholeUrl } from "./text-urls.js";
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ // @parcha/agentrun-web: web search and web fetch for an agent. It imports nothing of a server, a harness, a browser or a
2
+ // vendor SDK: the public-host guard, the HTML reader, the run's cap, a native search and a product's words come in
3
+ // through WebConfig (createWeb) or as arguments, as data or injected functions.
4
+ //
5
+ // The package's whole API, named one by one: createWeb and its types, the pieces it is built from (README), and the
6
+ // bounds and words AgentRun's server reads. Anything else in src is internal and may change in any release.
7
+ export { createWeb } from "./web.js";
8
+ export { PARALLEL_EXTRACT_USD, PARALLEL_SEARCH_INCLUDED, PARALLEL_SEARCH_MODE_USD, PARALLEL_SEARCH_RESULT_USD, PARALLEL_SEARCH_USD, PaidRefused, parallelExtractFee, parallelFeeOf, parallelSearchFee, unmetered, } from "./fees.js";
9
+ export { ANSWER_MAX, breakers, CITE, fitSearch, QUERY_MAX, RESULTS_DEFAULT, RESULTS_MAX, SEARCH_MAX_CHARS, SNIPPET_MAX, searchArgs, searchInTurn, searchText, snippetOf, } from "./search.js";
10
+ export { FETCH_ORDER, PAGES_HELD, webFetch, webFetchText } from "./fetch.js";
11
+ export { askedUrl, clip, HTML_READ_CHARS, LINKS_CAP, LINKS_CHARS, MAX_CHARS_MIN, PAGE_CHARS, PAGE_MAX_BYTES, PAGE_READ_MAX_CHARS, partEnd, partProblem, TEXT_CAP, TITLE_CAP, URL_MAX, } from "./page.js";
12
+ export { fetchPage, readDirect } from "./providers/direct.js";
13
+ export { exaSearch } from "./providers/exa-keyless.js";
14
+ export { firecrawlFetch, firecrawlScrape, firecrawlSearch } from "./providers/firecrawl-keyless.js";
15
+ export { PARALLEL_EXTRACT_URL, PARALLEL_SEARCH_URL, parallelExtract, parallelSearched } from "./providers/parallel.js";
16
+ export { linksOf, linksWritten, TRAILING, trimmed, wholeUrl } from "./text-urls.js";
package/dist/page.d.ts ADDED
@@ -0,0 +1,117 @@
1
+ /** On a page that was read, `chars`: the length of `text`, the part of the page's text this answer holds. `truncated`
2
+ * while more of it follows this part, and `next_offset` where that begins; `offset` where this part begins, when not 0;
3
+ * `original_chars` the whole text's length in characters, when it is known and this part is not all of it;
4
+ * `beyond_read` on the last part a read reaches of a page that goes on past PAGE_READ_MAX_CHARS; `links_omitted`, with the
5
+ * first part, how many of the page's links its caps left out. `html_chars`, on every part of a page whose HTML readPage
6
+ * cut before it was read: the page's whole length in characters. Its text, all its parts together, is then the start of
7
+ * the page's, so no part gives original_chars, and the last part (no truncated: no part follows) still says the page was
8
+ * cut. `converted: "text"` when the text is the page's plain text, its conversion to markdown having run out of time. */
9
+ export type Page = {
10
+ ok: boolean;
11
+ url: string;
12
+ status: number;
13
+ title: string;
14
+ text: string;
15
+ chars?: number;
16
+ truncated?: true;
17
+ original_chars?: number;
18
+ beyond_read?: true;
19
+ offset?: number;
20
+ next_offset?: number;
21
+ html_chars?: number;
22
+ converted?: "text";
23
+ links: string[];
24
+ links_omitted?: number;
25
+ refused?: string;
26
+ error?: string;
27
+ };
28
+ /** The most of a page's text one answer holds (max_chars at most), what it holds when max_chars is not given, and the
29
+ * least max_chars a tool's call may ask for (a smaller one is refused, saying so). */
30
+ export declare const TEXT_CAP = 50000;
31
+ export declare const PAGE_CHARS = 20000;
32
+ export declare const MAX_CHARS_MIN = 200;
33
+ /** The most of a page's TEXT web_fetch reads, from either provider: its first million characters (not HTML_READ_CHARS,
34
+ * readPage's cut of the HTML before any text is read). A part reads within it, Parallel is never asked for more of a
35
+ * page than that and one character (providers/parallel.ts), and an offset at or past it is refused. */
36
+ export declare const PAGE_READ_MAX_CHARS = 1000000;
37
+ /** A page's links, with its first part only: at most LINKS_CAP of them, in at most LINKS_CHARS characters of the answer. */
38
+ export declare const LINKS_CAP = 200;
39
+ export declare const LINKS_CHARS = 20000;
40
+ export declare const TITLE_CAP = 500;
41
+ /** The longest URL fetched: a longer one is refused before anything is sent. */
42
+ export declare const URL_MAX = 4096;
43
+ export declare const TIMEOUT_MS = 30000;
44
+ /** Where the HTML reader cuts a page's HTML before it reads it, scripts and styles aside (not PAGE_READ_MAX_CHARS, the
45
+ * most of the text read): pi-browser's READ_MAX_CHARS, the reader serve injects, held here so the tool's words name it
46
+ * without loading a reader where nothing is fetched (web-fetch-direct-cut.test holds the two equal). */
47
+ export declare const HTML_READ_CHARS = 1000000;
48
+ /** The most bytes of a page any path reads: the guarded direct fetch's bound (pi-browser's PUBLIC_MAX_BYTES, 5 MiB,
49
+ * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. */
50
+ export declare const PAGE_MAX_BYTES: number;
51
+ export declare const clip: (text: string, max: number) => string;
52
+ /** `text` with any URL in it stripped of its user name and password (`//user:pass@host` to `//host`). An error may quote
53
+ * a URL that holds them (undici's refusal of a redirect to one quotes it whole). Run it on the whole text, before any
54
+ * cut: a cut can end inside them, leaving no "@" for it to find. It reads on to the last "@" before the host, as a URL
55
+ * does: a password may hold an "@" left unencoded. */
56
+ export declare const withoutUserinfo: (text: string) => string;
57
+ /** `url`, a page's, with no user name or password, cleared as a URL (a URL drops a tab or a newline in them and encodes a
58
+ * space, where withoutUserinfo, reading free text, stops); "" where it does not parse, as no URL to name: a scrub of its
59
+ * text can stop short of them (at a space). A provider that followed a redirect names the URL it ended at, which may
60
+ * hold them. Run it before a url is cut: a cut can end inside them, leaving a url that does not parse. */
61
+ export declare function withoutCredentials(url: string): string;
62
+ /** The URL a call asked for, as a page names it: with no user name or password, and cut; "" where it is no string or
63
+ * does not parse (withoutCredentials). */
64
+ export declare const askedUrl: (url: unknown) => string;
65
+ /** Which part of a page's text an answer holds: from `offset` (0 by default), about `maxChars` characters (PAGE_CHARS by
66
+ * default, at most TEXT_CAP). */
67
+ export type Part = {
68
+ offset?: number;
69
+ maxChars?: number;
70
+ };
71
+ /** Why a tool's call may not read `part`, or undefined: an offset that is not a whole number of 0 or more, a maxChars that
72
+ * is not a number of MAX_CHARS_MIN or more (one past TEXT_CAP reads TEXT_CAP). */
73
+ export declare function partProblem({ offset, maxChars }: Part): string | undefined;
74
+ /** `part` in range: a whole offset of 0 or more, a whole maxChars of 1 to TEXT_CAP. */
75
+ export declare const partOf: (part?: Part) => Required<Part>;
76
+ /** Where the longest run of `text` from `start` ends whose JSON string takes at most `budget` characters (less its
77
+ * quotes): a character takes one, a quote, a backslash or a control character JSON writes short (\n, \t) two, any other
78
+ * control character or a lone surrogate six. A surrogate pair is never split. While a character is left the run holds
79
+ * one at least, whatever it takes, so a part always advances (only a budget under six can be passed, by that one). */
80
+ export declare function partEnd(text: string, start: number, budget: number): number;
81
+ /** A page's text as it is read once: its first PAGE_READ_MAX_CHARS characters (`text`), whether the page's text goes on
82
+ * past them (`beyond`), and its whole length where it is known (`length`). */
83
+ export type Text = {
84
+ text: string;
85
+ beyond: boolean;
86
+ length?: number;
87
+ };
88
+ /** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
89
+ * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
90
+ * it would, it is one unit short. */
91
+ export declare function textOf(text: string, whole: boolean): Text;
92
+ /** The part of a page's text an answer holds, and what it says of the rest. */
93
+ export declare function pageText({ text, beyond, length }: Text, part?: Part): Pick<Page, "text" | "chars" | "truncated" | "original_chars" | "beyond_read" | "offset" | "next_offset">;
94
+ /** A page's links as its first part holds them: in page order, at most LINKS_CAP of them, each one that fits in what is
95
+ * left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
96
+ export declare function linksWithin(links: Iterable<string>): Pick<Page, "links" | "links_omitted">;
97
+ /** A page read once, before any part of it is taken: its final url, status and title, its Text, the links its first part
98
+ * holds (linksWithin), and readPage's `html_chars` and `converted` where it gave them. */
99
+ export type Read = {
100
+ ok: true;
101
+ url: string;
102
+ status: number;
103
+ title: string;
104
+ links: string[];
105
+ links_omitted?: number;
106
+ html_chars?: number;
107
+ converted?: "text";
108
+ } & Text;
109
+ /** A Page that was not read, saying why. */
110
+ export type Unread = Page & {
111
+ ok: false;
112
+ };
113
+ /** The part `part` names of a page read once, as a Page: the links with its first part only. */
114
+ export declare function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }: Read, part?: Part): Page;
115
+ /** A page a provider read for us as markdown (Parallel's extract, keyless Firecrawl's scrape), as a Read: its url,
116
+ * title and status, the text (`whole`: all of the page's, so its length is the page's) and the links it holds. */
117
+ export declare const markdownRead: (url: string, title: string, text: string, whole: boolean, status?: number) => Read;
package/dist/page.js ADDED
@@ -0,0 +1,143 @@
1
+ // A page as web_fetch answers it. A page is read once (a Read, at most PAGE_READ_MAX_CHARS characters of text) and
2
+ // answered in parts (offset, maxChars). Every field of a Page is capped, so one answer stays under the host's bound.
3
+ import { linksOf } from "./text-urls.js";
4
+ /** The most of a page's text one answer holds (max_chars at most), what it holds when max_chars is not given, and the
5
+ * least max_chars a tool's call may ask for (a smaller one is refused, saying so). */
6
+ export const TEXT_CAP = 50_000;
7
+ export const PAGE_CHARS = 20_000;
8
+ export const MAX_CHARS_MIN = 200;
9
+ /** The most of a page's TEXT web_fetch reads, from either provider: its first million characters (not HTML_READ_CHARS,
10
+ * readPage's cut of the HTML before any text is read). A part reads within it, Parallel is never asked for more of a
11
+ * page than that and one character (providers/parallel.ts), and an offset at or past it is refused. */
12
+ export const PAGE_READ_MAX_CHARS = 1_000_000;
13
+ /** A page's links, with its first part only: at most LINKS_CAP of them, in at most LINKS_CHARS characters of the answer. */
14
+ export const LINKS_CAP = 200;
15
+ export const LINKS_CHARS = 20_000;
16
+ export const TITLE_CAP = 500;
17
+ /** The longest URL fetched: a longer one is refused before anything is sent. */
18
+ export const URL_MAX = 4_096;
19
+ export const TIMEOUT_MS = 30_000;
20
+ /** Where the HTML reader cuts a page's HTML before it reads it, scripts and styles aside (not PAGE_READ_MAX_CHARS, the
21
+ * most of the text read): pi-browser's READ_MAX_CHARS, the reader serve injects, held here so the tool's words name it
22
+ * without loading a reader where nothing is fetched (web-fetch-direct-cut.test holds the two equal). */
23
+ export const HTML_READ_CHARS = 1_000_000;
24
+ /** The most bytes of a page any path reads: the guarded direct fetch's bound (pi-browser's PUBLIC_MAX_BYTES, 5 MiB,
25
+ * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. */
26
+ export const PAGE_MAX_BYTES = 5 * 1024 * 1024;
27
+ export const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
28
+ /** `text` with any URL in it stripped of its user name and password (`//user:pass@host` to `//host`). An error may quote
29
+ * a URL that holds them (undici's refusal of a redirect to one quotes it whole). Run it on the whole text, before any
30
+ * cut: a cut can end inside them, leaving no "@" for it to find. It reads on to the last "@" before the host, as a URL
31
+ * does: a password may hold an "@" left unencoded. */
32
+ export const withoutUserinfo = (text) => text.replace(/\/\/[^\s/?#]*@/g, "//");
33
+ /** `url`, a page's, with no user name or password, cleared as a URL (a URL drops a tab or a newline in them and encodes a
34
+ * space, where withoutUserinfo, reading free text, stops); "" where it does not parse, as no URL to name: a scrub of its
35
+ * text can stop short of them (at a space). A provider that followed a redirect names the URL it ended at, which may
36
+ * hold them. Run it before a url is cut: a cut can end inside them, leaving a url that does not parse. */
37
+ export function withoutCredentials(url) {
38
+ const parsed = URL.parse(url);
39
+ if (!parsed)
40
+ return "";
41
+ if (!parsed.username && !parsed.password)
42
+ return url;
43
+ parsed.username = "";
44
+ parsed.password = "";
45
+ return clip(parsed.href, URL_MAX);
46
+ }
47
+ /** The URL a call asked for, as a page names it: with no user name or password, and cut; "" where it is no string or
48
+ * does not parse (withoutCredentials). */
49
+ export const askedUrl = (url) => (typeof url === "string" ? clip(withoutCredentials(url), URL_MAX) : "");
50
+ /** Why a tool's call may not read `part`, or undefined: an offset that is not a whole number of 0 or more, a maxChars that
51
+ * is not a number of MAX_CHARS_MIN or more (one past TEXT_CAP reads TEXT_CAP). */
52
+ export function partProblem({ offset, maxChars }) {
53
+ const shown = (value) => (typeof value === "number" ? String(value) : String(JSON.stringify(value)).slice(0, 40));
54
+ if (offset !== undefined && !(Number.isInteger(offset) && offset >= 0))
55
+ return `offset must be a whole number, 0 or more (it was ${shown(offset)})`;
56
+ if (offset !== undefined && offset >= PAGE_READ_MAX_CHARS)
57
+ return `offset must be under ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")}: web_fetch reads a page's first ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")} characters (it was ${shown(offset)})`;
58
+ if (maxChars !== undefined && !(typeof maxChars === "number" && maxChars >= MAX_CHARS_MIN))
59
+ return `max_chars must be ${typeof maxChars === "number" ? "" : "a number, "}at least ${MAX_CHARS_MIN} (it was ${shown(maxChars)})`;
60
+ return undefined;
61
+ }
62
+ /** `part` in range: a whole offset of 0 or more, a whole maxChars of 1 to TEXT_CAP. */
63
+ export const partOf = (part = {}) => ({
64
+ offset: Math.max(0, Math.floor(Number(part.offset) || 0)),
65
+ maxChars: Math.max(1, Math.min(TEXT_CAP, Math.floor(Number(part.maxChars) || PAGE_CHARS))),
66
+ });
67
+ /** Where the longest run of `text` from `start` ends whose JSON string takes at most `budget` characters (less its
68
+ * quotes): a character takes one, a quote, a backslash or a control character JSON writes short (\n, \t) two, any other
69
+ * control character or a lone surrogate six. A surrogate pair is never split. While a character is left the run holds
70
+ * one at least, whatever it takes, so a part always advances (only a budget under six can be passed, by that one). */
71
+ export function partEnd(text, start, budget) {
72
+ let at = start;
73
+ for (let used = 0; at < text.length;) {
74
+ const unit = text.charCodeAt(at);
75
+ let width = 1;
76
+ let cost = 1;
77
+ if (unit >= 0xd800 && unit <= 0xdbff && at + 1 < text.length && (text.charCodeAt(at + 1) & 0xfc00) === 0xdc00)
78
+ [width, cost] = [2, 2];
79
+ else if ((unit & 0xf800) === 0xd800)
80
+ cost = 6;
81
+ else if (unit === 0x22 || unit === 0x5c || unit === 0x08 || unit === 0x09 || unit === 0x0a || unit === 0x0c || unit === 0x0d)
82
+ cost = 2;
83
+ else if (unit < 0x20)
84
+ cost = 6;
85
+ if (used + cost > budget && at > start)
86
+ break;
87
+ used += cost;
88
+ at += width;
89
+ }
90
+ return at;
91
+ }
92
+ /** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
93
+ * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
94
+ * it would, it is one unit short. */
95
+ export function textOf(text, whole) {
96
+ const beyond = text.length > PAGE_READ_MAX_CHARS;
97
+ const split = (text.charCodeAt(PAGE_READ_MAX_CHARS - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(PAGE_READ_MAX_CHARS) & 0xfc00) === 0xdc00;
98
+ return { text: beyond ? text.slice(0, PAGE_READ_MAX_CHARS - (split ? 1 : 0)) : text, beyond, ...(whole ? { length: text.length } : {}) };
99
+ }
100
+ /** The part of a page's text an answer holds, and what it says of the rest. */
101
+ export function pageText({ text, beyond, length }, part = {}) {
102
+ const { offset, maxChars } = partOf(part);
103
+ const start = Math.min(offset, text.length);
104
+ const end = partEnd(text, start, maxChars);
105
+ const held = text.slice(start, end);
106
+ const more = end < text.length;
107
+ // The last part a read reaches of a page that goes on past it.
108
+ const last = !more && beyond;
109
+ return {
110
+ text: held,
111
+ chars: held.length,
112
+ ...(more ? { truncated: true } : {}),
113
+ ...(length !== undefined && (offset > 0 || more || last) ? { original_chars: length } : {}),
114
+ ...(last ? { beyond_read: true } : {}),
115
+ ...(offset > 0 ? { offset } : {}),
116
+ ...(more ? { next_offset: end } : {}),
117
+ };
118
+ }
119
+ /** A page's links as its first part holds them: in page order, at most LINKS_CAP of them, each one that fits in what is
120
+ * left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
121
+ export function linksWithin(links) {
122
+ const kept = [];
123
+ let used = 0;
124
+ let omitted = 0;
125
+ for (const link of links) {
126
+ const cost = JSON.stringify(link).length + 1;
127
+ if (kept.length === LINKS_CAP || used + cost > LINKS_CHARS) {
128
+ omitted += 1;
129
+ continue;
130
+ }
131
+ kept.push(link);
132
+ used += cost;
133
+ }
134
+ return { links: kept, ...(omitted ? { links_omitted: omitted } : {}) };
135
+ }
136
+ /** The part `part` names of a page read once, as a Page: the links with its first part only. */
137
+ export function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }, part = {}) {
138
+ const first = partOf(part).offset === 0;
139
+ return { ...page, ...pageText({ text, beyond, length }, part), ...(html_chars === undefined ? {} : { html_chars }), ...(converted ? { converted } : {}), links: first ? links : [], ...(first && links_omitted ? { links_omitted } : {}) };
140
+ }
141
+ /** A page a provider read for us as markdown (Parallel's extract, keyless Firecrawl's scrape), as a Read: its url,
142
+ * title and status, the text (`whole`: all of the page's, so its length is the page's) and the links it holds. */
143
+ export const markdownRead = (url, title, text, whole, status = 200) => ({ ok: true, url: clip(withoutCredentials(url), URL_MAX), status, title: clip(title, TITLE_CAP), ...textOf(text, whole), ...linksWithin(linksOf(text)) });
@@ -0,0 +1,9 @@
1
+ import { type Guard, type GuardOptions } from "../guard.js";
2
+ import { type Page, type Part, type Read, type Unread } from "../page.js";
3
+ /** The page at `url`, read once through `guard`'s fetch (an HTML page through its reader), or why it was not. `options`
4
+ * are the guard's resolver and fetch, for a test; a signal ends it early. */
5
+ export declare function readDirect(url: unknown, guard: Guard | undefined, options?: GuardOptions): Promise<Read | Unread>;
6
+ /** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
7
+ export declare function fetchPage(url: unknown, { guard, offset, maxChars, ...options }?: GuardOptions & Part & {
8
+ guard?: Guard;
9
+ }): Promise<Page>;
@@ -0,0 +1,53 @@
1
+ // The guarded direct fetch: one page through the injected public-host guard. A refusal or a failure is a Page with ok
2
+ // false, never a throw. With no guard nothing is fetched.
3
+ import { isRefused } from "../guard.js";
4
+ import { askedUrl, clip, linksWithin, partOfRead, TIMEOUT_MS, TITLE_CAP, textOf, URL_MAX, withoutCredentials, withoutUserinfo } from "../page.js";
5
+ import { linksOf } from "../text-urls.js";
6
+ /** The page at `url`, read once through `guard`'s fetch (an HTML page through its reader), or why it was not. `options`
7
+ * are the guard's resolver and fetch, for a test; a signal ends it early. */
8
+ export async function readDirect(url, guard, options = {}) {
9
+ const failed = (fields) => ({ ok: false, url: askedUrl(url), status: 0, title: "", text: "", links: [], ...fields });
10
+ if (typeof url !== "string" || !URL.canParse(url))
11
+ return failed({ error: "url is not an absolute URL" });
12
+ const target = new URL(url);
13
+ // The bound is on the href, what the guard fetches: percent-encoding can grow it past the string as asked.
14
+ if (target.href.length > URL_MAX)
15
+ return failed({ error: `url is longer than ${URL_MAX.toLocaleString("en-US")} characters` });
16
+ const { port, username, password } = target;
17
+ if (port && port !== "80" && port !== "443")
18
+ return failed({ refused: `refused: port ${port} is not 80 or 443` });
19
+ // A URL's user name and password are never sent anywhere: a fetch refuses them, never a third party's read of them.
20
+ if (username || password)
21
+ return failed({ refused: "refused: the URL holds a user name or password" });
22
+ if (!guard)
23
+ return failed({ error: "no public-host guard was given, so nothing is fetched directly" });
24
+ try {
25
+ const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(options.signal ? [options.signal] : [])]);
26
+ const answer = await guard.fetch(url, { ...options, signal });
27
+ if (answer.body === null)
28
+ return failed({ url: clip(withoutCredentials(answer.url), URL_MAX), status: answer.status, error: `the page answered ${answer.status}` });
29
+ // The caller's stop reaches the read too; the timeout is the network's, and the reader keeps its own deadline.
30
+ const read = guard.html && /html/i.test(answer.contentType) ? await guard.html(answer.body, answer.url, options.signal ? { signal: options.signal } : {}) : null;
31
+ const page = read ?? { title: "", text: answer.body, links: linksOf(answer.body) };
32
+ return {
33
+ ok: true,
34
+ url: clip(withoutCredentials(answer.url), URL_MAX),
35
+ status: answer.status,
36
+ title: clip(page.title, TITLE_CAP),
37
+ ...textOf(page.text, !read?.truncated),
38
+ ...(read?.truncated ? { html_chars: read.html_chars } : {}),
39
+ ...(read?.converted === "text" ? { converted: "text" } : {}),
40
+ ...linksWithin(page.links),
41
+ };
42
+ }
43
+ catch (error) {
44
+ // Never a URL's user name or password: undici's refusal of a redirect to a URL holding them quotes it whole.
45
+ const message = withoutUserinfo(error?.message ?? String(error));
46
+ return failed(isRefused(error) ? { refused: message } : { error: message });
47
+ }
48
+ }
49
+ /** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
50
+ export async function fetchPage(url, { guard, offset, maxChars, ...options } = {}) {
51
+ const read = await readDirect(url, guard, options);
52
+ return read.ok ? partOfRead(read, { offset, maxChars }) : read;
53
+ }
@@ -0,0 +1,35 @@
1
+ import type { LookupFunction } from "node:net";
2
+ import { type Limit, type Search } from "../search.js";
3
+ import { type Words } from "./mcp.js";
4
+ export declare const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
5
+ export declare const EXA_SEARCH_TOOL = "web_search_exa";
6
+ /** A search Exa refused for its free limit (`retryAfterS`, the wait it named, when it named one) or for the connection
7
+ * (403): a reason another provider may get past, which the caller reads before the model reads `error` alone. */
8
+ export type ExaLimited = {
9
+ error: string;
10
+ limit: "rate_limited";
11
+ retryAfterS?: number;
12
+ } | {
13
+ error: string;
14
+ limit: "connection_refused";
15
+ };
16
+ /** A fetch that reaches hosts over IPv4 alone: each name looked up for family 4 (through `lookup`, default the system
17
+ * resolver) and the connection dialled at the address found, never an IPv6 one. undici loads at the first request, so
18
+ * a run that never searches never loads it; `close` ends the connections. */
19
+ export declare function ipv4Fetch(lookup?: LookupFunction): {
20
+ send: typeof fetch;
21
+ close(): Promise<void>;
22
+ };
23
+ /** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
24
+ * ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
25
+ * `pause` (default a wait the search's signal ends; a test's records it). `words`: the caller's for its free limit. */
26
+ export declare function exaSearch(query: string, n: number, { send, signal, pause, words }?: {
27
+ send?: typeof fetch;
28
+ signal?: AbortSignal;
29
+ pause?: (ms: number, signal: AbortSignal) => Promise<void>;
30
+ words?: Words;
31
+ }): Promise<Search | ExaLimited>;
32
+ /** Keyless Exa's refusal as the run's breaker reads it: a rate limit, with the wait it named. One naming no wait (its MCP
33
+ * notice, as its daily count running out answers) is marked repeatIsQuota, so a second one past a wait is that count; a
34
+ * 429 with Retry-After is a timed limit, unmarked. A refused connection is no limit (a 403 no wait lifts). */
35
+ export declare function exaLimitOf(found: ExaLimited): Limit | undefined;
@@ -0,0 +1,109 @@
1
+ // Keyless Exa: web_search through Exa's public MCP endpoint, no key, at a free rate limit. A limited search is tried
2
+ // once more after a short wait (a Retry-After of 5 s at most); still limited, it answers the caller's words, never Exa's.
3
+ // Exa is dialled over IPv4 only, the one way it takes keyless use.
4
+ import { lookup as dnsLookup } from "node:dns";
5
+ import { clip, TITLE_CAP } from "../page.js";
6
+ import { snippetOf } from "../search.js";
7
+ import { callTool, RATE_LIMITED, sleep, textBlocks } from "./mcp.js";
8
+ export const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
9
+ export const EXA_SEARCH_TOOL = "web_search_exa";
10
+ const TIMEOUT_MS = 60_000;
11
+ /** The most results Exa's free endpoint is asked for (its default is 10). Its own cap on purpose, not web search's
12
+ * RESULTS_MAX: the hosted providers take more, and Exa's keyless limit is per request. */
13
+ const RESULTS_MAX = 8;
14
+ /** The most of Exa's own words a failure quotes: the first sentence of its first line, cut on a word. */
15
+ const SAID_MAX = 120;
16
+ /** A failure Exa answered, in our words: the first sentence of its text, short and quoted. Its later lines (a fix for its
17
+ * MCP URL, a timestamp) are never passed on, so a deployment that does not mark its free limit says no setup text. */
18
+ function exaSaid(text) {
19
+ const line = text.split("\n").map((part) => part.trim()).find(Boolean) ?? "";
20
+ const sentence = /^.*?[.!?](?=\s|$)/.exec(line)?.[0] ?? line;
21
+ const short = sentence.length <= SAID_MAX ? sentence : `${sentence.slice(0, SAID_MAX - 1).replace(/\s+\S*$/, "")}…`;
22
+ return short ? `Free web search failed. Exa said: "${short}"` : "Free web search failed: Exa gave no answer";
23
+ }
24
+ /** The `_meta` key Exa's MCP server marks a tool result reporting its free limit with (isError as well). */
25
+ const RATE_LIMITED_META = "ai.exa/rateLimited";
26
+ /** The longest Retry-After waited out before the one retry. */
27
+ const RETRY_AFTER_MAX_S = 5;
28
+ /** The wait before the one retry: the Retry-After Exa named, else 1 to 3 s, each with jitter so runs limited together
29
+ * do not all ask again at once. */
30
+ const retryPause = (retryAfterS) => (retryAfterS === undefined ? 1_000 + Math.random() * 2_000 : retryAfterS * 1_000 + Math.random() * 500);
31
+ /** A fetch that reaches hosts over IPv4 alone: each name looked up for family 4 (through `lookup`, default the system
32
+ * resolver) and the connection dialled at the address found, never an IPv6 one. undici loads at the first request, so
33
+ * a run that never searches never loads it; `close` ends the connections. */
34
+ export function ipv4Fetch(lookup = dnsLookup) {
35
+ const ipv4 = (host, options, callback) => lookup(host, { ...options, family: 4 }, callback);
36
+ let opened;
37
+ const open = () => (opened ??= import("undici").then(({ Agent, fetch }) => ({ dispatcher: new Agent({ connect: { family: 4, lookup: ipv4 } }), dial: fetch })));
38
+ const send = async (url, init) => {
39
+ const { dispatcher, dial } = await open();
40
+ return dial(url, { ...init, dispatcher });
41
+ };
42
+ return { send: send, close: async () => void (opened && (await (await opened).dispatcher.close())) };
43
+ }
44
+ /** Exa's text for one result as a Hit, or undefined when it names no URL. */
45
+ function hitOf(section) {
46
+ const lines = section.split("\n");
47
+ const field = (name) => lines.find((line) => line.startsWith(`${name}:`))?.slice(name.length + 1).trim();
48
+ const url = field("URL");
49
+ if (!url || !URL.canParse(url))
50
+ return undefined;
51
+ const known = (value) => (value && value !== "N/A" ? value : undefined);
52
+ const body = lines.findIndex((line) => /^(Highlights|Text):/.test(line));
53
+ const snippet = body < 0 ? "" : [lines[body].replace(/^(Highlights|Text):\s*/, ""), ...lines.slice(body + 1)].join(" ").trim();
54
+ const published = known(field("Published"));
55
+ return { url, title: clip(known(field("Title")) ?? "", TITLE_CAP), snippet: snippetOf(snippet), ...(published ? { published } : {}) };
56
+ }
57
+ /** One exchange's outcome as Exa's answer to a search for `query`, at most `n` results: its refusals and failures in our
58
+ * words, else its hits. */
59
+ function searchOf(called, query, n, rateLimited) {
60
+ if ("status" in called) {
61
+ if (called.status === 429)
62
+ return { error: rateLimited, limit: "rate_limited", ...(called.retryAfterS === undefined ? {} : { retryAfterS: called.retryAfterS }) };
63
+ if (called.status === 403)
64
+ return { error: "Exa refused keyless use from this connection (403): it takes keyless searches only over IPv4, straight to its endpoint, not over IPv6 or through a proxy", limit: "connection_refused" };
65
+ return { error: `Exa's MCP endpoint answered ${called.status} to ${called.step === "initialize" ? "initialize" : "the search"}` };
66
+ }
67
+ if ("error" in called)
68
+ return { error: called.rpc ? exaSaid(called.error) : "Exa's MCP endpoint did not answer initialize" };
69
+ const { result } = called;
70
+ const meta = result?._meta;
71
+ if (result?.isError === true && typeof meta === "object" && meta !== null && meta[RATE_LIMITED_META] === true)
72
+ return { error: rateLimited, limit: "rate_limited" };
73
+ const said = textBlocks(result);
74
+ if (!Array.isArray(result?.content) || result.isError === true)
75
+ return { error: exaSaid(said) };
76
+ const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
77
+ return { provider: "exa-keyless", query, results: hits.slice(0, n) };
78
+ }
79
+ /** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
80
+ * ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
81
+ * `pause` (default a wait the search's signal ends; a test's records it). `words`: the caller's for its free limit. */
82
+ export async function exaSearch(query, n, { send, signal, pause = sleep, words = {} } = {}) {
83
+ const deadline = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]);
84
+ const own = send ? undefined : ipv4Fetch();
85
+ const dial = send ?? own.send;
86
+ const once = async () => searchOf(await callTool(EXA_MCP_URL, dial, deadline, EXA_SEARCH_TOOL, { query, numResults: Math.min(n, RESULTS_MAX) }), query, n, words.rateLimited ?? RATE_LIMITED);
87
+ try {
88
+ const first = await once();
89
+ if (!("limit" in first) || first.limit !== "rate_limited" || (first.retryAfterS ?? 0) > RETRY_AFTER_MAX_S)
90
+ return first;
91
+ await pause(retryPause(first.retryAfterS), deadline);
92
+ return await once();
93
+ }
94
+ catch (error) {
95
+ const name = error?.name;
96
+ return { error: name === "TimeoutError" ? "Exa's search did not answer within 60 s" : name === "AbortError" ? "the search was stopped" : `Exa's search failed: ${String(error?.message ?? error).slice(0, 300)}` };
97
+ }
98
+ finally {
99
+ await own?.close().catch(() => undefined);
100
+ }
101
+ }
102
+ /** Keyless Exa's refusal as the run's breaker reads it: a rate limit, with the wait it named. One naming no wait (its MCP
103
+ * notice, as its daily count running out answers) is marked repeatIsQuota, so a second one past a wait is that count; a
104
+ * 429 with Retry-After is a timed limit, unmarked. A refused connection is no limit (a 403 no wait lifts). */
105
+ export function exaLimitOf(found) {
106
+ if (found.limit !== "rate_limited")
107
+ return undefined;
108
+ return found.retryAfterS === undefined ? { kind: "rate", repeatIsQuota: true } : { kind: "rate", retryAfter: found.retryAfterS };
109
+ }
@@ -0,0 +1,40 @@
1
+ import { type Read } from "../page.js";
2
+ import { type Limit, type Search } from "../search.js";
3
+ import { type Words } from "./mcp.js";
4
+ export declare const FIRECRAWL_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
5
+ export declare const FIRECRAWL_SEARCH_TOOL = "firecrawl_search";
6
+ export declare const FIRECRAWL_SCRAPE_TOOL = "firecrawl_scrape";
7
+ /** The most one call to Firecrawl takes: half a search's one deadline (search.ts KEYLESS_SEARCH_MS). */
8
+ export declare const FIRECRAWL_MS = 30000;
9
+ /** A call Firecrawl refused or failed, in our words, and the limit it met, if any (for the run's breaker). */
10
+ export type FirecrawlFailed = {
11
+ error: string;
12
+ limit?: Limit;
13
+ };
14
+ /** Where a call goes: `endpoint` (default Firecrawl's), through `send` (default fetch), ended at `timeoutMs` (default
15
+ * FIRECRAWL_MS) or by `signal`, whichever is first; `words`, the caller's for a rate limit (default RATE_LIMITED). */
16
+ export type FirecrawlOptions = {
17
+ endpoint?: string;
18
+ send?: typeof fetch;
19
+ signal?: AbortSignal;
20
+ timeoutMs?: number;
21
+ words?: Words;
22
+ };
23
+ /** The limit a refusal's `code` names (QUOTA_CODES, RATE_CODES), with the wait its payload names; undefined for any
24
+ * other code. */
25
+ export declare function firecrawlLimitOf(payload: Record<string, unknown> | undefined): Limit | undefined;
26
+ /** `query` searched on Firecrawl's keyless endpoint, at most `n` results, its answer at most MAX_BYTES. */
27
+ export declare function firecrawlSearch(query: string, n: number, options?: FirecrawlOptions): Promise<Search | FirecrawlFailed>;
28
+ /** The page at `url` scraped by Firecrawl's keyless endpoint, as markdown, its answer at most the direct fetch's bound
29
+ * (PAGE_MAX_BYTES). Firecrawl names no cut, so the text is read as the whole page's. A page whose status
30
+ * is not 2xx is no read: the caller fetches directly, as for a refusal. */
31
+ export declare function firecrawlScrape(url: string, options?: FirecrawlOptions): Promise<Read | FirecrawlFailed>;
32
+ /** keyless Firecrawl's scrape for one run's web_fetch, with the run's breaker on it: `live` is false once a quota answer
33
+ * came (for the rest of the run) and while a rate limit's wait holds (waitOf: the wait Firecrawl named, else 60 s, at
34
+ * most 15 minutes); `read` is one scrape, the page or, for any failure, why there is none (the caller then fetches
35
+ * directly). `now` is the breaker's clock (a test's). */
36
+ export type KeylessFetch = {
37
+ live(): boolean;
38
+ read(url: string, signal?: AbortSignal): Promise<Read | string>;
39
+ };
40
+ export declare function firecrawlFetch(options?: Omit<FirecrawlOptions, "signal">, now?: () => number): KeylessFetch;