@parcha/agentrun-web 0.1.0-beta.64 → 0.1.0-beta.66

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.
@@ -2,11 +2,11 @@
2
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
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
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";
5
+ import { clip, PAGE_MAX_BYTES } from "../page.js";
6
6
  import { defineProvider, readerOf } from "../provider.js";
7
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";
8
+ import { firecrawlHits, firecrawlMerged, firecrawlPageOf, firecrawlQueries, firecrawlScrapeOptions } from "./firecrawl.js";
9
+ import { KEYED_MAX_BYTES, thrownFailure } from "./keyed.js";
10
10
  import { callTool, MAX_BYTES, RATE_LIMITED, textBlocks } from "./mcp.js";
11
11
  export const FIRECRAWL_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
12
12
  export const FIRECRAWL_SEARCH_TOOL = "firecrawl_search";
@@ -116,10 +116,7 @@ async function firecrawlCall(name, args, what, maxBytes, read, { endpoint = FIRE
116
116
  // Firecrawl's own bound, or the caller's: its deadline (a search's, spent) or its stop.
117
117
  if (own.aborted)
118
118
  return failed("infra", "TIMEOUT", `Firecrawl's ${what} did not answer within ${timeoutMs / 1000} s`);
119
- const reason = signal?.aborted ? signal.reason?.name : error?.name;
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)}`);
119
+ return thrownFailure(error, { who: "Firecrawl", what, signal, timeout: `Firecrawl's ${what} did not answer before the ${what}'s time ran out`, timeoutCode: "DEADLINE", stopped: `the ${what} was stopped`, failedWith: (said) => `Firecrawl's ${what} failed: ${said}` });
123
120
  }
124
121
  }
125
122
  /** `ask` searched on Firecrawl's keyless endpoint as keyed Firecrawl searches it (firecrawl.ts firecrawlSearched): up to
@@ -140,16 +137,7 @@ export async function firecrawlSearch(query, n, options = {}) {
140
137
  * (PAGE_MAX_BYTES), a failure typed. Firecrawl names no cut, so the text is read as the whole page's. A page whose
141
138
  * status is not 2xx is no read: the caller fetches directly, as for a refusal. */
142
139
  function scrapeTyped(url, options) {
143
- return firecrawlCall(FIRECRAWL_SCRAPE_TOOL, { url, formats: ["markdown"] }, "fetch", PAGE_MAX_BYTES, (json) => {
144
- if (typeof json.markdown !== "string" || json.markdown.trim() === "")
145
- return failed("not_text", "NO_TEXT", "Firecrawl's fetch answered no page text");
146
- const meta = (typeof json.metadata === "object" && json.metadata !== null ? json.metadata : {});
147
- const final = [meta.url, meta.sourceURL].find((one) => typeof one === "string" && URL.canParse(one)) ?? url;
148
- const status = typeof meta.statusCode === "number" && Number.isInteger(meta.statusCode) ? meta.statusCode : 200;
149
- if (status < 200 || status > 299)
150
- return failed("error", `PAGE_${status}`, `Firecrawl's fetch: the page answered ${status}`);
151
- return markdownRead(final, typeof meta.title === "string" ? meta.title : "", json.markdown, true, status);
152
- }, options);
140
+ return firecrawlCall(FIRECRAWL_SCRAPE_TOOL, { url, formats: ["markdown"] }, "fetch", PAGE_MAX_BYTES, (json) => firecrawlPageOf(url, json), options);
153
141
  }
154
142
  /** firecrawlScrape's page, or why there is none (as scrapeTyped, bare). */
155
143
  export async function firecrawlScrape(url, options = {}) {
@@ -169,8 +157,11 @@ export const firecrawlKeyless = defineProvider({ id: "firecrawl-keyless", label:
169
157
  return {
170
158
  async search(ask, deadline, _signal, called) {
171
159
  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 }) });
160
+ // Which limit Firecrawl met is the breaker's to read, never the model's; the words it answers for one (limitWords,
161
+ // the caller's among them) are the model's, and the breaker passes them on (Searched.worded).
162
+ const searched = await searchTyped(ask, { ...options, signal: deadline, ...(firecrawlMs === undefined ? {} : { timeoutMs: firecrawlMs }) });
163
+ const limitSaid = searched.limit && (searched.failure?.class === "rate" || searched.failure?.class === "quota");
164
+ return limitSaid ? { ...searched, worded: true } : searched;
174
165
  },
175
166
  read: (url, { signal }) => scrapeTyped(url, { ...options, ...(signal ? { signal } : {}) }),
176
167
  };
@@ -56,8 +56,15 @@ export declare function firecrawlSearchBody(query: string, n: number, settings?:
56
56
  export declare function firecrawlSearched(args: Record<string, unknown>, client: Keyed | null, settings?: FirecrawlSettings, signal?: AbortSignal): Promise<Searched>;
57
57
  /** The /v2/scrape request for `url` under `settings`: markdown alone. */
58
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. */
59
+ /** A page Firecrawl scraped for `url` (`page`, its scrape's `{markdown, metadata}`, keyed or keyless alike) as a Read:
60
+ * the url it ended at (metadata's url, else its sourceURL, else `url`), its title (a list's first string), its status.
61
+ * Firecrawl names no cut, so the text is read as the whole page's; no markdown is no text, and a page whose status is
62
+ * not 2xx is no read. */
63
+ export declare function firecrawlPageOf(url: string, page: {
64
+ markdown?: unknown;
65
+ metadata?: unknown;
66
+ }): Read | Failed;
67
+ /** The page at `url` scraped through `client` under `settings` (firecrawlPageOf), or why there is none. */
61
68
  export declare function firecrawlRead(url: string, client: Keyed | null, settings?: FirecrawlSettings, signal?: AbortSignal): Promise<Read | KeyedFailed>;
62
69
  /** Firecrawl on the run's key, both tools on one client, as keyed Exa is. */
63
70
  export declare const firecrawl: {
@@ -116,22 +116,28 @@ export async function firecrawlSearched(args, client, settings = {}, signal) {
116
116
  export function firecrawlScrapeBody(url, settings = {}) {
117
117
  return { url, formats: ["markdown"], onlyMainContent: settings.onlyMainContent ?? FIRECRAWL_DEFAULTS.onlyMainContent, ...(settings.maxAgeMs === undefined ? {} : { maxAge: settings.maxAgeMs }) };
118
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() === "")
119
+ /** A page Firecrawl scraped for `url` (`page`, its scrape's `{markdown, metadata}`, keyed or keyless alike) as a Read:
120
+ * the url it ended at (metadata's url, else its sourceURL, else `url`), its title (a list's first string), its status.
121
+ * Firecrawl names no cut, so the text is read as the whole page's; no markdown is no text, and a page whose status is
122
+ * not 2xx is no read. */
123
+ export function firecrawlPageOf(url, page) {
124
+ if (typeof page.markdown !== "string" || page.markdown.trim() === "")
127
125
  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 : {});
126
+ const meta = (typeof page.metadata === "object" && page.metadata !== null ? page.metadata : {});
129
127
  const final = [meta.url, meta.sourceURL].find((one) => typeof one === "string" && URL.canParse(one)) ?? url;
130
128
  const status = typeof meta.statusCode === "number" && Number.isInteger(meta.statusCode) ? meta.statusCode : 200;
131
129
  if (status < 200 || status > 299)
132
130
  return failed("error", `PAGE_${status}`, `Firecrawl's fetch: the page answered ${status}`);
133
131
  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);
132
+ return markdownRead(final, title, page.markdown, true, status);
133
+ }
134
+ /** The page at `url` scraped through `client` under `settings` (firecrawlPageOf), or why there is none. */
135
+ export async function firecrawlRead(url, client, settings = {}, signal) {
136
+ const got = await keyedCall(client, "Firecrawl", "FIRECRAWL_API_KEY", "fetch", "/v2/scrape", firecrawlScrapeBody(url, settings), signal);
137
+ if ("error" in got)
138
+ return got;
139
+ const data = (typeof got.json.data === "object" && got.json.data !== null ? got.json.data : {});
140
+ return firecrawlPageOf(url, got.json.success === false ? {} : data);
135
141
  }
136
142
  /** Firecrawl on the run's key, both tools on one client, as keyed Exa is. */
137
143
  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 }) => {
@@ -140,6 +146,6 @@ export const firecrawl = defineProvider({ id: "firecrawl", label: "Firecrawl", k
140
146
  return {
141
147
  search: (ask, _deadline, signal) => firecrawlSearched(ask, client, asked, signal),
142
148
  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),
149
+ unready: () => (!client ? failure("refused", "NO_KEY", "not tried: this run holds no Firecrawl key") : client.live() ? undefined : failure("refused", "KEY_REFUSED", "not tried: refused earlier in this run")),
144
150
  };
145
151
  });
@@ -22,10 +22,40 @@ export type KeyedSpec = {
22
22
  refuseOn: readonly number[];
23
23
  };
24
24
  export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
25
+ /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
26
+ * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
27
+ * that failed connecting (its cause's code, UNSENT_CODES, a certificate's CERT_* or a handshake's ERR_TLS_*). Anything
28
+ * else may have reached the provider: a reset socket (ECONNRESET, UND_ERR_SOCKET), a timeout or a stop after the send
29
+ * started, a body that broke. */
30
+ export declare function unsentWhy(error: unknown, stoppedFirst: boolean): string | undefined;
31
+ /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
32
+ * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
33
+ * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
34
+ * thrown inside `pay`, which books it at its fee. */
35
+ export declare function paidSend(pay: Pay, fee: Fee, signal: AbortSignal | undefined, send: () => Promise<Response>): Promise<Response>;
25
36
  /** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
26
37
  export declare function statusLimit(response: Response): Limit | undefined;
27
38
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
28
39
  export declare const codeOf: (said: unknown) => string | undefined;
40
+ /** How a provider names a thrown failure: `who` and `what` (its name, the tool), the caller's `signal`, `read` where it
41
+ * broke while the answer was read, and the provider's own words where it keeps them: `timeout` (with its `timeoutCode`)
42
+ * for a bound it names, `stopped`, and `failedWith`, the words around what the error said. */
43
+ export type ThrownSay = {
44
+ who: string;
45
+ what: string;
46
+ signal?: AbortSignal | undefined;
47
+ read?: boolean;
48
+ timeout?: string;
49
+ timeoutCode?: string;
50
+ stopped?: string;
51
+ failedWith?: (said: string) => string;
52
+ };
53
+ /** `error`, thrown by a provider's request, typed one way for every provider, by the caller's signal's reason where it
54
+ * stopped (a run stops with a reason of its own, which the request fails with), else by the error: a TimeoutError is
55
+ * the bound running out (TIMEOUT); an AbortError, or the caller's signal stopped, a stop (STOPPED); anything else
56
+ * CONNECT, what it said with no URL's user name or password, cut at THROWN_SAID_MAX ("answer broke off" where it broke
57
+ * while the answer was read). A provider without words of its own says "<who>'s <what> ...". */
58
+ export declare function thrownFailure(error: unknown, { who, what, signal, read, timeout, timeoutCode, stopped, failedWith }: ThrownSay): Failed;
29
59
  /** 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
60
  * words: no key (`keyEnv` names the variable), the key refused, the cap's refusal, a timeout, a status (its code where
31
61
  * the provider gives one, its limit for the breaker), or an answer that is not JSON. */
@@ -1,8 +1,10 @@
1
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
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
3
+ // spent (a quota) and a 429 a rate limit for its Retry-After, both for the run's breaker. A request on a stopped call is
4
+ // never asked of the Pay, and one that failed before it left (paidSend) is settled at $0. Nothing is retried. A
4
5
  // 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 { PaidRefused, unmetered, unsentAnswer } from "../fees.js";
7
+ import { cutAt, withoutUserinfo } from "../page.js";
6
8
  import { failed, keyWide } from "../search.js";
7
9
  /** The most bytes of one answer read: past it the answer is not read. */
8
10
  export const KEYED_MAX_BYTES = 8 * 1024 * 1024;
@@ -16,7 +18,7 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn },
16
18
  const fee = feeOf(path, body);
17
19
  if (!fee)
18
20
  throw new PaidRefused(`${who}'s ${path} was not sent: it has no price here`);
19
- return pay(fee, async () => {
21
+ return paidSend(pay, fee, signal, async () => {
20
22
  const response = await send(`${root}${path}`, {
21
23
  method: "POST",
22
24
  headers: { ...headers, "content-type": "application/json" },
@@ -32,6 +34,63 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn },
32
34
  },
33
35
  };
34
36
  }
37
+ /** The codes of a fetch's failure (the cause of undici's TypeError "fetch failed") from before its request was written:
38
+ * the host's name not resolved, the host or its network not reached, the connection refused or not made within
39
+ * undici's connect bound, the TLS handshake refusing the host's certificate. A request failing with one never reached
40
+ * the provider. */
41
+ const UNSENT_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN"]);
42
+ /** Node's TLS codes (ERR_TLS_*) that can come once a connection is up, after a request may have left: not unsent. */
43
+ const TLS_LATER = new Set(["ERR_TLS_RENEGOTIATION_DISABLED", "ERR_TLS_SESSION_ATTACK"]);
44
+ /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
45
+ * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
46
+ * that failed connecting (its cause's code, UNSENT_CODES, a certificate's CERT_* or a handshake's ERR_TLS_*). Anything
47
+ * else may have reached the provider: a reset socket (ECONNRESET, UND_ERR_SOCKET), a timeout or a stop after the send
48
+ * started, a body that broke. */
49
+ export function unsentWhy(error, stoppedFirst) {
50
+ if (stoppedFirst)
51
+ return "stopped";
52
+ const thrown = error;
53
+ if (thrown?.name !== "TypeError" || thrown.message !== "fetch failed")
54
+ return undefined;
55
+ const code = thrown.cause?.code;
56
+ if (typeof code !== "string")
57
+ return undefined;
58
+ return UNSENT_CODES.has(code) || code.startsWith("CERT_") || (code.startsWith("ERR_TLS_") && !TLS_LATER.has(code)) ? code : undefined;
59
+ }
60
+ /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
61
+ * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
62
+ * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
63
+ * thrown inside `pay`, which books it at its fee. */
64
+ export async function paidSend(pay, fee, signal, send) {
65
+ if (signal?.aborted)
66
+ throw signal.reason;
67
+ let unsent;
68
+ const answer = await pay(fee, async () => {
69
+ const stoppedFirst = signal?.aborted === true;
70
+ try {
71
+ return await send();
72
+ }
73
+ catch (error) {
74
+ const why = unsentWhy(error, stoppedFirst);
75
+ if (why === undefined)
76
+ throw error;
77
+ unsent = { error };
78
+ return unsentAnswer(why);
79
+ }
80
+ });
81
+ if (unsent) {
82
+ const { error } = unsent;
83
+ // Marked where it can be: a frozen or sealed error is thrown as it was, never replaced by the marking's own failure.
84
+ if (error !== null && typeof error === "object") {
85
+ try {
86
+ Object.assign(error, { unsent: true });
87
+ }
88
+ catch { }
89
+ }
90
+ throw error;
91
+ }
92
+ return answer;
93
+ }
35
94
  /** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
36
95
  export function statusLimit(response) {
37
96
  if (response.status === 402)
@@ -66,6 +125,22 @@ async function jsonOf(response) {
66
125
  return undefined;
67
126
  }
68
127
  }
128
+ /** The most of what a thrown error said that a failure quotes. */
129
+ const THROWN_SAID_MAX = 300;
130
+ /** `error`, thrown by a provider's request, typed one way for every provider, by the caller's signal's reason where it
131
+ * stopped (a run stops with a reason of its own, which the request fails with), else by the error: a TimeoutError is
132
+ * the bound running out (TIMEOUT); an AbortError, or the caller's signal stopped, a stop (STOPPED); anything else
133
+ * CONNECT, what it said with no URL's user name or password, cut at THROWN_SAID_MAX ("answer broke off" where it broke
134
+ * while the answer was read). A provider without words of its own says "<who>'s <what> ...". */
135
+ export function thrownFailure(error, { who, what, signal, read = false, timeout, timeoutCode = "TIMEOUT", stopped, failedWith }) {
136
+ const name = (signal?.aborted ? signal.reason : error)?.name;
137
+ if (name === "TimeoutError")
138
+ return failed("infra", timeoutCode, timeout ?? `${who}'s ${what} did not answer in time`);
139
+ if (name === "AbortError" || signal?.aborted)
140
+ return failed("infra", "STOPPED", stopped ?? `${who}'s ${what} was stopped`);
141
+ const said = cutAt(withoutUserinfo(String(error?.message ?? error)), THROWN_SAID_MAX);
142
+ return failed("infra", "CONNECT", failedWith ? failedWith(said) : read ? `${who}'s ${what} answer broke off` : `${who}'s ${what} failed to connect`);
143
+ }
69
144
  /** 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
145
  * words: no key (`keyEnv` names the variable), the key refused, the cap's refusal, a timeout, a status (its code where
71
146
  * the provider gives one, its limit for the breaker), or an answer that is not JSON. */
@@ -74,15 +149,9 @@ export async function keyedCall(client, who, keyEnv, what, path, body, signal) {
74
149
  return failed("refused", "NO_KEY", `web_${what} goes through ${who} here, and this run holds no ${who} key (${keyEnv})`);
75
150
  if (!client.live())
76
151
  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
- };
152
+ // A request that failed, or an answer whose body broke after its headers came: typed by why (thrownFailure), never
153
+ // thrown, so the receipt keeps the turn and the order goes on.
154
+ const unanswered = (error, read) => thrownFailure(error, { who, what, signal, read });
86
155
  let response;
87
156
  try {
88
157
  response = await client.post(path, body, signal);
@@ -25,8 +25,9 @@ export declare const PARALLEL_DEFAULTS: Readonly<{
25
25
  }>;
26
26
  export declare function parallelSettingsProblems(settings: unknown): string[];
27
27
  /** Parallel for one run, on one key: `extract`, its extract of a page (one billed request), the page it read or, for
28
- * any failure, why it read none, typed; `read`, the same with why in Parallel's words alone; `post`, one request to another of its endpoints (web_search's, parallelSearched). Neither
29
- * retries, and each stops at 60 s. `live` is false once a 401 or 403 to either said the key is not served. */
28
+ * any failure, why it read none, typed; `read`, the same with why in Parallel's words alone; `post`, one request to
29
+ * another of its endpoints (web_search's, parallelSearched), a URL below Parallel's API. Neither retries, and each stops
30
+ * at 60 s. `live` is false once a 401 or 403 to either said the key is not served. */
30
31
  export type Extract = {
31
32
  live(): boolean;
32
33
  extract?(url: string, signal?: AbortSignal, client?: WebClient): Promise<Read | Failed>;
@@ -1,12 +1,14 @@
1
1
  // Parallel on the run's key: Extract for web_fetch, Search for web_search. Every request is paid through the injected
2
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
3
  import { PARALLEL_SEARCH_MODE_USD, PaidRefused, parallelFeeOf, unmetered } from "../fees.js";
4
- import { clip, markdownRead, PAGE_READ_MAX_CHARS, TITLE_CAP, withoutUserinfo } from "../page.js";
4
+ import { clip, cutAt, markdownRead, PAGE_READ_MAX_CHARS, TITLE_CAP } from "../page.js";
5
5
  import { failed, failure, keyWide, searchArgs, searchFailed, snippetOf } from "../search.js";
6
6
  import { defineProvider, settingsOf } from "../provider.js";
7
- import { domains, matching, oneOf, settingsProblems, wholeIn } from "./keyed.js";
8
- export const PARALLEL_SEARCH_URL = "https://api.parallel.ai/v1/search";
9
- export const PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
7
+ import { domains, keyedClient, matching, oneOf, settingsProblems, statusLimit, thrownFailure, wholeIn } from "./keyed.js";
8
+ /** Parallel's API: every request the web tools send goes below it. */
9
+ const PARALLEL_API_URL = "https://api.parallel.ai";
10
+ export const PARALLEL_SEARCH_URL = `${PARALLEL_API_URL}/v1/search`;
11
+ export const PARALLEL_EXTRACT_URL = `${PARALLEL_API_URL}/v1/extract`;
10
12
  const PARALLEL_TIMEOUT_MS = 60_000;
11
13
  /** Parallel's cap on a search's session_id, in characters: a longer session is sent as its first SESSION_MAX. */
12
14
  const SESSION_MAX = 1_000;
@@ -39,27 +41,15 @@ const clientFields = (client) => ({
39
41
  * web_fetch reads as the page's text (markdown), its links read from it, status 200 (Parallel answers a page it could
40
42
  * not read in `errors`, with no content), told the read's client (clientFields). */
41
43
  export function parallelExtract(apiKey, send = fetch, pay = unmetered, settings = {}) {
42
- let refused = false;
43
- // 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
44
- // as the call's cost at its endpoint's price). One the cap refuses is not sent: it throws its refusal (PaidRefused).
44
+ // One keyed client for both tools (keyed.ts keyedClient): each request paid through `pay` at its endpoint's price
45
+ // (fees.ts; serve's paid-calls.ts holds it to the run's cap), one with no price, or one the cap refuses, not sent
46
+ // (PaidRefused), a stopped call sending nothing and one that never left not billed (paidSend).
47
+ const client = keyedClient({ who: "Parallel", base: PARALLEL_API_URL, headers: { "x-api-key": apiKey }, feeOf: (path, body) => parallelFeeOf(`${PARALLEL_API_URL}${path}`, body), timeoutMs: PARALLEL_TIMEOUT_MS, refuseOn: [401, 403] }, send, pay);
45
48
  const post = async (url, body, signal) => {
46
- const sent = async () => {
47
- const response = await send(url, {
48
- method: "POST",
49
- headers: { "x-api-key": apiKey, "content-type": "application/json" },
50
- body: JSON.stringify(body),
51
- // It carries the key: a redirect is an error, never followed to an address the key was not meant for.
52
- redirect: "error",
53
- signal: AbortSignal.any([AbortSignal.timeout(PARALLEL_TIMEOUT_MS), ...(signal ? [signal] : [])]),
54
- });
55
- if (response.status === 401 || response.status === 403)
56
- refused = true;
57
- return response;
58
- };
59
- const fee = parallelFeeOf(url, body);
60
- if (!fee)
49
+ // It carries the key: a URL not below Parallel's API is never sent, as a request with no price here.
50
+ if (!url.startsWith(`${PARALLEL_API_URL}/`))
61
51
  throw new PaidRefused(`Parallel's ${URL.parse(url)?.pathname ?? url} was not sent: it has no price here`);
62
- return pay(fee, sent);
52
+ return client.post(url.slice(PARALLEL_API_URL.length), body, signal);
63
53
  };
64
54
  const extract = async (url, signal, client = {}) => {
65
55
  try {
@@ -85,12 +75,12 @@ export function parallelExtract(apiKey, send = fetch, pay = unmetered, settings
85
75
  catch (error) {
86
76
  if (error instanceof PaidRefused)
87
77
  return failed("refused", "CAP_REFUSED", error.message);
88
- const name = error?.name;
89
- return name === "TimeoutError" ? failed("infra", "TIMEOUT", "timed out") : name === "AbortError" ? failed("infra", "STOPPED", "was stopped") : failed("infra", "CONNECT", `failed: ${withoutUserinfo(String(error?.message ?? error)).slice(0, 200)}`);
78
+ // Said on the page beside Parallel's name: its own words, what an error said cut at 200.
79
+ return thrownFailure(error, { who: "Parallel", what: "fetch", signal, timeout: "timed out", stopped: "was stopped", failedWith: (said) => `failed: ${cutAt(said, 200)}` });
90
80
  }
91
81
  };
92
82
  return {
93
- live: () => !refused,
83
+ live: client.live,
94
84
  post,
95
85
  extract,
96
86
  read: async (url, signal, client) => {
@@ -99,14 +89,6 @@ export function parallelExtract(apiKey, send = fetch, pay = unmetered, settings
99
89
  },
100
90
  };
101
91
  }
102
- /** What a Parallel answer's status says of the run's search: out of credit (402), or rate-limited (429) for its
103
- * Retry-After. */
104
- const parallelLimit = (response) => {
105
- if (response.status === 402)
106
- return { kind: "quota" };
107
- const retryAfter = response.headers.get("retry-after");
108
- return response.status === 429 ? { kind: "rate", ...(retryAfter ? { retryAfter } : {}) } : undefined;
109
- };
110
92
  /** The /v1/search request for `ask` (searchArgs), under `settings`, as Parallel's guidance for agents asks: the
111
93
  * objective, a goal in plain words, as its objective; the keyword queries as search_queries; and the model and
112
94
  * session of `client` (cut at SESSION_MAX) where the run knows them. Excerpts are Parallel's own length
@@ -142,7 +124,7 @@ export async function parallelSearched(args, parallel, signal, settings = {}, cl
142
124
  const response = await parallel.post(PARALLEL_SEARCH_URL, parallelSearchBody(ask, settings, client), signal);
143
125
  if (!response.ok) {
144
126
  await response.body?.cancel().catch(() => undefined);
145
- const limit = parallelLimit(response);
127
+ const limit = statusLimit(response);
146
128
  if (!parallel.live())
147
129
  return searchFailed(failed("refused", "KEY_REFUSED", REFUSED));
148
130
  const said = failed(limit ? limit.kind : response.status >= 500 ? "infra" : "error", `HTTP_${response.status}`, `Parallel's search answered ${response.status}`, limit);
@@ -160,7 +142,7 @@ export async function parallelSearched(args, parallel, signal, settings = {}, cl
160
142
  catch (error) {
161
143
  if (error instanceof PaidRefused)
162
144
  return searchFailed(failed("refused", "CAP_REFUSED", error.message));
163
- return searchFailed(error?.name === "TimeoutError" ? failed("infra", "TIMEOUT", "Parallel's search did not answer within 60 s") : failed("infra", "CONNECT", `Parallel's search failed: ${error?.message ?? String(error)}`));
145
+ return searchFailed(thrownFailure(error, { who: "Parallel", what: "search", signal, timeout: "Parallel's search did not answer within 60 s", failedWith: (said) => `Parallel's search failed: ${said}` }));
164
146
  }
165
147
  }
166
148
  /** web_fetch's reads through `client` (null: the run holds no key), told `told` (the Web's client, each field in place
package/dist/search.d.ts CHANGED
@@ -82,11 +82,14 @@ export declare const keyWide: (one: Failed) => Failed;
82
82
  /** `value` without its typed failure: what an exported call answers, as it did before failures were typed. */
83
83
  export declare function bare<T>(value: T): T;
84
84
  /** A Search, and the failure and limit its provider answered, if any: the run's breaker reads `limit` (searchBreaker),
85
- * the receipt `failure`, the model the Search alone. */
85
+ * the receipt `failure`, the model the Search alone. `worded`: the error is the provider's words for the model about the
86
+ * limit it met (a keyless search's, a caller's Words among them), which the breaker passes on where its own would say
87
+ * no more; else a limit's error is said in the breaker's words. */
86
88
  export type Searched = {
87
89
  answer: Search;
88
90
  failure?: Failure;
89
91
  limit?: Limit;
92
+ worded?: true;
90
93
  };
91
94
  /** A failed search as searchInTurn reads it. */
92
95
  export declare const searchFailed: ({ error, failure, limit }: Failed) => Searched;
@@ -102,9 +105,10 @@ export declare function waitOf(retryAfter: string | number | undefined, nowMs: n
102
105
  export declare function offUntil(limit: Limit, nowMs: number): number | undefined;
103
106
  /** A breaker on one backend, read at `now`. `held`: what a call answers unsent while it holds (SEARCH_UNAVAILABLE once
104
107
  * off, searchBusy for the seconds left of a wait). `read` takes a search and its limit: a quota answer, or a rate limit
105
- * naming a wait past 15 minutes, turns it off (offUntil), the call keeping any results it has; a shorter rate limit
106
- * opens a wait, never shrinking one already open; a repeatIsQuota limit after an earlier one whose wait has passed,
107
- * with no success between, is a quota answer and the call answers SEARCH_UNAVAILABLE. */
108
+ * naming a wait past 15 minutes, turns it off (offUntil); a shorter rate limit opens a wait, never shrinking one
109
+ * already open; a repeatIsQuota limit after an earlier one whose wait has passed, with no success between, is a quota
110
+ * answer. The call that met a limit keeps any results it has; with none it answers `held`'s words, as the next call
111
+ * would, never the provider's for the limit. */
108
112
  export type Breaker = {
109
113
  held(): Search | undefined;
110
114
  read(searched: Searched): Search;
@@ -148,11 +152,12 @@ export type Backend = {
148
152
  name: string;
149
153
  ask(deadline: AbortSignal): Promise<Searched>;
150
154
  };
151
- /** One backend's turn in a call: answered (`ok`), failed (`error`: its message, the failure typed where the provider
152
- * typed it, the limit it met), or held by its breaker. */
155
+ /** One backend's turn in a call: answered (`ok`), answered no results (`empty`: a search passed on to the next
156
+ * backend), failed (`error`: its message, the failure typed where the provider typed it, the limit it met), or held by
157
+ * its breaker. */
153
158
  export type Try = {
154
159
  provider: string;
155
- outcome: "ok" | "error" | "held";
160
+ outcome: "ok" | "empty" | "error" | "held";
156
161
  error?: string;
157
162
  failure?: Failure;
158
163
  limit?: Limit;
@@ -169,8 +174,11 @@ export type SearchBounds = {
169
174
  firecrawlMs?: number;
170
175
  };
171
176
  /** A call's search through `backends` in turn, each behind its breaker, all under one deadline (`boundMs` or `signal`):
172
- * the first with results answers; none starts on a spent deadline. None left: SEARCH_UNAVAILABLE where every backend is
173
- * off (a lone backend's own answer where it was asked), else the last failure, else searchBusy for the shortest wait. */
177
+ * the first with results (or a short answer of its own) answers; one answering none passes the call on, and the first
178
+ * such answers only when no backend after it has results. None starts on a spent deadline: one spent before any was
179
+ * asked answers SEARCH_STOPPED, a stopped turn of the first not held. None left: SEARCH_UNAVAILABLE
180
+ * where every backend is off (a lone backend's own answer where it was asked), else the last failure (one that met a
181
+ * limit in its breaker's words), else searchBusy for the shortest wait. */
174
182
  export declare function searchInTurn(backends: readonly Backend[], breakerOf: (name: string) => Breaker, signal?: AbortSignal, boundMs?: number, tries?: Try[]): Promise<Search>;
175
183
  /** `own`, one tool's breaker on a provider, joined with `key`, the provider's breaker across both tools: held while
176
184
  * either holds; a limit whose failure covers the key (Failure.covers) trips both, any other `own` alone. */
package/dist/search.js CHANGED
@@ -1,3 +1,8 @@
1
+ // web_search's one answer shape (Search), its bounds, and searchInTurn: a call asks its backends in order, each behind
2
+ // a breaker of its own. A quota answer turns a backend off until the reset it names, else for the breaker's life; a rate
3
+ // limit holds it for the wait it named (60 s when none), and one naming a wait past 15 minutes turns it off for that
4
+ // wait. A backend that fails, answers no results, is held or is off passes the call to the next.
5
+ import { cutAt } from "./page.js";
1
6
  /** The most of one keyword query a search sends (Parallel's own bound on a query). */
2
7
  export const QUERY_MAX = 200;
3
8
  /** The most of a search's objective, its goal in plain words, a search sends. */
@@ -72,34 +77,37 @@ export function searchBreaker(now = Date.now) {
72
77
  let offKind = "quota";
73
78
  let waitKind = "rate";
74
79
  const off = () => now() < offTill;
80
+ const held = () => {
81
+ if (off())
82
+ return { error: SEARCH_UNAVAILABLE };
83
+ const left = until - now();
84
+ return left > 0 ? busyFor(left) : undefined;
85
+ };
75
86
  return {
76
87
  holding() {
77
88
  if (off())
78
89
  return { kind: offKind, until: offTill };
79
90
  return until > now() ? { kind: waitKind, until } : undefined;
80
91
  },
81
- held() {
82
- if (off())
83
- return { error: SEARCH_UNAVAILABLE };
84
- const left = until - now();
85
- return left > 0 ? busyFor(left) : undefined;
86
- },
92
+ held,
87
93
  off,
88
94
  left: () => Math.max(0, until - now()),
89
- read({ answer, limit }) {
95
+ read({ answer, limit, worded }) {
90
96
  if (!("error" in answer))
91
97
  marked = false;
92
98
  if (!limit)
93
99
  return answer;
94
100
  const at = now();
95
101
  const till = offUntil(limit, at);
96
- // The call that turns search off for a rate limit answers its results if it has any (a merged search's other
97
- // requests), else SEARCH_UNAVAILABLE, never its limit's "try again" words.
102
+ // The call that met a limit answers its results if it has any (a merged search's other requests), else what a call
103
+ // held by it answers (held: SEARCH_UNAVAILABLE, or searchBusy for its wait), never the provider's "answered 429";
104
+ // a provider's own words for the model (worded) stand, but for a rate limit that turns it off ("try again" words).
105
+ const heldOr = (words = !worded) => ("error" in answer && words ? (held() ?? answer) : answer);
98
106
  if (till !== undefined) {
99
107
  if (till >= offTill)
100
108
  offKind = limit.kind;
101
109
  offTill = Math.max(offTill, till);
102
- return limit.kind === "quota" || !("error" in answer) ? answer : { error: SEARCH_UNAVAILABLE };
110
+ return heldOr(limit.kind === "rate" || !worded);
103
111
  }
104
112
  if (limit.kind === "rate" && limit.repeatIsQuota && marked && at >= until) {
105
113
  offTill = Number.POSITIVE_INFINITY;
@@ -110,7 +118,7 @@ export function searchBreaker(now = Date.now) {
110
118
  marked = true;
111
119
  until = Math.max(until, at + waitOf(limit.retryAfter, at));
112
120
  waitKind = limit.kind;
113
- return answer;
121
+ return heldOr();
114
122
  },
115
123
  };
116
124
  }
@@ -140,7 +148,7 @@ export function snippetOf(raw) {
140
148
  const text = raw.replace(/!?\[([^\]]*)\]\([^)\s]*\)/g, "$1").replace(/\s+/g, " ").trim();
141
149
  if (text.length <= SNIPPET_MAX)
142
150
  return text;
143
- const cut = text.slice(0, SNIPPET_MAX - 1);
151
+ const cut = cutAt(text, SNIPPET_MAX - 1);
144
152
  const space = cut.lastIndexOf(" ");
145
153
  return `${(space > SNIPPET_MAX / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
146
154
  }
@@ -161,12 +169,21 @@ export function searchArgs(args) {
161
169
  * leaves Exa what is left of it, never a fresh bound. Firecrawl's own bound inside it (FIRECRAWL_MS, 30 s) leaves Exa
162
170
  * at least the rest. */
163
171
  export const KEYLESS_SEARCH_MS = 60_000;
172
+ /** What a call stopped before any backend was asked answers (searchInTurn): the keyless backends' words for a stop. */
173
+ const SEARCH_STOPPED = "the search was stopped";
174
+ /** Whether a search's answer holds nothing for the model: no results and no short answer of its own (`text`). */
175
+ const emptyAnswer = (answer) => !("error" in answer) && !answer.results.length && !answer.text;
164
176
  /** A call's search through `backends` in turn, each behind its breaker, all under one deadline (`boundMs` or `signal`):
165
- * the first with results answers; none starts on a spent deadline. None left: SEARCH_UNAVAILABLE where every backend is
166
- * off (a lone backend's own answer where it was asked), else the last failure, else searchBusy for the shortest wait. */
177
+ * the first with results (or a short answer of its own) answers; one answering none passes the call on, and the first
178
+ * such answers only when no backend after it has results. None starts on a spent deadline: one spent before any was
179
+ * asked answers SEARCH_STOPPED, a stopped turn of the first not held. None left: SEARCH_UNAVAILABLE
180
+ * where every backend is off (a lone backend's own answer where it was asked), else the last failure (one that met a
181
+ * limit in its breaker's words), else searchBusy for the shortest wait. */
167
182
  export async function searchInTurn(backends, breakerOf, signal, boundMs = KEYLESS_SEARCH_MS, tries) {
168
183
  const deadline = AbortSignal.any([AbortSignal.timeout(boundMs), ...(signal ? [signal] : [])]);
169
184
  let last;
185
+ // The first answer with no results: the call's, if no backend after it has any.
186
+ let empty;
170
187
  for (const backend of backends) {
171
188
  const breaker = breakerOf(backend.name);
172
189
  const held = breaker.held();
@@ -175,16 +192,29 @@ export async function searchInTurn(backends, breakerOf, signal, boundMs = KEYLES
175
192
  tries?.push({ provider: backend.name, outcome: "held", ...(holding && "error" in held ? { failure: failure(holding.kind, "HELD", held.error) } : {}), ms: 0 });
176
193
  continue;
177
194
  }
178
- if (last && deadline.aborted)
179
- break;
195
+ if (deadline.aborted) {
196
+ if (last || empty)
197
+ break;
198
+ // A call stopped before any backend was asked starts none (a paid one would be held, or sent, for nothing): its
199
+ // turn is the stopped one the backend would have answered, in the keyless backends' words.
200
+ tries?.push({ provider: backend.name, outcome: "error", error: SEARCH_STOPPED, failure: failure("infra", "STOPPED", SEARCH_STOPPED), ms: 0 });
201
+ return { error: SEARCH_STOPPED };
202
+ }
180
203
  const started = tries ? performance.now() : 0;
181
204
  const searched = await backend.ask(deadline);
182
205
  const answer = breaker.read(searched);
183
- tries?.push({ provider: backend.name, outcome: "error" in answer ? "error" : "ok", ...("error" in answer ? { error: answer.error, ...(searched.failure ? { failure: searched.failure } : {}) } : {}), ...(searched.limit ? { limit: searched.limit } : {}), ms: Math.round(performance.now() - started) });
184
- if (!("error" in answer))
206
+ const outcome = "error" in answer ? "error" : emptyAnswer(answer) ? "empty" : "ok";
207
+ // The receipt keeps what the provider said; the model reads the breaker's words for a limit.
208
+ tries?.push({ provider: backend.name, outcome, ...("error" in answer ? { error: "error" in searched.answer ? searched.answer.error : answer.error, ...(searched.failure ? { failure: searched.failure } : {}) } : {}), ...(searched.limit ? { limit: searched.limit } : {}), ms: Math.round(performance.now() - started) });
209
+ if (outcome === "ok")
185
210
  return answer;
186
- last = answer;
211
+ if (outcome === "empty")
212
+ empty ??= answer;
213
+ else
214
+ last = answer;
187
215
  }
216
+ if (empty)
217
+ return empty;
188
218
  const breakers = backends.map((backend) => breakerOf(backend.name));
189
219
  if (breakers.every((breaker) => breaker.off()))
190
220
  return backends.length === 1 && last ? last : { error: SEARCH_UNAVAILABLE };