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

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/README.md CHANGED
@@ -57,8 +57,8 @@ const page = await web.fetch("https://example.org/", { offset: 0, maxChars: 20_0
57
57
  empty objective is `{ error: "web_search needs an objective" }`, and no provider is asked. Each provider is sent what
58
58
  it takes: Parallel the objective and the queries (`objective`, `search_queries`, mode `fast`, plus `client_model` and
59
59
  `session_id` when `client` names them); Exa, keyed and keyless, the objective as its query; Firecrawl, keyed and
60
- keyless, up to 3 of the queries at once, each asked for `ceil(n / k)` results scraped as markdown (main content only),
61
- the results merged by URL in first-seen order and cut at `n`, each snippet its page's markdown; keyless Firecrawl
60
+ keyless, up to 3 of the queries at once, each asked for `ceil(n / k)` results (keyless: each result scraped as markdown, main content only;
61
+ keyed: no scrape, each snippet Firecrawl's description of the result), the results merged by URL in first-seen order and cut at `n`, each snippet its page's markdown where it has one, else its description; keyless Firecrawl
62
62
  sends the objective too, which its tool requires; `native` the first query. The answer is `{ provider, objective,
63
63
  queries, results }`.
64
64
  - `client` (WebConfig) is `{ model?, session? }`: the model the run calls, as a bare id (`claude-opus-4-7`), and an id of
@@ -134,6 +134,19 @@ const { answer, receipt } = await web.search({ objective: "Where Widgets, Inc. i
134
134
  offset"` (`max_chars`, or `offset and max_chars`, as given). With no decider the answer is the part asked for, its
135
135
  `sift` `"objective not applied (no classifier in this run); this part is in page order"`; with one that fails, the
136
136
  part asked for with `sift: "objective not applied (<why>); this part is in page order"`. The page is read once a run either way; a blank objective is none.
137
+ - A decider may carry a Jev setup (`setup`, one of `JEV_SETUPS`), which says what the steps do with its scores; one
138
+ with none runs as `"shipped"`. `jevWebDecider(jev, name?)` builds Jev's under the setup `name` names, `DEFAULT_JEV_SETUP`
139
+ (`"shipped"`) when none is given; an unknown name throws. `"shipped"` is every step as described here.
140
+ `"top2-best300-found5"`, under rerank+label, keeps the 2 most relevant results whole and shows each later one only the
141
+ passage of its snippet (at most 300 characters, "…" where it is cut) the decider scores most likely to hold what the
142
+ search needs (its excerpts kept apart by " …"; a snippet of 300 characters or less stays whole). The passage
143
+ requests go one per such result, `REQUESTS_AT_ONCE` at a time, within what the step's deadline left after the sift,
144
+ and are on the step's record (cost, tokens, question hashes); after one fails no more are sent, those in flight
145
+ settle, and every cut result shows its snippet's first 300 characters instead. Its url,
146
+ title and relevance stay, and the `sift` adds `"; past the first 2, a result shows only its passage most relevant to
147
+ the search: web_fetch its url to read it"`. A fetch's objective then holds 5 found chunks in place of 8.
148
+ `"top3-best300-found8"` keeps the 3 most relevant results whole and picks the same passage for each later one (the
149
+ `sift` says `"past the first 3"`), and a fetch's objective holds 8 found chunks, as under `"shipped"`.
137
150
  - A fetched part is judged in passages (`passagesOf`: whole paragraphs packed to about 1,000 characters, at most 50).
138
151
  The kept ones stay in order, `LEFT_OUT` stands for each run left out, and the part's `chars`, `offset` and
139
152
  `next_offset` are unchanged. A fetch with no `task` is not judged.
@@ -1,5 +1,6 @@
1
1
  import type { Fee } from "../fees.js";
2
2
  import type { Hit } from "../search.js";
3
+ import { type JevSetup } from "./setup.js";
3
4
  /** What a provider said of one item: p(needed), or null where it refused the question. What is done with it is the
4
5
  * step's (search.ts, fetch.ts), never the decider's. */
5
6
  export type Verdict = number | null;
@@ -52,6 +53,8 @@ export type PageAnswers = {
52
53
  } & Omit<Verdicts, "verdicts" | "trimmed">;
53
54
  export interface WebDecider {
54
55
  readonly id: string;
56
+ /** What the decide layer does with this decider's scores in each step (setup.ts); absent: as under "shipped". */
57
+ readonly setup?: JevSetup;
55
58
  sift(query: string, hits: readonly Hit[], task: string | undefined, ctx: DecideContext): Promise<Verdicts>;
56
59
  judge(url: string, task: string, passages: readonly string[], ctx: DecideContext): Promise<Verdicts>;
57
60
  guard(url: string, status: number, text: string, ctx: DecideContext): Promise<PageAnswers>;
@@ -138,6 +141,7 @@ export declare const REQUESTS_AT_ONCE = 4;
138
141
  * TypeSafe: "If you have tuned confidence thresholds against one version, send that version's ID instead of the
139
142
  * alias." OpenRouter's route names models its own way and is sent none: the provider's own default holds there. */
140
143
  export declare const JEV_MODEL = "jev-1.14.0";
144
+ export declare function tokensTogether(a: Tokens | null, b: Tokens | null): Tokens | null;
141
145
  /** A provider's published price, as a request is held to it before it is sent: a fee per request, and per million
142
146
  * tokens in and out (the long rates past `longPromptTokens` input tokens). The input is bounded by the request's
143
147
  * UTF-8 bytes, times `inputTokensPerByte` (1: a token is at least a byte), plus `extraInputTokens` the provider adds
@@ -173,11 +177,13 @@ export type JevWeb = {
173
177
  fetch?: typeof fetch;
174
178
  };
175
179
  /** The web decider Jev gives on TypeSafe's route, as a host's web tools run it: JEV_MODEL on every request, results
176
- * ranked under rerank+label. Built from what it is handed alone, never from the process's environment: `null` (no
177
- * TypeSafe key, or Jev turned off) gives none. */
178
- export declare function jevWebDecider(jev: JevWeb | null): {
180
+ * ranked under rerank+label, under the Jev setup `setup` names (setup.ts; DEFAULT_JEV_SETUP when none is given, an
181
+ * unknown name throws). Built from what it is handed alone, never from the process's environment: `null` (no TypeSafe
182
+ * key, or Jev turned off) gives none. */
183
+ export declare function jevWebDecider(jev: JevWeb | null, setup?: string): {
179
184
  decider: WebDecider;
180
185
  policy: "rerank+label";
181
186
  model: typeof JEV_MODEL;
187
+ setup: JevSetup;
182
188
  } | undefined;
183
189
  export declare function deciderFrom(provider: DecisionAsker, options: DeciderOptions): WebDecider;
@@ -2,6 +2,7 @@
2
2
  import { createHash } from "node:crypto";
3
3
  import { codeOf, costOf, costTogether } from "./failure.js";
4
4
  import { PASSAGES_MAX } from "./passages.js";
5
+ import { setupOf } from "./setup.js";
5
6
  /** A decider's failure: `code` as the DSL's DecisionProviderError names it, and what a billed request cost. */
6
7
  export class DecideError extends Error {
7
8
  code;
@@ -129,7 +130,7 @@ function requestsOf(items, request, most = QUESTIONS_PER_REQUEST) {
129
130
  }
130
131
  /** Two requests' verdicts as one ask's: the first's model and temperature, the rest in order and summed. */
131
132
  const together = (a, b) => ({ ...a, verdicts: [...a.verdicts, ...b.verdicts], tokens: tokensTogether(a.tokens, b.tokens), cost: costTogether(a.cost, b.cost), questions_sha256: [...a.questions_sha256, ...b.questions_sha256] });
132
- function tokensTogether(a, b) {
133
+ export function tokensTogether(a, b) {
133
134
  if (!a || !b)
134
135
  return null;
135
136
  return { in: a.in + b.in, out: a.out === null || b.out === null ? null : a.out + b.out, basis: a.basis === "reported" && b.basis === "reported" ? "reported" : "counted" };
@@ -149,16 +150,18 @@ const isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v
149
150
  const noulOf = (answer) => (answer.type === "noul" && isUnit(answer.noul) ? answer.noul : undefined);
150
151
  const choiceOf = (answer) => answer.type === "choice" && isRecord(answer.probabilities) && Object.values(answer.probabilities).every(isUnit) ? answer.probabilities : undefined;
151
152
  /** The web decider Jev gives on TypeSafe's route, as a host's web tools run it: JEV_MODEL on every request, results
152
- * ranked under rerank+label. Built from what it is handed alone, never from the process's environment: `null` (no
153
- * TypeSafe key, or Jev turned off) gives none. */
154
- export function jevWebDecider(jev) {
153
+ * ranked under rerank+label, under the Jev setup `setup` names (setup.ts; DEFAULT_JEV_SETUP when none is given, an
154
+ * unknown name throws). Built from what it is handed alone, never from the process's environment: `null` (no TypeSafe
155
+ * key, or Jev turned off) gives none. */
156
+ export function jevWebDecider(jev, setup) {
155
157
  if (jev === null)
156
158
  return undefined;
157
159
  if (typeof jev?.key !== "string" || jev.key.trim() === "")
158
160
  throw new TypeError("jevWebDecider needs TypeSafe's key, or null for no Jev");
161
+ const chosen = setupOf(setup);
159
162
  const provider = jev.jevProvider({ apiKey: jev.key, ...(jev.fetch ? { fetch: jev.fetch } : {}) });
160
163
  // Jev's provider on TypeSafe's route needs TYPESAFE_API_KEY, so deciderFrom pins JEV_MODEL (pinnedModel), as for any caller.
161
- return { decider: deciderFrom(provider, { price: jev.price }), policy: "rerank+label", model: JEV_MODEL };
164
+ return { decider: { ...deciderFrom(provider, { price: jev.price }), setup: chosen }, policy: "rerank+label", model: JEV_MODEL, setup: chosen };
162
165
  }
163
166
  export function deciderFrom(provider, options) {
164
167
  if (options?.price === null || typeof options?.price !== "object")
@@ -171,7 +174,16 @@ export function deciderFrom(provider, options) {
171
174
  const text = JSON.stringify({ state: request.state, questions: request.questions });
172
175
  const bytes = Buffer.byteLength(text);
173
176
  const fee = { name, by: provider.id, usd: holdOf(price, bytes), basis: `the most a request of ${bytes} bytes may cost at ${provider.id}'s price` };
174
- const go = () => provider.decide(request, { decisionId: `web-${request.kind}-${sha256(text).slice(0, 24)}`, signal: ctx.signal, deadlineMs: ctx.deadlineMs });
177
+ // A request on a call already stopped asks no hold. One stopped while its hold was admitted is never sent, and is
178
+ // unsent, so decisionPay settles it at $0: a provider's own pre-send stop reads as a failure that may have billed.
179
+ const unsent = () => Object.assign(new DecideError("aborted", `${provider.id}'s request was stopped before it was sent`), { unsent: true });
180
+ if (ctx.signal.aborted)
181
+ throw unsent();
182
+ const go = async () => {
183
+ if (ctx.signal.aborted)
184
+ throw unsent();
185
+ return provider.decide(request, { decisionId: `web-${request.kind}-${sha256(text).slice(0, 24)}`, signal: ctx.signal, deadlineMs: ctx.deadlineMs });
186
+ };
175
187
  const outcome = await (ctx.pay ? ctx.pay(fee, go, (answered) => ({ usd: answered.cost_usd, basis: answered.cost_basis })) : go());
176
188
  const cost = { usd: outcome.cost_usd, basis: outcome.cost_basis };
177
189
  const tokens = outcome.usage
@@ -27,11 +27,11 @@ export type FoundPage = Pick<Page, "ok" | "url" | "status" | "title" | "original
27
27
  found: FoundChunk[];
28
28
  sift: string;
29
29
  };
30
- /** The FOUND_CHUNKS chunks of the whole page `read` most likely to hold `need` (what the agent wants from it), in page
31
- * order: its text cut into at most FIND_CHUNKS_MAX chunks, each judged by `decider` with `need` as the task (its
30
+ /** The `found` chunks (its setup's, else FOUND_CHUNKS) of the whole page `read` most likely to hold `need` (what the
31
+ * agent wants from it), in page order: its text cut into at most FIND_CHUNKS_MAX chunks, each judged by `decider` with `need` as the task (its
32
32
  * judge request), ranked by score, a refused one after every scored one, ties in page order. A step that fails answers
33
33
  * null, its record saying why. */
34
- export declare function findInPage(decider: WebDecider, url: string, read: WebRead, need: string, options: StepOptions): Promise<Sifted<FoundPage | null>>;
34
+ export declare function findInPage(decider: WebDecider, url: string, read: WebRead, need: string, options: StepOptions, found?: number): Promise<Sifted<FoundPage | null>>;
35
35
  /** A fetch's answer: the part (judged or not), or what its objective found; with the guard's warning when it gave one. */
36
36
  export type FetchAnswer = (((WebPage | Page) & Sift) | FoundPage) & Warned;
37
37
  /** How a fetch is decided: the call's `task` and `objective`, the part it asked for (`offset`, `maxChars`, as given), the
@@ -39,11 +39,11 @@ async function judgeSpans(decider, url, need, text, spans, base, options) {
39
39
  /** The most chunks a page is cut into for an objective (passagesOf), and how many of them an answer shows. */
40
40
  export const FIND_CHUNKS_MAX = 200;
41
41
  export const FOUND_CHUNKS = 8;
42
- /** The FOUND_CHUNKS chunks of the whole page `read` most likely to hold `need` (what the agent wants from it), in page
43
- * order: its text cut into at most FIND_CHUNKS_MAX chunks, each judged by `decider` with `need` as the task (its
42
+ /** The `found` chunks (its setup's, else FOUND_CHUNKS) of the whole page `read` most likely to hold `need` (what the
43
+ * agent wants from it), in page order: its text cut into at most FIND_CHUNKS_MAX chunks, each judged by `decider` with `need` as the task (its
44
44
  * judge request), ranked by score, a refused one after every scored one, ties in page order. A step that fails answers
45
45
  * null, its record saying why. */
46
- export async function findInPage(decider, url, read, need, options) {
46
+ export async function findInPage(decider, url, read, need, options, found = decider.setup?.fetch.found ?? FOUND_CHUNKS) {
47
47
  const spans = passagesOf(read.text, FIND_CHUNKS_MAX);
48
48
  const judged = await judgeSpans(decider, url, need, read.text, spans, 0, options);
49
49
  if ("failure" in judged)
@@ -52,7 +52,7 @@ export async function findInPage(decider, url, read, need, options) {
52
52
  const shown = spans
53
53
  .map((_, i) => i)
54
54
  .sort((a, b) => byScore(scored[a].score, scored[b].score) || a - b)
55
- .slice(0, FOUND_CHUNKS)
55
+ .slice(0, found)
56
56
  .sort((a, b) => a - b);
57
57
  const answer = {
58
58
  ok: true,
@@ -1,5 +1,5 @@
1
1
  import { type Search } from "../search.js";
2
- import type { WebDecider } from "./decider.js";
2
+ import { type WebDecider } from "./decider.js";
3
3
  import { type Sifted, type StepOptions } from "./record.js";
4
4
  /** Under label or rerank+label, the score at least one result must reach for the search not to be called a miss. */
5
5
  export declare const LOW_RELEVANCE = 0.3;
@@ -2,7 +2,10 @@
2
2
  import { clip } from "../page.js";
3
3
  import { kindOf } from "../providers/keyed.js";
4
4
  import { QUERY_MAX } from "../search.js";
5
- import { bounded, byScore, droppedOf, drops, failed, ran, relevanceOf, since, skipped } from "./record.js";
5
+ import { REQUESTS_AT_ONCE, tokensTogether } from "./decider.js";
6
+ import { costOf, costTogether } from "./failure.js";
7
+ import { cutSnippet, passagesOfSnippet } from "./setup.js";
8
+ import { bounded, byScore, DECIDE_MS, droppedOf, drops, failed, ran, relevanceOf, since, skipped } from "./record.js";
6
9
  /** Under label or rerank+label, the score at least one result must reach for the search not to be called a miss. */
7
10
  export const LOW_RELEVANCE = 0.3;
8
11
  const POLICIES = ["drop", "label", "rerank+label"];
@@ -24,21 +27,99 @@ export async function siftSearch(decider, answer, options) {
24
27
  if ("code" in got)
25
28
  return { answer: { ...answer, sift: `not run (${got.code}); these results are unsifted` }, classifier: failed(decider, "search", n, since(start), requests, got) };
26
29
  const scored = answer.results.map((hit, i) => ({ id: hit.url, score: got.verdicts[i] }));
27
- if (policy !== "drop")
28
- return { answer: labelled(decider.id, answer, scored, options.task, policy === "rerank+label"), classifier: ran(decider, "search", got, since(start), requests, scored, []) };
30
+ if (policy !== "drop") {
31
+ const rerank = policy === "rerank+label";
32
+ const picked = rerank ? await bestPassages(decider, answer, scored, options, start) : { best: new Map(), requests: 0, asked: { answered: [], failed: [] } };
33
+ return { answer: labelled(decider.id, answer, scored, options.task, rerank, rerank ? decider.setup?.search : undefined, picked.best), classifier: ran(decider, "search", withAsked(got, picked.asked), since(start), requests + picked.requests, scored, []) };
34
+ }
29
35
  const results = answer.results.filter((_, i) => !drops(scored[i].score));
30
36
  return { answer: { ...answer, results, sift: `${decider.id} kept ${results.length} of ${n} results` }, classifier: ran(decider, "search", got, since(start), requests, scored, droppedOf(scored)) };
31
37
  }
38
+ async function bestPassages(decider, answer, scored, options, started) {
39
+ const best = new Map();
40
+ const none = { best, requests: 0, asked: { answered: [], failed: [] } };
41
+ const setup = decider.setup?.search;
42
+ if (setup?.pick !== "best" || setup.full === undefined || !setup.cut)
43
+ return none;
44
+ const cut = setup.cut;
45
+ const order = answer.results.map((hit, i) => ({ hit, score: scored[i].score })).sort((a, b) => byScore(a.score, b.score));
46
+ const asking = order
47
+ .slice(setup.full)
48
+ .filter(({ hit }) => hit.snippet.length > cut)
49
+ .map(({ hit }) => ({ url: hit.url, passages: passagesOfSnippet(hit.snippet, cut) }))
50
+ .filter((one) => one.passages.length > 1);
51
+ const left = Math.floor((options.ms ?? DECIDE_MS) - (performance.now() - started));
52
+ if (!asking.length || left <= 0)
53
+ return none;
54
+ const need = options.task ?? answer.objective;
55
+ const got = [];
56
+ const failed = [];
57
+ const { got: step, requests } = await bounded(async (ctx) => {
58
+ let next = 0;
59
+ const work = async () => {
60
+ while (next < asking.length && !failed.length && !ctx.signal.aborted) {
61
+ const k = next++;
62
+ try {
63
+ got[k] = await decider.judge(asking[k].url, need, asking[k].passages, ctx);
64
+ }
65
+ catch (thrown) {
66
+ failed.push(costOf(thrown));
67
+ }
68
+ }
69
+ };
70
+ await Promise.all(Array.from({ length: Math.min(REQUESTS_AT_ONCE, asking.length) }, work));
71
+ ctx.signal.throwIfAborted();
72
+ }, { ...options, ms: left });
73
+ const asked = { answered: got.filter(Boolean), failed: step && "code" in step ? [...failed, step.cost] : failed };
74
+ if (asked.failed.length)
75
+ return { best, requests, asked };
76
+ asking.forEach((one, k) => {
77
+ const verdicts = got[k].verdicts;
78
+ let at = 0;
79
+ verdicts.forEach((v, i) => {
80
+ if ((v ?? -1) > (verdicts[at] ?? -1))
81
+ at = i;
82
+ });
83
+ best.set(one.url, { text: one.passages[at], first: at === 0, last: at === one.passages.length - 1 });
84
+ });
85
+ return { best, requests, asked };
86
+ }
87
+ /** The sift's verdicts with what the passage requests answered and cost: their tokens (unknown where one failed), cost
88
+ * and question hashes added after the sift's. */
89
+ function withAsked(got, asked) {
90
+ if (!asked.answered.length && !asked.failed.length)
91
+ return got;
92
+ return {
93
+ ...got,
94
+ tokens: [...asked.answered.map((one) => one.tokens), ...asked.failed.map(() => null)].reduce(tokensTogether, got.tokens),
95
+ cost: [...asked.answered.map((one) => one.cost), ...asked.failed].reduce(costTogether, got.cost),
96
+ questions_sha256: [...got.questions_sha256, ...asked.answered.flatMap((one) => one.questions_sha256)],
97
+ };
98
+ }
32
99
  /** `answer`'s results, every one, each scored one with `relevance`, its score to two places; when `rerank`, the most
33
- * relevant first (a stable sort: ties in the provider's order, a refused one last). The sift line says which, and that
34
- * nothing looks relevant to the need when no result reaches LOW_RELEVANCE. */
35
- function labelled(id, answer, scored, task, rerank) {
100
+ * relevant first (a stable sort: ties in the provider's order, a refused one last). Under `setup`'s `full`, each result
101
+ * past the first `full` keeps at most `cut` characters of its snippet: its passage in `picked`, else its start. The
102
+ * sift line says which, and that nothing looks relevant to the need when no result reaches LOW_RELEVANCE. */
103
+ function labelled(id, answer, scored, task, rerank, setup, picked = new Map()) {
36
104
  const pairs = answer.results.map((hit, i) => ({ hit, score: scored[i].score }));
37
105
  if (rerank)
38
106
  pairs.sort((a, b) => byScore(a.score, b.score));
39
- const results = pairs.map(({ hit, score }) => ({ ...hit, ...relevanceOf(score) }));
107
+ const full = setup?.full;
108
+ const cut = setup?.cut ?? 0;
109
+ let shortened = 0;
110
+ const results = pairs.map(({ hit, score }, i) => {
111
+ if (full === undefined || i < full)
112
+ return { ...hit, ...relevanceOf(score) };
113
+ const pick = picked.get(hit.url);
114
+ const snippet = pick ? `${pick.first ? "" : "… "}${cutSnippet(pick.text, cut)}${pick.last ? "" : " …"}` : cutSnippet(hit.snippet, cut);
115
+ if (snippet !== hit.snippet)
116
+ shortened += 1;
117
+ return { ...hit, snippet, ...relevanceOf(score) };
118
+ });
40
119
  const best = Math.max(...scored.map((item) => item.score ?? 0));
41
120
  const miss = best < LOW_RELEVANCE ? `; nothing here looks relevant to ${JSON.stringify(clip(task ?? answer.objective, QUERY_MAX))}; consider rephrasing` : "";
42
121
  const done = rerank ? `ordered ${results.length} results by relevance` : `labelled ${results.length} results with their relevance`;
43
- return { ...answer, results, sift: `${id} ${done}, how likely each holds what the search asks for (0 to 1)${miss}` };
122
+ const shown = !cut ? "no text" : picked.size ? "only its passage most relevant to the search" : "only the start of its text";
123
+ const short = shortened ? `; past the first ${full}, a result shows ${shown}: web_fetch its url to read it` : "";
124
+ return { ...answer, results, sift: `${id} ${done}, how likely each holds what the search asks for (0 to 1)${short}${miss}` };
44
125
  }
@@ -0,0 +1,32 @@
1
+ /** The search step under a setup. Every result is labelled with its relevance and the most relevant come first. `full`:
2
+ * the most relevant `full` results keep their whole snippet; each later one keeps at most `cut` characters of it, its
3
+ * url, title and relevance kept. `pick`: which `cut` characters, the snippet's start ("start") or its passage
4
+ * (passagesOfSnippet) Jev scores most likely to hold what the search needs ("best"; the start where that ask fails).
5
+ * Unset `full`: every snippet whole. */
6
+ export type SearchSetup = {
7
+ full?: number;
8
+ cut?: number;
9
+ pick?: "start" | "best";
10
+ };
11
+ /** The fetch step under a setup: with an objective, the `found` chunks of the page most likely to hold it. */
12
+ export type FetchSetup = {
13
+ found: number;
14
+ };
15
+ export type JevSetup = {
16
+ readonly name: string;
17
+ readonly search: SearchSetup;
18
+ readonly fetch: FetchSetup;
19
+ };
20
+ export declare const JEV_SETUPS: Readonly<Record<string, JevSetup>>;
21
+ /** The setup a host's Jev runs under when it names none (jevWebDecider). */
22
+ export declare const DEFAULT_JEV_SETUP = "shipped";
23
+ /** The setup named `name`, DEFAULT_JEV_SETUP when none is given; an unknown name throws. */
24
+ export declare function setupOf(name?: string): JevSetup;
25
+ /** `s` cut to at most `n` characters on a word, with "…" after it; "" for n = 0; whole when it fits. */
26
+ export declare function cutSnippet(s: string, n: number): string;
27
+ /** The most passages one snippet is cut into for a "best" pick. */
28
+ export declare const SNIPPET_PASSAGES_MAX = 24;
29
+ /** `snippet` as passages of at most `size` characters, in order: its sentences and lines packed together, a sentence
30
+ * longer than `size` cut on a word. Its excerpts (Parallel and Exa join theirs with " … ") stay apart: two packed into
31
+ * one passage are joined with " … " again, never run together. At most SNIPPET_PASSAGES_MAX (the rest dropped). */
32
+ export declare function passagesOfSnippet(snippet: string, size: number): string[];
@@ -0,0 +1,69 @@
1
+ // A Jev setup: what the decide layer does with Jev's scores in each step. Only the decide layer reads one: the tools,
2
+ // their schemas and the providers are the same under every setup.
3
+ export const JEV_SETUPS = Object.freeze({
4
+ /** Every result whole, a fetch's objective shown 8 chunks. */
5
+ shipped: Object.freeze({ name: "shipped", search: Object.freeze({}), fetch: Object.freeze({ found: 8 }) }),
6
+ /** Jev's top 2 results whole, each later one its passage of at most 300 characters Jev scores most relevant, a fetch's
7
+ * objective shown 5 chunks. */
8
+ "top2-best300-found5": Object.freeze({ name: "top2-best300-found5", search: Object.freeze({ full: 2, cut: 300, pick: "best" }), fetch: Object.freeze({ found: 5 }) }),
9
+ /** Jev's top 3 results whole, each later one its passage of at most 300 characters Jev scores most relevant, a fetch's
10
+ * objective shown 8 chunks, as shipped. */
11
+ "top3-best300-found8": Object.freeze({ name: "top3-best300-found8", search: Object.freeze({ full: 3, cut: 300, pick: "best" }), fetch: Object.freeze({ found: 8 }) }),
12
+ });
13
+ /** The setup a host's Jev runs under when it names none (jevWebDecider). */
14
+ export const DEFAULT_JEV_SETUP = "shipped";
15
+ /** The setup named `name`, DEFAULT_JEV_SETUP when none is given; an unknown name throws. */
16
+ export function setupOf(name = DEFAULT_JEV_SETUP) {
17
+ const setup = Object.hasOwn(JEV_SETUPS, name) ? JEV_SETUPS[name] : undefined;
18
+ if (!setup)
19
+ throw new RangeError(`no Jev setup ${JSON.stringify(name)}: one of ${Object.keys(JEV_SETUPS).join(", ")}`);
20
+ return setup;
21
+ }
22
+ /** `s` cut to at most `n` characters on a word, with "…" after it; "" for n = 0; whole when it fits. */
23
+ export function cutSnippet(s, n) {
24
+ if (n <= 0)
25
+ return "";
26
+ if (s.length <= n)
27
+ return s;
28
+ const high = (s.charCodeAt(n - 1) & 0xfc00) === 0xd800;
29
+ const head = s.slice(0, high ? n - 1 : n);
30
+ const space = head.lastIndexOf(" ");
31
+ return `${(space > n / 2 ? head.slice(0, space) : head).trimEnd()}…`;
32
+ }
33
+ /** The most passages one snippet is cut into for a "best" pick. */
34
+ export const SNIPPET_PASSAGES_MAX = 24;
35
+ /** `snippet` as passages of at most `size` characters, in order: its sentences and lines packed together, a sentence
36
+ * longer than `size` cut on a word. Its excerpts (Parallel and Exa join theirs with " … ") stay apart: two packed into
37
+ * one passage are joined with " … " again, never run together. At most SNIPPET_PASSAGES_MAX (the rest dropped). */
38
+ export function passagesOfSnippet(snippet, size) {
39
+ const pieces = snippet.split(/\s…\s/).flatMap((excerpt, e) => excerpt
40
+ .split(/\n+/)
41
+ .flatMap((part) => part.split(/(?<=[.!?])\s+/))
42
+ .map((one) => one.trim())
43
+ .filter(Boolean)
44
+ .flatMap((one) => {
45
+ const out = [];
46
+ let rest = one;
47
+ while (rest.length > size) {
48
+ const head = cutSnippet(rest, size).replace(/…$/, "");
49
+ out.push(head);
50
+ rest = rest.slice(head.length).trimStart();
51
+ }
52
+ if (rest)
53
+ out.push(rest);
54
+ return out;
55
+ })
56
+ .map((text) => ({ text, e })));
57
+ const passages = [];
58
+ let lastExcerpt = -1;
59
+ for (const { text, e } of pieces) {
60
+ const last = passages.at(-1);
61
+ const gap = e === lastExcerpt ? " " : " … ";
62
+ if (last !== undefined && last.length + gap.length + text.length <= size)
63
+ passages[passages.length - 1] = `${last}${gap}${text}`;
64
+ else
65
+ passages.push(text);
66
+ lastExcerpt = e;
67
+ }
68
+ return passages.slice(0, SNIPPET_PASSAGES_MAX);
69
+ }
package/dist/fees.d.ts CHANGED
@@ -44,15 +44,37 @@ export declare const EXA_SUMMARY_USD = 0.001;
44
44
  export declare function exaFeeOf(path: string, body: unknown): Fee | undefined;
45
45
  /** Firecrawl's price of a credit at the key's plan: Standard, $99 a month for 100,000 credits
46
46
  * (https://www.firecrawl.dev/pricing, read 2026-11-24; the plan's credits read from /v2/team/credit-usage that day).
47
- * Credits past the plan cost $5 per 2,000 ($0.0025). A search is 2 credits per 10 results, and a credit for each result
48
- * it scrapes; a scrape is 1 credit, and 4 more for the JSON format. */
47
+ * Credits past the plan cost $5 per 2,000 ($0.0025). Firecrawl's credit rule (https://docs.firecrawl.dev/billing, read
48
+ * 2026-11-28): a search is "2 credits / 10 results", "Rounded up per 10 results", and "Additional per-page scrape costs
49
+ * apply to each result that is scraped"; a scrape is "1 credit / page", a PDF "+1 credit / PDF page", JSON "+4 credits /
50
+ * page"; "Firecrawl returned no document: 0 credits". Measured on 2026-11-28 (17 calls, creditsUsed equal to the
51
+ * account's counter each time): a PDF is 1 credit a page parsed, not 1 more than its pages, and a result with no
52
+ * document is 0. */
49
53
  export declare const FIRECRAWL_CREDIT_USD = 0.00099;
50
54
  export declare const FIRECRAWL_SEARCH_CREDITS = 2;
51
55
  export declare const FIRECRAWL_SCRAPE_CREDITS = 1;
52
56
  export declare const FIRECRAWL_JSON_CREDITS = 4;
53
- /** The fee of a request to Firecrawl's `path` with `body`: a search's by its limit (10 by default) and whether it scrapes
54
- * its results, a scrape's by whether it asks for JSON. Undefined for an endpoint the web tools do not ask. */
57
+ /** The most pages Firecrawl parses of one PDF (its parsers' maxPages bound): a body that caps none is held at it. */
58
+ export declare const FIRECRAWL_PDF_PAGES_MAX = 10000;
59
+ /** The fee of a request to Firecrawl's `path` with `body`, its hold: the most it may cost under the body's caps. A search
60
+ * is 2 credits per 10 of its limit (10 by default), rounded up, and, when it scrapes its results, each result at the
61
+ * most one scraped document may cost (documentCredits); a scrape is one document's most. What it is charged is the
62
+ * credits Firecrawl reports, never above this (firecrawlChargeOf). Undefined for an endpoint the web tools do not ask,
63
+ * and for a body asking a proxy other than basic (a search for its results, a scrape for its page). */
55
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):
66
+ * a search's top-level creditsUsed, a scrape's data.metadata.creditsUsed; undefined unless a whole number, 0 or more. */
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): {
71
+ usd: number;
72
+ basis: string;
73
+ };
74
+ /** `charged`, carrying `said`, the receipt's words for its charge (undefined until there is one). */
75
+ export declare const chargedSaying: (charged: () => number, said: () => string | undefined) => (() => number);
76
+ /** The receipt's words `charged` carries (chargedSaying), if any. */
77
+ export declare const chargedSaid: (charged: (() => number) | undefined) => string | undefined;
56
78
  /** A paid request that was not sent: the run's cap refused it, or it has no price here. Its message says why, in the
57
79
  * cap's words. */
58
80
  export declare class PaidRefused extends Error {
package/dist/fees.js CHANGED
@@ -70,28 +70,79 @@ export function exaFeeOf(path, body) {
70
70
  }
71
71
  /** Firecrawl's price of a credit at the key's plan: Standard, $99 a month for 100,000 credits
72
72
  * (https://www.firecrawl.dev/pricing, read 2026-11-24; the plan's credits read from /v2/team/credit-usage that day).
73
- * Credits past the plan cost $5 per 2,000 ($0.0025). A search is 2 credits per 10 results, and a credit for each result
74
- * it scrapes; a scrape is 1 credit, and 4 more for the JSON format. */
73
+ * Credits past the plan cost $5 per 2,000 ($0.0025). Firecrawl's credit rule (https://docs.firecrawl.dev/billing, read
74
+ * 2026-11-28): a search is "2 credits / 10 results", "Rounded up per 10 results", and "Additional per-page scrape costs
75
+ * apply to each result that is scraped"; a scrape is "1 credit / page", a PDF "+1 credit / PDF page", JSON "+4 credits /
76
+ * page"; "Firecrawl returned no document: 0 credits". Measured on 2026-11-28 (17 calls, creditsUsed equal to the
77
+ * account's counter each time): a PDF is 1 credit a page parsed, not 1 more than its pages, and a result with no
78
+ * document is 0. */
75
79
  export const FIRECRAWL_CREDIT_USD = 0.00099;
76
80
  export const FIRECRAWL_SEARCH_CREDITS = 2;
77
81
  export const FIRECRAWL_SCRAPE_CREDITS = 1;
78
82
  export const FIRECRAWL_JSON_CREDITS = 4;
83
+ /** The most pages Firecrawl parses of one PDF (its parsers' maxPages bound): a body that caps none is held at it. */
84
+ export const FIRECRAWL_PDF_PAGES_MAX = 10_000;
79
85
  /** Whether a scrape's `formats` asks for JSON (a string or an object of that type). */
80
86
  const asksJson = (formats) => Array.isArray(formats) && formats.some((format) => format === "json" || (typeof format === "object" && format !== null && format.type === "json"));
81
- /** The fee of a request to Firecrawl's `path` with `body`: a search's by its limit (10 by default) and whether it scrapes
82
- * its results, a scrape's by whether it asks for JSON. Undefined for an endpoint the web tools do not ask. */
87
+ /** The most pages `parsers` lets Firecrawl parse of a PDF: its pdf parser's maxPages, else Firecrawl's own most. */
88
+ const pdfPagesOf = (parsers) => {
89
+ const pdf = Array.isArray(parsers) ? parsers.find((one) => typeof one === "object" && one !== null && one.type === "pdf") : undefined;
90
+ const pages = pdf?.maxPages;
91
+ return typeof pages === "number" && Number.isInteger(pages) && pages >= 1 ? Math.min(pages, FIRECRAWL_PDF_PAGES_MAX) : FIRECRAWL_PDF_PAGES_MAX;
92
+ };
93
+ /** The most credits one document scraped under `options` may cost (an HTML page 1, a PDF 1 a page up to its cap, JSON
94
+ * 4 more), or undefined when it asks a proxy other than basic: an escalated proxy is priced nowhere here, so a body
95
+ * asking one (or leaving it to Firecrawl's own "auto") is never sent. */
96
+ const documentCredits = (options) => options.proxy !== "basic" ? undefined : Math.max(FIRECRAWL_SCRAPE_CREDITS, pdfPagesOf(options.parsers)) + (asksJson(options.formats) ? FIRECRAWL_JSON_CREDITS : 0);
97
+ /** The fee of a request to Firecrawl's `path` with `body`, its hold: the most it may cost under the body's caps. A search
98
+ * is 2 credits per 10 of its limit (10 by default), rounded up, and, when it scrapes its results, each result at the
99
+ * most one scraped document may cost (documentCredits); a scrape is one document's most. What it is charged is the
100
+ * credits Firecrawl reports, never above this (firecrawlChargeOf). Undefined for an endpoint the web tools do not ask,
101
+ * and for a body asking a proxy other than basic (a search for its results, a scrape for its page). */
83
102
  export function firecrawlFeeOf(path, body) {
84
103
  const asked = (body ?? {});
85
104
  const fee = (name, credits, basis) => ({ name, by: "firecrawl", usd: usd(FIRECRAWL_CREDIT_USD * credits), basis: `${basis}: ${credits} credit${credits === 1 ? "" : "s"} at the key's plan price` });
86
105
  if (path === "/v2/search") {
87
106
  const n = typeof asked.limit === "number" && asked.limit > 0 ? Math.floor(asked.limit) : 10;
88
- const scraped = asked.scrapeOptions ? n * (FIRECRAWL_SCRAPE_CREDITS + (asksJson(asked.scrapeOptions.formats) ? FIRECRAWL_JSON_CREDITS : 0)) : 0;
89
- return fee("Firecrawl's search", FIRECRAWL_SEARCH_CREDITS * Math.ceil(n / 10) + scraped, `Firecrawl's list price for a search of ${n} results${scraped ? ", each scraped" : ""}`);
107
+ const each = asked.scrapeOptions ? documentCredits(asked.scrapeOptions) : 0;
108
+ if (each === undefined)
109
+ return undefined;
110
+ return fee("Firecrawl's search", FIRECRAWL_SEARCH_CREDITS * Math.ceil(n / 10) + n * each, `Firecrawl's most for a search of ${n} results${each ? `, each scraped at up to ${each} credit${each === 1 ? "" : "s"}` : ""}`);
111
+ }
112
+ if (path === "/v2/scrape") {
113
+ const most = documentCredits(asked);
114
+ return most === undefined ? undefined : fee("Firecrawl's scrape", most, "Firecrawl's most for a scrape");
90
115
  }
91
- if (path === "/v2/scrape")
92
- return fee("Firecrawl's scrape", FIRECRAWL_SCRAPE_CREDITS + (asksJson(asked.formats) ? FIRECRAWL_JSON_CREDITS : 0), "Firecrawl's list price for a scrape");
93
116
  return undefined;
94
117
  }
118
+ /** The credits Firecrawl reports a 2xx answer to `path` cost (`json`, its parsed body; undefined when it was not JSON):
119
+ * a search's top-level creditsUsed, a scrape's data.metadata.creditsUsed; undefined unless a whole number, 0 or more. */
120
+ export function firecrawlCreditsOf(path, json) {
121
+ const said = path === "/v2/search" ? json?.creditsUsed : json?.data?.metadata?.creditsUsed;
122
+ return typeof said === "number" && Number.isInteger(said) && said >= 0 ? said : undefined;
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) {
127
+ const hold = Math.round(fee.usd / FIRECRAWL_CREDIT_USD);
128
+ const plural = (n) => `${n} credit${n === 1 ? "" : "s"}`;
129
+ const reported = firecrawlCreditsOf(path, json);
130
+ if (reported === undefined)
131
+ return { usd: fee.usd, basis: `the hold, ${plural(hold)}; Firecrawl reported no credit count` };
132
+ const charged = usd(FIRECRAWL_CREDIT_USD * reported);
133
+ if (charged > fee.usd)
134
+ return { usd: fee.usd, basis: `the hold, ${plural(hold)}; Firecrawl reported ${plural(reported)}` };
135
+ return { usd: charged, basis: `Firecrawl reported ${plural(reported)} (hold ${plural(hold)}), at the key's plan price` };
136
+ }
137
+ /** The words a Pay's `charged` carries for the receipt's line (chargedSaying): what a request was charged, and why. */
138
+ const chargedWords = new WeakMap();
139
+ /** `charged`, carrying `said`, the receipt's words for its charge (undefined until there is one). */
140
+ export const chargedSaying = (charged, said) => {
141
+ chargedWords.set(charged, said);
142
+ return charged;
143
+ };
144
+ /** The receipt's words `charged` carries (chargedSaying), if any. */
145
+ export const chargedSaid = (charged) => (charged ? chargedWords.get(charged)?.() : undefined);
95
146
  /** A paid request that was not sent: the run's cap refused it, or it has no price here. Its message says why, in the
96
147
  * cap's words. */
97
148
  export class PaidRefused extends Error {
package/dist/index.d.ts CHANGED
@@ -21,3 +21,4 @@ export { type InjectionVerdict, type WallVerdict, INJECTION_THRESHOLD, WALL_THRE
21
21
  export { PASSAGES_MAX, passagesOf } from "./decide/passages.js";
22
22
  export { DECIDE_MS, decisionPay, type DecisionRecord, type Scored, type Sift, type StepOptions, THRESHOLD } from "./decide/record.js";
23
23
  export { type DecidePolicy, LOW_RELEVANCE, siftSearch } from "./decide/search.js";
24
+ export { DEFAULT_JEV_SETUP, type FetchSetup, JEV_SETUPS, type JevSetup, type SearchSetup } from "./decide/setup.js";
package/dist/index.js CHANGED
@@ -26,3 +26,4 @@ export { INJECTION_THRESHOLD, WALL_THRESHOLD } from "./decide/page-guard.js";
26
26
  export { PASSAGES_MAX, passagesOf } from "./decide/passages.js";
27
27
  export { DECIDE_MS, decisionPay, THRESHOLD } from "./decide/record.js";
28
28
  export { LOW_RELEVANCE, siftSearch } from "./decide/search.js";
29
+ export { DEFAULT_JEV_SETUP, JEV_SETUPS } from "./decide/setup.js";
@@ -11,7 +11,9 @@ export declare const FIRECRAWL_KEYED_MS = 60000;
11
11
  * - `tbs`: a search's time filter in Firecrawl's words ("qdr:d" the past day, "qdr:w" the past week, ...); unset, none;
12
12
  * - `includeDomains` or `excludeDomains` (not both): the hostnames a search keeps to or leaves out;
13
13
  * - `country`: the country a search is made from, ISO 3166-1 alpha-2; unset, Firecrawl's own (US);
14
- * - `highlights`: each result's description is its query-relevant highlight; unset, Firecrawl's own (true). */
14
+ * - `highlights`: each result's description is its query-relevant highlight; unset, Firecrawl's own (true);
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). */
15
17
  export type FirecrawlSettings = {
16
18
  onlyMainContent?: boolean;
17
19
  maxAgeMs?: number;
@@ -20,6 +22,7 @@ export type FirecrawlSettings = {
20
22
  excludeDomains?: string[];
21
23
  country?: string;
22
24
  highlights?: boolean;
25
+ pdfMaxPages?: number;
23
26
  };
24
27
  export declare const FIRECRAWL_DEFAULTS: Readonly<{
25
28
  readonly onlyMainContent: true;
@@ -29,8 +32,8 @@ export declare function firecrawlSettingsProblems(settings: unknown): string[];
29
32
  export declare const firecrawlClient: (apiKey: string, send?: typeof fetch, pay?: Pay, base?: string) => Keyed;
30
33
  /** How many of a search's queries Firecrawl is sent: one request each, at once. */
31
34
  export declare const FIRECRAWL_QUERIES_MAX = 3;
32
- /** The scrape a Firecrawl search asks of each result, as Firecrawl's guidance for agents asks: its page as markdown, its
33
- * main content alone unless `settings` say otherwise (each a scrape, priced by fees.ts firecrawlFeeOf). */
35
+ /** The scrape keyless Firecrawl's search asks of each result, as Firecrawl's guidance for agents asks: its page as
36
+ * markdown, its main content alone unless `settings` say otherwise. A keyed search asks none (firecrawlSearchBody). */
34
37
  export declare const firecrawlScrapeOptions: (settings?: FirecrawlSettings) => {
35
38
  formats: string[];
36
39
  onlyMainContent: boolean;
@@ -48,17 +51,20 @@ export declare const firecrawlQueries: ({ queries, n }: SearchAsk) => {
48
51
  * with none answered, the first failure in query order. The most binding limit any request met (a quota over a rate
49
52
  * limit, else the longest wait) goes to the run's breaker either way, typed as the failure that met it. */
50
53
  export declare function firecrawlMerged(provider: "firecrawl" | "firecrawl-keyless", { objective, queries, n }: SearchAsk, each: readonly (Hit[] | Failed)[]): Searched;
51
- /** The /v2/search request for `query`, `n` results, under `settings`: each result scraped (firecrawlScrapeOptions). */
54
+ /** The /v2/search request for `query`, `n` results, under `settings`. It asks no scrape of its results: each result's
55
+ * snippet is Firecrawl's description of it (its query-relevant highlight unless `highlights` is false), as Exa's
56
+ * highlights and Parallel's excerpts are, and the search is Firecrawl's 2 credits per 10 results alone. */
52
57
  export declare function firecrawlSearchBody(query: string, n: number, settings?: FirecrawlSettings): Record<string, unknown>;
53
58
  /** `{objective, queries?, n?}` (searchArgs) searched through `client` (null: the run holds no key) under `settings`:
54
59
  * up to FIRECRAWL_QUERIES_MAX of its queries, one paid request each, all at once, merged (firecrawlMerged), and the
55
60
  * limit Firecrawl answered for the run's key, if any. */
56
61
  export declare function firecrawlSearched(args: Record<string, unknown>, client: Keyed | null, settings?: FirecrawlSettings, signal?: AbortSignal): Promise<Searched>;
57
- /** The /v2/scrape request for `url` under `settings`: markdown alone. */
62
+ /** The /v2/scrape request for `url` under `settings`: markdown alone, on the basic proxy, a PDF to pdfMaxPages when set. */
58
63
  export declare function firecrawlScrapeBody(url: string, settings?: FirecrawlSettings): Record<string, unknown>;
59
64
  /** A page Firecrawl scraped for `url` (`page`, its scrape's `{markdown, metadata}`, keyed or keyless alike) as a Read:
60
65
  * 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
66
+ * A PDF Firecrawl parsed only part of (metadata numPages below totalPages) says so at the head of its text, and is
67
+ * read as cut; any other page's text is read as the whole page's. No markdown is no text, and a page whose status is
62
68
  * not 2xx is no read. */
63
69
  export declare function firecrawlPageOf(url: string, page: {
64
70
  markdown?: unknown;
@@ -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 { firecrawlFeeOf } from "../fees.js";
5
+ import { firecrawlChargeOf, firecrawlFeeOf } 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";
@@ -19,6 +19,7 @@ const FIRECRAWL_CHECKS = {
19
19
  excludeDomains: domains(100),
20
20
  country: matching(/^[A-Z]{2}$/, "a two-letter country code, such as \"US\""),
21
21
  highlights: yesNo,
22
+ pdfMaxPages: wholeIn(1, 10_000),
22
23
  };
23
24
  export function firecrawlSettingsProblems(settings) {
24
25
  const problems = settingsProblems("Firecrawl", settings, FIRECRAWL_CHECKS);
@@ -28,12 +29,15 @@ export function firecrawlSettingsProblems(settings) {
28
29
  return problems;
29
30
  }
30
31
  /** Firecrawl on `apiKey`, each request paid through `pay`. */
31
- export const firecrawlClient = (apiKey, send = fetch, pay, base = FIRECRAWL_API_URL) => keyedClient({ who: "Firecrawl", base, headers: { authorization: `Bearer ${apiKey}` }, feeOf: firecrawlFeeOf, 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, timeoutMs: FIRECRAWL_KEYED_MS, refuseOn: [401] }, send, pay);
32
33
  /** How many of a search's queries Firecrawl is sent: one request each, at once. */
33
34
  export const FIRECRAWL_QUERIES_MAX = 3;
34
- /** The scrape a Firecrawl search asks of each result, as Firecrawl's guidance for agents asks: its page as markdown, its
35
- * main content alone unless `settings` say otherwise (each a scrape, priced by fees.ts firecrawlFeeOf). */
35
+ /** The scrape keyless Firecrawl's search asks of each result, as Firecrawl's guidance for agents asks: its page as
36
+ * markdown, its main content alone unless `settings` say otherwise. A keyed search asks none (firecrawlSearchBody). */
36
37
  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 }] }) });
37
41
  /** Firecrawl's search rows, an answer's `data` or its `data.web`, as hits: each row whose url parses, its snippet its
38
42
  * page's markdown, else its description; undefined where the answer holds no rows this server reads. */
39
43
  export function firecrawlHits(data) {
@@ -83,12 +87,13 @@ export function firecrawlMerged(provider, { objective, queries, n }, each) {
83
87
  const results = answered.flat().filter((hit) => !seen.has(hit.url) && Boolean(seen.add(hit.url))).slice(0, n);
84
88
  return { answer: { provider, objective, queries, results }, ...held };
85
89
  }
86
- /** The /v2/search request for `query`, `n` results, under `settings`: each result scraped (firecrawlScrapeOptions). */
90
+ /** The /v2/search request for `query`, `n` results, under `settings`. It asks no scrape of its results: each result's
91
+ * snippet is Firecrawl's description of it (its query-relevant highlight unless `highlights` is false), as Exa's
92
+ * highlights and Parallel's excerpts are, and the search is Firecrawl's 2 credits per 10 results alone. */
87
93
  export function firecrawlSearchBody(query, n, settings = {}) {
88
94
  return {
89
95
  query,
90
96
  limit: n,
91
- scrapeOptions: firecrawlScrapeOptions(settings),
92
97
  ...(settings.tbs ? { tbs: settings.tbs } : {}),
93
98
  ...(settings.includeDomains ? { includeDomains: settings.includeDomains } : {}),
94
99
  ...(settings.excludeDomains ? { excludeDomains: settings.excludeDomains } : {}),
@@ -112,13 +117,14 @@ export async function firecrawlSearched(args, client, settings = {}, signal) {
112
117
  }));
113
118
  return firecrawlMerged("firecrawl", ask, each);
114
119
  }
115
- /** The /v2/scrape request for `url` under `settings`: markdown alone. */
120
+ /** The /v2/scrape request for `url` under `settings`: markdown alone, on the basic proxy, a PDF to pdfMaxPages when set. */
116
121
  export function firecrawlScrapeBody(url, settings = {}) {
117
- return { url, formats: ["markdown"], onlyMainContent: settings.onlyMainContent ?? FIRECRAWL_DEFAULTS.onlyMainContent, ...(settings.maxAgeMs === undefined ? {} : { maxAge: settings.maxAgeMs }) };
122
+ return { url, formats: ["markdown"], onlyMainContent: settings.onlyMainContent ?? FIRECRAWL_DEFAULTS.onlyMainContent, ...(settings.maxAgeMs === undefined ? {} : { maxAge: settings.maxAgeMs }), ...keyedRead(settings.pdfMaxPages) };
118
123
  }
119
124
  /** A page Firecrawl scraped for `url` (`page`, its scrape's `{markdown, metadata}`, keyed or keyless alike) as a Read:
120
125
  * 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
126
+ * A PDF Firecrawl parsed only part of (metadata numPages below totalPages) says so at the head of its text, and is
127
+ * read as cut; any other page's text is read as the whole page's. No markdown is no text, and a page whose status is
122
128
  * not 2xx is no read. */
123
129
  export function firecrawlPageOf(url, page) {
124
130
  if (typeof page.markdown !== "string" || page.markdown.trim() === "")
@@ -129,7 +135,9 @@ export function firecrawlPageOf(url, page) {
129
135
  if (status < 200 || status > 299)
130
136
  return failed("error", `PAGE_${status}`, `Firecrawl's fetch: the page answered ${status}`);
131
137
  const title = typeof meta.title === "string" ? meta.title : Array.isArray(meta.title) && typeof meta.title[0] === "string" ? meta.title[0] : "";
132
- return markdownRead(final, title, page.markdown, true, status);
138
+ const whole = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
139
+ const cut = whole(meta.numPages) && whole(meta.totalPages) && meta.numPages < meta.totalPages ? `[PDF: pages 1-${meta.numPages} of ${meta.totalPages} were read; pages ${meta.numPages + 1}-${meta.totalPages} are not in this text]\n\n` : "";
140
+ return markdownRead(final, title, cut + page.markdown, !cut, status);
133
141
  }
134
142
  /** The page at `url` scraped through `client` under `settings` (firecrawlPageOf), or why there is none. */
135
143
  export async function firecrawlRead(url, client, settings = {}, signal) {
@@ -12,7 +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. */
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. */
16
18
  export type KeyedSpec = {
17
19
  who: string;
18
20
  base: string;
@@ -20,8 +22,12 @@ export type KeyedSpec = {
20
22
  feeOf: (path: string, body: unknown) => Fee | undefined;
21
23
  timeoutMs: number;
22
24
  refuseOn: readonly number[];
25
+ chargeOf?: (fee: Fee, path: string, json: unknown) => {
26
+ usd: number;
27
+ basis: string;
28
+ };
23
29
  };
24
- export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
30
+ export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
25
31
  /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
26
32
  * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
27
33
  * that failed connecting (its cause's code, UNSENT_CODES, a certificate's CERT_* or a handshake's ERR_TLS_*). Anything
@@ -32,7 +38,7 @@ export declare function unsentWhy(error: unknown, stoppedFirst: boolean): string
32
38
  * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
33
39
  * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
34
40
  * thrown inside `pay`, which books it at its fee. */
35
- export declare function paidSend(pay: Pay, fee: Fee, signal: AbortSignal | undefined, send: () => Promise<Response>): Promise<Response>;
41
+ export declare function paidSend(pay: Pay, fee: Fee, signal: AbortSignal | undefined, send: () => Promise<Response>, charged?: () => number): Promise<Response>;
36
42
  /** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
37
43
  export declare function statusLimit(response: Response): Limit | undefined;
38
44
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
@@ -3,12 +3,12 @@
3
3
  // spent (a quota) and a 429 a rate limit for its Retry-After, both for the run's breaker. A request on a stopped call is
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
- import { PaidRefused, unmetered, unsentAnswer } from "../fees.js";
6
+ import { chargedSaying, PaidRefused, unmetered, unsentAnswer } from "../fees.js";
7
7
  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 }, send = fetch, pay = unmetered) {
11
+ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn, chargeOf }, send = fetch, pay = unmetered) {
12
12
  let refused = false;
13
13
  const root = base.replace(/\/+$/, "");
14
14
  return {
@@ -18,6 +18,9 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn },
18
18
  const fee = feeOf(path, body);
19
19
  if (!fee)
20
20
  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.
22
+ let charge;
23
+ const charged = chargeOf ? chargedSaying(() => Math.min(charge?.usd ?? fee.usd, fee.usd), () => charge?.basis) : undefined;
21
24
  return paidSend(pay, fee, signal, async () => {
22
25
  const response = await send(`${root}${path}`, {
23
26
  method: "POST",
@@ -29,8 +32,17 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn },
29
32
  });
30
33
  if (refuseOn.includes(response.status))
31
34
  refused = true;
32
- return response;
33
- });
35
+ if (!chargeOf || !response.ok)
36
+ return response;
37
+ // 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);
40
+ const json = bytes === undefined ? undefined : parsed(bytes);
41
+ charge = chargeOf(fee, path, json);
42
+ const read = new Response(bytes === undefined ? null : new Uint8Array(bytes), { status: response.status, statusText: response.statusText, headers: response.headers });
43
+ readAhead.set(read, json);
44
+ return read;
45
+ }, charged);
34
46
  },
35
47
  };
36
48
  }
@@ -61,7 +73,7 @@ export function unsentWhy(error, stoppedFirst) {
61
73
  * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
62
74
  * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
63
75
  * thrown inside `pay`, which books it at its fee. */
64
- export async function paidSend(pay, fee, signal, send) {
76
+ export async function paidSend(pay, fee, signal, send, charged) {
65
77
  if (signal?.aborted)
66
78
  throw signal.reason;
67
79
  let unsent;
@@ -77,7 +89,7 @@ export async function paidSend(pay, fee, signal, send) {
77
89
  unsent = { error };
78
90
  return unsentAnswer(why);
79
91
  }
80
- });
92
+ }, charged);
81
93
  if (unsent) {
82
94
  const { error } = unsent;
83
95
  // Marked where it can be: a frozen or sealed error is thrown as it was, never replaced by the marking's own failure.
@@ -100,8 +112,9 @@ export function statusLimit(response) {
100
112
  }
101
113
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
102
114
  export const codeOf = (said) => (typeof said === "string" && /^[A-Z][A-Z0-9_]{2,63}$/.test(said) ? said : undefined);
103
- /** An answer's JSON, read to at most KEYED_MAX_BYTES; undefined when it runs past them or is not JSON. */
104
- async function jsonOf(response) {
115
+ /** 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
+ * read). */
117
+ async function bytesOf(response) {
105
118
  const reader = response.body?.getReader();
106
119
  if (!reader)
107
120
  return undefined;
@@ -118,12 +131,25 @@ async function jsonOf(response) {
118
131
  }
119
132
  chunks.push(value);
120
133
  }
134
+ return Buffer.concat(chunks);
135
+ }
136
+ /** `bytes` as JSON, or undefined when they are not. */
137
+ const parsed = (bytes) => {
121
138
  try {
122
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
139
+ return JSON.parse(bytes.toString("utf8"));
123
140
  }
124
141
  catch {
125
142
  return undefined;
126
143
  }
144
+ };
145
+ /** The parse of an answer a keyed client read ahead (keyedClient's chargeOf), so it is not parsed again. */
146
+ const readAhead = new WeakMap();
147
+ /** An answer's JSON, read to at most KEYED_MAX_BYTES; undefined when it runs past them or is not JSON. */
148
+ async function jsonOf(response) {
149
+ if (readAhead.has(response))
150
+ return readAhead.get(response);
151
+ const bytes = await bytesOf(response);
152
+ return bytes === undefined ? undefined : parsed(bytes);
127
153
  }
128
154
  /** The most of what a thrown error said that a failure quotes. */
129
155
  const THROWN_SAID_MAX = 300;
package/dist/search.js CHANGED
@@ -65,6 +65,8 @@ export function offUntil(limit, nowMs) {
65
65
  return ms === undefined ? Number.POSITIVE_INFINITY : nowMs + Math.max(ms, 0);
66
66
  return ms !== undefined && ms > MAX_WAIT_MS ? nowMs + ms : undefined;
67
67
  }
68
+ /** Of two holds, the one that ends last: a provider held by both may be asked again only when that one ends. */
69
+ const later = (a, b) => (!a ? b : !b ? a : b.until > a.until ? b : a);
68
70
  /** `ms` of a wait as searchBusy's seconds: rounded up, at least 1. */
69
71
  const busyFor = (ms) => ({ error: searchBusy(Math.max(1, Math.ceil(ms / 1_000))) });
70
72
  export function searchBreaker(now = Date.now) {
@@ -85,9 +87,7 @@ export function searchBreaker(now = Date.now) {
85
87
  };
86
88
  return {
87
89
  holding() {
88
- if (off())
89
- return { kind: offKind, until: offTill };
90
- return until > now() ? { kind: waitKind, until } : undefined;
90
+ return later(off() ? { kind: offKind, until: offTill } : undefined, until > now() ? { kind: waitKind, until } : undefined);
91
91
  },
92
92
  held,
93
93
  off,
@@ -171,6 +171,9 @@ export function searchArgs(args) {
171
171
  export const KEYLESS_SEARCH_MS = 60_000;
172
172
  /** What a call stopped before any backend was asked answers (searchInTurn): the keyless backends' words for a stop. */
173
173
  const SEARCH_STOPPED = "the search was stopped";
174
+ /** `name` held, in the model's words: out of quota or rate-limited, until its reset (UTC, to the second), or for the
175
+ * rest of the run where it named none. */
176
+ const heldWords = (name, holding) => `${name} is ${holding.kind === "quota" ? "out of quota" : "rate-limited"} ${Number.isFinite(holding.until) ? `until ${new Date(holding.until).toISOString().replace(/\.\d{3}Z$/, "Z")}` : "for the rest of this run"}`;
174
177
  /** Whether a search's answer holds nothing for the model: no results and no short answer of its own (`text`). */
175
178
  const emptyAnswer = (answer) => !("error" in answer) && !answer.results.length && !answer.text;
176
179
  /** A call's search through `backends` in turn, each behind its breaker, all under one deadline (`boundMs` or `signal`):
@@ -213,11 +216,29 @@ export async function searchInTurn(backends, breakerOf, signal, boundMs = KEYLES
213
216
  else
214
217
  last = answer;
215
218
  }
216
- if (empty)
217
- return empty;
218
219
  const breakers = backends.map((backend) => breakerOf(backend.name));
219
- if (breakers.every((breaker) => breaker.off()))
220
+ // Each backend held now (off, or waiting out a short rate limit), in the model's words: who, why, and when it may be
221
+ // asked again.
222
+ const offs = backends.flatMap((backend, i) => {
223
+ const holding = breakers[i].holding();
224
+ return holding ? [{ name: backend.name, holding }] : [];
225
+ });
226
+ // No results while a backend is held reads as "nothing exists": the answer says the search is short of it instead.
227
+ if (empty) {
228
+ const others = offs.filter(({ name }) => !("provider" in empty && empty.provider === name));
229
+ if (!others.length || "error" in empty)
230
+ return empty;
231
+ return { error: `${empty.provider} found no results, and ${others.map(({ name, holding }) => heldWords(name, holding)).join("; ")}; search again after that or answer from what you have` };
232
+ }
233
+ if (breakers.every((breaker) => breaker.off())) {
234
+ // A hold with a named reset says so; one with none keeps SEARCH_UNAVAILABLE, as does a lone backend's own words.
235
+ const named = offs.some(({ holding }) => Number.isFinite(holding.until));
236
+ if (backends.length === 1 && last && !("error" in last && last.error === SEARCH_UNAVAILABLE))
237
+ return last;
238
+ if (named)
239
+ return { error: `search is unavailable: ${offs.map(({ name, holding }) => heldWords(name, holding)).join("; ")}; answer from what you have` };
220
240
  return backends.length === 1 && last ? last : { error: SEARCH_UNAVAILABLE };
241
+ }
221
242
  // A backend that turned off in this call while another only waits: the run's search is not off, so it waits.
222
243
  if (last && !("error" in last && last.error === SEARCH_UNAVAILABLE))
223
244
  return last;
@@ -235,7 +256,7 @@ export function withKeyBreaker(own, key) {
235
256
  },
236
257
  off: () => own.off() || key.off(),
237
258
  left: () => Math.max(own.left(), key.left()),
238
- holding: () => own.holding() ?? key.holding(),
259
+ holding: () => later(own.holding(), key.holding()),
239
260
  };
240
261
  }
241
262
  /** Breakers by backend name, made at first use: one run's (serve's webSearchTool), or one call's (its searchFor). */
package/dist/web.js CHANGED
@@ -6,7 +6,7 @@ import { guardPage } from "./decide/page-guard.js";
6
6
  import { decisionPay, heldOnRefusal } from "./decide/record.js";
7
7
  import { policyOf, siftSearch } from "./decide/search.js";
8
8
  import { missesOf, pageKey, sharedRead, webFetchText, webPart, webRead } from "./fetch.js";
9
- import { unmetered, unsentOf } from "./fees.js";
9
+ import { chargedSaid, unmetered, unsentOf } from "./fees.js";
10
10
  import { askedUrl, partProblem } from "./page.js";
11
11
  import { holdingWords, readerOf } from "./provider.js";
12
12
  import { kindOf } from "./providers/keyed.js";
@@ -149,6 +149,11 @@ export function createWeb(config) {
149
149
  });
150
150
  if (lines && at >= 0 && unsent !== undefined)
151
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})` };
152
+ // A provider that reports what an answer cost (keyed.ts chargeOf): the line is that charge, in its words, once the
153
+ // cap's settle is written; a settle that failed leaves it at the hold.
154
+ const said = unsent === undefined ? chargedSaid(charged) : undefined;
155
+ 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})` };
152
157
  return answer;
153
158
  };
154
159
  // Each provider an order names is made once per Web, at its first use, from the run's parts for it: one client a
@@ -210,8 +215,9 @@ export function createWeb(config) {
210
215
  const said = [asked.objective, asked.query].find((one) => typeof one === "string") ?? "";
211
216
  // A copy: a sift this call stopped waiting for may still pay, and its fee is not on this receipt.
212
217
  const spent = [...lines];
213
- // An empty search's receipt keeps the words it was given.
214
- const receipt = { op: "search", asked: ask.objective || said, queries: ask.queries, provider: "error" in answer ? null : answer.provider, tries, classifier, ...unjudged, out: outOf(searchText(answer)), cost: { usd: usd(spent), lines: spent }, ...unsifted(() => searchText(fitSearch(found))) };
218
+ // An empty search's receipt keeps the words it was given. One whose provider found nothing while another was held
219
+ // answers an error (searchInTurn), and its receipt still names the provider asked.
220
+ const receipt = { op: "search", asked: ask.objective || said, queries: ask.queries, provider: "error" in answer ? (tries.find(({ outcome }) => outcome === "empty")?.provider ?? null) : answer.provider, tries, classifier, ...unjudged, out: outOf(searchText(answer)), cost: { usd: usd(spent), lines: spent }, ...unsifted(() => searchText(fitSearch(found))) };
215
221
  return { answer, receipt };
216
222
  },
217
223
  // Only the call's part, resolver, transport, signal, task, objective and session are read: the guard, its bound, the order
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-web",
3
- "version": "0.1.0-beta.66",
3
+ "version": "0.1.0-beta.68",
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",
@@ -43,10 +43,10 @@
43
43
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
44
44
  },
45
45
  "dependencies": {
46
- "undici": "^8.12.2"
46
+ "undici": "^8.14.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@parcha/pi-browser": "0.1.0-beta.66"
49
+ "@parcha/pi-browser": "0.1.0-beta.68"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",