@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,132 @@
1
+ // Keyless Firecrawl: search and scrape through Firecrawl's public MCP endpoint, no key, under a free daily limit. A
2
+ // refusal is read by its code alone (quota: off for the run; limit: held for its wait), never by Firecrawl's words. A
3
+ // call is never retried and ends at FIRECRAWL_MS. A URL the public-host guard refuses is never sent (fetch.ts).
4
+ import { clip, markdownRead, PAGE_MAX_BYTES, TITLE_CAP, withoutUserinfo } from "../page.js";
5
+ import { snippetOf, waitOf } from "../search.js";
6
+ import { callTool, MAX_BYTES, RATE_LIMITED, textBlocks } from "./mcp.js";
7
+ export const FIRECRAWL_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
8
+ export const FIRECRAWL_SEARCH_TOOL = "firecrawl_search";
9
+ export const FIRECRAWL_SCRAPE_TOOL = "firecrawl_scrape";
10
+ /** The most one call to Firecrawl takes: half a search's one deadline (search.ts KEYLESS_SEARCH_MS). */
11
+ export const FIRECRAWL_MS = 30_000;
12
+ /** Firecrawl's keyless refusal codes, by what the run's breaker makes of each. */
13
+ const QUOTA_CODES = new Set(["KEYLESS_QUOTA_EXHAUSTED", "KEYLESS_ACCESS_NOT_AVAILABLE", "KEYLESS_TOOL_NOT_AVAILABLE"]);
14
+ const RATE_CODES = new Set(["KEYLESS_LIMIT_REACHED"]);
15
+ /** A refusal's payload: the result's structuredContent, else its text read as JSON; undefined when neither is an object. */
16
+ function payloadOf(result) {
17
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18
+ if (isObject(result?.structuredContent) && typeof result.structuredContent.code === "string")
19
+ return result.structuredContent;
20
+ try {
21
+ const parsed = JSON.parse(textBlocks(result));
22
+ return isObject(parsed) ? parsed : undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ /** The limit a refusal's `code` names (QUOTA_CODES, RATE_CODES), with the wait its payload names; undefined for any
29
+ * other code. */
30
+ export function firecrawlLimitOf(payload) {
31
+ const code = payload?.code;
32
+ if (typeof code !== "string")
33
+ return undefined;
34
+ if (QUOTA_CODES.has(code))
35
+ return { kind: "quota" };
36
+ if (!RATE_CODES.has(code))
37
+ return undefined;
38
+ const seconds = payload.retry_after_seconds;
39
+ if (typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0)
40
+ return { kind: "rate", retryAfter: seconds };
41
+ return { kind: "rate" };
42
+ }
43
+ /** What a call answers for a limit Firecrawl met. */
44
+ const limitWords = (limit, what, words = {}) => (limit.kind === "rate" ? (words.rateLimited ?? RATE_LIMITED) : `Keyless Firecrawl will not serve this server's ${what}es now (its free limit is spent, or keyless use is not open to it): it is not asked again in this run`);
45
+ /** One call's outcome as Firecrawl's answer to `what`: its refusals and failures in our words, else `read` of the result's
46
+ * JSON text. */
47
+ function readCalled(called, what, read, words) {
48
+ if ("status" in called) {
49
+ if (called.status === 429) {
50
+ const limit = { kind: "rate", ...(called.retryAfterS === undefined ? {} : { retryAfter: called.retryAfterS }) };
51
+ return { error: limitWords(limit, what, words), limit };
52
+ }
53
+ return { error: `Firecrawl's MCP endpoint answered ${called.status} to ${called.step === "initialize" ? "initialize" : `the ${what}`}` };
54
+ }
55
+ if ("over" in called)
56
+ return { error: `Firecrawl's ${what} answered more than ${called.over / MAX_BYTES} MiB: not read` };
57
+ if ("error" in called)
58
+ return { error: called.rpc ? `Firecrawl's ${what} failed: its MCP endpoint answered an error` : "Firecrawl's MCP endpoint did not answer initialize" };
59
+ const { result } = called;
60
+ if (result?.isError === true) {
61
+ const payload = payloadOf(result);
62
+ const limit = firecrawlLimitOf(payload);
63
+ if (limit)
64
+ return { error: limitWords(limit, what, words), limit };
65
+ return { error: typeof payload?.code === "string" ? `Firecrawl's ${what} failed (${clip(payload.code, 60)})` : `Firecrawl's ${what} failed` };
66
+ }
67
+ try {
68
+ const parsed = JSON.parse(textBlocks(result));
69
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
70
+ return read(parsed);
71
+ }
72
+ catch { }
73
+ return { error: `Firecrawl's ${what} answered no result this server reads` };
74
+ }
75
+ /** The tool `name` with `args` on Firecrawl's keyless endpoint, its answer bounded at `maxBytes`, read by `read`: once. */
76
+ async function firecrawlCall(name, args, what, maxBytes, read, { endpoint = FIRECRAWL_MCP_URL, send = fetch, signal, timeoutMs = FIRECRAWL_MS, words }) {
77
+ const own = AbortSignal.timeout(timeoutMs);
78
+ const deadline = AbortSignal.any([own, ...(signal ? [signal] : [])]);
79
+ try {
80
+ return readCalled(await callTool(endpoint, send, deadline, name, args, maxBytes), what, read, words);
81
+ }
82
+ catch (error) {
83
+ // Firecrawl's own bound, or the caller's: its deadline (a search's, spent) or its stop.
84
+ if (own.aborted)
85
+ return { error: `Firecrawl's ${what} did not answer within ${timeoutMs / 1000} s` };
86
+ const reason = signal?.aborted ? signal.reason?.name : error?.name;
87
+ return { error: reason === "TimeoutError" ? `Firecrawl's ${what} did not answer before the ${what}'s time ran out` : reason === "AbortError" ? `the ${what} was stopped` : `Firecrawl's ${what} failed: ${withoutUserinfo(String(error?.message ?? error)).slice(0, 300)}` };
88
+ }
89
+ }
90
+ /** `query` searched on Firecrawl's keyless endpoint, at most `n` results, its answer at most MAX_BYTES. */
91
+ export async function firecrawlSearch(query, n, options = {}) {
92
+ return firecrawlCall(FIRECRAWL_SEARCH_TOOL, { query, limit: n }, "search", MAX_BYTES, (json) => {
93
+ const data = json.data;
94
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.web) ? data.web : undefined;
95
+ if (!rows)
96
+ return { error: "Firecrawl's search answered no results this server reads" };
97
+ const hits = rows.flatMap((row) => (typeof row?.url === "string" && URL.canParse(row.url) ? [{ url: row.url, title: typeof row.title === "string" ? clip(row.title, TITLE_CAP) : "", snippet: snippetOf(typeof row.description === "string" ? row.description : "") }] : []));
98
+ return { provider: "firecrawl-keyless", query, results: hits.slice(0, n) };
99
+ }, options);
100
+ }
101
+ /** The page at `url` scraped by Firecrawl's keyless endpoint, as markdown, its answer at most the direct fetch's bound
102
+ * (PAGE_MAX_BYTES). Firecrawl names no cut, so the text is read as the whole page's. A page whose status
103
+ * is not 2xx is no read: the caller fetches directly, as for a refusal. */
104
+ export async function firecrawlScrape(url, options = {}) {
105
+ return firecrawlCall(FIRECRAWL_SCRAPE_TOOL, { url, formats: ["markdown"] }, "fetch", PAGE_MAX_BYTES, (json) => {
106
+ if (typeof json.markdown !== "string" || json.markdown.trim() === "")
107
+ return { error: "Firecrawl's fetch answered no page text" };
108
+ const meta = (typeof json.metadata === "object" && json.metadata !== null ? json.metadata : {});
109
+ const final = [meta.url, meta.sourceURL].find((one) => typeof one === "string" && URL.canParse(one)) ?? url;
110
+ const status = typeof meta.statusCode === "number" && Number.isInteger(meta.statusCode) ? meta.statusCode : 200;
111
+ if (status < 200 || status > 299)
112
+ return { error: `Firecrawl's fetch: the page answered ${status}` };
113
+ return markdownRead(final, typeof meta.title === "string" ? meta.title : "", json.markdown, true, status);
114
+ }, options);
115
+ }
116
+ export function firecrawlFetch(options = {}, now = Date.now) {
117
+ let off = false;
118
+ let until = 0;
119
+ return {
120
+ live: () => !off && now() >= until,
121
+ async read(url, signal) {
122
+ const read = await firecrawlScrape(url, { ...options, ...(signal ? { signal } : {}) });
123
+ if ("ok" in read)
124
+ return read;
125
+ if (read.limit?.kind === "quota")
126
+ off = true;
127
+ else if (read.limit)
128
+ until = Math.max(until, now() + waitOf(read.limit.retryAfter, now()));
129
+ return read.error;
130
+ },
131
+ };
132
+ }
@@ -0,0 +1,39 @@
1
+ /** The MCP revision this client speaks; the server answers the one it takes. */
2
+ export declare const PROTOCOL = "2025-06-18";
3
+ /** The most of an answer read: a search's text is a few kilobytes, a page's markdown more; past this the rest is never
4
+ * read. */
5
+ export declare const MAX_BYTES: number;
6
+ /** What a free web search answers when its free limit holds, in our words: a backend's own (a link to sign up, a key in
7
+ * its MCP URL) mean nothing to a person here, so they are never passed on. A product names its own way past the limit
8
+ * as Words' rateLimited (serve's names its settings). */
9
+ export declare const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute.";
10
+ /** The words a caller gives in place of web's own: `rateLimited` in place of RATE_LIMITED. */
11
+ export type Words = {
12
+ rateLimited?: string;
13
+ };
14
+ /** One tool call's outcome: `status`, a non-2xx answer to `step` (with the seconds its Retry-After named); `error`, a
15
+ * JSON-RPC error's message, or that the server answered no initialize; else the call's `result` (undefined: no answer
16
+ * to the call came). */
17
+ export type Called = {
18
+ status: number;
19
+ retryAfterS?: number;
20
+ step: "initialize" | "the call";
21
+ } | {
22
+ error: string;
23
+ rpc: boolean;
24
+ } | {
25
+ result: Record<string, unknown> | undefined;
26
+ };
27
+ /** A call given its own bound: as Called, or `over`, its answer ran past that bound (in bytes), unread. */
28
+ export type Bounded = Called | {
29
+ over: number;
30
+ };
31
+ /** `ms` of waiting that `signal` ends, rejecting with its reason. */
32
+ export declare const sleep: (ms: number, signal: AbortSignal) => Promise<void>;
33
+ /** A tool result's text blocks, joined by lines; empty when it has none. */
34
+ export declare const textBlocks: (result: Record<string, unknown> | undefined) => string;
35
+ /** The tool `name` called with `args` on the MCP server at `endpoint` through `dial`, each request ended by `deadline`:
36
+ * one exchange (initialize, notifications/initialized, tools/call). `maxBytes`: the call's answer's own bound, past
37
+ * which it is `over` (none: its first MAX_BYTES read). A failure to reach the server throws. */
38
+ export declare function callTool(endpoint: string, dial: typeof fetch, deadline: AbortSignal, name: string, args: Record<string, unknown>): Promise<Called>;
39
+ export declare function callTool(endpoint: string, dial: typeof fetch, deadline: AbortSignal, name: string, args: Record<string, unknown>, maxBytes: number): Promise<Bounded>;
@@ -0,0 +1,107 @@
1
+ // The MCP client the keyless backends share: one tool call is one exchange (initialize, notifications/initialized,
2
+ // tools/call) over streamable HTTP. No key and no header beyond the transport's own is sent; an answer is read to a cap.
3
+ import { retryAfterMs } from "../search.js";
4
+ /** The MCP revision this client speaks; the server answers the one it takes. */
5
+ export const PROTOCOL = "2025-06-18";
6
+ const ACCEPT = "application/json, text/event-stream";
7
+ /** The most of an answer read: a search's text is a few kilobytes, a page's markdown more; past this the rest is never
8
+ * read. */
9
+ export const MAX_BYTES = 1 << 20;
10
+ /** What a free web search answers when its free limit holds, in our words: a backend's own (a link to sign up, a key in
11
+ * its MCP URL) mean nothing to a person here, so they are never passed on. A product names its own way past the limit
12
+ * as Words' rateLimited (serve's names its settings). */
13
+ export const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute.";
14
+ /** The whole seconds an answer's Retry-After names (retryAfterMs), none below 0; undefined when it names none. */
15
+ function retryAfterOf(response) {
16
+ const ms = retryAfterMs(response.headers.get("retry-after") ?? undefined, Date.now());
17
+ return ms === undefined ? undefined : Math.max(0, Math.ceil(ms / 1_000));
18
+ }
19
+ /** `ms` of waiting that `signal` ends, rejecting with its reason. */
20
+ export const sleep = (ms, signal) => new Promise((resolve, reject) => {
21
+ if (signal.aborted)
22
+ return reject(signal.reason);
23
+ const stop = () => {
24
+ clearTimeout(timer);
25
+ reject(signal.reason);
26
+ };
27
+ const timer = setTimeout(() => {
28
+ signal.removeEventListener("abort", stop);
29
+ resolve();
30
+ }, ms);
31
+ signal.addEventListener("abort", stop, { once: true });
32
+ });
33
+ /** A body as text, read to at most `max` bytes; the rest is never read. `cut`: a longer body's first `max` bytes; else
34
+ * undefined for one that runs past them. */
35
+ async function bodyText(response, max, cut) {
36
+ const reader = response.body?.getReader();
37
+ const chunks = [];
38
+ for (let size = 0; reader;) {
39
+ const { done, value } = await reader.read();
40
+ if (done)
41
+ break;
42
+ chunks.push(value);
43
+ size += value.byteLength;
44
+ if (cut ? size >= max : size > max) {
45
+ await reader.cancel().catch(() => undefined);
46
+ return cut ? Buffer.concat(chunks).subarray(0, max).toString("utf8") : undefined;
47
+ }
48
+ }
49
+ return Buffer.concat(chunks).toString("utf8");
50
+ }
51
+ /** A JSON-RPC answer's body: JSON, or the `data:` lines of an event stream, the one answering `id`. With `max`, a body
52
+ * past it is "over"; without, its first MAX_BYTES are read. */
53
+ async function answerOf(response, id, max) {
54
+ const text = await bodyText(response, max ?? MAX_BYTES, max === undefined);
55
+ if (text === undefined)
56
+ return "over";
57
+ const messages = /event-stream/i.test(response.headers.get("content-type") ?? "")
58
+ ? text.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim())
59
+ : [text];
60
+ for (const message of messages) {
61
+ try {
62
+ const parsed = JSON.parse(message);
63
+ if (parsed.id === id)
64
+ return parsed;
65
+ }
66
+ catch { }
67
+ }
68
+ return undefined;
69
+ }
70
+ /** A tool result's text blocks, joined by lines; empty when it has none. */
71
+ export const textBlocks = (result) => (Array.isArray(result?.content) ? result.content : []).flatMap((part) => (part.type === "text" && typeof part.text === "string" ? [part.text] : [])).join("\n");
72
+ export async function callTool(endpoint, dial, deadline, name, args, maxBytes) {
73
+ let session;
74
+ const post = (body) => dial(endpoint, {
75
+ method: "POST",
76
+ headers: { "content-type": "application/json", accept: ACCEPT, "mcp-protocol-version": PROTOCOL, ...(session ? { "mcp-session-id": session } : {}) },
77
+ body: JSON.stringify({ jsonrpc: "2.0", ...body }),
78
+ signal: deadline,
79
+ });
80
+ const refused = async (response, step) => {
81
+ if (response.ok)
82
+ return undefined;
83
+ await response.body?.cancel().catch(() => undefined);
84
+ const retryAfterS = retryAfterOf(response);
85
+ return { status: response.status, step, ...(retryAfterS === undefined ? {} : { retryAfterS }) };
86
+ };
87
+ const opened = await post({ id: 1, method: "initialize", params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "agentrun-web", version: "1" } } });
88
+ const failed = await refused(opened, "initialize");
89
+ if (failed)
90
+ return failed;
91
+ session = opened.headers.get("mcp-session-id") ?? undefined;
92
+ const hello = await answerOf(opened, 1);
93
+ if (hello === "over" || !hello?.result)
94
+ return { error: "", rpc: false };
95
+ const ready = await post({ method: "notifications/initialized" });
96
+ await ready.body?.cancel().catch(() => undefined);
97
+ const called = await post({ id: 2, method: "tools/call", params: { name, arguments: args } });
98
+ const late = await refused(called, "the call");
99
+ if (late)
100
+ return late;
101
+ const answer = await answerOf(called, 2, maxBytes);
102
+ if (answer === "over")
103
+ return { over: maxBytes };
104
+ if (answer?.error)
105
+ return { error: typeof answer.error.message === "string" ? answer.error.message : "", rpc: true };
106
+ return { result: answer?.result };
107
+ }
@@ -0,0 +1,20 @@
1
+ import { type Pay } from "../fees.js";
2
+ import { type Read } from "../page.js";
3
+ import { type Searched } from "../search.js";
4
+ export declare const PARALLEL_SEARCH_URL = "https://api.parallel.ai/v1/search";
5
+ export declare const PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
6
+ /** Parallel for one run, on one key: `read`, its extract of a page (one billed request), the page it read or, for any
7
+ * failure, why it read none; `post`, one request to another of its endpoints (web_search's, parallelSearched). Neither
8
+ * retries, and each stops at 60 s. `live` is false once a 401 or 403 to either said the key is not served. */
9
+ export type Extract = {
10
+ live(): boolean;
11
+ read(url: string, signal?: AbortSignal): Promise<Read | string>;
12
+ post(url: string, body: unknown, signal?: AbortSignal): Promise<Response>;
13
+ };
14
+ /** Parallel's extract on `apiKey`: one URL a request, each a billed extract, its full content to the most of a page
15
+ * web_fetch reads as the page's text (markdown), its links read from it, status 200 (Parallel answers a page it could
16
+ * not read in `errors`, with no content). */
17
+ export declare function parallelExtract(apiKey: string, send?: typeof fetch, pay?: Pay): Extract;
18
+ /** `{query, n?}` searched through `parallel` (null: the run holds no key), and the limit Parallel answered for the run's
19
+ * key, if any. */
20
+ export declare function parallelSearched(args: Record<string, unknown>, parallel: Extract | null, signal?: AbortSignal): Promise<Searched>;
@@ -0,0 +1,102 @@
1
+ // Parallel on the run's key: Extract for web_fetch, Search for web_search. Every request is paid through the injected
2
+ // Pay at its endpoint's price, and a 401 or 403 stops both for the client's life. Nothing is retried; each ends at 60 s.
3
+ import { PaidRefused, parallelFeeOf, unmetered } from "../fees.js";
4
+ import { clip, markdownRead, PAGE_READ_MAX_CHARS, TITLE_CAP, withoutUserinfo } from "../page.js";
5
+ import { SNIPPET_MAX, searchArgs, snippetOf } from "../search.js";
6
+ export const PARALLEL_SEARCH_URL = "https://api.parallel.ai/v1/search";
7
+ export const PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
8
+ const PARALLEL_TIMEOUT_MS = 60_000;
9
+ const REFUSED = "Parallel refused this run's key (401 or 403): it is not asked again in this run";
10
+ /** Parallel's extract on `apiKey`: one URL a request, each a billed extract, its full content to the most of a page
11
+ * web_fetch reads as the page's text (markdown), its links read from it, status 200 (Parallel answers a page it could
12
+ * not read in `errors`, with no content). */
13
+ export function parallelExtract(apiKey, send = fetch, pay = unmetered) {
14
+ let refused = false;
15
+ // Each request is a paid one, sent through `pay` (fees.ts; serve's paid-calls.ts holds it to the run's cap and books it
16
+ // as the call's cost at its endpoint's price). One the cap refuses is not sent: it throws its refusal (PaidRefused).
17
+ const post = async (url, body, signal) => {
18
+ const sent = async () => {
19
+ const response = await send(url, {
20
+ method: "POST",
21
+ headers: { "x-api-key": apiKey, "content-type": "application/json" },
22
+ body: JSON.stringify(body),
23
+ signal: AbortSignal.any([AbortSignal.timeout(PARALLEL_TIMEOUT_MS), ...(signal ? [signal] : [])]),
24
+ });
25
+ if (response.status === 401 || response.status === 403)
26
+ refused = true;
27
+ return response;
28
+ };
29
+ const fee = parallelFeeOf(url, body);
30
+ if (!fee)
31
+ throw new PaidRefused(`Parallel's ${URL.parse(url)?.pathname ?? url} was not sent: it has no price here`);
32
+ return pay(fee, sent);
33
+ };
34
+ return {
35
+ live: () => !refused,
36
+ post,
37
+ async read(url, signal) {
38
+ try {
39
+ // The most of a page a read reaches and one character more, so a page Parallel cut there shows as going on.
40
+ const asked = PAGE_READ_MAX_CHARS + 1;
41
+ const response = await post(PARALLEL_EXTRACT_URL, { urls: [url], advanced_settings: { full_content: { max_chars_per_result: asked } } }, signal);
42
+ if (!response.ok) {
43
+ await response.body?.cancel().catch(() => undefined);
44
+ return response.status === 401 || response.status === 403 ? `refused the key (${response.status})` : `answered ${response.status}`;
45
+ }
46
+ const { results, errors } = (await response.json());
47
+ const row = results?.find((r) => typeof r?.url === "string" && typeof r.full_content === "string" && r.full_content.trim() !== "");
48
+ if (!row)
49
+ return errors?.length ? "listed the URL in errors" : "answered no content";
50
+ const text = row.full_content;
51
+ return markdownRead(row.url, typeof row.title === "string" ? row.title : "", text, text.length < asked);
52
+ }
53
+ catch (error) {
54
+ if (error instanceof PaidRefused)
55
+ return error.message;
56
+ const name = error?.name;
57
+ return name === "TimeoutError" ? "timed out" : name === "AbortError" ? "was stopped" : `failed: ${withoutUserinfo(String(error?.message ?? error)).slice(0, 200)}`;
58
+ }
59
+ },
60
+ };
61
+ }
62
+ /** What a Parallel answer's status says of the run's search: out of credit (402), or rate-limited (429) for its
63
+ * Retry-After. */
64
+ const parallelLimit = (response) => {
65
+ if (response.status === 402)
66
+ return { kind: "quota" };
67
+ const retryAfter = response.headers.get("retry-after");
68
+ return response.status === 429 ? { kind: "rate", ...(retryAfter ? { retryAfter } : {}) } : undefined;
69
+ };
70
+ /** `{query, n?}` searched through `parallel` (null: the run holds no key), and the limit Parallel answered for the run's
71
+ * key, if any. */
72
+ export async function parallelSearched(args, parallel, signal) {
73
+ const answer = (search) => ({ answer: search });
74
+ const { query, n } = searchArgs(args);
75
+ if (!query)
76
+ return answer({ error: "web_search needs a query" });
77
+ if (!parallel)
78
+ return answer({ error: "web_search searches through Parallel, and this run holds no Parallel key (PARALLEL_API_KEY)" });
79
+ if (!parallel.live())
80
+ return answer({ error: REFUSED });
81
+ try {
82
+ const response = await parallel.post(PARALLEL_SEARCH_URL, { objective: query, search_queries: [query], mode: "fast", advanced_settings: { max_results: n, excerpt_settings: { max_chars_per_result: SNIPPET_MAX } } }, signal);
83
+ if (!response.ok) {
84
+ await response.body?.cancel().catch(() => undefined);
85
+ const limit = parallelLimit(response);
86
+ return parallel.live() ? { answer: { error: `Parallel's search answered ${response.status}` }, ...(limit ? { limit } : {}) } : answer({ error: REFUSED });
87
+ }
88
+ const { results } = (await response.json());
89
+ const hits = (Array.isArray(results) ? results : []).flatMap((row) => {
90
+ if (typeof row?.url !== "string")
91
+ return [];
92
+ const excerpts = Array.isArray(row.excerpts) ? row.excerpts.filter((text) => typeof text === "string") : [];
93
+ return [{ url: row.url, title: typeof row.title === "string" ? clip(row.title, TITLE_CAP) : "", snippet: snippetOf(excerpts.join(" … ")), ...(typeof row.publish_date === "string" ? { published: row.publish_date } : {}) }];
94
+ });
95
+ return answer({ provider: "parallel", query, results: hits.slice(0, n) });
96
+ }
97
+ catch (error) {
98
+ if (error instanceof PaidRefused)
99
+ return answer({ error: error.message });
100
+ return answer({ error: error?.name === "TimeoutError" ? "Parallel's search did not answer within 60 s" : `Parallel's search failed: ${error?.message ?? String(error)}` });
101
+ }
102
+ }
@@ -0,0 +1,110 @@
1
+ export declare const QUERY_MAX = 200;
2
+ export declare const RESULTS_MAX = 25;
3
+ export declare const RESULTS_DEFAULT = 10;
4
+ /** The most of a result's text its snippet keeps; Parallel is asked for as much of each result's excerpts. */
5
+ export declare const SNIPPET_MAX = 3000;
6
+ /** The most of the provider's own short answer (`text`) a search keeps (serve's hosted-search.ts). */
7
+ export declare const ANSWER_MAX = 4000;
8
+ /** The most characters a search's answer takes, its citing line included: about RESULTS_MAX results with whole snippets,
9
+ * under the host's result bound (HOST_RESULT_MAX_CHARS), which the host-bounds test holds it to. */
10
+ export declare const SEARCH_MAX_CHARS = 100000;
11
+ /** What every later web_search call of a run answers once its provider said the run is out of quota (a Limit of kind
12
+ * quota): the provider is not asked again in that run. */
13
+ export declare const SEARCH_UNAVAILABLE = "search is unavailable for the rest of this run; answer from what you have";
14
+ /** What a call answers while a rate limit's wait holds, `seconds` of it left. */
15
+ export declare const searchBusy: (seconds: number) => string;
16
+ export type Hit = {
17
+ url: string;
18
+ title: string;
19
+ snippet: string;
20
+ published?: string;
21
+ };
22
+ export type Search = {
23
+ provider: "native" | "firecrawl-keyless" | "exa-keyless" | "parallel";
24
+ query: string;
25
+ results: Hit[];
26
+ text?: string;
27
+ omitted?: number;
28
+ } | {
29
+ error: string;
30
+ };
31
+ /** What a provider's failure said of the run's search: out of quota, or rate-limited, with the wait it named as it
32
+ * handed it back (a Retry-After header's value, delta-seconds or an HTTP date, or Exa's seconds). `repeatIsQuota`, the
33
+ * server's mark on keyless Exa's limit naming no wait alone (exaLimitOf): Exa answers its daily count running out as
34
+ * that limit, so the same answer again once a wait has passed is that count (searchBreaker). */
35
+ export type Limit = {
36
+ kind: "quota";
37
+ } | {
38
+ kind: "rate";
39
+ retryAfter?: string | number;
40
+ repeatIsQuota?: true;
41
+ };
42
+ /** A Search, and the limit its provider answered, if any: the run's breaker reads `limit` (searchBreaker), the model the
43
+ * Search alone. */
44
+ export type Searched = {
45
+ answer: Search;
46
+ limit?: Limit;
47
+ };
48
+ /** The wait a Retry-After names, in ms from `nowMs` (negative for a date already passed): delta-seconds or an HTTP date,
49
+ * or a number of seconds; undefined when it names neither. The one reading of a Retry-After here. */
50
+ export declare function retryAfterMs(retryAfter: string | number | undefined, nowMs: number): number | undefined;
51
+ /** The wait a breaker holds for `retryAfter` (retryAfterMs): none named, 60 s; a date already passed, none; never more
52
+ * than 15 minutes (MAX_WAIT_MS). */
53
+ export declare function waitOf(retryAfter: string | number | undefined, nowMs: number): number;
54
+ /** A breaker on one backend, read at `now`. `held`: what a call answers unsent while it holds (SEARCH_UNAVAILABLE once
55
+ * off, searchBusy for the seconds left of a wait). `read` takes a search and its limit: a quota answer turns it off; a
56
+ * rate limit opens a wait, never shrinking one already open; a repeatIsQuota limit after an earlier one whose wait has
57
+ * passed, with no success between, is a quota answer and the call answers SEARCH_UNAVAILABLE. */
58
+ export type Breaker = {
59
+ held(): Search | undefined;
60
+ read(searched: Searched): Search;
61
+ off(): boolean;
62
+ left(): number;
63
+ };
64
+ export declare function searchBreaker(now?: () => number): Breaker;
65
+ /** The line that ends a search's answer to the model, as Claude Code's WebSearch ends its own. */
66
+ export declare const CITE = "Cite the URL of each result you rely on.";
67
+ /** `answer` within SEARCH_MAX_CHARS, as searchText writes it: whole when it fits, else without its least relevant results
68
+ * (the last), as many as it takes, `omitted` counting them. */
69
+ export declare function fitSearch(answer: Search): Search;
70
+ /** A search as the model reads it: its JSON (fitSearch), then the line asking it to cite the URLs it relies on; an
71
+ * error's JSON alone. */
72
+ export declare function searchText(answer: Search): string;
73
+ /** A result's text as its snippet: links reduced to their text, whitespace collapsed, cut at SNIPPET_MAX on a word. */
74
+ export declare function snippetOf(raw: string): string;
75
+ /** `{query, n?}` as every provider takes it: the query trimmed and cut at QUERY_MAX, n 1 to RESULTS_MAX. */
76
+ export declare const searchArgs: (args: Record<string, unknown>) => {
77
+ query: string;
78
+ n: number;
79
+ };
80
+ /** A backend a call of web_search asks: its name (its breaker's), and its one search. The keyless backends end at
81
+ * `deadline`, the call's one deadline for every backend it asks (searchInTurn); Parallel and a native search keep the
82
+ * caller's signal and their own bounds. */
83
+ export type Backend = {
84
+ name: string;
85
+ ask(deadline: AbortSignal): Promise<Searched>;
86
+ };
87
+ /** One backend's turn in a call: answered (`ok`), failed (`error`, with the limit it met), or held by its breaker. */
88
+ export type Try = {
89
+ provider: string;
90
+ outcome: "ok" | "error" | "held";
91
+ error?: string;
92
+ limit?: Limit;
93
+ ms?: number;
94
+ };
95
+ /** The most one call of web_search spends across its keyless backends together: Firecrawl's failing or timing out
96
+ * leaves Exa what is left of it, never a fresh bound. Firecrawl's own bound inside it (FIRECRAWL_MS, 30 s) leaves Exa
97
+ * at least the rest. */
98
+ export declare const KEYLESS_SEARCH_MS = 60000;
99
+ /** A call's bounds, a test's: `searchMs`, its one deadline (KEYLESS_SEARCH_MS); `firecrawlMs`, Firecrawl's own inside it
100
+ * (FIRECRAWL_MS). */
101
+ export type SearchBounds = {
102
+ searchMs?: number;
103
+ firecrawlMs?: number;
104
+ };
105
+ /** A call's search through `backends` in turn, each behind its breaker, all under one deadline (`boundMs` or `signal`):
106
+ * the first with results answers; none starts on a spent deadline. None left: SEARCH_UNAVAILABLE where every backend is
107
+ * off (a lone backend's own answer where it was asked), else the last failure, else searchBusy for the shortest wait. */
108
+ export declare function searchInTurn(backends: readonly Backend[], breakerOf: (name: string) => Breaker, signal?: AbortSignal, boundMs?: number, tries?: Try[]): Promise<Search>;
109
+ /** Breakers by backend name, made at first use: one run's (serve's webSearchTool), or one call's (its searchFor). */
110
+ export declare const breakers: (now?: () => number) => (name: string) => Breaker;