@parcha/agentrun-web 0.1.0-beta.68 → 0.1.0-beta.70

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,12 +69,20 @@ 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;
65
- /** The credits Firecrawl reports a 2xx answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
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;
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;
68
- /** What a 2xx answer to `path` held at `fee` is charged, and the receipt's line for it: the credits Firecrawl reports at
69
- * the plan price; the hold when it reports more (saying how many), or none it can be read by (saying so). */
70
- export declare function firecrawlChargeOf(fee: Fee, path: string, json: unknown): {
82
+ /** What an answer of `status` to `path` held at `fee` is charged, and the receipt's line for it: the credits Firecrawl
83
+ * reports at the plan price; the hold when it reports more (saying how many). Reporting none it can be read by, a 2xx
84
+ * is charged the hold, and a 408 or a 5xx 0 credits (saying so). */
85
+ export declare function firecrawlChargeOf(fee: Fee, path: string, json: unknown, status?: number): {
71
86
  usd: number;
72
87
  basis: string;
73
88
  };
@@ -81,12 +96,14 @@ export declare class PaidRefused extends Error {
81
96
  readonly name = "PaidRefused";
82
97
  }
83
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.
84
101
  * `charged`, from a caller that learns what the request cost once it is answered (decisionPay: the cost a decision's
85
102
  * provider reported), is what the cap settles a billed answer at, never above `fee.usd`; without it, the cap settles
86
103
  * at `fee.usd`. `settled`, from a caller whose line must say what the cap booked (decisionPay), is told whether the
87
104
  * settle of an answered request was written (true) or failed, its hold standing (false); a Pay with no cap never
88
105
  * calls it. */
89
- 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>;
90
107
  /** No cap: the request is sent as it is. */
91
108
  export declare const unmetered: Pay;
92
109
  export declare const unsentAnswer: (why: string) => Response;
package/dist/fees.js CHANGED
@@ -111,22 +111,57 @@ 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
  }
118
- /** The credits Firecrawl reports a 2xx answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
148
+ /** The credits Firecrawl reports an answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
119
149
  * a search's top-level creditsUsed, a scrape's data.metadata.creditsUsed; undefined unless a whole number, 0 or more. */
120
150
  export function firecrawlCreditsOf(path, json) {
121
151
  const said = path === "/v2/search" ? json?.creditsUsed : json?.data?.metadata?.creditsUsed;
122
152
  return typeof said === "number" && Number.isInteger(said) && said >= 0 ? said : undefined;
123
153
  }
124
- /** What a 2xx answer to `path` held at `fee` is charged, and the receipt's line for it: the credits Firecrawl reports at
125
- * the plan price; the hold when it reports more (saying how many), or none it can be read by (saying so). */
126
- export function firecrawlChargeOf(fee, path, json) {
154
+ /** What an answer of `status` to `path` held at `fee` is charged, and the receipt's line for it: the credits Firecrawl
155
+ * reports at the plan price; the hold when it reports more (saying how many). Reporting none it can be read by, a 2xx
156
+ * is charged the hold, and a 408 or a 5xx 0 credits (saying so). */
157
+ export function firecrawlChargeOf(fee, path, json, status = 200) {
127
158
  const hold = Math.round(fee.usd / FIRECRAWL_CREDIT_USD);
128
159
  const plural = (n) => `${n} credit${n === 1 ? "" : "s"}`;
129
160
  const reported = firecrawlCreditsOf(path, json);
161
+ // Firecrawl's billing page (https://docs.firecrawl.dev/billing): "A scrape that fails outright, for example because
162
+ // the site never responded, is not charged." A 408 or a 5xx with no count of its own is that failure: 0 credits.
163
+ if (reported === undefined && (status === 408 || status >= 500))
164
+ return { usd: 0, basis: `Firecrawl answered ${status} and reported no credit count: 0 credits; a request that fails outright is not charged` };
130
165
  if (reported === undefined)
131
166
  return { usd: fee.usd, basis: `the hold, ${plural(hold)}; Firecrawl reported no credit count` };
132
167
  const charged = usd(FIRECRAWL_CREDIT_USD * reported);
@@ -13,7 +13,8 @@ export declare const FIRECRAWL_KEYED_MS = 60000;
13
13
  * - `country`: the country a search is made from, ISO 3166-1 alpha-2; unset, Firecrawl's own (US);
14
14
  * - `highlights`: each result's description is its query-relevant highlight; unset, Firecrawl's own (true);
15
15
  * - `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). */
16
+ * no cap: a PDF is read whole, and a fetch is held at Firecrawl's most, 10,000 pages (fees.ts firecrawlFeeOf). A run
17
+ * whose cap has less than that hold left holds what it has left and asks only the pages that buys (firecrawlFitOf). */
17
18
  export type FirecrawlSettings = {
18
19
  onlyMainContent?: boolean;
19
20
  maxAgeMs?: number;
@@ -2,7 +2,7 @@
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";
@@ -29,7 +29,7 @@ export function firecrawlSettingsProblems(settings) {
29
29
  return problems;
30
30
  }
31
31
  /** 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);
32
+ 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
33
  /** How many of a search's queries Firecrawl is sent: one request each, at once. */
34
34
  export const FIRECRAWL_QUERIES_MAX = 3;
35
35
  /** The scrape keyless Firecrawl's search asks of each result, as Firecrawl's guidance for agents asks: its page as
@@ -12,9 +12,11 @@ export type Keyed = {
12
12
  post(path: string, body: unknown, signal?: AbortSignal): Promise<Response>;
13
13
  };
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
- * refuse the key for the client's life. `chargeOf`, for a provider that reports what a request cost: what a 2xx
16
- * answer held at `fee` is charged and the receipt's words for it, from its body (`json`, undefined when not JSON);
17
- * without it, a 2xx is charged its fee. */
15
+ * refuse the key for the client's life. `chargeOf`, for a provider that reports what a request cost: what an answer
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.
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;
@@ -22,12 +24,19 @@ export type KeyedSpec = {
22
24
  feeOf: (path: string, body: unknown) => Fee | undefined;
23
25
  timeoutMs: number;
24
26
  refuseOn: readonly number[];
25
- chargeOf?: (fee: Fee, path: string, json: unknown) => {
27
+ chargeOf?: (fee: Fee, path: string, json: unknown, status: number) => {
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
- export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
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
37
+ * 4xx is booked at nothing, so its body is not read for a charge. */
38
+ export declare const billedStatus: (status: number) => boolean;
39
+ export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf, fitOf }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
31
40
  /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
32
41
  * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
33
42
  * that failed connecting (its cause's code, UNSENT_CODES, a certificate's CERT_* or a handshake's ERR_TLS_*). Anything
@@ -37,8 +46,8 @@ export declare function unsentWhy(error: unknown, stoppedFirst: boolean): string
37
46
  /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
38
47
  * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
39
48
  * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
40
- * thrown inside `pay`, which books it at its fee. */
41
- 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>;
42
51
  /** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
43
52
  export declare function statusLimit(response: Response): Limit | undefined;
44
53
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
@@ -8,7 +8,10 @@ import { cutAt, withoutUserinfo } from "../page.js";
8
8
  import { failed, keyWide } from "../search.js";
9
9
  /** The most bytes of one answer read: past it the answer is not read. */
10
10
  export const KEYED_MAX_BYTES = 8 * 1024 * 1024;
11
- export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }, send = fetch, pay = unmetered) {
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
+ * 4xx is booked at nothing, so its body is not read for a charge. */
13
+ export const billedStatus = (status) => (status >= 200 && status < 300) || status === 408 || status >= 500;
14
+ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf, fitOf }, send = fetch, pay = unmetered) {
12
15
  let refused = false;
13
16
  const root = base.replace(/\/+$/, "");
14
17
  return {
@@ -18,27 +21,40 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, ch
18
21
  const fee = feeOf(path, body);
19
22
  if (!fee)
20
23
  throw new PaidRefused(`${who}'s ${path} was not sent: it has no price here`);
21
- // What a 2xx answer reports it cost, read from its body before the cap settles; never above the hold.
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 };
27
+ // What an answer the cap books at its price reports it cost, read from its body before the cap settles; never
28
+ // above the hold.
22
29
  let charge;
23
- const charged = chargeOf ? chargedSaying(() => Math.min(charge?.usd ?? fee.usd, fee.usd), () => charge?.basis) : undefined;
24
- 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
+ }
25
39
  const response = await send(`${root}${path}`, {
26
40
  method: "POST",
27
41
  headers: { ...headers, "content-type": "application/json" },
28
- body: JSON.stringify(body),
42
+ body: JSON.stringify(sent.body),
29
43
  // It carries the key: a redirect is an error, never followed to an address the key was not meant for.
30
44
  redirect: "error",
31
45
  signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(signal ? [signal] : [])]),
32
46
  });
33
47
  if (refuseOn.includes(response.status))
34
48
  refused = true;
35
- if (!chargeOf || !response.ok)
49
+ if (!chargeOf || !billedStatus(response.status))
36
50
  return response;
37
51
  // The answer read once, to KEYED_MAX_BYTES at most (bytesOf), and handed on as read: keyedCall takes its parse
38
- // (readAhead), and one past the bound goes on with no body, unreadable as before; its charge is the hold.
39
- const bytes = await bytesOf(response);
52
+ // (readAhead), and one past the bound goes on with no body, unreadable as before; its charge is the hold. A 2xx
53
+ // whose body breaks throws, charged its hold; a 408 or a 5xx whose body breaks goes on with none, its charge
54
+ // read as for one that reported no count.
55
+ const bytes = response.ok ? await bytesOf(response).catch((error) => { throw brokeOff(error); }) : await bytesOf(response).catch(() => undefined);
40
56
  const json = bytes === undefined ? undefined : parsed(bytes);
41
- charge = chargeOf(fee, path, json);
57
+ charge = chargeOf(sent.fee, path, json, response.status);
42
58
  const read = new Response(bytes === undefined ? null : new Uint8Array(bytes), { status: response.status, statusText: response.statusText, headers: response.headers });
43
59
  readAhead.set(read, json);
44
60
  return read;
@@ -72,15 +88,15 @@ export function unsentWhy(error, stoppedFirst) {
72
88
  /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
73
89
  * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
74
90
  * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
75
- * 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). */
76
92
  export async function paidSend(pay, fee, signal, send, charged) {
77
93
  if (signal?.aborted)
78
94
  throw signal.reason;
79
95
  let unsent;
80
- const answer = await pay(fee, async () => {
96
+ const answer = await pay(fee, async (heldUsd) => {
81
97
  const stoppedFirst = signal?.aborted === true;
82
98
  try {
83
- return await send();
99
+ return await send(heldUsd);
84
100
  }
85
101
  catch (error) {
86
102
  const why = unsentWhy(error, stoppedFirst);
@@ -112,6 +128,15 @@ export function statusLimit(response) {
112
128
  }
113
129
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
114
130
  export const codeOf = (said) => (typeof said === "string" && /^[A-Z][A-Z0-9_]{2,63}$/.test(said) ? said : undefined);
131
+ /** The errors of a body that broke while post read it for its credits (chargeOf): an answer came, so keyedCall words
132
+ * one as an answer that broke off, never as a failure to connect. */
133
+ const brokenOff = new WeakSet();
134
+ /** `error`, marked as a body that broke after its answer came (brokenOff) where it can be. */
135
+ const brokeOff = (error) => {
136
+ if (error !== null && typeof error === "object")
137
+ brokenOff.add(error);
138
+ return error;
139
+ };
115
140
  /** An answer's body, read to at most KEYED_MAX_BYTES; undefined when it has none or runs past them (the rest is not
116
141
  * read). */
117
142
  async function bytesOf(response) {
@@ -185,7 +210,7 @@ export async function keyedCall(client, who, keyEnv, what, path, body, signal) {
185
210
  catch (error) {
186
211
  if (error instanceof PaidRefused)
187
212
  return failed("refused", "CAP_REFUSED", error.message);
188
- return unanswered(error, false);
213
+ return unanswered(error, error !== null && typeof error === "object" && brokenOff.has(error));
189
214
  }
190
215
  if (!response.ok) {
191
216
  // The status says what it is; a body that broke only loses the provider's code.
package/dist/text-urls.js CHANGED
@@ -12,6 +12,9 @@ export const SCRUBBED_URL = new RegExp(`https?://[^${URL_ENDS}]+`, "gi");
12
12
  * "*", a closing bracket the URL did not open (trimmed). */
13
13
  export const TRAILING = ".,;:!?*)]}'";
14
14
  const OPENER = { ")": "(", "]": "[", "}": "{" };
15
+ /** @internal The characters this module's readings have visited, each pass's span added once when it ends: the count a
16
+ * test bounds as linear in a text's length. Not in the package's types (stripInternal). */
17
+ export const scanned = { steps: 0 };
15
18
  /** A URL found in text less its tail (TRAILING): a closing bracket stays where the URL opened as many as it closes (a wiki
16
19
  * title's `Foo_(bar)`). One count of the brackets, then one walk back, so a long run of them is linear. */
17
20
  export function trimmed(raw) {
@@ -28,6 +31,7 @@ export function trimmed(raw) {
28
31
  if (opener)
29
32
  count[char] -= 1;
30
33
  }
34
+ scanned.steps += raw.length + (raw.length - end);
31
35
  return raw.slice(0, end);
32
36
  }
33
37
  /** Where a markdown link's target (`text` from `from`, the character after its "](") ends: at the ")" that closes the link,
@@ -40,15 +44,18 @@ export function targetEnd(text, from = 0, to = text.length) {
40
44
  else if (text[end] === ")" && depth-- === 0)
41
45
  break;
42
46
  }
47
+ scanned.steps += end - from;
43
48
  return end;
44
49
  }
45
50
  /** Where a markdown target in angle brackets (`text` from `from`, the character after its "<") ends: the index of its ">",
46
51
  * or -1 where whitespace, another "<" or `to` comes first (no such target: read it as targetEnd does). */
47
52
  function angledEnd(text, from, to) {
48
- for (let end = from; end < to && !/[\s<]/.test(text[end]); end++)
53
+ let end = from;
54
+ for (; end < to && !/[\s<]/.test(text[end]); end++)
49
55
  if (text[end] === ">")
50
- return end;
51
- return -1;
56
+ break;
57
+ scanned.steps += end - from;
58
+ return end < to && text[end] === ">" ? end : -1;
52
59
  }
53
60
  /** A string that is one URL whole (a JSON field holding a link means all of it, its last character too), trimmed of the
54
61
  * whitespace around it; else undefined. */
@@ -66,7 +73,14 @@ const LINK_AT = new RegExp(`\\]\\(|${TEXT_URL.source}`, "gi");
66
73
  * hostile page holds. A page's links (hrefsIn) and an answer's cited links (link-check.ts) both read it. */
67
74
  export function* linksWritten(text) {
68
75
  const at = new RegExp(LINK_AT.source, "gi");
69
- for (let found = at.exec(text); found; found = at.exec(text)) {
76
+ // Each search runs from where the last left off (lastIndex) to its match's end, or the text's.
77
+ const next = () => {
78
+ const from = at.lastIndex;
79
+ const found = at.exec(text);
80
+ scanned.steps += (found ? at.lastIndex : text.length) - from;
81
+ return found;
82
+ };
83
+ for (let found = next(); found; found = next()) {
70
84
  // A "](" alone is ["", ""]: one target, after it.
71
85
  const pieces = found[0].split("](");
72
86
  if (pieces[0])
@@ -95,6 +109,9 @@ const NAMED = { quot: '"', amp: "&", lt: "<", gt: ">", apos: "'" };
95
109
  /** An XML attribute: its name, and its value in double quotes (kept as it is, so an "='" in its query is never taken for
96
110
  * an attribute) or in single quotes (the fourth group). */
97
111
  const ATTRIBUTE = /(\s)([^\s=<>"'/]+)(\s*=\s*)(?:"[^"]*"|'([^'<]*)')/g;
112
+ /** @internal Every pattern this module scans a whole text with, for the test that compiles each on V8's linear engine (a
113
+ * pattern that backtracks is refused there). Not in the package's types (stripInternal). */
114
+ export const scanPatterns = [TEXT_URL, SCRUBBED_URL, LINK_AT, ENTITY, ATTRIBUTE];
98
115
  /** `text` read for its links, where it is not JSON: its entities undone once, so an escaped `&lt;a href=&quot;…&quot;&gt;`
99
116
  * (an Atom feed's content) ends its URL at the quote, never running on to the next space, and an attribute's
100
117
  * `href="https://a/?x=1&amp;y=2"` is the URL `https://a/?x=1&y=2`. One pass, so `&amp;lt;` is `&lt;`. Where it is XML,
@@ -102,6 +119,7 @@ const ATTRIBUTE = /(\s)([^\s=<>"'/]+)(\s*=\s*)(?:"[^"]*"|'([^'<]*)')/g;
102
119
  * value holds no "'" or "<" of its own), and a namespace's name (`xmlns="http://www.w3.org/2005/Atom"`), an identifier,
103
120
  * never a link, is dropped. Attributes are read in order, each whole. */
104
121
  function readable(text) {
122
+ scanned.steps += text.length;
105
123
  const xml = /^\s*<[?!A-Za-z]/.test(text)
106
124
  ? text.replace(ATTRIBUTE, (attribute, space, name, equals, single) => {
107
125
  if (/^xmlns(:|$)/i.test(name))
@@ -109,6 +127,7 @@ function readable(text) {
109
127
  return single === undefined ? attribute : `${space}${name}${equals}"${single}"`;
110
128
  })
111
129
  : text;
130
+ scanned.steps += xml.length;
112
131
  return xml.replace(ENTITY, (entity, name, decimal, hex) => {
113
132
  if (name)
114
133
  return NAMED[name.toLowerCase()];
@@ -124,6 +143,7 @@ function jsonHrefs(text) {
124
143
  if (!/^\s*[[{"]/.test(text))
125
144
  return undefined;
126
145
  let body;
146
+ scanned.steps += text.length;
127
147
  try {
128
148
  body = JSON.parse(text);
129
149
  }
@@ -154,6 +174,7 @@ function jsonHrefs(text) {
154
174
  export function* linksOf(text) {
155
175
  const seen = new Set();
156
176
  for (const href of jsonHrefs(text) ?? hrefsIn(readable(text))) {
177
+ scanned.steps += href.length;
157
178
  const link = /^https?:\/\//i.test(href) ? URL.parse(href) : null;
158
179
  if (!link)
159
180
  continue;
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.68",
3
+ "version": "0.1.0-beta.70",
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.68"
49
+ "@parcha/pi-browser": "0.1.0-beta.70"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",