@parcha/agentrun-web 0.1.0-beta.58 → 0.1.0-beta.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -11
- package/dist/decide/decider.d.ts +183 -0
- package/dist/decide/decider.js +248 -0
- package/dist/decide/failure.d.ts +6 -0
- package/dist/decide/failure.js +22 -0
- package/dist/decide/fetch.d.ts +53 -0
- package/dist/decide/fetch.js +95 -0
- package/dist/decide/page-guard.d.ts +36 -0
- package/dist/decide/page-guard.js +26 -0
- package/dist/decide/passages.d.ts +6 -0
- package/dist/decide/passages.js +54 -0
- package/dist/decide/record.d.ts +102 -0
- package/dist/decide/record.js +125 -0
- package/dist/decide/search.d.ts +18 -0
- package/dist/decide/search.js +43 -0
- package/dist/fees.d.ts +35 -2
- package/dist/fees.js +62 -2
- package/dist/fetch.d.ts +48 -41
- package/dist/fetch.js +112 -72
- package/dist/index.d.ts +17 -6
- package/dist/index.js +19 -7
- package/dist/provider.d.ts +113 -0
- package/dist/provider.js +34 -0
- package/dist/providers/direct.d.ts +15 -0
- package/dist/providers/direct.js +24 -8
- package/dist/providers/exa-keyless.d.ts +13 -2
- package/dist/providers/exa-keyless.js +33 -14
- package/dist/providers/exa.d.ts +68 -0
- package/dist/providers/exa.js +111 -0
- package/dist/providers/firecrawl-keyless.d.ts +25 -14
- package/dist/providers/firecrawl-keyless.js +91 -46
- package/dist/providers/firecrawl.d.ts +77 -0
- package/dist/providers/firecrawl.js +145 -0
- package/dist/providers/keyed.d.ts +44 -0
- package/dist/providers/keyed.js +137 -0
- package/dist/providers/native.d.ts +5 -0
- package/dist/providers/native.js +11 -0
- package/dist/providers/parallel.d.ts +55 -10
- package/dist/providers/parallel.js +127 -39
- package/dist/providers/registry.d.ts +119 -0
- package/dist/providers/registry.js +35 -0
- package/dist/search.d.ts +86 -17
- package/dist/search.js +101 -34
- package/dist/tool-specs.d.ts +65 -0
- package/dist/tool-specs.js +36 -0
- package/dist/web.d.ts +109 -30
- package/dist/web.js +165 -63
- package/package.json +2 -2
|
@@ -1,17 +1,31 @@
|
|
|
1
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
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
import {
|
|
2
|
+
// refusal is read by its code (quota: off for the run; limit: held for its wait), and a spent daily limit by the one
|
|
3
|
+
// plain-text answer Firecrawl gives for it (off until 00:00 UTC). Firecrawl's words are never passed on. A call is never
|
|
4
|
+
// retried and ends at FIRECRAWL_MS. A URL the public-host guard refuses is never sent (fetch.ts).
|
|
5
|
+
import { clip, markdownRead, PAGE_MAX_BYTES, withoutUserinfo } from "../page.js";
|
|
6
|
+
import { defineProvider, readerOf } from "../provider.js";
|
|
7
|
+
import { bare, failed, keyWide, searchBreaker } from "../search.js";
|
|
8
|
+
import { firecrawlHits, firecrawlMerged, firecrawlQueries, firecrawlScrapeOptions } from "./firecrawl.js";
|
|
9
|
+
import { KEYED_MAX_BYTES } from "./keyed.js";
|
|
6
10
|
import { callTool, MAX_BYTES, RATE_LIMITED, textBlocks } from "./mcp.js";
|
|
7
11
|
export const FIRECRAWL_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
|
|
8
12
|
export const FIRECRAWL_SEARCH_TOOL = "firecrawl_search";
|
|
9
13
|
export const FIRECRAWL_SCRAPE_TOOL = "firecrawl_scrape";
|
|
10
14
|
/** The most one call to Firecrawl takes: half a search's one deadline (search.ts KEYLESS_SEARCH_MS). */
|
|
11
15
|
export const FIRECRAWL_MS = 30_000;
|
|
12
|
-
/** Firecrawl's keyless refusal codes, by what the run's breaker makes of each
|
|
16
|
+
/** Firecrawl's keyless refusal codes, by what the run's breaker makes of each; of the quotas, those of the host's whole
|
|
17
|
+
* keyless allowance (KEY_QUOTA_CODES) hold both tools, the one tool's (KEYLESS_TOOL_NOT_AVAILABLE) its tool alone. */
|
|
13
18
|
const QUOTA_CODES = new Set(["KEYLESS_QUOTA_EXHAUSTED", "KEYLESS_ACCESS_NOT_AVAILABLE", "KEYLESS_TOOL_NOT_AVAILABLE"]);
|
|
19
|
+
const KEY_QUOTA_CODES = new Set(["KEYLESS_QUOTA_EXHAUSTED", "KEYLESS_ACCESS_NOT_AVAILABLE"]);
|
|
14
20
|
const RATE_CODES = new Set(["KEYLESS_LIMIT_REACHED"]);
|
|
21
|
+
/** Firecrawl's answer once its keyless daily limit is spent: plain text, with no code, as a tool result marked isError
|
|
22
|
+
* or a JSON-RPC error. */
|
|
23
|
+
const DAILY_LIMIT = /daily limit without an account was reached/i;
|
|
24
|
+
/** A spent daily limit, met at `nowMs`: a quota until the next 00:00 UTC, as an HTTP date (Firecrawl names no reset). */
|
|
25
|
+
function dailyLimitAt(nowMs) {
|
|
26
|
+
const day = new Date(nowMs);
|
|
27
|
+
return { kind: "quota", retryAfter: new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate() + 1)).toUTCString() };
|
|
28
|
+
}
|
|
15
29
|
/** A refusal's payload: the result's structuredContent, else its text read as JSON; undefined when neither is an object. */
|
|
16
30
|
function payloadOf(result) {
|
|
17
31
|
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -41,28 +55,47 @@ export function firecrawlLimitOf(payload) {
|
|
|
41
55
|
return { kind: "rate" };
|
|
42
56
|
}
|
|
43
57
|
/** What a call answers for a limit Firecrawl met. */
|
|
44
|
-
|
|
58
|
+
function limitWords(limit, what, words = {}) {
|
|
59
|
+
if (limit.kind === "rate")
|
|
60
|
+
return words.rateLimited ?? RATE_LIMITED;
|
|
61
|
+
if (limit.retryAfter !== undefined)
|
|
62
|
+
return `Keyless Firecrawl will not serve this server's ${what}es now (its free daily limit is spent): it is not asked again before 00:00 UTC`;
|
|
63
|
+
return `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`;
|
|
64
|
+
}
|
|
45
65
|
/** One call's outcome as Firecrawl's answer to `what`: its refusals and failures in our words, else `read` of the result's
|
|
46
66
|
* JSON text. */
|
|
47
|
-
function readCalled(called, what, read, words) {
|
|
67
|
+
function readCalled(called, what, read, words, now) {
|
|
68
|
+
const spent = (said) => {
|
|
69
|
+
if (!DAILY_LIMIT.test(said))
|
|
70
|
+
return undefined;
|
|
71
|
+
const limit = dailyLimitAt(now());
|
|
72
|
+
// The host's daily allowance, for both tools.
|
|
73
|
+
return keyWide(failed("quota", "DAILY_LIMIT", limitWords(limit, what, words), limit));
|
|
74
|
+
};
|
|
48
75
|
if ("status" in called) {
|
|
49
76
|
if (called.status === 429) {
|
|
50
77
|
const limit = { kind: "rate", ...(called.retryAfterS === undefined ? {} : { retryAfter: called.retryAfterS }) };
|
|
51
|
-
return
|
|
78
|
+
return failed("rate", "HTTP_429", limitWords(limit, what, words), limit);
|
|
52
79
|
}
|
|
53
|
-
return {
|
|
80
|
+
return failed("infra", `HTTP_${called.status}`, `Firecrawl's MCP endpoint answered ${called.status} to ${called.step === "initialize" ? "initialize" : `the ${what}`}`);
|
|
54
81
|
}
|
|
55
82
|
if ("over" in called)
|
|
56
|
-
return
|
|
83
|
+
return failed("error", "TOO_LARGE", `Firecrawl's ${what} answered more than ${called.over / MAX_BYTES} MiB: not read`);
|
|
57
84
|
if ("error" in called)
|
|
58
|
-
return
|
|
85
|
+
return (called.rpc ? spent(called.error) : undefined) ?? (called.rpc ? failed("error", "RPC_ERROR", `Firecrawl's ${what} failed: its MCP endpoint answered an error`) : failed("infra", "NO_INITIALIZE", "Firecrawl's MCP endpoint did not answer initialize"));
|
|
59
86
|
const { result } = called;
|
|
60
87
|
if (result?.isError === true) {
|
|
61
88
|
const payload = payloadOf(result);
|
|
89
|
+
const code = typeof payload?.code === "string" ? clip(payload.code, 60) : undefined;
|
|
62
90
|
const limit = firecrawlLimitOf(payload);
|
|
63
|
-
if (limit)
|
|
64
|
-
|
|
65
|
-
|
|
91
|
+
if (limit) {
|
|
92
|
+
const said = failed(limit.kind, code, limitWords(limit, what, words), limit);
|
|
93
|
+
return KEY_QUOTA_CODES.has(code) ? keyWide(said) : said;
|
|
94
|
+
}
|
|
95
|
+
const daily = payload ? undefined : spent(textBlocks(result));
|
|
96
|
+
if (daily)
|
|
97
|
+
return daily;
|
|
98
|
+
return failed("error", code ?? "FAILED", code ? `Firecrawl's ${what} failed (${code})` : `Firecrawl's ${what} failed`);
|
|
66
99
|
}
|
|
67
100
|
try {
|
|
68
101
|
const parsed = JSON.parse(textBlocks(result));
|
|
@@ -70,63 +103,75 @@ function readCalled(called, what, read, words) {
|
|
|
70
103
|
return read(parsed);
|
|
71
104
|
}
|
|
72
105
|
catch { }
|
|
73
|
-
return
|
|
106
|
+
return failed("error", "UNREADABLE", `Firecrawl's ${what} answered no result this server reads`);
|
|
74
107
|
}
|
|
75
108
|
/** 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 }) {
|
|
109
|
+
async function firecrawlCall(name, args, what, maxBytes, read, { endpoint = FIRECRAWL_MCP_URL, send = fetch, signal, timeoutMs = FIRECRAWL_MS, words, now = Date.now }) {
|
|
77
110
|
const own = AbortSignal.timeout(timeoutMs);
|
|
78
111
|
const deadline = AbortSignal.any([own, ...(signal ? [signal] : [])]);
|
|
79
112
|
try {
|
|
80
|
-
return readCalled(await callTool(endpoint, send, deadline, name, args, maxBytes), what, read, words);
|
|
113
|
+
return readCalled(await callTool(endpoint, send, deadline, name, args, maxBytes), what, read, words, now);
|
|
81
114
|
}
|
|
82
115
|
catch (error) {
|
|
83
116
|
// Firecrawl's own bound, or the caller's: its deadline (a search's, spent) or its stop.
|
|
84
117
|
if (own.aborted)
|
|
85
|
-
return
|
|
118
|
+
return failed("infra", "TIMEOUT", `Firecrawl's ${what} did not answer within ${timeoutMs / 1000} s`);
|
|
86
119
|
const reason = signal?.aborted ? signal.reason?.name : error?.name;
|
|
87
|
-
|
|
120
|
+
if (reason === "TimeoutError")
|
|
121
|
+
return failed("infra", "DEADLINE", `Firecrawl's ${what} did not answer before the ${what}'s time ran out`);
|
|
122
|
+
return reason === "AbortError" ? failed("infra", "STOPPED", `the ${what} was stopped`) : failed("infra", "CONNECT", `Firecrawl's ${what} failed: ${withoutUserinfo(String(error?.message ?? error)).slice(0, 300)}`);
|
|
88
123
|
}
|
|
89
124
|
}
|
|
90
|
-
/** `
|
|
125
|
+
/** `ask` searched on Firecrawl's keyless endpoint as keyed Firecrawl searches it (firecrawl.ts firecrawlSearched): up to
|
|
126
|
+
* FIRECRAWL_QUERIES_MAX of its queries, one call each, all at once, each sent the objective (which the keyless tool
|
|
127
|
+
* requires) and the same scrape of its results, each answer at most KEYED_MAX_BYTES, merged (firecrawlMerged). No
|
|
128
|
+
* conversation id is sent. A failure typed. */
|
|
129
|
+
async function searchTyped(ask, options) {
|
|
130
|
+
const { queries, limit } = firecrawlQueries(ask);
|
|
131
|
+
const each = await Promise.all(queries.map((query) => firecrawlCall(FIRECRAWL_SEARCH_TOOL, { query, limit, objective: ask.objective, scrapeOptions: firecrawlScrapeOptions() }, "search", KEYED_MAX_BYTES, (json) => firecrawlHits(json.data) ?? failed("error", "UNREADABLE", "Firecrawl's search answered no results this server reads"), options)));
|
|
132
|
+
return firecrawlMerged("firecrawl-keyless", ask, each);
|
|
133
|
+
}
|
|
134
|
+
/** `query` searched on Firecrawl's keyless endpoint as the objective and the one query, at most `n` results. */
|
|
91
135
|
export async function firecrawlSearch(query, n, options = {}) {
|
|
92
|
-
|
|
93
|
-
|
|
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);
|
|
136
|
+
const { answer, limit } = await searchTyped({ objective: query, queries: [query], n }, options);
|
|
137
|
+
return "error" in answer ? { error: answer.error, ...(limit ? { limit } : {}) } : answer;
|
|
100
138
|
}
|
|
101
139
|
/** 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
|
|
103
|
-
* is not 2xx is no read: the caller fetches directly, as for a refusal. */
|
|
104
|
-
|
|
140
|
+
* (PAGE_MAX_BYTES), a failure typed. Firecrawl names no cut, so the text is read as the whole page's. A page whose
|
|
141
|
+
* status is not 2xx is no read: the caller fetches directly, as for a refusal. */
|
|
142
|
+
function scrapeTyped(url, options) {
|
|
105
143
|
return firecrawlCall(FIRECRAWL_SCRAPE_TOOL, { url, formats: ["markdown"] }, "fetch", PAGE_MAX_BYTES, (json) => {
|
|
106
144
|
if (typeof json.markdown !== "string" || json.markdown.trim() === "")
|
|
107
|
-
return
|
|
145
|
+
return failed("not_text", "NO_TEXT", "Firecrawl's fetch answered no page text");
|
|
108
146
|
const meta = (typeof json.metadata === "object" && json.metadata !== null ? json.metadata : {});
|
|
109
147
|
const final = [meta.url, meta.sourceURL].find((one) => typeof one === "string" && URL.canParse(one)) ?? url;
|
|
110
148
|
const status = typeof meta.statusCode === "number" && Number.isInteger(meta.statusCode) ? meta.statusCode : 200;
|
|
111
149
|
if (status < 200 || status > 299)
|
|
112
|
-
return
|
|
150
|
+
return failed("error", `PAGE_${status}`, `Firecrawl's fetch: the page answered ${status}`);
|
|
113
151
|
return markdownRead(final, typeof meta.title === "string" ? meta.title : "", json.markdown, true, status);
|
|
114
152
|
}, options);
|
|
115
153
|
}
|
|
154
|
+
/** firecrawlScrape's page, or why there is none (as scrapeTyped, bare). */
|
|
155
|
+
export async function firecrawlScrape(url, options = {}) {
|
|
156
|
+
return bare(await scrapeTyped(url, options));
|
|
157
|
+
}
|
|
158
|
+
/** keyless Firecrawl's scrape for one run's web_fetch behind its own breaker (readerOf, on searchBreaker at `now`): held
|
|
159
|
+
* while a limit keeps it off or a rate limit's wait holds; each read one scrape, the page or why there is none. */
|
|
116
160
|
export function firecrawlFetch(options = {}, now = Date.now) {
|
|
117
|
-
|
|
118
|
-
|
|
161
|
+
return readerOf({ read: (url, { signal }) => scrapeTyped(url, { ...options, now, ...(signal ? { signal } : {}) }) }, searchBreaker(now));
|
|
162
|
+
}
|
|
163
|
+
/** Keyless Firecrawl: search and scrape on its public MCP endpoint (or `endpoint`). Its search ends at the call's deadline
|
|
164
|
+
* or its own bound (`bounds.firecrawlMs`: the call's where it gives one, else the Web's; default FIRECRAWL_MS); why a
|
|
165
|
+
* fetch gave no page is said on the page in our words (Firecrawl's own are never passed on) and logged once the direct
|
|
166
|
+
* fetch has answered. */
|
|
167
|
+
export const firecrawlKeyless = defineProvider({ id: "firecrawl-keyless", label: "Firecrawl", keyless: true, ops: ["search", "fetch"], fetch: { miss: { log: "web_fetch_firecrawl_failed", when: "ends" } } }, ({ endpoint, send, words, now, bounds }) => {
|
|
168
|
+
const options = { ...(endpoint ? { endpoint } : {}), ...(send ? { send } : {}), ...(words ? { words } : {}), now };
|
|
119
169
|
return {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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;
|
|
170
|
+
async search(ask, deadline, _signal, called) {
|
|
171
|
+
const firecrawlMs = called?.firecrawlMs ?? bounds?.firecrawlMs;
|
|
172
|
+
// Which limit Firecrawl met is the breaker's to read, never the model's.
|
|
173
|
+
return searchTyped(ask, { ...options, signal: deadline, ...(firecrawlMs === undefined ? {} : { timeoutMs: firecrawlMs }) });
|
|
130
174
|
},
|
|
175
|
+
read: (url, { signal }) => scrapeTyped(url, { ...options, ...(signal ? { signal } : {}) }),
|
|
131
176
|
};
|
|
132
|
-
}
|
|
177
|
+
});
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type Pay } from "../fees.js";
|
|
2
|
+
import { type Read } from "../page.js";
|
|
3
|
+
import { type Failed, type Hit, type SearchAsk, type Searched } from "../search.js";
|
|
4
|
+
import { type Keyed, type KeyedFailed } from "./keyed.js";
|
|
5
|
+
export declare const FIRECRAWL_API_URL = "https://api.firecrawl.dev";
|
|
6
|
+
/** Firecrawl's bound on one request: its own default timeout for a scrape. */
|
|
7
|
+
export declare const FIRECRAWL_KEYED_MS = 60000;
|
|
8
|
+
/** How Firecrawl searches and reads, each setting optional (FIRECRAWL_DEFAULTS):
|
|
9
|
+
* - `onlyMainContent`: a scrape leaves out a page's headers, navigation and footers, default true;
|
|
10
|
+
* - `maxAgeMs`: the oldest cached page a scrape may answer from, 0 a fresh scrape; unset, Firecrawl's own (2 days);
|
|
11
|
+
* - `tbs`: a search's time filter in Firecrawl's words ("qdr:d" the past day, "qdr:w" the past week, ...); unset, none;
|
|
12
|
+
* - `includeDomains` or `excludeDomains` (not both): the hostnames a search keeps to or leaves out;
|
|
13
|
+
* - `country`: the country a search is made from, ISO 3166-1 alpha-2; unset, Firecrawl's own (US);
|
|
14
|
+
* - `highlights`: each result's description is its query-relevant highlight; unset, Firecrawl's own (true). */
|
|
15
|
+
export type FirecrawlSettings = {
|
|
16
|
+
onlyMainContent?: boolean;
|
|
17
|
+
maxAgeMs?: number;
|
|
18
|
+
tbs?: string;
|
|
19
|
+
includeDomains?: string[];
|
|
20
|
+
excludeDomains?: string[];
|
|
21
|
+
country?: string;
|
|
22
|
+
highlights?: boolean;
|
|
23
|
+
};
|
|
24
|
+
export declare const FIRECRAWL_DEFAULTS: Readonly<{
|
|
25
|
+
readonly onlyMainContent: true;
|
|
26
|
+
}>;
|
|
27
|
+
export declare function firecrawlSettingsProblems(settings: unknown): string[];
|
|
28
|
+
/** Firecrawl on `apiKey`, each request paid through `pay`. */
|
|
29
|
+
export declare const firecrawlClient: (apiKey: string, send?: typeof fetch, pay?: Pay, base?: string) => Keyed;
|
|
30
|
+
/** How many of a search's queries Firecrawl is sent: one request each, at once. */
|
|
31
|
+
export declare const FIRECRAWL_QUERIES_MAX = 3;
|
|
32
|
+
/** The scrape a Firecrawl search asks of each result, as Firecrawl's guidance for agents asks: its page as markdown, its
|
|
33
|
+
* main content alone unless `settings` say otherwise (each a scrape, priced by fees.ts firecrawlFeeOf). */
|
|
34
|
+
export declare const firecrawlScrapeOptions: (settings?: FirecrawlSettings) => {
|
|
35
|
+
formats: string[];
|
|
36
|
+
onlyMainContent: boolean;
|
|
37
|
+
};
|
|
38
|
+
/** Firecrawl's search rows, an answer's `data` or its `data.web`, as hits: each row whose url parses, its snippet its
|
|
39
|
+
* page's markdown, else its description; undefined where the answer holds no rows this server reads. */
|
|
40
|
+
export declare function firecrawlHits(data: unknown): Hit[] | undefined;
|
|
41
|
+
/** The queries of `ask` Firecrawl is sent (FIRECRAWL_QUERIES_MAX), and each one's limit: n shared among them, rounded up. */
|
|
42
|
+
export declare const firecrawlQueries: ({ queries, n }: SearchAsk) => {
|
|
43
|
+
queries: string[];
|
|
44
|
+
limit: number;
|
|
45
|
+
};
|
|
46
|
+
/** One search's answer from `each`, its queries' requests in query order, each its hits or its failure: the hits of every
|
|
47
|
+
* request that answered, deduped by url (the first seen kept, in query order then the provider's), cut at `ask.n`;
|
|
48
|
+
* with none answered, the first failure in query order. The most binding limit any request met (a quota over a rate
|
|
49
|
+
* limit, else the longest wait) goes to the run's breaker either way, typed as the failure that met it. */
|
|
50
|
+
export declare function firecrawlMerged(provider: "firecrawl" | "firecrawl-keyless", { objective, queries, n }: SearchAsk, each: readonly (Hit[] | Failed)[]): Searched;
|
|
51
|
+
/** The /v2/search request for `query`, `n` results, under `settings`: each result scraped (firecrawlScrapeOptions). */
|
|
52
|
+
export declare function firecrawlSearchBody(query: string, n: number, settings?: FirecrawlSettings): Record<string, unknown>;
|
|
53
|
+
/** `{objective, queries?, n?}` (searchArgs) searched through `client` (null: the run holds no key) under `settings`:
|
|
54
|
+
* up to FIRECRAWL_QUERIES_MAX of its queries, one paid request each, all at once, merged (firecrawlMerged), and the
|
|
55
|
+
* limit Firecrawl answered for the run's key, if any. */
|
|
56
|
+
export declare function firecrawlSearched(args: Record<string, unknown>, client: Keyed | null, settings?: FirecrawlSettings, signal?: AbortSignal): Promise<Searched>;
|
|
57
|
+
/** The /v2/scrape request for `url` under `settings`: markdown alone. */
|
|
58
|
+
export declare function firecrawlScrapeBody(url: string, settings?: FirecrawlSettings): Record<string, unknown>;
|
|
59
|
+
/** The page at `url` scraped through `client` under `settings`: the page, or why there is none. Firecrawl names no cut,
|
|
60
|
+
* so the text is read as the whole page's; a page whose status is not 2xx is no read. */
|
|
61
|
+
export declare function firecrawlRead(url: string, client: Keyed | null, settings?: FirecrawlSettings, signal?: AbortSignal): Promise<Read | KeyedFailed>;
|
|
62
|
+
/** Firecrawl on the run's key, both tools on one client, as keyed Exa is. */
|
|
63
|
+
export declare const firecrawl: {
|
|
64
|
+
readonly id: "firecrawl";
|
|
65
|
+
readonly label: "Firecrawl";
|
|
66
|
+
readonly key: {
|
|
67
|
+
readonly env: "FIRECRAWL_API_KEY";
|
|
68
|
+
};
|
|
69
|
+
readonly ops: readonly ["search", "fetch"];
|
|
70
|
+
readonly fetch: {
|
|
71
|
+
readonly miss: {
|
|
72
|
+
readonly log: "web_fetch_provider_failed";
|
|
73
|
+
readonly when: "failed";
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
readonly settings: import("../provider.js").SettingsSpec<FirecrawlSettings>;
|
|
77
|
+
} & Pick<import("../provider.js").WebProvider<string>, "make">;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Firecrawl on the run's key (https://docs.firecrawl.dev, API v2): /v2/search for web_search, /v2/scrape for web_fetch,
|
|
2
|
+
// each one paid request (fees.ts firecrawlFeeOf) through the run's Pay, on a bearer token. Its settings are typed, each
|
|
3
|
+
// with a default (FIRECRAWL_DEFAULTS); a setting it does not take is refused when the Web is made. A 401 refuses the key
|
|
4
|
+
// for the run; a 403 refuses one request only (Firecrawl answers it for a page, as for a prompt injection it found).
|
|
5
|
+
import { firecrawlFeeOf } from "../fees.js";
|
|
6
|
+
import { clip, markdownRead, TITLE_CAP } from "../page.js";
|
|
7
|
+
import { defineProvider, settingsOf } from "../provider.js";
|
|
8
|
+
import { failed, failure, retryAfterMs, searchArgs, snippetOf, waitOf } from "../search.js";
|
|
9
|
+
import { domains, keyedCall, keyedClient, matching, settingsProblems, wholeIn, yesNo } from "./keyed.js";
|
|
10
|
+
export const FIRECRAWL_API_URL = "https://api.firecrawl.dev";
|
|
11
|
+
/** Firecrawl's bound on one request: its own default timeout for a scrape. */
|
|
12
|
+
export const FIRECRAWL_KEYED_MS = 60_000;
|
|
13
|
+
export const FIRECRAWL_DEFAULTS = Object.freeze({ onlyMainContent: true });
|
|
14
|
+
const FIRECRAWL_CHECKS = {
|
|
15
|
+
onlyMainContent: yesNo,
|
|
16
|
+
maxAgeMs: wholeIn(0, 31_536_000_000),
|
|
17
|
+
tbs: matching(/^[a-z_]+:[^\s]{1,120}$/, 'Firecrawl\'s time filter, such as "qdr:w"'),
|
|
18
|
+
includeDomains: domains(100),
|
|
19
|
+
excludeDomains: domains(100),
|
|
20
|
+
country: matching(/^[A-Z]{2}$/, "a two-letter country code, such as \"US\""),
|
|
21
|
+
highlights: yesNo,
|
|
22
|
+
};
|
|
23
|
+
export function firecrawlSettingsProblems(settings) {
|
|
24
|
+
const problems = settingsProblems("Firecrawl", settings, FIRECRAWL_CHECKS);
|
|
25
|
+
const asked = settings;
|
|
26
|
+
if (!problems.length && asked.includeDomains && asked.excludeDomains)
|
|
27
|
+
problems.push("Firecrawl takes includeDomains or excludeDomains, not both");
|
|
28
|
+
return problems;
|
|
29
|
+
}
|
|
30
|
+
/** Firecrawl on `apiKey`, each request paid through `pay`. */
|
|
31
|
+
export const firecrawlClient = (apiKey, send = fetch, pay, base = FIRECRAWL_API_URL) => keyedClient({ who: "Firecrawl", base, headers: { authorization: `Bearer ${apiKey}` }, feeOf: firecrawlFeeOf, timeoutMs: FIRECRAWL_KEYED_MS, refuseOn: [401] }, send, pay);
|
|
32
|
+
/** How many of a search's queries Firecrawl is sent: one request each, at once. */
|
|
33
|
+
export const FIRECRAWL_QUERIES_MAX = 3;
|
|
34
|
+
/** The scrape a Firecrawl search asks of each result, as Firecrawl's guidance for agents asks: its page as markdown, its
|
|
35
|
+
* main content alone unless `settings` say otherwise (each a scrape, priced by fees.ts firecrawlFeeOf). */
|
|
36
|
+
export const firecrawlScrapeOptions = (settings = {}) => ({ formats: ["markdown"], onlyMainContent: settings.onlyMainContent ?? FIRECRAWL_DEFAULTS.onlyMainContent });
|
|
37
|
+
/** Firecrawl's search rows, an answer's `data` or its `data.web`, as hits: each row whose url parses, its snippet its
|
|
38
|
+
* page's markdown, else its description; undefined where the answer holds no rows this server reads. */
|
|
39
|
+
export function firecrawlHits(data) {
|
|
40
|
+
const holder = data;
|
|
41
|
+
const rows = Array.isArray(holder) ? holder : Array.isArray(holder?.web) ? holder.web : undefined;
|
|
42
|
+
if (!rows)
|
|
43
|
+
return undefined;
|
|
44
|
+
return rows.flatMap((row) => {
|
|
45
|
+
if (typeof row?.url !== "string" || !URL.canParse(row.url))
|
|
46
|
+
return [];
|
|
47
|
+
const text = typeof row.markdown === "string" && row.markdown.trim() ? row.markdown : typeof row.description === "string" ? row.description : "";
|
|
48
|
+
return [{ url: row.url, title: typeof row.title === "string" ? clip(row.title, TITLE_CAP) : "", snippet: snippetOf(text) }];
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** The queries of `ask` Firecrawl is sent (FIRECRAWL_QUERIES_MAX), and each one's limit: n shared among them, rounded up. */
|
|
52
|
+
export const firecrawlQueries = ({ queries, n }) => {
|
|
53
|
+
const sent = queries.slice(0, FIRECRAWL_QUERIES_MAX);
|
|
54
|
+
return { queries: sent, limit: Math.ceil(n / Math.max(1, sent.length)) };
|
|
55
|
+
};
|
|
56
|
+
/** How long `limit`, met at `nowMs`, says to wait: its Retry-After (retryAfterMs), else the breaker's default wait. */
|
|
57
|
+
const waitedMs = (limit, nowMs) => retryAfterMs(limit.retryAfter, nowMs) ?? waitOf(undefined, nowMs);
|
|
58
|
+
/** The most binding limit among `failures`: a quota over any rate limit, else the rate limit naming the longest wait
|
|
59
|
+
* (the first met of those that tie); the failure that met it. The queries go out at once, so every limit is met at
|
|
60
|
+
* about the same moment, and the breaker must hold the longest any of them named. */
|
|
61
|
+
const bindingOf = (failures, nowMs = Date.now()) => {
|
|
62
|
+
const quota = failures.find((one) => one.limit?.kind === "quota");
|
|
63
|
+
if (quota)
|
|
64
|
+
return quota;
|
|
65
|
+
return failures.filter((one) => one.limit).reduce((longest, one) => (longest === undefined || waitedMs(one.limit, nowMs) > waitedMs(longest.limit, nowMs) ? one : longest), undefined);
|
|
66
|
+
};
|
|
67
|
+
/** One search's answer from `each`, its queries' requests in query order, each its hits or its failure: the hits of every
|
|
68
|
+
* request that answered, deduped by url (the first seen kept, in query order then the provider's), cut at `ask.n`;
|
|
69
|
+
* with none answered, the first failure in query order. The most binding limit any request met (a quota over a rate
|
|
70
|
+
* limit, else the longest wait) goes to the run's breaker either way, typed as the failure that met it. */
|
|
71
|
+
export function firecrawlMerged(provider, { objective, queries, n }, each) {
|
|
72
|
+
const failures = each.filter((one) => !Array.isArray(one));
|
|
73
|
+
const binding = bindingOf(failures);
|
|
74
|
+
const answered = each.filter((one) => Array.isArray(one));
|
|
75
|
+
if (!answered.length) {
|
|
76
|
+
const first = failures[0];
|
|
77
|
+
// The first failure's words and type; the binding limit, and whether it covers the key, from the one that met it.
|
|
78
|
+
const covers = binding?.failure.covers;
|
|
79
|
+
return { answer: { error: first.error }, failure: { ...first.failure, ...(covers ? { covers } : {}) }, ...(binding ? { limit: binding.limit } : {}) };
|
|
80
|
+
}
|
|
81
|
+
const held = binding ? { failure: binding.failure, limit: binding.limit } : {};
|
|
82
|
+
const seen = new Set();
|
|
83
|
+
const results = answered.flat().filter((hit) => !seen.has(hit.url) && Boolean(seen.add(hit.url))).slice(0, n);
|
|
84
|
+
return { answer: { provider, objective, queries, results }, ...held };
|
|
85
|
+
}
|
|
86
|
+
/** The /v2/search request for `query`, `n` results, under `settings`: each result scraped (firecrawlScrapeOptions). */
|
|
87
|
+
export function firecrawlSearchBody(query, n, settings = {}) {
|
|
88
|
+
return {
|
|
89
|
+
query,
|
|
90
|
+
limit: n,
|
|
91
|
+
scrapeOptions: firecrawlScrapeOptions(settings),
|
|
92
|
+
...(settings.tbs ? { tbs: settings.tbs } : {}),
|
|
93
|
+
...(settings.includeDomains ? { includeDomains: settings.includeDomains } : {}),
|
|
94
|
+
...(settings.excludeDomains ? { excludeDomains: settings.excludeDomains } : {}),
|
|
95
|
+
...(settings.country ? { country: settings.country } : {}),
|
|
96
|
+
...(settings.highlights === undefined ? {} : { highlights: settings.highlights }),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** `{objective, queries?, n?}` (searchArgs) searched through `client` (null: the run holds no key) under `settings`:
|
|
100
|
+
* up to FIRECRAWL_QUERIES_MAX of its queries, one paid request each, all at once, merged (firecrawlMerged), and the
|
|
101
|
+
* limit Firecrawl answered for the run's key, if any. */
|
|
102
|
+
export async function firecrawlSearched(args, client, settings = {}, signal) {
|
|
103
|
+
const ask = searchArgs(args);
|
|
104
|
+
if (!ask.objective)
|
|
105
|
+
return { answer: { error: "web_search needs an objective" } };
|
|
106
|
+
const { queries, limit } = firecrawlQueries(ask);
|
|
107
|
+
const each = await Promise.all(queries.map(async (query) => {
|
|
108
|
+
const got = await keyedCall(client, "Firecrawl", "FIRECRAWL_API_KEY", "search", "/v2/search", firecrawlSearchBody(query, limit, settings), signal);
|
|
109
|
+
if ("error" in got)
|
|
110
|
+
return got;
|
|
111
|
+
return (got.json.success === false ? undefined : firecrawlHits(got.json.data)) ?? failed("error", "UNREADABLE", "Firecrawl's search answered no results this server reads");
|
|
112
|
+
}));
|
|
113
|
+
return firecrawlMerged("firecrawl", ask, each);
|
|
114
|
+
}
|
|
115
|
+
/** The /v2/scrape request for `url` under `settings`: markdown alone. */
|
|
116
|
+
export function firecrawlScrapeBody(url, settings = {}) {
|
|
117
|
+
return { url, formats: ["markdown"], onlyMainContent: settings.onlyMainContent ?? FIRECRAWL_DEFAULTS.onlyMainContent, ...(settings.maxAgeMs === undefined ? {} : { maxAge: settings.maxAgeMs }) };
|
|
118
|
+
}
|
|
119
|
+
/** The page at `url` scraped through `client` under `settings`: the page, or why there is none. Firecrawl names no cut,
|
|
120
|
+
* so the text is read as the whole page's; a page whose status is not 2xx is no read. */
|
|
121
|
+
export async function firecrawlRead(url, client, settings = {}, signal) {
|
|
122
|
+
const got = await keyedCall(client, "Firecrawl", "FIRECRAWL_API_KEY", "fetch", "/v2/scrape", firecrawlScrapeBody(url, settings), signal);
|
|
123
|
+
if ("error" in got)
|
|
124
|
+
return got;
|
|
125
|
+
const data = (typeof got.json.data === "object" && got.json.data !== null ? got.json.data : {});
|
|
126
|
+
if (got.json.success === false || typeof data.markdown !== "string" || data.markdown.trim() === "")
|
|
127
|
+
return failed("not_text", "NO_TEXT", "Firecrawl's fetch answered no page text");
|
|
128
|
+
const meta = (typeof data.metadata === "object" && data.metadata !== null ? data.metadata : {});
|
|
129
|
+
const final = [meta.url, meta.sourceURL].find((one) => typeof one === "string" && URL.canParse(one)) ?? url;
|
|
130
|
+
const status = typeof meta.statusCode === "number" && Number.isInteger(meta.statusCode) ? meta.statusCode : 200;
|
|
131
|
+
if (status < 200 || status > 299)
|
|
132
|
+
return failed("error", `PAGE_${status}`, `Firecrawl's fetch: the page answered ${status}`);
|
|
133
|
+
const title = typeof meta.title === "string" ? meta.title : Array.isArray(meta.title) && typeof meta.title[0] === "string" ? meta.title[0] : "";
|
|
134
|
+
return markdownRead(final, title, data.markdown, true, status);
|
|
135
|
+
}
|
|
136
|
+
/** Firecrawl on the run's key, both tools on one client, as keyed Exa is. */
|
|
137
|
+
export const firecrawl = defineProvider({ id: "firecrawl", label: "Firecrawl", key: { env: "FIRECRAWL_API_KEY" }, ops: ["search", "fetch"], fetch: { miss: { log: "web_fetch_provider_failed", when: "failed" } }, settings: settingsOf(firecrawlSettingsProblems) }, ({ key, send, pay, endpoint, settings }) => {
|
|
138
|
+
const asked = (settings ?? {});
|
|
139
|
+
const client = key === undefined ? null : firecrawlClient(key, send ?? fetch, pay, endpoint ?? FIRECRAWL_API_URL);
|
|
140
|
+
return {
|
|
141
|
+
search: (ask, _deadline, signal) => firecrawlSearched(ask, client, asked, signal),
|
|
142
|
+
read: (url, { signal }) => firecrawlRead(url, client, asked, signal),
|
|
143
|
+
unready: () => (client && !client.live() ? failure("refused", "KEY_REFUSED", "not tried: refused earlier in this run") : undefined),
|
|
144
|
+
};
|
|
145
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Fee, type Pay } from "../fees.js";
|
|
2
|
+
import { type Failed, type Limit } from "../search.js";
|
|
3
|
+
/** The most bytes of one answer read: past it the answer is not read. */
|
|
4
|
+
export declare const KEYED_MAX_BYTES: number;
|
|
5
|
+
/** A request that gave no answer this server reads, typed, and the limit it met, if any (for the breaker). */
|
|
6
|
+
export type KeyedFailed = Failed;
|
|
7
|
+
/** One provider on one key: `who` names it in our words, `live` is false once it refused the key, `post` is one paid
|
|
8
|
+
* request to `path` below its base. */
|
|
9
|
+
export type Keyed = {
|
|
10
|
+
who: string;
|
|
11
|
+
live(): boolean;
|
|
12
|
+
post(path: string, body: unknown, signal?: AbortSignal): Promise<Response>;
|
|
13
|
+
};
|
|
14
|
+
/** A provider's API: its name in our words, its base URL, its auth headers, its prices, its bound, the statuses that
|
|
15
|
+
* refuse the key for the client's life. */
|
|
16
|
+
export type KeyedSpec = {
|
|
17
|
+
who: string;
|
|
18
|
+
base: string;
|
|
19
|
+
headers: Record<string, string>;
|
|
20
|
+
feeOf: (path: string, body: unknown) => Fee | undefined;
|
|
21
|
+
timeoutMs: number;
|
|
22
|
+
refuseOn: readonly number[];
|
|
23
|
+
};
|
|
24
|
+
export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
|
|
25
|
+
/** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
|
|
26
|
+
export declare function statusLimit(response: Response): Limit | undefined;
|
|
27
|
+
/** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
|
|
28
|
+
export declare const codeOf: (said: unknown) => string | undefined;
|
|
29
|
+
/** One paid request to `client`'s `path` for a tool's `what`, read as JSON: its answer, or why there is none, in our
|
|
30
|
+
* words: no key (`keyEnv` names the variable), the key refused, the cap's refusal, a timeout, a status (its code where
|
|
31
|
+
* the provider gives one, its limit for the breaker), or an answer that is not JSON. */
|
|
32
|
+
export declare function keyedCall(client: Keyed | null, who: string, keyEnv: string, what: "search" | "fetch", path: string, body: unknown, signal?: AbortSignal): Promise<{
|
|
33
|
+
json: Record<string, unknown>;
|
|
34
|
+
} | KeyedFailed>;
|
|
35
|
+
/** A setting's check, and what it must be, in words. */
|
|
36
|
+
export type Check = [ok: (value: unknown) => boolean, must: string];
|
|
37
|
+
export declare const oneOf: (values: readonly string[]) => Check;
|
|
38
|
+
export declare const wholeIn: (min: number, max: number) => Check;
|
|
39
|
+
export declare const yesNo: Check;
|
|
40
|
+
export declare const matching: (pattern: RegExp, must: string) => Check;
|
|
41
|
+
export declare const domains: (max: number) => Check;
|
|
42
|
+
/** What is wrong with `settings` for `who` by `checks`, one line each: not an object, a setting it does not take, or a
|
|
43
|
+
* value its check refuses. */
|
|
44
|
+
export declare function settingsProblems(who: string, settings: unknown, checks: Readonly<Record<string, Check>>): string[];
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// A provider on the run's key over its HTTP API (Exa's, Firecrawl's): each request paid through the injected Pay at its
|
|
2
|
+
// price and never sent without one; a status in `refuseOn` stops the client for its life; a 402 is the key's credit
|
|
3
|
+
// spent (a quota) and a 429 a rate limit for its Retry-After, both for the run's breaker. Nothing is retried. A
|
|
4
|
+
// provider's own words are never passed on: a failure is said in ours, with its status and, where it gives one, its code.
|
|
5
|
+
import { PaidRefused, unmetered } from "../fees.js";
|
|
6
|
+
import { failed, keyWide } from "../search.js";
|
|
7
|
+
/** The most bytes of one answer read: past it the answer is not read. */
|
|
8
|
+
export const KEYED_MAX_BYTES = 8 * 1024 * 1024;
|
|
9
|
+
export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn }, send = fetch, pay = unmetered) {
|
|
10
|
+
let refused = false;
|
|
11
|
+
const root = base.replace(/\/+$/, "");
|
|
12
|
+
return {
|
|
13
|
+
who,
|
|
14
|
+
live: () => !refused,
|
|
15
|
+
async post(path, body, signal) {
|
|
16
|
+
const fee = feeOf(path, body);
|
|
17
|
+
if (!fee)
|
|
18
|
+
throw new PaidRefused(`${who}'s ${path} was not sent: it has no price here`);
|
|
19
|
+
return pay(fee, async () => {
|
|
20
|
+
const response = await send(`${root}${path}`, {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
23
|
+
body: JSON.stringify(body),
|
|
24
|
+
// It carries the key: a redirect is an error, never followed to an address the key was not meant for.
|
|
25
|
+
redirect: "error",
|
|
26
|
+
signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(signal ? [signal] : [])]),
|
|
27
|
+
});
|
|
28
|
+
if (refuseOn.includes(response.status))
|
|
29
|
+
refused = true;
|
|
30
|
+
return response;
|
|
31
|
+
});
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
|
|
36
|
+
export function statusLimit(response) {
|
|
37
|
+
if (response.status === 402)
|
|
38
|
+
return { kind: "quota" };
|
|
39
|
+
const retryAfter = response.headers.get("retry-after");
|
|
40
|
+
return response.status === 429 ? { kind: "rate", ...(retryAfter ? { retryAfter } : {}) } : undefined;
|
|
41
|
+
}
|
|
42
|
+
/** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
|
|
43
|
+
export const codeOf = (said) => (typeof said === "string" && /^[A-Z][A-Z0-9_]{2,63}$/.test(said) ? said : undefined);
|
|
44
|
+
/** An answer's JSON, read to at most KEYED_MAX_BYTES; undefined when it runs past them or is not JSON. */
|
|
45
|
+
async function jsonOf(response) {
|
|
46
|
+
const reader = response.body?.getReader();
|
|
47
|
+
if (!reader)
|
|
48
|
+
return undefined;
|
|
49
|
+
const chunks = [];
|
|
50
|
+
let bytes = 0;
|
|
51
|
+
for (;;) {
|
|
52
|
+
const { done, value } = await reader.read();
|
|
53
|
+
if (done)
|
|
54
|
+
break;
|
|
55
|
+
bytes += value.byteLength;
|
|
56
|
+
if (bytes > KEYED_MAX_BYTES) {
|
|
57
|
+
await reader.cancel().catch(() => undefined);
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
chunks.push(value);
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** One paid request to `client`'s `path` for a tool's `what`, read as JSON: its answer, or why there is none, in our
|
|
70
|
+
* words: no key (`keyEnv` names the variable), the key refused, the cap's refusal, a timeout, a status (its code where
|
|
71
|
+
* the provider gives one, its limit for the breaker), or an answer that is not JSON. */
|
|
72
|
+
export async function keyedCall(client, who, keyEnv, what, path, body, signal) {
|
|
73
|
+
if (!client)
|
|
74
|
+
return failed("refused", "NO_KEY", `web_${what} goes through ${who} here, and this run holds no ${who} key (${keyEnv})`);
|
|
75
|
+
if (!client.live())
|
|
76
|
+
return failed("refused", "KEY_REFUSED", `${who} refused this run's key: it is not asked again in this run`);
|
|
77
|
+
// A request that failed, or an answer whose body broke after its headers came (the request's timeout, its stop, a
|
|
78
|
+
// reset socket): typed by why, never thrown, so the receipt keeps the turn and the order goes on. A stop is known by
|
|
79
|
+
// the caller's signal, never by the error's name: a run stops with a reason of its own, which the request fails with.
|
|
80
|
+
const unanswered = (error, read) => {
|
|
81
|
+
if (signal?.aborted)
|
|
82
|
+
return failed("infra", "STOPPED", `${who}'s ${what} was stopped`);
|
|
83
|
+
const name = error?.name;
|
|
84
|
+
return name === "TimeoutError" || name === "AbortError" ? failed("infra", "TIMEOUT", `${who}'s ${what} did not answer in time`) : failed("infra", "CONNECT", read ? `${who}'s ${what} answer broke off` : `${who}'s ${what} failed to connect`);
|
|
85
|
+
};
|
|
86
|
+
let response;
|
|
87
|
+
try {
|
|
88
|
+
response = await client.post(path, body, signal);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (error instanceof PaidRefused)
|
|
92
|
+
return failed("refused", "CAP_REFUSED", error.message);
|
|
93
|
+
return unanswered(error, false);
|
|
94
|
+
}
|
|
95
|
+
if (!response.ok) {
|
|
96
|
+
// The status says what it is; a body that broke only loses the provider's code.
|
|
97
|
+
const said = (await jsonOf(response).catch(() => undefined));
|
|
98
|
+
const code = codeOf(said?.code) ?? codeOf(said?.tag);
|
|
99
|
+
if (!client.live())
|
|
100
|
+
return failed("refused", code ?? "KEY_REFUSED", `${who} refused this run's key (${response.status}): it is not asked again in this run`);
|
|
101
|
+
const limit = statusLimit(response);
|
|
102
|
+
const kind = limit ? limit.kind : response.status >= 500 ? "infra" : "error";
|
|
103
|
+
const failure = failed(kind, code ?? `HTTP_${response.status}`, `${who}'s ${what} answered ${response.status}${code ? ` (${code})` : ""}`, limit);
|
|
104
|
+
// A 402 is the key's credit spent, for both tools.
|
|
105
|
+
return response.status === 402 ? keyWide(failure) : failure;
|
|
106
|
+
}
|
|
107
|
+
let json;
|
|
108
|
+
try {
|
|
109
|
+
json = await jsonOf(response);
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
return unanswered(error, true);
|
|
113
|
+
}
|
|
114
|
+
if (typeof json !== "object" || json === null || Array.isArray(json))
|
|
115
|
+
return failed("error", "UNREADABLE", `${who}'s ${what} answered nothing this server reads`);
|
|
116
|
+
return { json: json };
|
|
117
|
+
}
|
|
118
|
+
export const oneOf = (values) => [(value) => typeof value === "string" && values.includes(value), `one of ${values.map((one) => JSON.stringify(one)).join(", ")}`];
|
|
119
|
+
export const wholeIn = (min, max) => [(value) => Number.isInteger(value) && value >= min && value <= max, `a whole number from ${min} to ${max}`];
|
|
120
|
+
export const yesNo = [(value) => typeof value === "boolean", "true or false"];
|
|
121
|
+
export const matching = (pattern, must) => [(value) => typeof value === "string" && pattern.test(value), must];
|
|
122
|
+
export const domains = (max) => [(value) => Array.isArray(value) && value.length <= max && value.every((one) => typeof one === "string" && one.trim() !== "" && one.length <= 253), `a list of at most ${max} domains`];
|
|
123
|
+
/** What is wrong with `settings` for `who` by `checks`, one line each: not an object, a setting it does not take, or a
|
|
124
|
+
* value its check refuses. */
|
|
125
|
+
export function settingsProblems(who, settings, checks) {
|
|
126
|
+
if (typeof settings !== "object" || settings === null || Array.isArray(settings))
|
|
127
|
+
return [`${who}'s settings must be an object`];
|
|
128
|
+
return Object.entries(settings).flatMap(([name, value]) => {
|
|
129
|
+
// Its own checks alone: a setting named constructor or __proto__ is not Object's member.
|
|
130
|
+
const check = Object.hasOwn(checks, name) ? checks[name] : undefined;
|
|
131
|
+
if (!check)
|
|
132
|
+
return [`${who} takes no setting ${JSON.stringify(name)} (it takes ${Object.keys(checks).join(", ")})`];
|
|
133
|
+
if (value === undefined || check[0](value))
|
|
134
|
+
return [];
|
|
135
|
+
return [`${who}'s ${name} must be ${check[1]} (it was ${String(JSON.stringify(value)).slice(0, 60)})`];
|
|
136
|
+
});
|
|
137
|
+
}
|