@parcha/agentrun-web 0.1.0-beta.69 → 0.1.0-beta.73

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/fees.d.ts CHANGED
@@ -9,12 +9,19 @@ export declare const PARALLEL_SEARCH_USD: number;
9
9
  export declare const PARALLEL_SEARCH_RESULT_USD = 0.001;
10
10
  export declare const PARALLEL_SEARCH_INCLUDED = 10;
11
11
  export declare const PARALLEL_EXTRACT_USD = 0.001;
12
- /** One paid request: `name` in the cap's refusal, `tool` and `by` on its records, `usd` its price, `basis` why. */
12
+ /** One paid request: `name` in the cap's refusal, `tool` and `by` on its records, `usd` its price, `basis` why. `least`,
13
+ * for a request that can be sent smaller to fit a cap (a Firecrawl scrape, its PDF pages capped): the least it can be
14
+ * sent at and why; a cap that does not hold `usd` but holds that may hold what it has left, and the request is then
15
+ * sent at no more than that buys (Pay). */
13
16
  export type Fee = {
14
17
  name: string;
15
18
  by: string;
16
19
  usd: number;
17
20
  basis: string;
21
+ least?: {
22
+ usd: number;
23
+ basis: string;
24
+ };
18
25
  };
19
26
  /** A search in `mode` for `n` results: the mode's price (PARALLEL_SEARCH_MODE_USD), and $0.001 for each past the 10 it
20
27
  * includes. The web tools search `fast`: $0.001. */
@@ -62,6 +69,13 @@ export declare const FIRECRAWL_PDF_PAGES_MAX = 10000;
62
69
  * credits Firecrawl reports, never above this (firecrawlChargeOf). Undefined for an endpoint the web tools do not ask,
63
70
  * and for a body asking a proxy other than basic (a search for its results, a scrape for its page). */
64
71
  export declare function firecrawlFeeOf(path: string, body: unknown): Fee | undefined;
72
+ /** A /v2/scrape `body` sent at `heldUsd`, less than its fee (a cap held what it had left, Fee.least): the body with its
73
+ * PDF pages capped to the most that hold buys (its pdf parser's maxPages, set or lowered), and its fee, never above the
74
+ * hold. Undefined for any other path, or when the hold buys not one page. */
75
+ export declare function firecrawlFitOf(path: string, body: unknown, heldUsd: number): {
76
+ body: Record<string, unknown>;
77
+ fee: Fee;
78
+ } | undefined;
65
79
  /** The credits Firecrawl reports an answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
66
80
  * a search's top-level creditsUsed, a scrape's data.metadata.creditsUsed; undefined unless a whole number, 0 or more. */
67
81
  export declare function firecrawlCreditsOf(path: string, json: unknown): number | undefined;
@@ -82,12 +96,14 @@ export declare class PaidRefused extends Error {
82
96
  readonly name = "PaidRefused";
83
97
  }
84
98
  /** How a paid request is sent: `send` once the run's cap admits `fee`, or a throw of PaidRefused when it does not.
99
+ * `send` is told what the cap held, `fee.usd` or, for a fee with a `least`, less (what the cap had left); it sends no
100
+ * more than that buys, and its charge is never above it.
85
101
  * `charged`, from a caller that learns what the request cost once it is answered (decisionPay: the cost a decision's
86
102
  * provider reported), is what the cap settles a billed answer at, never above `fee.usd`; without it, the cap settles
87
103
  * at `fee.usd`. `settled`, from a caller whose line must say what the cap booked (decisionPay), is told whether the
88
104
  * settle of an answered request was written (true) or failed, its hold standing (false); a Pay with no cap never
89
105
  * calls it. */
90
- export type Pay = (fee: Fee, send: () => Promise<Response>, charged?: () => number, settled?: (booked: boolean) => void) => Promise<Response>;
106
+ export type Pay = (fee: Fee, send: (heldUsd?: number) => Promise<Response>, charged?: () => number, settled?: (booked: boolean) => void) => Promise<Response>;
91
107
  /** No cap: the request is sent as it is. */
92
108
  export declare const unmetered: Pay;
93
109
  export declare const unsentAnswer: (why: string) => Response;
package/dist/fees.js CHANGED
@@ -111,7 +111,37 @@ export function firecrawlFeeOf(path, body) {
111
111
  }
112
112
  if (path === "/v2/scrape") {
113
113
  const most = documentCredits(asked);
114
- return most === undefined ? undefined : fee("Firecrawl's scrape", most, "Firecrawl's most for a scrape");
114
+ if (most === undefined)
115
+ return undefined;
116
+ const held = fee("Firecrawl's scrape", most, "Firecrawl's most for a scrape");
117
+ // Its least: one page (and JSON's 4 when asked), what a scrape whose PDF pages are capped to fit a cap costs at most.
118
+ const least = FIRECRAWL_SCRAPE_CREDITS + (asksJson(asked.formats) ? FIRECRAWL_JSON_CREDITS : 0);
119
+ if (least >= most)
120
+ return held;
121
+ const one = fee("Firecrawl's scrape", least, "Firecrawl's most for a scrape of one page");
122
+ return { ...held, least: { usd: one.usd, basis: one.basis } };
123
+ }
124
+ return undefined;
125
+ }
126
+ /** A /v2/scrape `body` sent at `heldUsd`, less than its fee (a cap held what it had left, Fee.least): the body with its
127
+ * PDF pages capped to the most that hold buys (its pdf parser's maxPages, set or lowered), and its fee, never above the
128
+ * hold. Undefined for any other path, or when the hold buys not one page. */
129
+ export function firecrawlFitOf(path, body, heldUsd) {
130
+ if (path !== "/v2/scrape" || !Number.isFinite(heldUsd))
131
+ return undefined;
132
+ const asked = (body ?? {});
133
+ const others = Array.isArray(asked.parsers) ? asked.parsers.filter((one) => !(typeof one === "object" && one !== null && one.type === "pdf")) : [];
134
+ const json = asksJson(asked.formats) ? FIRECRAWL_JSON_CREDITS : 0;
135
+ // A float's division a hair under a whole number of credits counts as it.
136
+ for (let pages = Math.min(pdfPagesOf(asked.parsers), Math.floor(heldUsd / FIRECRAWL_CREDIT_USD + 1e-9) - json); pages >= FIRECRAWL_SCRAPE_CREDITS; pages -= 1) {
137
+ const fitted = { ...asked, parsers: [...others, { type: "pdf", maxPages: pages }] };
138
+ const fee = firecrawlFeeOf(path, fitted);
139
+ if (fee === undefined)
140
+ return undefined;
141
+ if (fee.usd <= heldUsd + 1e-12) {
142
+ const { least: _least, ...priced } = fee;
143
+ return { body: fitted, fee: priced };
144
+ }
115
145
  }
116
146
  return undefined;
117
147
  }
@@ -51,7 +51,7 @@ async function readTyped(url, guard, options) {
51
51
  };
52
52
  }
53
53
  catch (error) {
54
- // Never a URL's user name or password: undici's refusal of a redirect to a URL holding them quotes it whole.
54
+ // Never a URL's user name or password: an error may quote a URL whole (undici's refusal of one does).
55
55
  const message = withoutUserinfo(error?.message ?? String(error));
56
56
  if (isRefused(error))
57
57
  return failed("refused", "GUARD", { refused: message });
@@ -3,8 +3,18 @@ import { type Read } from "../page.js";
3
3
  import { type Failed, type Hit, type SearchAsk, type Searched } from "../search.js";
4
4
  import { type Keyed, type KeyedFailed } from "./keyed.js";
5
5
  export declare const FIRECRAWL_API_URL = "https://api.firecrawl.dev";
6
- /** Firecrawl's bound on one request: its own default timeout for a scrape. */
7
- export declare const FIRECRAWL_KEYED_MS = 60000;
6
+ /** This client's bound on one request: past it, it hangs up. A scrape tells Firecrawl to stop well before it
7
+ * (FIRECRAWL_SCRAPE_TIMEOUT_MS), so Firecrawl answers first. */
8
+ export declare const FIRECRAWL_KEYED_MS = 120000;
9
+ /** The time a scrape gives Firecrawl (its body's `timeout`): below this client's bound by the time its answer, up to
10
+ * KEYED_MAX_BYTES, takes to come back. A scrape sent with no timeout has no limit at Firecrawl: a PDF is parsed to its
11
+ * last page asked, and billed, after this client has hung up. With one, a PDF Firecrawl reckons it cannot parse in
12
+ * time (150 ms a page, out of the time left once it has the file) is refused at once, and a scrape that runs out
13
+ * answers 408; Firecrawl bills neither (fees.ts firecrawlChargeOf charges them 0 credits). */
14
+ export declare const FIRECRAWL_SCRAPE_TIMEOUT_MS = 100000;
15
+ /** The most PDF pages a scrape asks unless pdfMaxPages says otherwise: what Firecrawl reads within its timeout once it
16
+ * has the file, 200. Past it a PDF comes back cut, and its text says which pages it holds (firecrawlPageOf). */
17
+ export declare const FIRECRAWL_PDF_PAGES_IN_TIME: number;
8
18
  /** How Firecrawl searches and reads, each setting optional (FIRECRAWL_DEFAULTS):
9
19
  * - `onlyMainContent`: a scrape leaves out a page's headers, navigation and footers, default true;
10
20
  * - `maxAgeMs`: the oldest cached page a scrape may answer from, 0 a fresh scrape; unset, Firecrawl's own (2 days);
@@ -13,7 +23,9 @@ export declare const FIRECRAWL_KEYED_MS = 60000;
13
23
  * - `country`: the country a search is made from, ISO 3166-1 alpha-2; unset, Firecrawl's own (US);
14
24
  * - `highlights`: each result's description is its query-relevant highlight; unset, Firecrawl's own (true);
15
25
  * - `pdfMaxPages`: the most pages of a PDF a web_fetch parses, and is held for (1 credit a page), 1 to 10,000; unset,
16
- * no cap: a PDF is read whole, and a fetch is held at Firecrawl's most, 10,000 pages (fees.ts firecrawlFeeOf). */
26
+ * the pages Firecrawl reads within its timeout, FIRECRAWL_PDF_PAGES_IN_TIME (200). Set past that, a long PDF may be
27
+ * one Firecrawl refuses or runs out of time on, at no charge. A run whose cap has less than the hold left holds what
28
+ * it has left and asks only the pages that buys (firecrawlFitOf). */
17
29
  export type FirecrawlSettings = {
18
30
  onlyMainContent?: boolean;
19
31
  maxAgeMs?: number;
@@ -59,7 +71,8 @@ export declare function firecrawlSearchBody(query: string, n: number, settings?:
59
71
  * up to FIRECRAWL_QUERIES_MAX of its queries, one paid request each, all at once, merged (firecrawlMerged), and the
60
72
  * limit Firecrawl answered for the run's key, if any. */
61
73
  export declare function firecrawlSearched(args: Record<string, unknown>, client: Keyed | null, settings?: FirecrawlSettings, signal?: AbortSignal): Promise<Searched>;
62
- /** The /v2/scrape request for `url` under `settings`: markdown alone, on the basic proxy, a PDF to pdfMaxPages when set. */
74
+ /** The /v2/scrape request for `url` under `settings`: markdown alone, on the basic proxy, within Firecrawl's timeout, a
75
+ * PDF to pdfMaxPages, else to the pages that timeout reads. */
63
76
  export declare function firecrawlScrapeBody(url: string, settings?: FirecrawlSettings): Record<string, unknown>;
64
77
  /** A page Firecrawl scraped for `url` (`page`, its scrape's `{markdown, metadata}`, keyed or keyless alike) as a Read:
65
78
  * the url it ended at (metadata's url, else its sourceURL, else `url`), its title (a list's first string), its status.
@@ -2,14 +2,28 @@
2
2
  // each one paid request (fees.ts firecrawlFeeOf) through the run's Pay, on a bearer token. Its settings are typed, each
3
3
  // with a default (FIRECRAWL_DEFAULTS); a setting it does not take is refused when the Web is made. A 401 refuses the key
4
4
  // for the run; a 403 refuses one request only (Firecrawl answers it for a page, as for a prompt injection it found).
5
- import { firecrawlChargeOf, firecrawlFeeOf } from "../fees.js";
5
+ import { firecrawlChargeOf, firecrawlFeeOf, firecrawlFitOf } from "../fees.js";
6
6
  import { clip, markdownRead, TITLE_CAP } from "../page.js";
7
7
  import { defineProvider, settingsOf } from "../provider.js";
8
8
  import { failed, failure, retryAfterMs, searchArgs, snippetOf, waitOf } from "../search.js";
9
9
  import { domains, keyedCall, keyedClient, matching, settingsProblems, wholeIn, yesNo } from "./keyed.js";
10
10
  export const FIRECRAWL_API_URL = "https://api.firecrawl.dev";
11
- /** Firecrawl's bound on one request: its own default timeout for a scrape. */
12
- export const FIRECRAWL_KEYED_MS = 60_000;
11
+ /** This client's bound on one request: past it, it hangs up. A scrape tells Firecrawl to stop well before it
12
+ * (FIRECRAWL_SCRAPE_TIMEOUT_MS), so Firecrawl answers first. */
13
+ export const FIRECRAWL_KEYED_MS = 120_000;
14
+ /** The time a scrape gives Firecrawl (its body's `timeout`): below this client's bound by the time its answer, up to
15
+ * KEYED_MAX_BYTES, takes to come back. A scrape sent with no timeout has no limit at Firecrawl: a PDF is parsed to its
16
+ * last page asked, and billed, after this client has hung up. With one, a PDF Firecrawl reckons it cannot parse in
17
+ * time (150 ms a page, out of the time left once it has the file) is refused at once, and a scrape that runs out
18
+ * answers 408; Firecrawl bills neither (fees.ts firecrawlChargeOf charges them 0 credits). */
19
+ export const FIRECRAWL_SCRAPE_TIMEOUT_MS = 100_000;
20
+ /** How long Firecrawl may take to fetch a PDF before it parses a page: an 841-page federal PDF took 46 s. */
21
+ const PDF_FETCH_ALLOWANCE_MS = 50_000;
22
+ /** How long Firecrawl takes to parse a PDF page: that PDF's pages took 0.22 s each. */
23
+ const PDF_PAGE_MS = 250;
24
+ /** The most PDF pages a scrape asks unless pdfMaxPages says otherwise: what Firecrawl reads within its timeout once it
25
+ * has the file, 200. Past it a PDF comes back cut, and its text says which pages it holds (firecrawlPageOf). */
26
+ export const FIRECRAWL_PDF_PAGES_IN_TIME = Math.floor((FIRECRAWL_SCRAPE_TIMEOUT_MS - PDF_FETCH_ALLOWANCE_MS) / PDF_PAGE_MS);
13
27
  export const FIRECRAWL_DEFAULTS = Object.freeze({ onlyMainContent: true });
14
28
  const FIRECRAWL_CHECKS = {
15
29
  onlyMainContent: yesNo,
@@ -29,15 +43,15 @@ export function firecrawlSettingsProblems(settings) {
29
43
  return problems;
30
44
  }
31
45
  /** Firecrawl on `apiKey`, each request paid through `pay`. */
32
- export const firecrawlClient = (apiKey, send = fetch, pay, base = FIRECRAWL_API_URL) => keyedClient({ who: "Firecrawl", base, headers: { authorization: `Bearer ${apiKey}` }, feeOf: firecrawlFeeOf, chargeOf: firecrawlChargeOf, timeoutMs: FIRECRAWL_KEYED_MS, refuseOn: [401] }, send, pay);
46
+ export const firecrawlClient = (apiKey, send = fetch, pay, base = FIRECRAWL_API_URL) => keyedClient({ who: "Firecrawl", base, headers: { authorization: `Bearer ${apiKey}` }, feeOf: firecrawlFeeOf, chargeOf: firecrawlChargeOf, fitOf: firecrawlFitOf, timeoutMs: FIRECRAWL_KEYED_MS, refuseOn: [401] }, send, pay);
33
47
  /** How many of a search's queries Firecrawl is sent: one request each, at once. */
34
48
  export const FIRECRAWL_QUERIES_MAX = 3;
35
49
  /** The scrape keyless Firecrawl's search asks of each result, as Firecrawl's guidance for agents asks: its page as
36
50
  * markdown, its main content alone unless `settings` say otherwise. A keyed search asks none (firecrawlSearchBody). */
37
51
  export const firecrawlScrapeOptions = (settings = {}) => ({ formats: ["markdown"], onlyMainContent: settings.onlyMainContent ?? FIRECRAWL_DEFAULTS.onlyMainContent });
38
- /** How a keyed web_fetch has Firecrawl read a page: on its basic proxy (the one priced here), a PDF to `pages` at most
39
- * when a cap is set (pdfMaxPages), else whole. */
40
- const keyedRead = (pages) => ({ proxy: "basic", ...(pages === undefined ? {} : { parsers: [{ type: "pdf", maxPages: pages }] }) });
52
+ /** How a keyed web_fetch has Firecrawl read a page: on its basic proxy (the one priced here), within its timeout
53
+ * (FIRECRAWL_SCRAPE_TIMEOUT_MS), a PDF to `pages` at most (pdfMaxPages), else to what that timeout reads. */
54
+ const keyedRead = (pages) => ({ proxy: "basic", timeout: FIRECRAWL_SCRAPE_TIMEOUT_MS, parsers: [{ type: "pdf", maxPages: pages ?? FIRECRAWL_PDF_PAGES_IN_TIME }] });
41
55
  /** Firecrawl's search rows, an answer's `data` or its `data.web`, as hits: each row whose url parses, its snippet its
42
56
  * page's markdown, else its description; undefined where the answer holds no rows this server reads. */
43
57
  export function firecrawlHits(data) {
@@ -117,7 +131,8 @@ export async function firecrawlSearched(args, client, settings = {}, signal) {
117
131
  }));
118
132
  return firecrawlMerged("firecrawl", ask, each);
119
133
  }
120
- /** The /v2/scrape request for `url` under `settings`: markdown alone, on the basic proxy, a PDF to pdfMaxPages when set. */
134
+ /** The /v2/scrape request for `url` under `settings`: markdown alone, on the basic proxy, within Firecrawl's timeout, a
135
+ * PDF to pdfMaxPages, else to the pages that timeout reads. */
121
136
  export function firecrawlScrapeBody(url, settings = {}) {
122
137
  return { url, formats: ["markdown"], onlyMainContent: settings.onlyMainContent ?? FIRECRAWL_DEFAULTS.onlyMainContent, ...(settings.maxAgeMs === undefined ? {} : { maxAge: settings.maxAgeMs }), ...keyedRead(settings.pdfMaxPages) };
123
138
  }
@@ -14,7 +14,9 @@ export type Keyed = {
14
14
  /** A provider's API: its name in our words, its base URL, its auth headers, its prices, its bound, the statuses that
15
15
  * refuse the key for the client's life. `chargeOf`, for a provider that reports what a request cost: what an answer
16
16
  * a cap books at its price (billedStatus: a 2xx, a 408 or a 5xx) held at `fee` is charged and the receipt's words for
17
- * it, from its body (`json`, undefined when not JSON) and its `status`; without it, such an answer is charged its fee. */
17
+ * it, from its body (`json`, undefined when not JSON) and its `status`; without it, such an answer is charged its fee.
18
+ * `fitOf`, for a provider whose fee has a `least` (Fee.least): the body to send, and its fee, when the cap held only
19
+ * `heldUsd` of the fee; undefined when that buys none, and then nothing is sent. */
18
20
  export type KeyedSpec = {
19
21
  who: string;
20
22
  base: string;
@@ -26,11 +28,15 @@ export type KeyedSpec = {
26
28
  usd: number;
27
29
  basis: string;
28
30
  };
31
+ fitOf?: (path: string, body: unknown, heldUsd: number) => {
32
+ body: unknown;
33
+ fee: Fee;
34
+ } | undefined;
29
35
  };
30
36
  /** Whether a cap books an answer of `status` at its price, as serve's paidRequest does: a 2xx, a 408 or a 5xx. Another
31
37
  * 4xx is booked at nothing, so its body is not read for a charge. */
32
38
  export declare const billedStatus: (status: number) => boolean;
33
- export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
39
+ export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf, fitOf }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
34
40
  /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
35
41
  * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
36
42
  * that failed connecting (its cause's code, UNSENT_CODES, a certificate's CERT_* or a handshake's ERR_TLS_*). Anything
@@ -40,8 +46,8 @@ export declare function unsentWhy(error: unknown, stoppedFirst: boolean): string
40
46
  /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
41
47
  * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
42
48
  * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
43
- * thrown inside `pay`, which books it at its fee. */
44
- export declare function paidSend(pay: Pay, fee: Fee, signal: AbortSignal | undefined, send: () => Promise<Response>, charged?: () => number): Promise<Response>;
49
+ * thrown inside `pay`, which books it at its hold. `send` is told what the cap held (Pay). */
50
+ export declare function paidSend(pay: Pay, fee: Fee, signal: AbortSignal | undefined, send: (heldUsd?: number) => Promise<Response>, charged?: () => number): Promise<Response>;
45
51
  /** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
46
52
  export declare function statusLimit(response: Response): Limit | undefined;
47
53
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
@@ -11,7 +11,7 @@ export const KEYED_MAX_BYTES = 8 * 1024 * 1024;
11
11
  /** Whether a cap books an answer of `status` at its price, as serve's paidRequest does: a 2xx, a 408 or a 5xx. Another
12
12
  * 4xx is booked at nothing, so its body is not read for a charge. */
13
13
  export const billedStatus = (status) => (status >= 200 && status < 300) || status === 408 || status >= 500;
14
- export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }, send = fetch, pay = unmetered) {
14
+ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf, fitOf }, send = fetch, pay = unmetered) {
15
15
  let refused = false;
16
16
  const root = base.replace(/\/+$/, "");
17
17
  return {
@@ -21,15 +21,25 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, ch
21
21
  const fee = feeOf(path, body);
22
22
  if (!fee)
23
23
  throw new PaidRefused(`${who}'s ${path} was not sent: it has no price here`);
24
+ // What was sent and its fee: the body as asked, or, when the cap held less than its fee (Fee.least), the body
25
+ // fitted to that hold (fitOf), whose fee is never above it.
26
+ let sent = { body, fee };
24
27
  // What an answer the cap books at its price reports it cost, read from its body before the cap settles; never
25
28
  // above the hold.
26
29
  let charge;
27
- const charged = chargeOf ? chargedSaying(() => Math.min(charge?.usd ?? fee.usd, fee.usd), () => charge?.basis) : undefined;
28
- return paidSend(pay, fee, signal, async () => {
30
+ const charged = chargeOf ? chargedSaying(() => Math.min(charge?.usd ?? sent.fee.usd, sent.fee.usd), () => charge?.basis) : undefined;
31
+ return paidSend(pay, fee, signal, async (heldUsd) => {
32
+ if (heldUsd !== undefined && heldUsd < fee.usd) {
33
+ const fitted = fitOf?.(path, body, heldUsd);
34
+ // A hold that buys none of it: not sent, settled at $0.
35
+ if (!fitted)
36
+ return unsentAnswer(`its hold, $${heldUsd}, buys none of it`);
37
+ sent = fitted;
38
+ }
29
39
  const response = await send(`${root}${path}`, {
30
40
  method: "POST",
31
41
  headers: { ...headers, "content-type": "application/json" },
32
- body: JSON.stringify(body),
42
+ body: JSON.stringify(sent.body),
33
43
  // It carries the key: a redirect is an error, never followed to an address the key was not meant for.
34
44
  redirect: "error",
35
45
  signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(signal ? [signal] : [])]),
@@ -44,7 +54,7 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, ch
44
54
  // read as for one that reported no count.
45
55
  const bytes = response.ok ? await bytesOf(response).catch((error) => { throw brokeOff(error); }) : await bytesOf(response).catch(() => undefined);
46
56
  const json = bytes === undefined ? undefined : parsed(bytes);
47
- charge = chargeOf(fee, path, json, response.status);
57
+ charge = chargeOf(sent.fee, path, json, response.status);
48
58
  const read = new Response(bytes === undefined ? null : new Uint8Array(bytes), { status: response.status, statusText: response.statusText, headers: response.headers });
49
59
  readAhead.set(read, json);
50
60
  return read;
@@ -78,15 +88,15 @@ export function unsentWhy(error, stoppedFirst) {
78
88
  /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
79
89
  * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
80
90
  * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
81
- * thrown inside `pay`, which books it at its fee. */
91
+ * thrown inside `pay`, which books it at its hold. `send` is told what the cap held (Pay). */
82
92
  export async function paidSend(pay, fee, signal, send, charged) {
83
93
  if (signal?.aborted)
84
94
  throw signal.reason;
85
95
  let unsent;
86
- const answer = await pay(fee, async () => {
96
+ const answer = await pay(fee, async (heldUsd) => {
87
97
  const stoppedFirst = signal?.aborted === true;
88
98
  try {
89
- return await send();
99
+ return await send(heldUsd);
90
100
  }
91
101
  catch (error) {
92
102
  const why = unsentWhy(error, stoppedFirst);
package/dist/web.js CHANGED
@@ -137,10 +137,15 @@ export function createWeb(config) {
137
137
  let at = -1;
138
138
  let unsent;
139
139
  let booked = true;
140
- const answer = await (config.pay ?? unmetered)(fee, async () => {
140
+ // Its line: the fee, or, when the cap held less of it (Fee.least), what the cap held. Never the fee's least.
141
+ const { least: _least, ...priced } = fee;
142
+ let line = priced;
143
+ const answer = await (config.pay ?? unmetered)(fee, async (heldUsd) => {
144
+ if (heldUsd !== undefined && heldUsd < fee.usd)
145
+ line = { ...priced, usd: heldUsd, basis: `${fee.basis}, held at the $${heldUsd} the cap had left` };
141
146
  if (lines)
142
- at = lines.push(fee) - 1;
143
- const response = await send();
147
+ at = lines.push(line) - 1;
148
+ const response = await send(heldUsd);
144
149
  unsent = unsentOf(response);
145
150
  return response;
146
151
  }, charged, (landed) => {
@@ -148,12 +153,12 @@ export function createWeb(config) {
148
153
  settled?.(landed);
149
154
  });
150
155
  if (lines && at >= 0 && unsent !== undefined)
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})` };
156
+ lines[at] = booked ? { ...line, usd: 0, basis: `not billed (not sent: ${unsent})` } : { ...line, basis: `${line.basis}; its settle failed, so the hold stands, not $0 (not sent: ${unsent})` };
152
157
  // A provider that reports what an answer cost (keyed.ts chargeOf): the line is that charge, in its words, once the
153
158
  // cap's settle is written; a settle that failed leaves it at the hold.
154
159
  const said = unsent === undefined ? chargedSaid(charged) : undefined;
155
160
  if (lines && at >= 0 && said !== undefined && charged)
156
- lines[at] = booked ? { ...fee, usd: Math.min(charged(), fee.usd), basis: said } : { ...fee, basis: `${fee.basis}; its settle failed, so the hold stands (${said})` };
161
+ lines[at] = booked ? { ...line, usd: Math.min(charged(), line.usd), basis: said } : { ...line, basis: `${line.basis}; its settle failed, so the hold stands (${said})` };
157
162
  return answer;
158
163
  };
159
164
  // Each provider an order names is made once per Web, at its first use, from the run's parts for it: one client a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-web",
3
- "version": "0.1.0-beta.69",
3
+ "version": "0.1.0-beta.73",
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.14.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@parcha/pi-browser": "0.1.0-beta.69"
49
+ "@parcha/pi-browser": "0.1.0-beta.73"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",