@parcha/agentrun-web 0.1.0-beta.57 → 0.1.0-beta.59

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.
Files changed (48) hide show
  1. package/README.md +126 -11
  2. package/dist/decide/decider.d.ts +183 -0
  3. package/dist/decide/decider.js +248 -0
  4. package/dist/decide/failure.d.ts +6 -0
  5. package/dist/decide/failure.js +22 -0
  6. package/dist/decide/fetch.d.ts +53 -0
  7. package/dist/decide/fetch.js +95 -0
  8. package/dist/decide/page-guard.d.ts +36 -0
  9. package/dist/decide/page-guard.js +26 -0
  10. package/dist/decide/passages.d.ts +6 -0
  11. package/dist/decide/passages.js +54 -0
  12. package/dist/decide/record.d.ts +102 -0
  13. package/dist/decide/record.js +125 -0
  14. package/dist/decide/search.d.ts +18 -0
  15. package/dist/decide/search.js +43 -0
  16. package/dist/fees.d.ts +35 -2
  17. package/dist/fees.js +62 -2
  18. package/dist/fetch.d.ts +48 -41
  19. package/dist/fetch.js +112 -72
  20. package/dist/index.d.ts +17 -6
  21. package/dist/index.js +19 -7
  22. package/dist/provider.d.ts +113 -0
  23. package/dist/provider.js +34 -0
  24. package/dist/providers/direct.d.ts +15 -0
  25. package/dist/providers/direct.js +24 -8
  26. package/dist/providers/exa-keyless.d.ts +13 -2
  27. package/dist/providers/exa-keyless.js +33 -14
  28. package/dist/providers/exa.d.ts +68 -0
  29. package/dist/providers/exa.js +111 -0
  30. package/dist/providers/firecrawl-keyless.d.ts +25 -14
  31. package/dist/providers/firecrawl-keyless.js +91 -46
  32. package/dist/providers/firecrawl.d.ts +77 -0
  33. package/dist/providers/firecrawl.js +145 -0
  34. package/dist/providers/keyed.d.ts +44 -0
  35. package/dist/providers/keyed.js +136 -0
  36. package/dist/providers/native.d.ts +5 -0
  37. package/dist/providers/native.js +11 -0
  38. package/dist/providers/parallel.d.ts +55 -10
  39. package/dist/providers/parallel.js +127 -39
  40. package/dist/providers/registry.d.ts +119 -0
  41. package/dist/providers/registry.js +35 -0
  42. package/dist/search.d.ts +86 -17
  43. package/dist/search.js +101 -34
  44. package/dist/tool-specs.d.ts +65 -0
  45. package/dist/tool-specs.js +36 -0
  46. package/dist/web.d.ts +109 -30
  47. package/dist/web.js +165 -63
  48. package/package.json +2 -2
@@ -0,0 +1,113 @@
1
+ import type { Pay } from "./fees.js";
2
+ import type { Guard, GuardOptions } from "./guard.js";
3
+ import type { Read, Unread } from "./page.js";
4
+ import type { Words } from "./providers/mcp.js";
5
+ import { type Breaker, type Failure, type Holding, type Limit, type SearchAsk, type SearchBounds, type Searched } from "./search.js";
6
+ export type { SearchAsk };
7
+ /** The run's own model provider's hosted search, asked one query (a search's first). `signal` is the caller's; it keeps
8
+ * its own bounds. */
9
+ export type NativeSearch = (query: string, n: number, signal?: AbortSignal) => Promise<Searched>;
10
+ /** What a Web hands a provider it makes: the run's key for it, where its requests go and through what, its settings
11
+ * (checked when the Web was made), the run's Pay, the clock, a product's words, a native search, the public-host guard,
12
+ * a call's bounds, and the client the run knows of (WebClient). Each is the run's, never another provider's. */
13
+ export type ProviderParts = {
14
+ key?: string;
15
+ endpoint?: string;
16
+ send?: typeof fetch;
17
+ settings?: unknown;
18
+ guard?: Guard;
19
+ pay: Pay;
20
+ now: () => number;
21
+ words?: Words;
22
+ native?: NativeSearch;
23
+ bounds?: SearchBounds;
24
+ client?: WebClient;
25
+ };
26
+ /** What a run knows of the agent calling the web tools, each only where known, never made up: `model`, the id of the
27
+ * model that writes the searches and reads their results; `session`, the run's id, the one session of every search the
28
+ * run makes. */
29
+ export type WebClient = {
30
+ model?: string;
31
+ session?: string;
32
+ };
33
+ /** A read's options: the guard's, and `client`, the call's own, each field in place of the Web's where given. */
34
+ export type ReadOptions = GuardOptions & {
35
+ client?: WebClient;
36
+ };
37
+ /** A read that gave no page: in our words, the failure typed (search.ts Failed; a stand-in's may give the words alone),
38
+ * and the limit it met, if any (for the run's breaker). */
39
+ export type ReadFailed = {
40
+ error: string;
41
+ failure?: Failure;
42
+ limit?: Limit;
43
+ };
44
+ /** A provider made for one Web. `search`: one search, ended by `deadline` (the call's one deadline for every provider it
45
+ * asks) or kept on the caller's `signal` and the provider's own bound, as the provider says; `bounds`, the call's own,
46
+ * each in place of the Web's (ProviderParts.bounds) where given; `client`, the call's own, each field in place
47
+ * of the Web's (ProviderParts.client) where given. `read`: one read of a page
48
+ * (one that passed the guard's check, unless the provider ends the order and reads through the guard itself).
49
+ * `unready`: why a read is not asked now, unsent (its key refused, or none where none means no turn), typed, or
50
+ * undefined. */
51
+ export type ProviderRun = {
52
+ search?(ask: SearchAsk, deadline: AbortSignal, signal?: AbortSignal, bounds?: SearchBounds, client?: WebClient): Promise<Searched>;
53
+ read?(url: unknown, options: ReadOptions): Promise<Read | Unread | ReadFailed>;
54
+ unready?(): Failure | undefined;
55
+ };
56
+ /** How a provider's fetch fits the order. `ends`: it answers whatever it reads, the order's last word (the guarded direct
57
+ * fetch). Otherwise the page names why the provider gave none under its id, and the model is told: a read that gave no
58
+ * page, and a turn it was not asked for being unready or held. `miss` says what more becomes of it:
59
+ * - "said": a turn the guard's check refused is told too;
60
+ * - `{log, when}`: a failed read is logged as `log`, at once with the provider and the limit it met (`when` "failed"),
61
+ * or once a provider that ends the order has answered, with what it did (`when` "ends"; never where none follows).
62
+ * Every turn not asked is on the receipt as search's is: one its breaker held as outcome "held", its failure the hold;
63
+ * any other (unready, or the guard's refusal) as a failed turn saying why. */
64
+ export type FetchShape = {
65
+ ends: true;
66
+ } | {
67
+ ends?: false;
68
+ miss: "said";
69
+ } | {
70
+ ends?: false;
71
+ miss: {
72
+ log: string;
73
+ when: "failed" | "ends";
74
+ };
75
+ };
76
+ /** A provider's settings, typed `S`: `problems` says what is wrong with a value, one line each (none: it is S). */
77
+ export type SettingsSpec<S> = {
78
+ problems(value: unknown): string[];
79
+ readonly typed?: S;
80
+ };
81
+ export declare const settingsOf: <S>(problems: (value: unknown) => string[]) => SettingsSpec<S>;
82
+ /** One provider: its `id` (what an order names), its `label` in our words, the variable its key is read from, `keyless`
83
+ * where it is the free use of a service another provider reads on a key, the tools it serves, what its fetch does where
84
+ * it serves web_fetch, its settings where it takes any, and `make`, the provider for one Web. */
85
+ export type WebProvider<Id extends string = string> = {
86
+ id: Id;
87
+ label: string;
88
+ key?: {
89
+ env: string;
90
+ };
91
+ keyless?: true;
92
+ ops: readonly ("search" | "fetch")[];
93
+ fetch?: FetchShape;
94
+ settings?: SettingsSpec<unknown>;
95
+ make(parts: ProviderParts): ProviderRun;
96
+ };
97
+ /** A provider as registered: `meta` (its id, ops, fetch shape, key and settings kept as literals, for the registry's
98
+ * unions) and `make`. Two arguments, so the unions are read from `meta` alone, never from what `make` answers. */
99
+ export declare const defineProvider: <const M extends Omit<WebProvider, "make">>(meta: M, make: WebProvider["make"]) => M & Pick<WebProvider, "make">;
100
+ /** The code of a turn not asked because its breaker holds the provider (Reader.held). */
101
+ export declare const HELD_CODE = "HELD";
102
+ /** When a breaker holding a provider lets it be asked again, in words: until the minute it names (UTC), or for the rest
103
+ * of the run. */
104
+ export declare function holdingWords({ kind, until }: Holding): string;
105
+ /** A provider's reads behind `breaker`: `held` is why it is not asked now, typed (unready, else the breaker holding it:
106
+ * its limit's kind, code HELD, and until when, holdingWords), `holding` what holds the breaker, and a failed read's limit
107
+ * trips the breaker. The fetch's breaker is search's (searchBreaker). */
108
+ export type Reader = {
109
+ held(): Failure | undefined;
110
+ holding?(): Holding | undefined;
111
+ read(url: unknown, options: ReadOptions): Promise<Read | Unread | ReadFailed>;
112
+ };
113
+ export declare function readerOf(run: ProviderRun, breaker: Breaker): Reader;
@@ -0,0 +1,34 @@
1
+ import { failure } from "./search.js";
2
+ export const settingsOf = (problems) => ({ problems });
3
+ /** A provider as registered: `meta` (its id, ops, fetch shape, key and settings kept as literals, for the registry's
4
+ * unions) and `make`. Two arguments, so the unions are read from `meta` alone, never from what `make` answers. */
5
+ export const defineProvider = (meta, make) => ({ ...meta, make });
6
+ /** The code of a turn not asked because its breaker holds the provider (Reader.held). */
7
+ export const HELD_CODE = "HELD";
8
+ /** When a breaker holding a provider lets it be asked again, in words: until the minute it names (UTC), or for the rest
9
+ * of the run. */
10
+ export function holdingWords({ kind, until }) {
11
+ const what = kind === "rate" ? "rate-limited" : "out of quota";
12
+ return Number.isFinite(until) ? `${what} until ${new Date(Math.ceil(until / 60_000) * 60_000).toISOString().slice(11, 16)} UTC` : `${what} for the rest of this run`;
13
+ }
14
+ export function readerOf(run, breaker) {
15
+ const read = run.read;
16
+ if (!read)
17
+ throw new Error("readerOf: the provider has no read");
18
+ return {
19
+ held() {
20
+ const unready = run.unready?.();
21
+ if (unready)
22
+ return unready;
23
+ const holding = breaker.holding();
24
+ return holding ? failure(holding.kind, HELD_CODE, `not tried: ${holdingWords(holding)}`) : undefined;
25
+ },
26
+ holding: () => breaker.holding(),
27
+ async read(url, options) {
28
+ const got = await read(url, options);
29
+ if (!("ok" in got) && got.limit)
30
+ breaker.read({ answer: { error: got.error }, limit: got.limit, ...(got.failure ? { failure: got.failure } : {}) });
31
+ return got;
32
+ },
33
+ };
34
+ }
@@ -1,5 +1,10 @@
1
1
  import { type Guard, type GuardOptions } from "../guard.js";
2
2
  import { type Page, type Part, type Read, type Unread } from "../page.js";
3
+ import { type Failure } from "../search.js";
4
+ /** A page the direct fetch did not read, with why typed (the provider's own; readDirect answers it bare). */
5
+ export type UnreadTyped = Unread & {
6
+ failure: Failure;
7
+ };
3
8
  /** The page at `url`, read once through `guard`'s fetch (an HTML page through its reader), or why it was not. `options`
4
9
  * are the guard's resolver and fetch, for a test; a signal ends it early. */
5
10
  export declare function readDirect(url: unknown, guard: Guard | undefined, options?: GuardOptions): Promise<Read | Unread>;
@@ -7,3 +12,13 @@ export declare function readDirect(url: unknown, guard: Guard | undefined, optio
7
12
  export declare function fetchPage(url: unknown, { guard, offset, maxChars, ...options }?: GuardOptions & Part & {
8
13
  guard?: Guard;
9
14
  }): Promise<Page>;
15
+ /** The guarded direct fetch, web_fetch only: it ends the order, answering whatever it reads (a refusal or a failure is
16
+ * its page). With no guard nothing is fetched. */
17
+ export declare const direct: {
18
+ readonly id: "direct";
19
+ readonly label: "the guarded direct fetch";
20
+ readonly ops: readonly ["fetch"];
21
+ readonly fetch: {
22
+ readonly ends: true;
23
+ };
24
+ } & Pick<import("../provider.js").WebProvider<string>, "make">;
@@ -2,30 +2,39 @@
2
2
  // false, never a throw. With no guard nothing is fetched.
3
3
  import { isRefused } from "../guard.js";
4
4
  import { askedUrl, clip, linksWithin, partOfRead, TIMEOUT_MS, TITLE_CAP, textOf, URL_MAX, withoutCredentials, withoutUserinfo } from "../page.js";
5
+ import { defineProvider } from "../provider.js";
6
+ import { bare } from "../search.js";
5
7
  import { linksOf } from "../text-urls.js";
6
8
  /** The page at `url`, read once through `guard`'s fetch (an HTML page through its reader), or why it was not. `options`
7
9
  * are the guard's resolver and fetch, for a test; a signal ends it early. */
8
10
  export async function readDirect(url, guard, options = {}) {
9
- const failed = (fields) => ({ ok: false, url: askedUrl(url), status: 0, title: "", text: "", links: [], ...fields });
11
+ return bare(await readTyped(url, guard, options));
12
+ }
13
+ /** readDirect, with why a page was not read typed. */
14
+ async function readTyped(url, guard, options) {
15
+ const failed = (kind, code, fields) => {
16
+ const page = { ok: false, url: askedUrl(url), status: 0, title: "", text: "", links: [], ...fields };
17
+ return { ...page, failure: { class: kind, code, message: "refused" in fields ? fields.refused : fields.error } };
18
+ };
10
19
  if (typeof url !== "string" || !URL.canParse(url))
11
- return failed({ error: "url is not an absolute URL" });
20
+ return failed("error", "BAD_URL", { error: "url is not an absolute URL" });
12
21
  const target = new URL(url);
13
22
  // The bound is on the href, what the guard fetches: percent-encoding can grow it past the string as asked.
14
23
  if (target.href.length > URL_MAX)
15
- return failed({ error: `url is longer than ${URL_MAX.toLocaleString("en-US")} characters` });
24
+ return failed("error", "URL_TOO_LONG", { error: `url is longer than ${URL_MAX.toLocaleString("en-US")} characters` });
16
25
  const { port, username, password } = target;
17
26
  if (port && port !== "80" && port !== "443")
18
- return failed({ refused: `refused: port ${port} is not 80 or 443` });
27
+ return failed("refused", "PORT", { refused: `refused: port ${port} is not 80 or 443` });
19
28
  // A URL's user name and password are never sent anywhere: a fetch refuses them, never a third party's read of them.
20
29
  if (username || password)
21
- return failed({ refused: "refused: the URL holds a user name or password" });
30
+ return failed("refused", "CREDENTIALS", { refused: "refused: the URL holds a user name or password" });
22
31
  if (!guard)
23
- return failed({ error: "no public-host guard was given, so nothing is fetched directly" });
32
+ return failed("refused", "NO_GUARD", { error: "no public-host guard was given, so nothing is fetched directly" });
24
33
  try {
25
34
  const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(options.signal ? [options.signal] : [])]);
26
35
  const answer = await guard.fetch(url, { ...options, signal });
27
36
  if (answer.body === null)
28
- return failed({ url: clip(withoutCredentials(answer.url), URL_MAX), status: answer.status, error: `the page answered ${answer.status}` });
37
+ return failed(answer.status >= 500 ? "infra" : "error", `PAGE_${answer.status}`, { url: clip(withoutCredentials(answer.url), URL_MAX), status: answer.status, error: `the page answered ${answer.status}` });
29
38
  // The caller's stop reaches the read too; the timeout is the network's, and the reader keeps its own deadline.
30
39
  const read = guard.html && /html/i.test(answer.contentType) ? await guard.html(answer.body, answer.url, options.signal ? { signal: options.signal } : {}) : null;
31
40
  const page = read ?? { title: "", text: answer.body, links: linksOf(answer.body) };
@@ -43,7 +52,9 @@ export async function readDirect(url, guard, options = {}) {
43
52
  catch (error) {
44
53
  // Never a URL's user name or password: undici's refusal of a redirect to a URL holding them quotes it whole.
45
54
  const message = withoutUserinfo(error?.message ?? String(error));
46
- return failed(isRefused(error) ? { refused: message } : { error: message });
55
+ if (isRefused(error))
56
+ return failed("refused", "GUARD", { refused: message });
57
+ return failed("infra", error?.name === "TimeoutError" ? "TIMEOUT" : "CONNECT", { error: message });
47
58
  }
48
59
  }
49
60
  /** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
@@ -51,3 +62,8 @@ export async function fetchPage(url, { guard, offset, maxChars, ...options } = {
51
62
  const read = await readDirect(url, guard, options);
52
63
  return read.ok ? partOfRead(read, { offset, maxChars }) : read;
53
64
  }
65
+ /** The guarded direct fetch, web_fetch only: it ends the order, answering whatever it reads (a refusal or a failure is
66
+ * its page). With no guard nothing is fetched. */
67
+ export const direct = defineProvider({ id: "direct", label: "the guarded direct fetch", ops: ["fetch"], fetch: { ends: true } }, ({ guard }) => ({
68
+ read: (url, { client: _client, ...options }) => readTyped(url, guard, options),
69
+ }));
@@ -23,13 +23,24 @@ export declare function ipv4Fetch(lookup?: LookupFunction): {
23
23
  /** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
24
24
  * ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
25
25
  * `pause` (default a wait the search's signal ends; a test's records it). `words`: the caller's for its free limit. */
26
- export declare function exaSearch(query: string, n: number, { send, signal, pause, words }?: {
26
+ export declare function exaSearch(query: string, n: number, options?: ExaOptions): Promise<Search | ExaLimited>;
27
+ /** What exaSearch takes: the fetch, the caller's signal, the pause before its one retry, the caller's words. */
28
+ type ExaOptions = {
27
29
  send?: typeof fetch;
28
30
  signal?: AbortSignal;
29
31
  pause?: (ms: number, signal: AbortSignal) => Promise<void>;
30
32
  words?: Words;
31
- }): Promise<Search | ExaLimited>;
33
+ };
32
34
  /** Keyless Exa's refusal as the run's breaker reads it: a rate limit, with the wait it named. One naming no wait (its MCP
33
35
  * notice, as its daily count running out answers) is marked repeatIsQuota, so a second one past a wait is that count; a
34
36
  * 429 with Retry-After is a timed limit, unmarked. A refused connection is no limit (a 403 no wait lifts). */
35
37
  export declare function exaLimitOf(found: ExaLimited): Limit | undefined;
38
+ /** Keyless Exa, web_search only: ended by the call's deadline; its free limit is the breaker's (exaLimitOf), its words
39
+ * the model's alone. */
40
+ export declare const exaKeyless: {
41
+ readonly id: "exa-keyless";
42
+ readonly label: "Exa";
43
+ readonly keyless: true;
44
+ readonly ops: readonly ["search"];
45
+ } & Pick<import("../provider.js").WebProvider<string>, "make">;
46
+ export {};
@@ -3,7 +3,8 @@
3
3
  // Exa is dialled over IPv4 only, the one way it takes keyless use.
4
4
  import { lookup as dnsLookup } from "node:dns";
5
5
  import { clip, TITLE_CAP } from "../page.js";
6
- import { snippetOf } from "../search.js";
6
+ import { defineProvider } from "../provider.js";
7
+ import { bare, snippetOf } from "../search.js";
7
8
  import { callTool, RATE_LIMITED, sleep, textBlocks } from "./mcp.js";
8
9
  export const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
9
10
  export const EXA_SEARCH_TOOL = "web_search_exa";
@@ -25,6 +26,7 @@ function exaSaid(text) {
25
26
  const RATE_LIMITED_META = "ai.exa/rateLimited";
26
27
  /** The longest Retry-After waited out before the one retry. */
27
28
  const RETRY_AFTER_MAX_S = 5;
29
+ const typed = (kind, code, found) => ({ ...found, failure: { class: kind, code, message: found.error } });
28
30
  /** The wait before the one retry: the Retry-After Exa named, else 1 to 3 s, each with jitter so runs limited together
29
31
  * do not all ask again at once. */
30
32
  const retryPause = (retryAfterS) => (retryAfterS === undefined ? 1_000 + Math.random() * 2_000 : retryAfterS * 1_000 + Math.random() * 500);
@@ -54,36 +56,40 @@ function hitOf(section) {
54
56
  const published = known(field("Published"));
55
57
  return { url, title: clip(known(field("Title")) ?? "", TITLE_CAP), snippet: snippetOf(snippet), ...(published ? { published } : {}) };
56
58
  }
57
- /** One exchange's outcome as Exa's answer to a search for `query`, at most `n` results: its refusals and failures in our
58
- * words, else its hits. */
59
- function searchOf(called, query, n, rateLimited) {
59
+ /** One exchange's outcome as Exa's answer to a search for `ask`'s objective, at most `ask.n` results: its refusals and
60
+ * failures in our words, else its hits. */
61
+ function searchOf(called, { objective, queries, n }, rateLimited) {
60
62
  if ("status" in called) {
61
63
  if (called.status === 429)
62
- return { error: rateLimited, limit: "rate_limited", ...(called.retryAfterS === undefined ? {} : { retryAfterS: called.retryAfterS }) };
64
+ return typed("rate", "HTTP_429", { error: rateLimited, limit: "rate_limited", ...(called.retryAfterS === undefined ? {} : { retryAfterS: called.retryAfterS }) });
63
65
  if (called.status === 403)
64
- return { error: "Exa refused keyless use from this connection (403): it takes keyless searches only over IPv4, straight to its endpoint, not over IPv6 or through a proxy", limit: "connection_refused" };
65
- return { error: `Exa's MCP endpoint answered ${called.status} to ${called.step === "initialize" ? "initialize" : "the search"}` };
66
+ return typed("refused", "CONNECTION_REFUSED", { error: "Exa refused keyless use from this connection (403): it takes keyless searches only over IPv4, straight to its endpoint, not over IPv6 or through a proxy", limit: "connection_refused" });
67
+ return typed("infra", `HTTP_${called.status}`, { error: `Exa's MCP endpoint answered ${called.status} to ${called.step === "initialize" ? "initialize" : "the search"}` });
66
68
  }
67
69
  if ("error" in called)
68
- return { error: called.rpc ? exaSaid(called.error) : "Exa's MCP endpoint did not answer initialize" };
70
+ return called.rpc ? typed("error", "RPC_ERROR", { error: exaSaid(called.error) }) : typed("infra", "NO_INITIALIZE", { error: "Exa's MCP endpoint did not answer initialize" });
69
71
  const { result } = called;
70
72
  const meta = result?._meta;
71
73
  if (result?.isError === true && typeof meta === "object" && meta !== null && meta[RATE_LIMITED_META] === true)
72
- return { error: rateLimited, limit: "rate_limited" };
74
+ return typed("rate", "RATE_LIMITED", { error: rateLimited, limit: "rate_limited" });
73
75
  const said = textBlocks(result);
74
76
  if (!Array.isArray(result?.content) || result.isError === true)
75
- return { error: exaSaid(said) };
77
+ return typed("error", "FAILED", { error: exaSaid(said) });
76
78
  const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
77
- return { provider: "exa-keyless", query, results: hits.slice(0, n) };
79
+ return { provider: "exa-keyless", objective, queries, results: hits.slice(0, n) };
78
80
  }
79
81
  /** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
80
82
  * ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
81
83
  * `pause` (default a wait the search's signal ends; a test's records it). `words`: the caller's for its free limit. */
82
- export async function exaSearch(query, n, { send, signal, pause = sleep, words = {} } = {}) {
84
+ export async function exaSearch(query, n, options = {}) {
85
+ return bare(await searchTyped({ objective: query, queries: [query], n }, options));
86
+ }
87
+ /** `ask` searched as exaSearch searches, its objective as Exa's query, a failure typed. */
88
+ async function searchTyped(ask, { send, signal, pause = sleep, words = {} }) {
83
89
  const deadline = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]);
84
90
  const own = send ? undefined : ipv4Fetch();
85
91
  const dial = send ?? own.send;
86
- const once = async () => searchOf(await callTool(EXA_MCP_URL, dial, deadline, EXA_SEARCH_TOOL, { query, numResults: Math.min(n, RESULTS_MAX) }), query, n, words.rateLimited ?? RATE_LIMITED);
92
+ const once = async () => searchOf(await callTool(EXA_MCP_URL, dial, deadline, EXA_SEARCH_TOOL, { query: ask.objective, numResults: Math.min(ask.n, RESULTS_MAX) }), ask, words.rateLimited ?? RATE_LIMITED);
87
93
  try {
88
94
  const first = await once();
89
95
  if (!("limit" in first) || first.limit !== "rate_limited" || (first.retryAfterS ?? 0) > RETRY_AFTER_MAX_S)
@@ -93,7 +99,9 @@ export async function exaSearch(query, n, { send, signal, pause = sleep, words =
93
99
  }
94
100
  catch (error) {
95
101
  const name = error?.name;
96
- return { error: name === "TimeoutError" ? "Exa's search did not answer within 60 s" : name === "AbortError" ? "the search was stopped" : `Exa's search failed: ${String(error?.message ?? error).slice(0, 300)}` };
102
+ if (name === "TimeoutError")
103
+ return typed("infra", "TIMEOUT", { error: "Exa's search did not answer within 60 s" });
104
+ return name === "AbortError" ? typed("infra", "STOPPED", { error: "the search was stopped" }) : typed("infra", "CONNECT", { error: `Exa's search failed: ${String(error?.message ?? error).slice(0, 300)}` });
97
105
  }
98
106
  finally {
99
107
  await own?.close().catch(() => undefined);
@@ -107,3 +115,14 @@ export function exaLimitOf(found) {
107
115
  return undefined;
108
116
  return found.retryAfterS === undefined ? { kind: "rate", repeatIsQuota: true } : { kind: "rate", retryAfter: found.retryAfterS };
109
117
  }
118
+ /** Keyless Exa, web_search only: ended by the call's deadline; its free limit is the breaker's (exaLimitOf), its words
119
+ * the model's alone. */
120
+ export const exaKeyless = defineProvider({ id: "exa-keyless", label: "Exa", keyless: true, ops: ["search"] }, ({ send, words }) => ({
121
+ async search(ask, deadline) {
122
+ const found = await searchTyped(ask, { ...(send ? { send } : {}), ...(words ? { words } : {}), signal: deadline });
123
+ if (!("failure" in found))
124
+ return { answer: found };
125
+ const limit = "limit" in found ? exaLimitOf(found) : undefined;
126
+ return { answer: { error: found.error }, failure: found.failure, ...(limit ? { limit } : {}) };
127
+ },
128
+ }));
@@ -0,0 +1,68 @@
1
+ import { type ExaSearchType, type Pay } from "../fees.js";
2
+ import { type Read } from "../page.js";
3
+ import { type Searched } from "../search.js";
4
+ import { type Keyed, type KeyedFailed } from "./keyed.js";
5
+ export declare const EXA_API_URL = "https://api.exa.ai";
6
+ /** Exa's bound on one request: a deep search takes tens of seconds. */
7
+ export declare const EXA_MS = 120000;
8
+ export declare const EXA_CATEGORIES: readonly ["company", "publication", "news", "personal site", "financial report", "people"];
9
+ /** How Exa searches and reads, each setting optional (EXA_DEFAULTS):
10
+ * - `type`: the search's depth and price (fees.ts EXA_SEARCH_TYPE_USD), default "auto";
11
+ * - `snippet`: each result's text for its snippet, its query-relevant `highlights` or the page's `text` from its start,
12
+ * default "highlights"; `snippetChars`, how many characters of it Exa gives, MAX_CHARS_MIN to SNIPPET_MAX, default
13
+ * SNIPPET_MAX (a snippet keeps at most SNIPPET_MAX);
14
+ * - `maxAgeHours`: the oldest cached page Exa may answer from, for a search's contents and a fetch, -1 (cache only) to
15
+ * 720, 0 a live crawl; unset, Exa's own (its cache, a live crawl for a page it has none of);
16
+ * - `includeDomains`, `excludeDomains`: the domains a search keeps to or leaves out; `category`: Exa's index to search;
17
+ * - `pageVerbosity`: how much of a page a fetch reads (Exa's compact, standard or full), default "compact";
18
+ * `pageLinks`: whether a fetched page's links stay in its text, default true. */
19
+ export type ExaSettings = {
20
+ type?: ExaSearchType;
21
+ snippet?: "highlights" | "text";
22
+ snippetChars?: number;
23
+ maxAgeHours?: number;
24
+ includeDomains?: string[];
25
+ excludeDomains?: string[];
26
+ category?: (typeof EXA_CATEGORIES)[number];
27
+ pageVerbosity?: "compact" | "standard" | "full";
28
+ pageLinks?: boolean;
29
+ };
30
+ export declare const EXA_DEFAULTS: Readonly<{
31
+ readonly type: "auto";
32
+ readonly snippet: "highlights";
33
+ readonly snippetChars: 3000;
34
+ readonly pageVerbosity: "compact";
35
+ readonly pageLinks: true;
36
+ }>;
37
+ export declare const exaSettingsProblems: (settings: unknown) => string[];
38
+ /** Exa on `apiKey`, each request paid through `pay`. */
39
+ export declare const exaClient: (apiKey: string, send?: typeof fetch, pay?: Pay, base?: string) => Keyed;
40
+ /** The /search request for `query`, `n` results, under `settings`. */
41
+ export declare function exaSearchBody(query: string, n: number, settings?: ExaSettings): Record<string, unknown>;
42
+ /** `{objective, queries?, n?}` (searchArgs) searched through `client` (null: the run holds no key) under `settings`,
43
+ * the objective as Exa's query (Exa reads a goal in plain words), and the limit Exa answered for the run's key, if any. */
44
+ export declare function exaSearched(args: Record<string, unknown>, client: Keyed | null, settings?: ExaSettings, signal?: AbortSignal): Promise<Searched>;
45
+ /** The /contents request for `url` under `settings`: its text to the most of a page web_fetch reads and one character
46
+ * more (so a page Exa cut there shows as going on), at the verbosity asked, its links kept or not. */
47
+ export declare function exaContentsBody(url: string, settings?: ExaSettings): Record<string, unknown>;
48
+ /** The page at `url` read through `client`'s /contents under `settings`: the page, or why there is none (its status and
49
+ * tag where Exa names them). */
50
+ export declare function exaRead(url: string, client: Keyed | null, settings?: ExaSettings, signal?: AbortSignal): Promise<Read | KeyedFailed>;
51
+ /** Exa on the run's key, both tools on one client. Its search keeps the caller's signal and its own bound (a paid request
52
+ * is not cut short by the keyless providers' deadline); a fetch it gives no page is logged with the limit it met. With
53
+ * no key, each request answers so, unsent. */
54
+ export declare const exa: {
55
+ readonly id: "exa";
56
+ readonly label: "Exa";
57
+ readonly key: {
58
+ readonly env: "EXA_API_KEY";
59
+ };
60
+ readonly ops: readonly ["search", "fetch"];
61
+ readonly fetch: {
62
+ readonly miss: {
63
+ readonly log: "web_fetch_provider_failed";
64
+ readonly when: "failed";
65
+ };
66
+ };
67
+ readonly settings: import("../provider.js").SettingsSpec<ExaSettings>;
68
+ } & Pick<import("../provider.js").WebProvider<string>, "make">;
@@ -0,0 +1,111 @@
1
+ // Exa on the run's key (https://docs.exa.ai): /search for web_search, /contents for web_fetch, each one paid request
2
+ // (fees.ts exaFeeOf) through the run's Pay, on the x-api-key header. Its settings are typed, each with a default
3
+ // (EXA_DEFAULTS); a setting it does not take is refused when the Web is made. A 401 or 403 refuses the key for the run.
4
+ import { EXA_SEARCH_TYPE_USD, exaFeeOf } from "../fees.js";
5
+ import { clip, linksWithin, MAX_CHARS_MIN, PAGE_READ_MAX_CHARS, TITLE_CAP, textOf, URL_MAX, withoutCredentials } from "../page.js";
6
+ import { failed, failure, SNIPPET_MAX, searchArgs, searchFailed, snippetOf } from "../search.js";
7
+ import { defineProvider, settingsOf } from "../provider.js";
8
+ import { linksOf } from "../text-urls.js";
9
+ import { codeOf, domains, keyedCall, keyedClient, oneOf, settingsProblems, wholeIn, yesNo } from "./keyed.js";
10
+ export const EXA_API_URL = "https://api.exa.ai";
11
+ /** Exa's bound on one request: a deep search takes tens of seconds. */
12
+ export const EXA_MS = 120_000;
13
+ export const EXA_CATEGORIES = ["company", "publication", "news", "personal site", "financial report", "people"];
14
+ export const EXA_DEFAULTS = Object.freeze({ type: "auto", snippet: "highlights", snippetChars: SNIPPET_MAX, pageVerbosity: "compact", pageLinks: true });
15
+ const EXA_CHECKS = {
16
+ type: oneOf(Object.keys(EXA_SEARCH_TYPE_USD)),
17
+ snippet: oneOf(["highlights", "text"]),
18
+ snippetChars: wholeIn(MAX_CHARS_MIN, SNIPPET_MAX),
19
+ maxAgeHours: wholeIn(-1, 720),
20
+ includeDomains: domains(1_200),
21
+ excludeDomains: domains(1_200),
22
+ category: oneOf(EXA_CATEGORIES),
23
+ pageVerbosity: oneOf(["compact", "standard", "full"]),
24
+ pageLinks: yesNo,
25
+ };
26
+ export const exaSettingsProblems = (settings) => settingsProblems("Exa", settings, EXA_CHECKS);
27
+ /** Exa on `apiKey`, each request paid through `pay`. */
28
+ export const exaClient = (apiKey, send = fetch, pay, base = EXA_API_URL) => keyedClient({ who: "Exa", base, headers: { "x-api-key": apiKey }, feeOf: exaFeeOf, timeoutMs: EXA_MS, refuseOn: [401, 403] }, send, pay);
29
+ /** The /search request for `query`, `n` results, under `settings`. */
30
+ export function exaSearchBody(query, n, settings = {}) {
31
+ const { type, snippet, snippetChars } = { ...EXA_DEFAULTS, ...settings };
32
+ const content = snippet === "text" ? { text: { maxCharacters: snippetChars } } : { highlights: { maxCharacters: snippetChars } };
33
+ return {
34
+ query,
35
+ type,
36
+ numResults: n,
37
+ ...(settings.includeDomains ? { includeDomains: settings.includeDomains } : {}),
38
+ ...(settings.excludeDomains ? { excludeDomains: settings.excludeDomains } : {}),
39
+ ...(settings.category ? { category: settings.category } : {}),
40
+ contents: { ...content, ...(settings.maxAgeHours === undefined ? {} : { maxAgeHours: settings.maxAgeHours }) },
41
+ };
42
+ }
43
+ /** A result's text for its snippet: the content asked first (highlights joined, or text), else the other. */
44
+ function snippetText(row, asked) {
45
+ const highlights = Array.isArray(row.highlights) ? row.highlights.filter((one) => typeof one === "string").join(" … ") : "";
46
+ const text = typeof row.text === "string" ? row.text : "";
47
+ return asked === "text" ? text || highlights : highlights || text;
48
+ }
49
+ /** `{objective, queries?, n?}` (searchArgs) searched through `client` (null: the run holds no key) under `settings`,
50
+ * the objective as Exa's query (Exa reads a goal in plain words), and the limit Exa answered for the run's key, if any. */
51
+ export async function exaSearched(args, client, settings = {}, signal) {
52
+ const { objective, queries, n } = searchArgs(args);
53
+ if (!objective)
54
+ return { answer: { error: "web_search needs an objective" } };
55
+ const got = await keyedCall(client, "Exa", "EXA_API_KEY", "search", "/search", exaSearchBody(objective, n, settings), signal);
56
+ if ("error" in got)
57
+ return searchFailed(got);
58
+ const { results } = got.json;
59
+ if (!Array.isArray(results))
60
+ return searchFailed(failed("error", "UNREADABLE", "Exa's search answered no results this server reads"));
61
+ const asked = settings.snippet ?? EXA_DEFAULTS.snippet;
62
+ const hits = results.flatMap((row) => {
63
+ if (typeof row?.url !== "string" || !URL.canParse(row.url))
64
+ return [];
65
+ return [{ url: row.url, title: typeof row.title === "string" ? clip(row.title, TITLE_CAP) : "", snippet: snippetOf(snippetText(row, asked)), ...(typeof row.publishedDate === "string" ? { published: row.publishedDate } : {}) }];
66
+ });
67
+ return { answer: { provider: "exa", objective, queries, results: hits.slice(0, n) } };
68
+ }
69
+ /** The /contents request for `url` under `settings`: its text to the most of a page web_fetch reads and one character
70
+ * more (so a page Exa cut there shows as going on), at the verbosity asked, its links kept or not. */
71
+ export function exaContentsBody(url, settings = {}) {
72
+ const { pageVerbosity, pageLinks } = { ...EXA_DEFAULTS, ...settings };
73
+ return {
74
+ urls: [url],
75
+ text: { maxCharacters: PAGE_READ_MAX_CHARS + 1, verbosity: pageVerbosity, ...(pageLinks ? { linkStyle: "full" } : {}) },
76
+ ...(settings.maxAgeHours === undefined ? {} : { maxAgeHours: settings.maxAgeHours }),
77
+ };
78
+ }
79
+ /** The page at `url` read through `client`'s /contents under `settings`: the page, or why there is none (its status and
80
+ * tag where Exa names them). */
81
+ export async function exaRead(url, client, settings = {}, signal) {
82
+ const got = await keyedCall(client, "Exa", "EXA_API_KEY", "fetch", "/contents", exaContentsBody(url, settings), signal);
83
+ if ("error" in got)
84
+ return got;
85
+ const { results, statuses } = got.json;
86
+ const crawl = (Array.isArray(statuses) ? statuses : []).find((one) => one?.status === "error");
87
+ if (crawl) {
88
+ const tag = codeOf(crawl.error?.tag);
89
+ const status = Number.isInteger(crawl.error?.httpStatusCode) ? crawl.error?.httpStatusCode : undefined;
90
+ const why = [tag, status].filter((one) => one !== undefined).join(", ");
91
+ return failed("error", tag ?? (status === undefined ? "CRAWL_FAILED" : `PAGE_${status}`), `Exa could not read the page${why ? ` (${why})` : ""}`);
92
+ }
93
+ const row = (Array.isArray(results) ? results : []).find((one) => typeof one?.text === "string" && one.text.trim() !== "");
94
+ if (!row)
95
+ return failed("not_text", "NO_TEXT", "Exa's fetch answered no page text");
96
+ const asked = PAGE_READ_MAX_CHARS + 1;
97
+ // The page's url names no user name or password: cleared first, then cut, as every client's page url is.
98
+ return { ok: true, url: clip(withoutCredentials(typeof row.url === "string" && URL.canParse(row.url) ? row.url : url), URL_MAX), status: 200, title: clip(typeof row.title === "string" ? row.title : "", TITLE_CAP), ...textOf(row.text, row.text.length < asked), ...linksWithin(linksOf(row.text)) };
99
+ }
100
+ /** Exa on the run's key, both tools on one client. Its search keeps the caller's signal and its own bound (a paid request
101
+ * is not cut short by the keyless providers' deadline); a fetch it gives no page is logged with the limit it met. With
102
+ * no key, each request answers so, unsent. */
103
+ export const exa = defineProvider({ id: "exa", label: "Exa", key: { env: "EXA_API_KEY" }, ops: ["search", "fetch"], fetch: { miss: { log: "web_fetch_provider_failed", when: "failed" } }, settings: settingsOf(exaSettingsProblems) }, ({ key, send, pay, endpoint, settings }) => {
104
+ const asked = (settings ?? {});
105
+ const client = key === undefined ? null : exaClient(key, send ?? fetch, pay, endpoint ?? EXA_API_URL);
106
+ return {
107
+ search: (ask, _deadline, signal) => exaSearched(ask, client, asked, signal),
108
+ read: (url, { signal }) => exaRead(url, client, asked, signal),
109
+ unready: () => (client && !client.live() ? failure("refused", "KEY_REFUSED", "not tried: refused earlier in this run") : undefined),
110
+ };
111
+ });
@@ -1,4 +1,5 @@
1
1
  import { type Read } from "../page.js";
2
+ import { type Reader } from "../provider.js";
2
3
  import { type Limit, type Search } from "../search.js";
3
4
  import { type Words } from "./mcp.js";
4
5
  export declare const FIRECRAWL_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
@@ -12,29 +13,39 @@ export type FirecrawlFailed = {
12
13
  limit?: Limit;
13
14
  };
14
15
  /** Where a call goes: `endpoint` (default Firecrawl's), through `send` (default fetch), ended at `timeoutMs` (default
15
- * FIRECRAWL_MS) or by `signal`, whichever is first; `words`, the caller's for a rate limit (default RATE_LIMITED). */
16
+ * FIRECRAWL_MS) or by `signal`, whichever is first; `words`, the caller's for a rate limit (default RATE_LIMITED);
17
+ * `now`, the clock a daily limit's reset is read on (the breaker's; default Date.now). */
16
18
  export type FirecrawlOptions = {
17
19
  endpoint?: string;
18
20
  send?: typeof fetch;
19
21
  signal?: AbortSignal;
20
22
  timeoutMs?: number;
21
23
  words?: Words;
24
+ now?: () => number;
22
25
  };
23
26
  /** The limit a refusal's `code` names (QUOTA_CODES, RATE_CODES), with the wait its payload names; undefined for any
24
27
  * other code. */
25
28
  export declare function firecrawlLimitOf(payload: Record<string, unknown> | undefined): Limit | undefined;
26
- /** `query` searched on Firecrawl's keyless endpoint, at most `n` results, its answer at most MAX_BYTES. */
29
+ /** `query` searched on Firecrawl's keyless endpoint as the objective and the one query, at most `n` results. */
27
30
  export declare function firecrawlSearch(query: string, n: number, options?: FirecrawlOptions): Promise<Search | FirecrawlFailed>;
28
- /** The page at `url` scraped by Firecrawl's keyless endpoint, as markdown, its answer at most the direct fetch's bound
29
- * (PAGE_MAX_BYTES). Firecrawl names no cut, so the text is read as the whole page's. A page whose status
30
- * is not 2xx is no read: the caller fetches directly, as for a refusal. */
31
+ /** firecrawlScrape's page, or why there is none (as scrapeTyped, bare). */
31
32
  export declare function firecrawlScrape(url: string, options?: FirecrawlOptions): Promise<Read | FirecrawlFailed>;
32
- /** keyless Firecrawl's scrape for one run's web_fetch, with the run's breaker on it: `live` is false once a quota answer
33
- * came (for the rest of the run) and while a rate limit's wait holds (waitOf: the wait Firecrawl named, else 60 s, at
34
- * most 15 minutes); `read` is one scrape, the page or, for any failure, why there is none (the caller then fetches
35
- * directly). `now` is the breaker's clock (a test's). */
36
- export type KeylessFetch = {
37
- live(): boolean;
38
- read(url: string, signal?: AbortSignal): Promise<Read | string>;
39
- };
40
- export declare function firecrawlFetch(options?: Omit<FirecrawlOptions, "signal">, now?: () => number): KeylessFetch;
33
+ /** keyless Firecrawl's scrape for one run's web_fetch behind its own breaker (readerOf, on searchBreaker at `now`): held
34
+ * while a limit keeps it off or a rate limit's wait holds; each read one scrape, the page or why there is none. */
35
+ export declare function firecrawlFetch(options?: Omit<FirecrawlOptions, "signal" | "now">, now?: () => number): Reader;
36
+ /** Keyless Firecrawl: search and scrape on its public MCP endpoint (or `endpoint`). Its search ends at the call's deadline
37
+ * or its own bound (`bounds.firecrawlMs`: the call's where it gives one, else the Web's; default FIRECRAWL_MS); why a
38
+ * fetch gave no page is said on the page in our words (Firecrawl's own are never passed on) and logged once the direct
39
+ * fetch has answered. */
40
+ export declare const firecrawlKeyless: {
41
+ readonly id: "firecrawl-keyless";
42
+ readonly label: "Firecrawl";
43
+ readonly keyless: true;
44
+ readonly ops: readonly ["search", "fetch"];
45
+ readonly fetch: {
46
+ readonly miss: {
47
+ readonly log: "web_fetch_firecrawl_failed";
48
+ readonly when: "ends";
49
+ };
50
+ };
51
+ } & Pick<import("../provider.js").WebProvider<string>, "make">;