@parcha/agentrun-web 0.1.0-beta.65 → 0.1.0-beta.67
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/dist/providers/direct.js +3 -1
- package/dist/providers/exa-keyless.js +2 -4
- package/dist/providers/firecrawl-keyless.js +5 -17
- package/dist/providers/firecrawl.d.ts +9 -2
- package/dist/providers/firecrawl.js +16 -10
- package/dist/providers/keyed.d.ts +19 -0
- package/dist/providers/keyed.js +20 -9
- package/dist/providers/parallel.d.ts +3 -2
- package/dist/providers/parallel.js +18 -37
- package/dist/web.js +45 -22
- package/package.json +2 -2
package/dist/providers/direct.js
CHANGED
|
@@ -5,6 +5,7 @@ import { askedUrl, clip, linksWithin, partOfRead, TIMEOUT_MS, TITLE_CAP, textOf,
|
|
|
5
5
|
import { defineProvider } from "../provider.js";
|
|
6
6
|
import { bare } from "../search.js";
|
|
7
7
|
import { linksOf } from "../text-urls.js";
|
|
8
|
+
import { thrownFailure } from "./keyed.js";
|
|
8
9
|
/** The page at `url`, read once through `guard`'s fetch (an HTML page through its reader), or why it was not. `options`
|
|
9
10
|
* are the guard's resolver and fetch, for a test; a signal ends it early. */
|
|
10
11
|
export async function readDirect(url, guard, options = {}) {
|
|
@@ -54,7 +55,8 @@ async function readTyped(url, guard, options) {
|
|
|
54
55
|
const message = withoutUserinfo(error?.message ?? String(error));
|
|
55
56
|
if (isRefused(error))
|
|
56
57
|
return failed("refused", "GUARD", { refused: message });
|
|
57
|
-
|
|
58
|
+
// Typed as every provider types a thrown failure (thrownFailure); the page says what the error said, whole.
|
|
59
|
+
return failed("infra", thrownFailure(error, { who: "the direct fetch", what: "fetch", signal: options.signal }).failure.code, { error: message });
|
|
58
60
|
}
|
|
59
61
|
}
|
|
60
62
|
/** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
|
|
@@ -5,6 +5,7 @@ import { lookup as dnsLookup } from "node:dns";
|
|
|
5
5
|
import { clip, cutAt, TITLE_CAP } from "../page.js";
|
|
6
6
|
import { defineProvider } from "../provider.js";
|
|
7
7
|
import { bare, snippetOf } from "../search.js";
|
|
8
|
+
import { thrownFailure } from "./keyed.js";
|
|
8
9
|
import { callTool, RATE_LIMITED, sleep, textBlocks } from "./mcp.js";
|
|
9
10
|
export const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
|
|
10
11
|
export const EXA_SEARCH_TOOL = "web_search_exa";
|
|
@@ -101,10 +102,7 @@ async function searchTyped(ask, { send, signal, pause = sleep, words = {} }) {
|
|
|
101
102
|
return await once();
|
|
102
103
|
}
|
|
103
104
|
catch (error) {
|
|
104
|
-
|
|
105
|
-
if (name === "TimeoutError")
|
|
106
|
-
return typed("infra", "TIMEOUT", { error: "Exa's search did not answer within 60 s" });
|
|
107
|
-
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)}` });
|
|
105
|
+
return thrownFailure(error, { who: "Exa", what: "search", signal, timeout: "Exa's search did not answer within 60 s", stopped: "the search was stopped", failedWith: (said) => `Exa's search failed: ${said}` });
|
|
108
106
|
}
|
|
109
107
|
finally {
|
|
110
108
|
await own?.close().catch(() => undefined);
|
|
@@ -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,
|
|
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
|
-
|
|
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 = {}) {
|
|
@@ -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
|
-
/**
|
|
60
|
-
*
|
|
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
|
-
/**
|
|
120
|
-
*
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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
|
|
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,
|
|
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 }) => {
|
|
@@ -37,6 +37,25 @@ export declare function paidSend(pay: Pay, fee: Fee, signal: AbortSignal | undef
|
|
|
37
37
|
export declare function statusLimit(response: Response): Limit | undefined;
|
|
38
38
|
/** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
|
|
39
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;
|
|
40
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
|
|
41
60
|
* words: no key (`keyEnv` names the variable), the key refused, the cap's refusal, a timeout, a status (its code where
|
|
42
61
|
* the provider gives one, its limit for the breaker), or an answer that is not JSON. */
|
package/dist/providers/keyed.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// never asked of the Pay, and one that failed before it left (paidSend) is settled at $0. Nothing is retried. A
|
|
5
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.
|
|
6
6
|
import { PaidRefused, unmetered, unsentAnswer } from "../fees.js";
|
|
7
|
+
import { cutAt, withoutUserinfo } from "../page.js";
|
|
7
8
|
import { failed, keyWide } from "../search.js";
|
|
8
9
|
/** The most bytes of one answer read: past it the answer is not read. */
|
|
9
10
|
export const KEYED_MAX_BYTES = 8 * 1024 * 1024;
|
|
@@ -124,6 +125,22 @@ async function jsonOf(response) {
|
|
|
124
125
|
return undefined;
|
|
125
126
|
}
|
|
126
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
|
+
}
|
|
127
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
|
|
128
145
|
* words: no key (`keyEnv` names the variable), the key refused, the cap's refusal, a timeout, a status (its code where
|
|
129
146
|
* the provider gives one, its limit for the breaker), or an answer that is not JSON. */
|
|
@@ -132,15 +149,9 @@ export async function keyedCall(client, who, keyEnv, what, path, body, signal) {
|
|
|
132
149
|
return failed("refused", "NO_KEY", `web_${what} goes through ${who} here, and this run holds no ${who} key (${keyEnv})`);
|
|
133
150
|
if (!client.live())
|
|
134
151
|
return failed("refused", "KEY_REFUSED", `${who} refused this run's key: it is not asked again in this run`);
|
|
135
|
-
// A request that failed, or an answer whose body broke after its headers came
|
|
136
|
-
//
|
|
137
|
-
|
|
138
|
-
const unanswered = (error, read) => {
|
|
139
|
-
if (signal?.aborted)
|
|
140
|
-
return failed("infra", "STOPPED", `${who}'s ${what} was stopped`);
|
|
141
|
-
const name = error?.name;
|
|
142
|
-
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`);
|
|
143
|
-
};
|
|
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 });
|
|
144
155
|
let response;
|
|
145
156
|
try {
|
|
146
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
|
|
29
|
-
*
|
|
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
|
|
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,
|
|
8
|
-
|
|
9
|
-
|
|
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,28 +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
|
-
|
|
43
|
-
//
|
|
44
|
-
//
|
|
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
|
-
|
|
47
|
-
|
|
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
|
-
|
|
63
|
-
return paidSend(pay, fee, signal, sent);
|
|
52
|
+
return client.post(url.slice(PARALLEL_API_URL.length), body, signal);
|
|
64
53
|
};
|
|
65
54
|
const extract = async (url, signal, client = {}) => {
|
|
66
55
|
try {
|
|
@@ -86,12 +75,12 @@ export function parallelExtract(apiKey, send = fetch, pay = unmetered, settings
|
|
|
86
75
|
catch (error) {
|
|
87
76
|
if (error instanceof PaidRefused)
|
|
88
77
|
return failed("refused", "CAP_REFUSED", error.message);
|
|
89
|
-
|
|
90
|
-
return
|
|
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)}` });
|
|
91
80
|
}
|
|
92
81
|
};
|
|
93
82
|
return {
|
|
94
|
-
live:
|
|
83
|
+
live: client.live,
|
|
95
84
|
post,
|
|
96
85
|
extract,
|
|
97
86
|
read: async (url, signal, client) => {
|
|
@@ -100,14 +89,6 @@ export function parallelExtract(apiKey, send = fetch, pay = unmetered, settings
|
|
|
100
89
|
},
|
|
101
90
|
};
|
|
102
91
|
}
|
|
103
|
-
/** What a Parallel answer's status says of the run's search: out of credit (402), or rate-limited (429) for its
|
|
104
|
-
* Retry-After. */
|
|
105
|
-
const parallelLimit = (response) => {
|
|
106
|
-
if (response.status === 402)
|
|
107
|
-
return { kind: "quota" };
|
|
108
|
-
const retryAfter = response.headers.get("retry-after");
|
|
109
|
-
return response.status === 429 ? { kind: "rate", ...(retryAfter ? { retryAfter } : {}) } : undefined;
|
|
110
|
-
};
|
|
111
92
|
/** The /v1/search request for `ask` (searchArgs), under `settings`, as Parallel's guidance for agents asks: the
|
|
112
93
|
* objective, a goal in plain words, as its objective; the keyword queries as search_queries; and the model and
|
|
113
94
|
* session of `client` (cut at SESSION_MAX) where the run knows them. Excerpts are Parallel's own length
|
|
@@ -143,7 +124,7 @@ export async function parallelSearched(args, parallel, signal, settings = {}, cl
|
|
|
143
124
|
const response = await parallel.post(PARALLEL_SEARCH_URL, parallelSearchBody(ask, settings, client), signal);
|
|
144
125
|
if (!response.ok) {
|
|
145
126
|
await response.body?.cancel().catch(() => undefined);
|
|
146
|
-
const limit =
|
|
127
|
+
const limit = statusLimit(response);
|
|
147
128
|
if (!parallel.live())
|
|
148
129
|
return searchFailed(failed("refused", "KEY_REFUSED", REFUSED));
|
|
149
130
|
const said = failed(limit ? limit.kind : response.status >= 500 ? "infra" : "error", `HTTP_${response.status}`, `Parallel's search answered ${response.status}`, limit);
|
|
@@ -161,7 +142,7 @@ export async function parallelSearched(args, parallel, signal, settings = {}, cl
|
|
|
161
142
|
catch (error) {
|
|
162
143
|
if (error instanceof PaidRefused)
|
|
163
144
|
return searchFailed(failed("refused", "CAP_REFUSED", error.message));
|
|
164
|
-
return searchFailed(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}` }));
|
|
165
146
|
}
|
|
166
147
|
}
|
|
167
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/web.js
CHANGED
|
@@ -29,19 +29,35 @@ const feesOfCall = new AsyncLocalStorage();
|
|
|
29
29
|
const usd = (lines) => Math.round(lines.reduce((sum, fee) => sum + fee.usd, 0) * 1e6) / 1e6;
|
|
30
30
|
const outOf = (text) => ({ bytes: Buffer.byteLength(text), chars: text.length });
|
|
31
31
|
const unjudged = { wall: { verdict: "unjudged" }, injection: "unjudged" };
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
-
function
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
return
|
|
41
|
-
|
|
42
|
-
signal.
|
|
43
|
-
|
|
44
|
-
|
|
32
|
+
/** The page left unjudged as a stopped guard check leaves it (code "aborted"), by `signal`'s reason. */
|
|
33
|
+
const stoppedGuard = (signal) => ({ wall: { verdict: "unjudged", error: { code: "aborted", message: String(signal.reason?.message ?? signal.reason).slice(0, 500) } }, injection: "unjudged" });
|
|
34
|
+
function sharedGuard(ask) {
|
|
35
|
+
const own = new AbortController();
|
|
36
|
+
let waiting = 0;
|
|
37
|
+
let settled = false;
|
|
38
|
+
const verdict = ask(own.signal);
|
|
39
|
+
void verdict.then(() => (settled = true), () => (settled = true));
|
|
40
|
+
return {
|
|
41
|
+
verdict,
|
|
42
|
+
stopped: () => own.signal.aborted,
|
|
43
|
+
wait(signal) {
|
|
44
|
+
if (signal?.aborted)
|
|
45
|
+
return Promise.resolve(stoppedGuard(signal));
|
|
46
|
+
waiting += 1;
|
|
47
|
+
if (!signal)
|
|
48
|
+
return verdict;
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const onStop = () => {
|
|
51
|
+
resolve(stoppedGuard(signal));
|
|
52
|
+
waiting -= 1;
|
|
53
|
+
if (waiting === 0 && !settled)
|
|
54
|
+
own.abort(signal.reason);
|
|
55
|
+
};
|
|
56
|
+
signal.addEventListener("abort", onStop, { once: true });
|
|
57
|
+
verdict.then((guard) => (signal.removeEventListener("abort", onStop), resolve(guard)), (error) => (signal.removeEventListener("abort", onStop), reject(error)));
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
};
|
|
45
61
|
}
|
|
46
62
|
export function createWeb(config) {
|
|
47
63
|
const problems = settingsProblemsOf(config.settings);
|
|
@@ -66,13 +82,17 @@ export function createWeb(config) {
|
|
|
66
82
|
// One verdict a page: a read another fragment of its URL shares is that page (sharedRead).
|
|
67
83
|
const page = sharedRead(read);
|
|
68
84
|
const known = pageVerdicts.get(page);
|
|
69
|
-
// A
|
|
70
|
-
if (known)
|
|
71
|
-
return
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
85
|
+
// A check every waiter stopped is not joined, though it is the page's until its verdict settles: ask anew.
|
|
86
|
+
if (known && !known.stopped())
|
|
87
|
+
return known.wait(step.signal);
|
|
88
|
+
// A call already stopped starts no check.
|
|
89
|
+
if (step.signal?.aborted)
|
|
90
|
+
return Promise.resolve(stoppedGuard(step.signal));
|
|
91
|
+
// The check is the page's, not the caller's: no caller's stop ends it while another call waits on it (sharedGuard).
|
|
92
|
+
const shared = sharedGuard((signal) => guardPage(decider, url, read, { ...step, signal }));
|
|
93
|
+
pageVerdicts.set(page, shared);
|
|
94
|
+
void shared.verdict.then((verdict) => verdict.wall.error && pageVerdicts.get(page) === shared && pageVerdicts.delete(page));
|
|
95
|
+
return shared.wait(step.signal);
|
|
76
96
|
};
|
|
77
97
|
/** A receipt's `unsifted`, only in a run with a classifier. */
|
|
78
98
|
const unsifted = (text) => (config.decider ? { unsifted: text() } : {});
|
|
@@ -112,7 +132,7 @@ export function createWeb(config) {
|
|
|
112
132
|
// A fee goes on the call's receipt once its request is sent, whatever the cap then books. One that never left (its send
|
|
113
133
|
// answered unsentAnswer, which the cap settles at $0) is $0 on it, saying so, as decisionPay's line for an unbilled
|
|
114
134
|
// request is, once the cap's settle is written: a settle that failed leaves the line at the hold, as the cap keeps it.
|
|
115
|
-
const pay = async (fee, send) => {
|
|
135
|
+
const pay = async (fee, send, charged, settled) => {
|
|
116
136
|
const lines = feesOfCall.getStore();
|
|
117
137
|
let at = -1;
|
|
118
138
|
let unsent;
|
|
@@ -123,7 +143,10 @@ export function createWeb(config) {
|
|
|
123
143
|
const response = await send();
|
|
124
144
|
unsent = unsentOf(response);
|
|
125
145
|
return response;
|
|
126
|
-
},
|
|
146
|
+
}, charged, (landed) => {
|
|
147
|
+
booked = landed;
|
|
148
|
+
settled?.(landed);
|
|
149
|
+
});
|
|
127
150
|
if (lines && at >= 0 && unsent !== undefined)
|
|
128
151
|
lines[at] = booked ? { ...fee, usd: 0, basis: `not billed (not sent: ${unsent})` } : { ...fee, basis: `${fee.basis}; its settle failed, so the hold stands, not $0 (not sent: ${unsent})` };
|
|
129
152
|
return answer;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-web",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.67",
|
|
4
4
|
"description": "Web search and web fetch for agents: providers asked in an order given as data, a breaker per provider, a per-run page cache read in parts, and a direct fetch through an injected public-host guard.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"undici": "^8.12.2"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@parcha/pi-browser": "0.1.0-beta.
|
|
49
|
+
"@parcha/pi-browser": "0.1.0-beta.67"
|
|
50
50
|
},
|
|
51
51
|
"repository": {
|
|
52
52
|
"type": "git",
|