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

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
@@ -62,12 +62,13 @@ export declare const FIRECRAWL_PDF_PAGES_MAX = 10000;
62
62
  * credits Firecrawl reports, never above this (firecrawlChargeOf). Undefined for an endpoint the web tools do not ask,
63
63
  * and for a body asking a proxy other than basic (a search for its results, a scrape for its page). */
64
64
  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):
65
+ /** The credits Firecrawl reports an answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
66
66
  * a search's top-level creditsUsed, a scrape's data.metadata.creditsUsed; undefined unless a whole number, 0 or more. */
67
67
  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): {
68
+ /** What an answer of `status` to `path` held at `fee` is charged, and the receipt's line for it: the credits Firecrawl
69
+ * reports at the plan price; the hold when it reports more (saying how many). Reporting none it can be read by, a 2xx
70
+ * is charged the hold, and a 408 or a 5xx 0 credits (saying so). */
71
+ export declare function firecrawlChargeOf(fee: Fee, path: string, json: unknown, status?: number): {
71
72
  usd: number;
72
73
  basis: string;
73
74
  };
package/dist/fees.js CHANGED
@@ -115,18 +115,23 @@ export function firecrawlFeeOf(path, body) {
115
115
  }
116
116
  return undefined;
117
117
  }
118
- /** The credits Firecrawl reports a 2xx answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
118
+ /** The credits Firecrawl reports an answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
119
119
  * a search's top-level creditsUsed, a scrape's data.metadata.creditsUsed; undefined unless a whole number, 0 or more. */
120
120
  export function firecrawlCreditsOf(path, json) {
121
121
  const said = path === "/v2/search" ? json?.creditsUsed : json?.data?.metadata?.creditsUsed;
122
122
  return typeof said === "number" && Number.isInteger(said) && said >= 0 ? said : undefined;
123
123
  }
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) {
124
+ /** What an answer of `status` to `path` held at `fee` is charged, and the receipt's line for it: the credits Firecrawl
125
+ * reports at the plan price; the hold when it reports more (saying how many). Reporting none it can be read by, a 2xx
126
+ * is charged the hold, and a 408 or a 5xx 0 credits (saying so). */
127
+ export function firecrawlChargeOf(fee, path, json, status = 200) {
127
128
  const hold = Math.round(fee.usd / FIRECRAWL_CREDIT_USD);
128
129
  const plural = (n) => `${n} credit${n === 1 ? "" : "s"}`;
129
130
  const reported = firecrawlCreditsOf(path, json);
131
+ // Firecrawl's billing page (https://docs.firecrawl.dev/billing): "A scrape that fails outright, for example because
132
+ // the site never responded, is not charged." A 408 or a 5xx with no count of its own is that failure: 0 credits.
133
+ if (reported === undefined && (status === 408 || status >= 500))
134
+ return { usd: 0, basis: `Firecrawl answered ${status} and reported no credit count: 0 credits; a request that fails outright is not charged` };
130
135
  if (reported === undefined)
131
136
  return { usd: fee.usd, basis: `the hold, ${plural(hold)}; Firecrawl reported no credit count` };
132
137
  const charged = usd(FIRECRAWL_CREDIT_USD * reported);
@@ -12,9 +12,9 @@ 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
18
  export type KeyedSpec = {
19
19
  who: string;
20
20
  base: string;
@@ -22,11 +22,14 @@ export type KeyedSpec = {
22
22
  feeOf: (path: string, body: unknown) => Fee | undefined;
23
23
  timeoutMs: number;
24
24
  refuseOn: readonly number[];
25
- chargeOf?: (fee: Fee, path: string, json: unknown) => {
25
+ chargeOf?: (fee: Fee, path: string, json: unknown, status: number) => {
26
26
  usd: number;
27
27
  basis: string;
28
28
  };
29
29
  };
30
+ /** 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
+ * 4xx is booked at nothing, so its body is not read for a charge. */
32
+ export declare const billedStatus: (status: number) => boolean;
30
33
  export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
31
34
  /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
32
35
  * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
@@ -8,6 +8,9 @@ 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
+ /** 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;
11
14
  export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }, send = fetch, pay = unmetered) {
12
15
  let refused = false;
13
16
  const root = base.replace(/\/+$/, "");
@@ -18,7 +21,8 @@ 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 an answer the cap books at its price reports it cost, read from its body before the cap settles; never
25
+ // above the hold.
22
26
  let charge;
23
27
  const charged = chargeOf ? chargedSaying(() => Math.min(charge?.usd ?? fee.usd, fee.usd), () => charge?.basis) : undefined;
24
28
  return paidSend(pay, fee, signal, async () => {
@@ -32,13 +36,15 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, ch
32
36
  });
33
37
  if (refuseOn.includes(response.status))
34
38
  refused = true;
35
- if (!chargeOf || !response.ok)
39
+ if (!chargeOf || !billedStatus(response.status))
36
40
  return response;
37
41
  // 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);
42
+ // (readAhead), and one past the bound goes on with no body, unreadable as before; its charge is the hold. A 2xx
43
+ // whose body breaks throws, charged its hold; a 408 or a 5xx whose body breaks goes on with none, its charge
44
+ // read as for one that reported no count.
45
+ const bytes = response.ok ? await bytesOf(response).catch((error) => { throw brokeOff(error); }) : await bytesOf(response).catch(() => undefined);
40
46
  const json = bytes === undefined ? undefined : parsed(bytes);
41
- charge = chargeOf(fee, path, json);
47
+ charge = chargeOf(fee, path, json, response.status);
42
48
  const read = new Response(bytes === undefined ? null : new Uint8Array(bytes), { status: response.status, statusText: response.statusText, headers: response.headers });
43
49
  readAhead.set(read, json);
44
50
  return read;
@@ -112,6 +118,15 @@ export function statusLimit(response) {
112
118
  }
113
119
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
114
120
  export const codeOf = (said) => (typeof said === "string" && /^[A-Z][A-Z0-9_]{2,63}$/.test(said) ? said : undefined);
121
+ /** The errors of a body that broke while post read it for its credits (chargeOf): an answer came, so keyedCall words
122
+ * one as an answer that broke off, never as a failure to connect. */
123
+ const brokenOff = new WeakSet();
124
+ /** `error`, marked as a body that broke after its answer came (brokenOff) where it can be. */
125
+ const brokeOff = (error) => {
126
+ if (error !== null && typeof error === "object")
127
+ brokenOff.add(error);
128
+ return error;
129
+ };
115
130
  /** 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
131
  * read). */
117
132
  async function bytesOf(response) {
@@ -185,7 +200,7 @@ export async function keyedCall(client, who, keyEnv, what, path, body, signal) {
185
200
  catch (error) {
186
201
  if (error instanceof PaidRefused)
187
202
  return failed("refused", "CAP_REFUSED", error.message);
188
- return unanswered(error, false);
203
+ return unanswered(error, error !== null && typeof error === "object" && brokenOff.has(error));
189
204
  }
190
205
  if (!response.ok) {
191
206
  // 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/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.69",
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.69"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",