@parcha/agentrun-web 0.1.0-beta.64 → 0.1.0-beta.65

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
@@ -34,9 +34,19 @@ const page = await web.fetch("https://example.org/", { offset: 0, maxChars: 20_0
34
34
  not read, and the model is told why. `guard.check` decides which URLs go to Firecrawl and Parallel, so it must refuse
35
35
  every URL `guard.fetch` would refuse: a check that passes everything sends private and internal URLs to a provider.
36
36
  A guard is the Web's alone; one passed with a `fetch` call is ignored.
37
+ - A page's `links` come with its first part. A page a provider read as markdown (Parallel, Firecrawl, Exa) writes each of
38
+ its links in its text, so that part lists only the links its own text does not write, within the caps, and
39
+ `links_omitted` counts those of them the caps left out. A page fetched directly lists its link targets as before.
37
40
  - `keys.parallel` is Parallel's key. `pay(fee, send)` is the run's cap: it sends the request when the fee fits, or
38
- throws a `PaidRefused`. Without it, a request is unmetered.
39
- - `words.rateLimited` is what a keyless provider's rate limit says to the model.
41
+ throws a `PaidRefused`. Without it, a request is unmetered. A request on a call already stopped is never handed to
42
+ `pay`. One whose send failed before it left (stopped as the send began, or a fetch that failed connecting: a name
43
+ not resolved, a connection refused or not made, a TLS certificate or handshake refused) gives `pay` a 400 to settle at
44
+ $0, its receipt line says `not billed (not sent: <code>)`, and the call then fails as it would have. A cap books a 4xx
45
+ at nothing; any other failure stays at the fee.
46
+ - `words.rateLimited` is what a keyless provider's rate limit says to the model. A keyed provider's limit (Parallel's,
47
+ keyed Exa's or Firecrawl's 402 or 429, a hosted search's) says, on the call that met it as on every call it holds,
48
+ what its breaker says: that search is busy for the seconds left of its wait, or unavailable for the rest of the run;
49
+ the receipt's turn keeps the provider's words.
40
50
  - `native` is the model's own hosted search, as a function. `send` and `endpoints` replace a provider's fetch or
41
51
  address (a test's fakes). `now` is the breakers' clock. `bounds` sets the searches' deadlines. `log` receives what a
42
52
  fetch notes that the model is not told.
@@ -65,7 +75,8 @@ const page = await web.fetch("https://example.org/", { offset: 0, maxChars: 20_0
65
75
  Each call returns its `answer` and a `receipt`, `{ op, asked, queries?, provider, tries, classifier, wall, injection, out, cost,
66
76
  cache?, unsifted? }`. `asked` is a search's objective (the words given, when it has none) or a fetch's URL, and
67
77
  `queries` a search's queries. `tries` lists the providers asked before the call returned, in the order asked, with each outcome,
68
- and a provider its breaker holds as `held`. A fetch also lists Parallel where it was passed over (no key, refused
78
+ a search's provider that answered no results as `empty` (the call goes on to the next, and that answer returns only when
79
+ none after it has results), and a provider its breaker holds as `held`. A fetch also lists Parallel where it was passed over (no key, refused
69
80
  earlier in the run, or a URL it may not be sent), with why; a part from the run's pages lists none. `cost` holds the fees
70
81
  of the requests sent before the call returned. A fetch stopped at its signal returns at once, but its read is the run's
71
82
  and goes on: a provider asked after the stop is in neither; one whose request was already sent has its fee in `cost` but
@@ -118,9 +129,11 @@ const { answer, receipt } = await web.search({ objective: "Where Widgets, Inc. i
118
129
  in page order, `found: [{ offset, relevance, text }]` (`relevance` as on a labelled search result, none where
119
130
  refused), in place of `text` and the part's offsets, and its `sift` reads `"jev showed the 8 of 31 chunks of the page
120
131
  most likely to hold what your objective asks for (relevance 0 to 1), in page order; to read on from one, call
121
- web_fetch with its offset and no objective"`. `offset` and `maxChars` are not used. With no decider the answer is the
122
- part asked for, word for word as without an objective; with one that fails, the part asked for with `sift: "objective
123
- not applied (<why>); this part is in page order"`. The page is read once a run either way; a blank objective is none.
132
+ web_fetch with its offset and no objective"`. `offset` and `maxChars` are not used: where a call gives an offset past 0
133
+ or a `maxChars`, the `sift` line ends `"; offset ignored: found chunks come from the whole page, each with its
134
+ offset"` (`max_chars`, or `offset and max_chars`, as given). With no decider the answer is the part asked for, its
135
+ `sift` `"objective not applied (no classifier in this run); this part is in page order"`; with one that fails, the
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.
124
137
  - A fetched part is judged in passages (`passagesOf`: whole paragraphs packed to about 1,000 characters, at most 50).
125
138
  The kept ones stay in order, `LEFT_OUT` stands for each run left out, and the part's `chars`, `offset` and
126
139
  `next_offset` are unchanged. A fetch with no `task` is not judged.
@@ -157,7 +157,8 @@ export function jevWebDecider(jev) {
157
157
  if (typeof jev?.key !== "string" || jev.key.trim() === "")
158
158
  throw new TypeError("jevWebDecider needs TypeSafe's key, or null for no Jev");
159
159
  const provider = jev.jevProvider({ apiKey: jev.key, ...(jev.fetch ? { fetch: jev.fetch } : {}) });
160
- return { decider: deciderFrom(provider, { price: jev.price, model: JEV_MODEL }), policy: "rerank+label", model: JEV_MODEL };
160
+ // 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 };
161
162
  }
162
163
  export function deciderFrom(provider, options) {
163
164
  if (options?.price === null || typeof options?.price !== "object")
@@ -1,6 +1,6 @@
1
1
  import type { Fee, Pay } from "../fees.js";
2
2
  import type { WebPage, WebRead, WebUnread } from "../fetch.js";
3
- import { type Page } from "../page.js";
3
+ import { type Page, type Part } from "../page.js";
4
4
  import type { WebDecider } from "./decider.js";
5
5
  import type { PageGuard, Warned } from "./page-guard.js";
6
6
  import { type DecisionRecord, type Sift, type Sifted, type StepOptions } from "./record.js";
@@ -34,18 +34,20 @@ export type FoundPage = Pick<Page, "ok" | "url" | "status" | "title" | "original
34
34
  export declare function findInPage(decider: WebDecider, url: string, read: WebRead, need: string, options: StepOptions): 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
- /** How a fetch is decided: the call's `task` and `objective`, the step's bounds, `pay` and the call's fee `lines`, and
38
- * `guard`, the run's page guard for this read (absent when it is off). */
39
- export type FetchStep = Pick<StepOptions, "task" | "signal" | "ms"> & {
37
+ /** How a fetch is decided: the call's `task` and `objective`, the part it asked for (`offset`, `maxChars`, as given), the
38
+ * step's bounds, `pay` and the call's fee `lines`, and `guard`, the run's page guard for this read (absent when it is
39
+ * off). */
40
+ export type FetchStep = Pick<StepOptions, "task" | "signal" | "ms"> & Part & {
40
41
  objective?: unknown;
41
42
  pay: Pay;
42
43
  lines: Fee[];
43
44
  guard?: ((options: StepOptions) => Promise<PageGuard>) | undefined;
44
45
  };
45
- /** A fetch decided: with an `objective` and a decider, what findInPage finds in the whole page (or the part, saying the
46
- * objective was not applied, where the step fails); else the part judged against `task`; and the page guard asked
47
- * beside either, its warning added and its fee lines put after the step's once both have settled. With no decider the
48
- * part is the answer, an objective or none. */
46
+ /** A fetch decided: with an `objective` and a decider, what findInPage finds in the whole page, its sift line naming an
47
+ * offset past 0 or a max_chars the call gave as ignored (or the part, saying the objective was not applied, where the
48
+ * step fails); else the part judged against `task`; and the page guard asked beside either, its warning added and its
49
+ * fee lines put after the step's once both have settled. With no decider the part is the answer, its sift line saying
50
+ * an objective given was not applied. */
49
51
  export declare function decideFetch(decider: WebDecider | undefined, url: string, whole: WebRead | WebUnread, part: WebPage, options: FetchStep): Promise<{
50
52
  answer: FetchAnswer;
51
53
  classifier: DecisionRecord | "off";
@@ -1,4 +1,4 @@
1
- import { clip } from "../page.js";
1
+ import { clip, unwrittenLinks } from "../page.js";
2
2
  import { QUERY_MAX } from "../search.js";
3
3
  import { passagesOf } from "./passages.js";
4
4
  import { bounded, byScore, decisionPay, droppedOf, drops, failed, ran, relevanceOf, since, skipped } from "./record.js";
@@ -68,10 +68,11 @@ export async function findInPage(decider, url, read, need, options) {
68
68
  };
69
69
  return { answer, classifier: judged.record([], shown.length) };
70
70
  }
71
- /** A fetch decided: with an `objective` and a decider, what findInPage finds in the whole page (or the part, saying the
72
- * objective was not applied, where the step fails); else the part judged against `task`; and the page guard asked
73
- * beside either, its warning added and its fee lines put after the step's once both have settled. With no decider the
74
- * part is the answer, an objective or none. */
71
+ /** A fetch decided: with an `objective` and a decider, what findInPage finds in the whole page, its sift line naming an
72
+ * offset past 0 or a max_chars the call gave as ignored (or the part, saying the objective was not applied, where the
73
+ * step fails); else the part judged against `task`; and the page guard asked beside either, its warning added and its
74
+ * fee lines put after the step's once both have settled. With no decider the part is the answer, its sift line saying
75
+ * an objective given was not applied. */
75
76
  export async function decideFetch(decider, url, whole, part, options) {
76
77
  const step = { signal: options.signal, ms: options.ms, pay: decisionPay(options.pay, options.lines) };
77
78
  const guardLines = [];
@@ -82,11 +83,21 @@ export async function decideFetch(decider, url, whole, part, options) {
82
83
  let classifier = "off";
83
84
  if (need && whole.ok && whole.text && decider) {
84
85
  const found = await findInPage(decider, url, whole, need, step);
85
- answer = found.answer ?? notApplied(found.classifier.error.code);
86
+ // What it found is the whole page's, whatever part the call named: the sift line says which of the call's bounds
87
+ // that leaves aside, so a call reading on with an objective is not handed the same chunks as if they were new.
88
+ const ignored = [...(options.offset ? ["offset"] : []), ...(options.maxChars === undefined ? [] : ["max_chars"])];
89
+ answer = !found.answer ? notApplied(found.classifier.error.code) : ignored.length ? { ...found.answer, sift: `${found.answer.sift}; ${ignored.join(" and ")} ignored: found chunks come from the whole page, each with its offset` } : found.answer;
86
90
  classifier = found.classifier;
87
91
  }
88
- else if (decider)
92
+ else if (decider) {
89
93
  ({ answer, classifier } = await judgePart(decider, url, part, { task: options.task, ...step }));
94
+ // A first part that left passages out lists again the links only they wrote: what it lists is checked against the
95
+ // text the model is given, never the part before judging.
96
+ if (whole.ok && whole.written && !(part.offset ?? 0) && "text" in answer && answer.text !== part.text)
97
+ answer = { ...answer, ...unwrittenLinks(whole.written, answer.text) };
98
+ }
99
+ else if (need && whole.ok && whole.text)
100
+ answer = notApplied("no classifier in this run");
90
101
  const guard = await guarding;
91
102
  options.lines.push(...guardLines);
92
103
  if (guard?.warning)
package/dist/fees.d.ts CHANGED
@@ -4,8 +4,8 @@ export type ParallelSearchMode = "turbo" | "fast" | "basic" | "advanced";
4
4
  * `mode`: `turbo` or `fast` $1 per 1,000 requests, `basic` or `advanced` $5 per 1,000, each with 10 results included,
5
5
  * and each result past those 10 $1 per 1,000. Extract: $1 per 1,000 URLs. */
6
6
  export declare const PARALLEL_SEARCH_MODE_USD: Readonly<Record<ParallelSearchMode, number>>;
7
- /** A `fast` search's price: the mode the web tools search in (web-search.ts). */
8
- export declare const PARALLEL_SEARCH_USD = 0.001;
7
+ /** A `fast` search's price, the mode the web tools search in by default (parallel.ts PARALLEL_DEFAULTS). */
8
+ 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;
@@ -67,3 +67,6 @@ export declare class PaidRefused extends Error {
67
67
  export type Pay = (fee: Fee, send: () => Promise<Response>, charged?: () => number, settled?: (booked: boolean) => void) => Promise<Response>;
68
68
  /** No cap: the request is sent as it is. */
69
69
  export declare const unmetered: Pay;
70
+ export declare const unsentAnswer: (why: string) => Response;
71
+ /** Why `answer` stands for a request that never left (unsentAnswer); undefined for any answer a provider gave. */
72
+ export declare const unsentOf: (answer: Response) => string | undefined;
package/dist/fees.js CHANGED
@@ -4,8 +4,8 @@
4
4
  * `mode`: `turbo` or `fast` $1 per 1,000 requests, `basic` or `advanced` $5 per 1,000, each with 10 results included,
5
5
  * and each result past those 10 $1 per 1,000. Extract: $1 per 1,000 URLs. */
6
6
  export const PARALLEL_SEARCH_MODE_USD = Object.freeze({ turbo: 0.001, fast: 0.001, basic: 0.005, advanced: 0.005 });
7
- /** A `fast` search's price: the mode the web tools search in (web-search.ts). */
8
- export const PARALLEL_SEARCH_USD = 0.001;
7
+ /** A `fast` search's price, the mode the web tools search in by default (parallel.ts PARALLEL_DEFAULTS). */
8
+ export const PARALLEL_SEARCH_USD = PARALLEL_SEARCH_MODE_USD.fast;
9
9
  export const PARALLEL_SEARCH_RESULT_USD = 0.001;
10
10
  export const PARALLEL_SEARCH_INCLUDED = 10;
11
11
  export const PARALLEL_EXTRACT_USD = 0.001;
@@ -99,3 +99,13 @@ export class PaidRefused extends Error {
99
99
  }
100
100
  /** No cap: the request is sent as it is. */
101
101
  export const unmetered = (_fee, send) => send();
102
+ /** What a paid request's send gives its Pay when the request never left this process (keyed.ts paidSend): a 400, which
103
+ * a cap settles at $0 (a 4xx is booked at nothing), marked with why, so the receipt's line for it says so (unsentOf). */
104
+ const unsentAnswers = new WeakMap();
105
+ export const unsentAnswer = (why) => {
106
+ const answer = new Response(null, { status: 400 });
107
+ unsentAnswers.set(answer, why);
108
+ return answer;
109
+ };
110
+ /** Why `answer` stands for a request that never left (unsentAnswer); undefined for any answer a provider gave. */
111
+ export const unsentOf = (answer) => unsentAnswers.get(answer);
package/dist/fetch.d.ts CHANGED
@@ -18,9 +18,12 @@ export type WebPage = Page & Via;
18
18
  export type WebRead = Read & Via;
19
19
  /** A page web_fetch could not read, and how it tried. */
20
20
  export type WebUnread = Unread & Via;
21
- /** The pages a run reads, by the URL asked for, each from its read's start (so calls at once share it), the last used
22
- * last: at most PAGES_HELD of them. */
21
+ /** The pages a run reads, by the URL asked for as a page's key (pageKey), each from its read's start (so calls at once
22
+ * share it), the last used last: at most PAGES_HELD of them. */
23
23
  export type Pages = Map<string, Promise<WebRead | WebUnread>>;
24
+ /** The key `url` holds a run's page under (Pages): its href as parsed (a host's case and default port as one), with no
25
+ * fragment, which never reaches an HTTP server; a string that does not parse as it is. */
26
+ export declare function pageKey(url: string): string;
24
27
  /** The readers a read asks, by provider: each held or not, each read one page (provider.ts Reader). */
25
28
  export type Readers = Partial<Record<FetchProvider, Reader>>;
26
29
  /** The order a read takes when none is given: keyless Firecrawl, then Parallel, each where its reader is given, then the
@@ -49,12 +52,14 @@ export type WebFetchOptions = ReadOptions & Part & {
49
52
  log?: WebLog;
50
53
  tries?: Try[];
51
54
  };
52
- /** The page at `url` as read once a run: from `pages`, the run's, where it holds the URL (read, or being read), with no
53
- * request of its own; else read once (readOnce), kept there from the read's start. A read that fails leaves `pages`, so
54
- * a later call reads again. The read is the run's, not a caller's: no caller's signal reaches it (it keeps Parallel's
55
+ /** The page at `url` as read once a run: from `pages`, the run's, where it holds the URL's page (pageKey: read, or being
56
+ * read), with no request of its own; else read once (readOnce), kept there from the read's start. A read that fails
57
+ * leaves `pages`, so a later call reads again. The read is the run's, not a caller's: no caller's signal reaches it (it keeps Parallel's
55
58
  * and the fetch's own time limits), so one caller's stop never fails another's; each caller stops waiting at its own
56
59
  * signal (untilStopped). */
57
60
  export declare function webRead(url: unknown, { readers, pages, order, guard, checkMs, signal, log, tries, ...options }?: Omit<WebFetchOptions, keyof Part>): Promise<WebRead | WebUnread>;
61
+ /** The run's own read behind `read`: one a call shared under another fragment names it as its own, the same page. */
62
+ export declare const sharedRead: <R extends WebRead | WebUnread>(read: R) => R;
58
63
  /** The part `part` names of a page read once (webRead), as a WebPage, how it came after it; a read that failed as it is. */
59
64
  export declare function webPart(read: WebRead | WebUnread, part?: Part): WebPage;
60
65
  /** Why each provider asked ahead of the one that gave `page` gave none, by its id (Via), in the order they were asked. */
package/dist/fetch.js CHANGED
@@ -1,11 +1,20 @@
1
1
  import { unmetered } from "./fees.js";
2
- import { askedUrl, HTML_READ_CHARS, PAGE_READ_MAX_CHARS, partOfRead, TIMEOUT_MS, URL_MAX, withoutCredentials, withoutUserinfo } from "./page.js";
2
+ import { askedUrl, clip, HTML_READ_CHARS, PAGE_READ_MAX_CHARS, partOfRead, TIMEOUT_MS, URL_MAX, withoutCredentials, withoutUserinfo } from "./page.js";
3
3
  import { HELD_CODE, holdingWords } from "./provider.js";
4
4
  import { AHEAD, providerName, providerOf } from "./providers/registry.js";
5
5
  import { failure } from "./search.js";
6
6
  const PORTS = new Set(["", "80", "443"]);
7
7
  /** How many pages a run keeps what it read of (Pages): each at most PAGE_READ_MAX_CHARS characters of text. */
8
8
  export const PAGES_HELD = 8;
9
+ /** The key `url` holds a run's page under (Pages): its href as parsed (a host's case and default port as one), with no
10
+ * fragment, which never reaches an HTTP server; a string that does not parse as it is. */
11
+ export function pageKey(url) {
12
+ const parsed = URL.parse(url);
13
+ if (!parsed)
14
+ return url;
15
+ parsed.hash = "";
16
+ return parsed.href;
17
+ }
9
18
  /** The order a read takes when none is given: keyless Firecrawl, then Parallel, each where its reader is given, then the
10
19
  * guarded direct fetch. */
11
20
  export const FETCH_ORDER = ["firecrawl-keyless", "parallel", "direct"];
@@ -82,13 +91,13 @@ async function readOnce(url, { readers, order, guard, checkMs, options, log, tri
82
91
  // A read that met a limit is said by what holds the provider now, never by the provider's words for it.
83
92
  const holding = limit ? reader.holding?.() : undefined;
84
93
  const words = holding ? holdingWords(holding) : error;
94
+ // Every failed read's turn is recorded alike: its words cut at 300, the limit it met.
95
+ tries.push({ provider: id, outcome: "error", ...(error ? { error: error.slice(0, 300) } : {}), ...typed, ...(limit ? { limit } : {}) });
85
96
  if (shape.miss === "said") {
86
97
  said[id] = words;
87
- tries.push({ provider: id, outcome: "error", error, ...typed });
88
98
  continue;
89
99
  }
90
100
  said[id] = words.slice(0, 300);
91
- tries.push({ provider: id, outcome: "error", ...(error ? { error: error.slice(0, 300) } : {}), ...typed, ...(limit ? { limit } : {}) });
92
101
  if (shape.miss.when === "failed")
93
102
  log?.(shape.miss.log, { provider: id, said: error.slice(0, 300), ...(limit ? { limit: JSON.stringify(limit) } : {}) });
94
103
  else
@@ -129,17 +138,19 @@ function untilStopped(url, reading, signal) {
129
138
  reading.then((read) => (signal.removeEventListener("abort", onStop), resolve(read)), (error) => (signal.removeEventListener("abort", onStop), reject(error)));
130
139
  });
131
140
  }
132
- /** The page at `url` as read once a run: from `pages`, the run's, where it holds the URL (read, or being read), with no
133
- * request of its own; else read once (readOnce), kept there from the read's start. A read that fails leaves `pages`, so
134
- * a later call reads again. The read is the run's, not a caller's: no caller's signal reaches it (it keeps Parallel's
141
+ /** The page at `url` as read once a run: from `pages`, the run's, where it holds the URL's page (pageKey: read, or being
142
+ * read), with no request of its own; else read once (readOnce), kept there from the read's start. A read that fails
143
+ * leaves `pages`, so a later call reads again. The read is the run's, not a caller's: no caller's signal reaches it (it keeps Parallel's
135
144
  * and the fetch's own time limits), so one caller's stop never fails another's; each caller stops waiting at its own
136
145
  * signal (untilStopped). */
137
146
  export async function webRead(url, { readers = {}, pages, order = FETCH_ORDER, guard, checkMs = TIMEOUT_MS, signal, log, tries = [], ...options } = {}) {
138
- const named = typeof url === "string" ? url : undefined;
147
+ const named = typeof url === "string" ? pageKey(url) : undefined;
139
148
  let reading = named === undefined ? undefined : pages?.get(named);
140
149
  if (!reading) {
141
150
  const ending = order.filter((id) => !readers[id] && providerOf(id).fetch?.ends).map((id) => [id, endingReader(id, guard)]);
142
151
  const started = readOnce(url, { readers: { ...readers, ...Object.fromEntries(ending) }, order, guard, checkMs, options, log, tries });
152
+ if (typeof url === "string")
153
+ startedFor.set(started, url);
143
154
  if (pages && named !== undefined) {
144
155
  // Ahead of any caller's await, so no call sees a failed read kept.
145
156
  const drop = () => void (pages.get(named) === started && pages.delete(named));
@@ -154,7 +165,29 @@ export async function webRead(url, { readers = {}, pages, order = FETCH_ORDER, g
154
165
  pages.set(named, reading);
155
166
  trim(pages);
156
167
  }
157
- return untilStopped(url, reading, signal);
168
+ const from = startedFor.get(reading);
169
+ const read = await untilStopped(url, reading, signal);
170
+ return typeof url === "string" && from !== undefined && from !== url ? asAskedBy(read, from, url) : read;
171
+ }
172
+ /** The URL each read of a run's pages was started for. */
173
+ const startedFor = new WeakMap();
174
+ /** The run's read each renamed copy (asAskedBy) stands for. */
175
+ const copied = new WeakMap();
176
+ /** The run's own read behind `read`: one a call shared under another fragment names it as its own, the same page. */
177
+ export const sharedRead = (read) => copied.get(read) ?? read;
178
+ /** `read`, started for `from` and shared by `url` (the same page's key, pageKey), as a read of `url` would name it: the
179
+ * fragment `from` asked for, where the page names it, becomes the one `url` asks for. A page that names another
180
+ * fragment (a redirect's, or none) is as it is. */
181
+ function asAskedBy(read, from, url) {
182
+ const named = URL.parse(read.url);
183
+ const was = URL.parse(from);
184
+ const asked = URL.parse(url);
185
+ if (!named || !was || !asked || named.hash !== was.hash || named.hash === asked.hash || pageKey(read.url) !== pageKey(url))
186
+ return read;
187
+ named.hash = asked.hash;
188
+ const copy = { ...read, url: clip(named.href, URL_MAX) };
189
+ copied.set(copy, read);
190
+ return copy;
158
191
  }
159
192
  /** A provider that ends the order, made for one read through `guard`: never held. */
160
193
  function endingReader(id, guard) {
@@ -203,15 +236,18 @@ function partLine(page, name) {
203
236
  return `Nothing at offset=${start}: the page has ${page.original_chars} characters.`;
204
237
  return `Characters ${start}-${end} of ${page.original_chars}: the end of the page.`;
205
238
  }
206
- /** What answered after the providers ahead gave no page: the direct fetch, or nothing (Via: reasons are said only there). */
207
- function cameBy(via) {
208
- return via === "none" ? "no provider after it read the page" : "this one was fetched directly";
239
+ /** What answered after the providers ahead gave no page: the direct fetch, which read it or failed too, or nothing (Via:
240
+ * reasons are said only there). */
241
+ function cameBy(page) {
242
+ if (page.via === "none")
243
+ return "no provider after it read the page";
244
+ return page.ok ? "this one was fetched directly" : "the direct fetch failed too";
209
245
  }
210
246
  /** A page as the tool `name` answers the model: its JSON, then a line for each provider ahead that gave none saying why
211
247
  * and what gave the page instead, and one saying where this part is in the page when it is not all of it. */
212
248
  export function webFetchText(page, name = "web_fetch") {
213
249
  const lines = [JSON.stringify(page)];
214
- const came = cameBy(page.via);
250
+ const came = cameBy(page);
215
251
  for (const [id, why] of Object.entries(missesOf(page))) {
216
252
  if (why)
217
253
  lines.push(`${providerName(id)} gave no page (${why}); ${came}.`);
package/dist/page.d.ts CHANGED
@@ -48,6 +48,9 @@ export declare const HTML_READ_CHARS = 1000000;
48
48
  /** The most bytes of a page any path reads: the guarded direct fetch's bound (pi-browser's PUBLIC_MAX_BYTES, 5 MiB,
49
49
  * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. */
50
50
  export declare const PAGE_MAX_BYTES: number;
51
+ /** `text`'s first `max` UTF-16 units, one fewer where the cut would split a surrogate pair: the one pair-safe cut. */
52
+ export declare function cutAt(text: string, max: number): string;
53
+ /** `text` at most `max` units: whole when it fits, else cut (cutAt) with an ellipsis ending it. */
51
54
  export declare const clip: (text: string, max: number) => string;
52
55
  /** `text` with any URL in it stripped of its user name and password (`//user:pass@host` to `//host`). An error may quote
53
56
  * a URL that holds them (undici's refusal of a redirect to one quotes it whole). Run it on the whole text, before any
@@ -86,8 +89,7 @@ export type Text = {
86
89
  length?: number;
87
90
  };
88
91
  /** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
89
- * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
90
- * it would, it is one unit short. */
92
+ * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair (cutAt). */
91
93
  export declare function textOf(text: string, whole: boolean): Text;
92
94
  /** The part of a page's text an answer holds, and what it says of the rest. */
93
95
  export declare function pageText({ text, beyond, length }: Text, part?: Part): Pick<Page, "text" | "chars" | "truncated" | "original_chars" | "beyond_read" | "offset" | "next_offset">;
@@ -95,7 +97,9 @@ export declare function pageText({ text, beyond, length }: Text, part?: Part): P
95
97
  * left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
96
98
  export declare function linksWithin(links: Iterable<string>): Pick<Page, "links" | "links_omitted">;
97
99
  /** A page read once, before any part of it is taken: its final url, status and title, its Text, the links its first part
98
- * holds (linksWithin), and readPage's `html_chars` and `converted` where it gave them. */
100
+ * holds (linksWithin), and readPage's `html_chars` and `converted` where it gave them. `written`, where its text writes
101
+ * every link it holds (a reading service's markdown, writtenRead): each link the service's whole answer writes, before
102
+ * any cap or cut, from which its first part lists only those its own text does not write (unwrittenLinks). */
99
103
  export type Read = {
100
104
  ok: true;
101
105
  url: string;
@@ -105,13 +109,22 @@ export type Read = {
105
109
  links_omitted?: number;
106
110
  html_chars?: number;
107
111
  converted?: "text";
112
+ written?: readonly string[];
108
113
  } & Text;
109
114
  /** A Page that was not read, saying why. */
110
115
  export type Unread = Page & {
111
116
  ok: false;
112
117
  };
113
- /** The part `part` names of a page read once, as a Page: the links with its first part only. */
114
- export declare function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }: Read, part?: Part): Page;
118
+ /** The links of `written` (a Read's) that `text`, the part the model is given, does not write, within the caps
119
+ * (linksWithin), with the count the caps left out: a link the model reads in the text is never listed again beside it. */
120
+ export declare function unwrittenLinks(written: readonly string[], text: string): Pick<Page, "links" | "links_omitted">;
121
+ /** The part `part` names of a page read once, as a Page: the links with its first part only, and of a read whose text
122
+ * writes them (`written`) only those the part's own text does not write (unwrittenLinks). */
123
+ export declare function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, written, ...page }: Read, part?: Part): Page;
124
+ /** A page's text as a reading service gives it, as a Read's: textOf, the links its whole answer writes (linksWithin),
125
+ * and every one of them (`written`), the text's cut aside. */
126
+ export declare const writtenRead: (text: string, whole: boolean) => Pick<Read, "links" | "links_omitted" | "written"> & Text;
115
127
  /** A page a provider read for us as markdown (Parallel's extract, keyless Firecrawl's scrape), as a Read: its url,
116
- * title and status, the text (`whole`: all of the page's, so its length is the page's) and the links it holds. */
128
+ * title and status, the text (`whole`: all of the page's, so its length is the page's) and the links it holds, each
129
+ * written in its text (writtenRead). */
117
130
  export declare const markdownRead: (url: string, title: string, text: string, whole: boolean, status?: number) => Read;
package/dist/page.js CHANGED
@@ -24,7 +24,13 @@ export const HTML_READ_CHARS = 1_000_000;
24
24
  /** The most bytes of a page any path reads: the guarded direct fetch's bound (pi-browser's PUBLIC_MAX_BYTES, 5 MiB,
25
25
  * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. */
26
26
  export const PAGE_MAX_BYTES = 5 * 1024 * 1024;
27
- export const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
27
+ /** `text`'s first `max` UTF-16 units, one fewer where the cut would split a surrogate pair: the one pair-safe cut. */
28
+ export function cutAt(text, max) {
29
+ const split = (text.charCodeAt(max - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(max) & 0xfc00) === 0xdc00;
30
+ return text.slice(0, split ? max - 1 : max);
31
+ }
32
+ /** `text` at most `max` units: whole when it fits, else cut (cutAt) with an ellipsis ending it. */
33
+ export const clip = (text, max) => (text.length > max ? `${cutAt(text, max - 1)}…` : text);
28
34
  /** `text` with any URL in it stripped of its user name and password (`//user:pass@host` to `//host`). An error may quote
29
35
  * a URL that holds them (undici's refusal of a redirect to one quotes it whole). Run it on the whole text, before any
30
36
  * cut: a cut can end inside them, leaving no "@" for it to find. It reads on to the last "@" before the host, as a URL
@@ -90,12 +96,10 @@ export function partEnd(text, start, budget) {
90
96
  return at;
91
97
  }
92
98
  /** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
93
- * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
94
- * it would, it is one unit short. */
99
+ * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair (cutAt). */
95
100
  export function textOf(text, whole) {
96
101
  const beyond = text.length > PAGE_READ_MAX_CHARS;
97
- const split = (text.charCodeAt(PAGE_READ_MAX_CHARS - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(PAGE_READ_MAX_CHARS) & 0xfc00) === 0xdc00;
98
- return { text: beyond ? text.slice(0, PAGE_READ_MAX_CHARS - (split ? 1 : 0)) : text, beyond, ...(whole ? { length: text.length } : {}) };
102
+ return { text: beyond ? cutAt(text, PAGE_READ_MAX_CHARS) : text, beyond, ...(whole ? { length: text.length } : {}) };
99
103
  }
100
104
  /** The part of a page's text an answer holds, and what it says of the rest. */
101
105
  export function pageText({ text, beyond, length }, part = {}) {
@@ -133,11 +137,27 @@ export function linksWithin(links) {
133
137
  }
134
138
  return { links: kept, ...(omitted ? { links_omitted: omitted } : {}) };
135
139
  }
136
- /** The part `part` names of a page read once, as a Page: the links with its first part only. */
137
- export function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }, part = {}) {
140
+ /** The links of `written` (a Read's) that `text`, the part the model is given, does not write, within the caps
141
+ * (linksWithin), with the count the caps left out: a link the model reads in the text is never listed again beside it. */
142
+ export function unwrittenLinks(written, text) {
143
+ const inText = new Set(linksOf(text));
144
+ return linksWithin(written.filter((link) => !inText.has(link)));
145
+ }
146
+ /** The part `part` names of a page read once, as a Page: the links with its first part only, and of a read whose text
147
+ * writes them (`written`) only those the part's own text does not write (unwrittenLinks). */
148
+ export function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, written, ...page }, part = {}) {
138
149
  const first = partOf(part).offset === 0;
139
- return { ...page, ...pageText({ text, beyond, length }, part), ...(html_chars === undefined ? {} : { html_chars }), ...(converted ? { converted } : {}), links: first ? links : [], ...(first && links_omitted ? { links_omitted } : {}) };
150
+ const held = pageText({ text, beyond, length }, part);
151
+ const listed = !first ? { links: [] } : written ? unwrittenLinks(written, held.text) : { links, ...(links_omitted ? { links_omitted } : {}) };
152
+ return { ...page, ...held, ...(html_chars === undefined ? {} : { html_chars }), ...(converted ? { converted } : {}), ...listed };
140
153
  }
154
+ /** A page's text as a reading service gives it, as a Read's: textOf, the links its whole answer writes (linksWithin),
155
+ * and every one of them (`written`), the text's cut aside. */
156
+ export const writtenRead = (text, whole) => {
157
+ const written = [...linksOf(text)];
158
+ return { ...textOf(text, whole), ...linksWithin(written), written };
159
+ };
141
160
  /** A page a provider read for us as markdown (Parallel's extract, keyless Firecrawl's scrape), as a Read: its url,
142
- * title and status, the text (`whole`: all of the page's, so its length is the page's) and the links it holds. */
143
- export const markdownRead = (url, title, text, whole, status = 200) => ({ ok: true, url: clip(withoutCredentials(url), URL_MAX), status, title: clip(title, TITLE_CAP), ...textOf(text, whole), ...linksWithin(linksOf(text)) });
161
+ * title and status, the text (`whole`: all of the page's, so its length is the page's) and the links it holds, each
162
+ * written in its text (writtenRead). */
163
+ export const markdownRead = (url, title, text, whole, status = 200) => ({ ok: true, url: clip(withoutCredentials(url), URL_MAX), status, title: clip(title, TITLE_CAP), ...writtenRead(text, whole) });
@@ -2,7 +2,7 @@
2
2
  // once more after a short wait (a Retry-After of 5 s at most); still limited, it answers the caller's words, never Exa's.
3
3
  // Exa is dialled over IPv4 only, the one way it takes keyless use.
4
4
  import { lookup as dnsLookup } from "node:dns";
5
- import { clip, TITLE_CAP } from "../page.js";
5
+ import { clip, cutAt, TITLE_CAP } from "../page.js";
6
6
  import { defineProvider } from "../provider.js";
7
7
  import { bare, snippetOf } from "../search.js";
8
8
  import { callTool, RATE_LIMITED, sleep, textBlocks } from "./mcp.js";
@@ -19,7 +19,7 @@ const SAID_MAX = 120;
19
19
  function exaSaid(text) {
20
20
  const line = text.split("\n").map((part) => part.trim()).find(Boolean) ?? "";
21
21
  const sentence = /^.*?[.!?](?=\s|$)/.exec(line)?.[0] ?? line;
22
- const short = sentence.length <= SAID_MAX ? sentence : `${sentence.slice(0, SAID_MAX - 1).replace(/\s+\S*$/, "")}…`;
22
+ const short = sentence.length <= SAID_MAX ? sentence : `${cutAt(sentence, SAID_MAX - 1).replace(/\s+\S*$/, "")}…`;
23
23
  return short ? `Free web search failed. Exa said: "${short}"` : "Free web search failed: Exa gave no answer";
24
24
  }
25
25
  /** The `_meta` key Exa's MCP server marks a tool result reporting its free limit with (isError as well). */
@@ -76,6 +76,9 @@ function searchOf(called, { objective, queries, n }, rateLimited) {
76
76
  if (!Array.isArray(result?.content) || result.isError === true)
77
77
  return typed("error", "FAILED", { error: exaSaid(said) });
78
78
  const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
79
+ // Text that names no result this server reads is a failure, never an answer of no results: the call goes on.
80
+ if (!hits.length && said.trim())
81
+ return typed("error", "UNREADABLE", { error: "Exa's search answered no results this server reads" });
79
82
  return { provider: "exa-keyless", objective, queries, results: hits.slice(0, n) };
80
83
  }
81
84
  /** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
@@ -123,6 +126,7 @@ export const exaKeyless = defineProvider({ id: "exa-keyless", label: "Exa", keyl
123
126
  if (!("failure" in found))
124
127
  return { answer: found };
125
128
  const limit = "limit" in found ? exaLimitOf(found) : undefined;
126
- return { answer: { error: found.error }, failure: found.failure, ...(limit ? { limit } : {}) };
129
+ // Its limit's words (RATE_LIMITED, or the caller's) are the model's: the breaker passes them on (Searched.worded).
130
+ return { answer: { error: found.error }, failure: found.failure, ...(limit ? { limit, worded: true } : {}) };
127
131
  },
128
132
  }));
@@ -2,10 +2,9 @@
2
2
  // (fees.ts exaFeeOf) through the run's Pay, on the x-api-key header. Its settings are typed, each with a default
3
3
  // (EXA_DEFAULTS); a setting it does not take is refused when the Web is made. A 401 or 403 refuses the key for the run.
4
4
  import { EXA_SEARCH_TYPE_USD, exaFeeOf } from "../fees.js";
5
- import { clip, linksWithin, MAX_CHARS_MIN, PAGE_READ_MAX_CHARS, TITLE_CAP, textOf, URL_MAX, withoutCredentials } from "../page.js";
5
+ import { clip, MAX_CHARS_MIN, PAGE_READ_MAX_CHARS, TITLE_CAP, URL_MAX, withoutCredentials, writtenRead } from "../page.js";
6
6
  import { failed, failure, SNIPPET_MAX, searchArgs, searchFailed, snippetOf } from "../search.js";
7
7
  import { defineProvider, settingsOf } from "../provider.js";
8
- import { linksOf } from "../text-urls.js";
9
8
  import { codeOf, domains, keyedCall, keyedClient, oneOf, settingsProblems, wholeIn, yesNo } from "./keyed.js";
10
9
  export const EXA_API_URL = "https://api.exa.ai";
11
10
  /** Exa's bound on one request: a deep search takes tens of seconds. */
@@ -96,7 +95,7 @@ export async function exaRead(url, client, settings = {}, signal) {
96
95
  return failed("not_text", "NO_TEXT", "Exa's fetch answered no page text");
97
96
  const asked = PAGE_READ_MAX_CHARS + 1;
98
97
  // The page's url names no user name or password: cleared first, then cut, as every client's page url is.
99
- return { ok: true, url: clip(withoutCredentials(typeof row.url === "string" && URL.canParse(row.url) ? row.url : url), URL_MAX), status: 200, title: clip(typeof row.title === "string" ? row.title : "", TITLE_CAP), ...textOf(row.text, row.text.length < asked), ...linksWithin(linksOf(row.text)) };
98
+ return { ok: true, url: clip(withoutCredentials(typeof row.url === "string" && URL.canParse(row.url) ? row.url : url), URL_MAX), status: 200, title: clip(typeof row.title === "string" ? row.title : "", TITLE_CAP), ...writtenRead(row.text, row.text.length < asked) };
100
99
  }
101
100
  /** Exa on the run's key, both tools on one client. Its search keeps the caller's signal and its own bound (a paid request
102
101
  * is not cut short by the keyless providers' deadline); a fetch it gives no page is logged with the limit it met. With
@@ -107,6 +106,6 @@ export const exa = defineProvider({ id: "exa", label: "Exa", key: { env: "EXA_AP
107
106
  return {
108
107
  search: (ask, _deadline, signal) => exaSearched(ask, client, asked, signal),
109
108
  read: (url, { signal }) => exaRead(url, client, asked, signal),
110
- unready: () => (client && !client.live() ? failure("refused", "KEY_REFUSED", "not tried: refused earlier in this run") : undefined),
109
+ unready: () => (!client ? failure("refused", "NO_KEY", "not tried: this run holds no Exa key") : client.live() ? undefined : failure("refused", "KEY_REFUSED", "not tried: refused earlier in this run")),
111
110
  };
112
111
  });
@@ -169,8 +169,11 @@ export const firecrawlKeyless = defineProvider({ id: "firecrawl-keyless", label:
169
169
  return {
170
170
  async search(ask, deadline, _signal, called) {
171
171
  const firecrawlMs = called?.firecrawlMs ?? bounds?.firecrawlMs;
172
- // Which limit Firecrawl met is the breaker's to read, never the model's.
173
- return searchTyped(ask, { ...options, signal: deadline, ...(firecrawlMs === undefined ? {} : { timeoutMs: firecrawlMs }) });
172
+ // Which limit Firecrawl met is the breaker's to read, never the model's; the words it answers for one (limitWords,
173
+ // the caller's among them) are the model's, and the breaker passes them on (Searched.worded).
174
+ const searched = await searchTyped(ask, { ...options, signal: deadline, ...(firecrawlMs === undefined ? {} : { timeoutMs: firecrawlMs }) });
175
+ const limitSaid = searched.limit && (searched.failure?.class === "rate" || searched.failure?.class === "quota");
176
+ return limitSaid ? { ...searched, worded: true } : searched;
174
177
  },
175
178
  read: (url, { signal }) => scrapeTyped(url, { ...options, ...(signal ? { signal } : {}) }),
176
179
  };
@@ -140,6 +140,6 @@ export const firecrawl = defineProvider({ id: "firecrawl", label: "Firecrawl", k
140
140
  return {
141
141
  search: (ask, _deadline, signal) => firecrawlSearched(ask, client, asked, signal),
142
142
  read: (url, { signal }) => firecrawlRead(url, client, asked, signal),
143
- unready: () => (client && !client.live() ? failure("refused", "KEY_REFUSED", "not tried: refused earlier in this run") : undefined),
143
+ unready: () => (!client ? failure("refused", "NO_KEY", "not tried: this run holds no Firecrawl key") : client.live() ? undefined : failure("refused", "KEY_REFUSED", "not tried: refused earlier in this run")),
144
144
  };
145
145
  });
@@ -22,6 +22,17 @@ export type KeyedSpec = {
22
22
  refuseOn: readonly number[];
23
23
  };
24
24
  export declare function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn }: KeyedSpec, send?: typeof fetch, pay?: Pay): Keyed;
25
+ /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
26
+ * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
27
+ * that failed connecting (its cause's code, UNSENT_CODES, a certificate's CERT_* or a handshake's ERR_TLS_*). Anything
28
+ * else may have reached the provider: a reset socket (ECONNRESET, UND_ERR_SOCKET), a timeout or a stop after the send
29
+ * started, a body that broke. */
30
+ export declare function unsentWhy(error: unknown, stoppedFirst: boolean): string | undefined;
31
+ /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
32
+ * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
33
+ * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
34
+ * 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>;
25
36
  /** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
26
37
  export declare function statusLimit(response: Response): Limit | undefined;
27
38
  /** A provider's machine code (Exa's `tag`, Firecrawl's `code`): upper-case words joined by underscores, else none. */
@@ -1,8 +1,9 @@
1
1
  // A provider on the run's key over its HTTP API (Exa's, Firecrawl's): each request paid through the injected Pay at its
2
2
  // price and never sent without one; a status in `refuseOn` stops the client for its life; a 402 is the key's credit
3
- // spent (a quota) and a 429 a rate limit for its Retry-After, both for the run's breaker. Nothing is retried. A
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
+ // never asked of the Pay, and one that failed before it left (paidSend) is settled at $0. Nothing is retried. A
4
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.
5
- import { PaidRefused, unmetered } from "../fees.js";
6
+ import { PaidRefused, unmetered, unsentAnswer } from "../fees.js";
6
7
  import { failed, keyWide } from "../search.js";
7
8
  /** The most bytes of one answer read: past it the answer is not read. */
8
9
  export const KEYED_MAX_BYTES = 8 * 1024 * 1024;
@@ -16,7 +17,7 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn },
16
17
  const fee = feeOf(path, body);
17
18
  if (!fee)
18
19
  throw new PaidRefused(`${who}'s ${path} was not sent: it has no price here`);
19
- return pay(fee, async () => {
20
+ return paidSend(pay, fee, signal, async () => {
20
21
  const response = await send(`${root}${path}`, {
21
22
  method: "POST",
22
23
  headers: { ...headers, "content-type": "application/json" },
@@ -32,6 +33,63 @@ export function keyedClient({ who, base, headers, feeOf, timeoutMs, refuseOn },
32
33
  },
33
34
  };
34
35
  }
36
+ /** The codes of a fetch's failure (the cause of undici's TypeError "fetch failed") from before its request was written:
37
+ * the host's name not resolved, the host or its network not reached, the connection refused or not made within
38
+ * undici's connect bound, the TLS handshake refusing the host's certificate. A request failing with one never reached
39
+ * the provider. */
40
+ const UNSENT_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN"]);
41
+ /** Node's TLS codes (ERR_TLS_*) that can come once a connection is up, after a request may have left: not unsent. */
42
+ const TLS_LATER = new Set(["ERR_TLS_RENEGOTIATION_DISABLED", "ERR_TLS_SESSION_ATTACK"]);
43
+ /** Why `error`, thrown by a paid request's send, is one that never left this process, or undefined when it may have
44
+ * left (and may be billed): `stoppedFirst`, the call's signal stopped when the send started ("stopped"), or a fetch
45
+ * that failed connecting (its cause's code, UNSENT_CODES, a certificate's CERT_* or a handshake's ERR_TLS_*). Anything
46
+ * else may have reached the provider: a reset socket (ECONNRESET, UND_ERR_SOCKET), a timeout or a stop after the send
47
+ * started, a body that broke. */
48
+ export function unsentWhy(error, stoppedFirst) {
49
+ if (stoppedFirst)
50
+ return "stopped";
51
+ const thrown = error;
52
+ if (thrown?.name !== "TypeError" || thrown.message !== "fetch failed")
53
+ return undefined;
54
+ const code = thrown.cause?.code;
55
+ if (typeof code !== "string")
56
+ return undefined;
57
+ return UNSENT_CODES.has(code) || code.startsWith("CERT_") || (code.startsWith("ERR_TLS_") && !TLS_LATER.has(code)) ? code : undefined;
58
+ }
59
+ /** `send`, one paid request at `fee`, through `pay`: on a signal already stopped, never asked of `pay` (nothing held),
60
+ * the stop's own reason thrown as fetch throws it; one whose send failed before it left (unsentWhy) answered to `pay`
61
+ * as unsentAnswer, a 4xx the cap settles at $0, and then thrown as it was, marked `unsent`. Every other failure is
62
+ * thrown inside `pay`, which books it at its fee. */
63
+ export async function paidSend(pay, fee, signal, send) {
64
+ if (signal?.aborted)
65
+ throw signal.reason;
66
+ let unsent;
67
+ const answer = await pay(fee, async () => {
68
+ const stoppedFirst = signal?.aborted === true;
69
+ try {
70
+ return await send();
71
+ }
72
+ catch (error) {
73
+ const why = unsentWhy(error, stoppedFirst);
74
+ if (why === undefined)
75
+ throw error;
76
+ unsent = { error };
77
+ return unsentAnswer(why);
78
+ }
79
+ });
80
+ if (unsent) {
81
+ const { error } = unsent;
82
+ // Marked where it can be: a frozen or sealed error is thrown as it was, never replaced by the marking's own failure.
83
+ if (error !== null && typeof error === "object") {
84
+ try {
85
+ Object.assign(error, { unsent: true });
86
+ }
87
+ catch { }
88
+ }
89
+ throw error;
90
+ }
91
+ return answer;
92
+ }
35
93
  /** What a status says of the run's key: its credit spent (402), or a rate limit (429) for its Retry-After. */
36
94
  export function statusLimit(response) {
37
95
  if (response.status === 402)
@@ -4,7 +4,7 @@ import { PARALLEL_SEARCH_MODE_USD, PaidRefused, parallelFeeOf, unmetered } from
4
4
  import { clip, markdownRead, PAGE_READ_MAX_CHARS, TITLE_CAP, withoutUserinfo } from "../page.js";
5
5
  import { failed, failure, keyWide, searchArgs, searchFailed, snippetOf } from "../search.js";
6
6
  import { defineProvider, settingsOf } from "../provider.js";
7
- import { domains, matching, oneOf, settingsProblems, wholeIn } from "./keyed.js";
7
+ import { domains, matching, oneOf, paidSend, settingsProblems, wholeIn } from "./keyed.js";
8
8
  export const PARALLEL_SEARCH_URL = "https://api.parallel.ai/v1/search";
9
9
  export const PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
10
10
  const PARALLEL_TIMEOUT_MS = 60_000;
@@ -59,7 +59,8 @@ export function parallelExtract(apiKey, send = fetch, pay = unmetered, settings
59
59
  const fee = parallelFeeOf(url, body);
60
60
  if (!fee)
61
61
  throw new PaidRefused(`Parallel's ${URL.parse(url)?.pathname ?? url} was not sent: it has no price here`);
62
- return pay(fee, sent);
62
+ // A stopped call sends nothing, and one that never left is not billed (paidSend).
63
+ return paidSend(pay, fee, signal, sent);
63
64
  };
64
65
  const extract = async (url, signal, client = {}) => {
65
66
  try {
package/dist/search.d.ts CHANGED
@@ -82,11 +82,14 @@ export declare const keyWide: (one: Failed) => Failed;
82
82
  /** `value` without its typed failure: what an exported call answers, as it did before failures were typed. */
83
83
  export declare function bare<T>(value: T): T;
84
84
  /** A Search, and the failure and limit its provider answered, if any: the run's breaker reads `limit` (searchBreaker),
85
- * the receipt `failure`, the model the Search alone. */
85
+ * the receipt `failure`, the model the Search alone. `worded`: the error is the provider's words for the model about the
86
+ * limit it met (a keyless search's, a caller's Words among them), which the breaker passes on where its own would say
87
+ * no more; else a limit's error is said in the breaker's words. */
86
88
  export type Searched = {
87
89
  answer: Search;
88
90
  failure?: Failure;
89
91
  limit?: Limit;
92
+ worded?: true;
90
93
  };
91
94
  /** A failed search as searchInTurn reads it. */
92
95
  export declare const searchFailed: ({ error, failure, limit }: Failed) => Searched;
@@ -102,9 +105,10 @@ export declare function waitOf(retryAfter: string | number | undefined, nowMs: n
102
105
  export declare function offUntil(limit: Limit, nowMs: number): number | undefined;
103
106
  /** A breaker on one backend, read at `now`. `held`: what a call answers unsent while it holds (SEARCH_UNAVAILABLE once
104
107
  * off, searchBusy for the seconds left of a wait). `read` takes a search and its limit: a quota answer, or a rate limit
105
- * naming a wait past 15 minutes, turns it off (offUntil), the call keeping any results it has; a shorter rate limit
106
- * opens a wait, never shrinking one already open; a repeatIsQuota limit after an earlier one whose wait has passed,
107
- * with no success between, is a quota answer and the call answers SEARCH_UNAVAILABLE. */
108
+ * naming a wait past 15 minutes, turns it off (offUntil); a shorter rate limit opens a wait, never shrinking one
109
+ * already open; a repeatIsQuota limit after an earlier one whose wait has passed, with no success between, is a quota
110
+ * answer. The call that met a limit keeps any results it has; with none it answers `held`'s words, as the next call
111
+ * would, never the provider's for the limit. */
108
112
  export type Breaker = {
109
113
  held(): Search | undefined;
110
114
  read(searched: Searched): Search;
@@ -148,11 +152,12 @@ export type Backend = {
148
152
  name: string;
149
153
  ask(deadline: AbortSignal): Promise<Searched>;
150
154
  };
151
- /** One backend's turn in a call: answered (`ok`), failed (`error`: its message, the failure typed where the provider
152
- * typed it, the limit it met), or held by its breaker. */
155
+ /** One backend's turn in a call: answered (`ok`), answered no results (`empty`: a search passed on to the next
156
+ * backend), failed (`error`: its message, the failure typed where the provider typed it, the limit it met), or held by
157
+ * its breaker. */
153
158
  export type Try = {
154
159
  provider: string;
155
- outcome: "ok" | "error" | "held";
160
+ outcome: "ok" | "empty" | "error" | "held";
156
161
  error?: string;
157
162
  failure?: Failure;
158
163
  limit?: Limit;
@@ -169,8 +174,11 @@ export type SearchBounds = {
169
174
  firecrawlMs?: number;
170
175
  };
171
176
  /** A call's search through `backends` in turn, each behind its breaker, all under one deadline (`boundMs` or `signal`):
172
- * the first with results answers; none starts on a spent deadline. None left: SEARCH_UNAVAILABLE where every backend is
173
- * off (a lone backend's own answer where it was asked), else the last failure, else searchBusy for the shortest wait. */
177
+ * the first with results (or a short answer of its own) answers; one answering none passes the call on, and the first
178
+ * such answers only when no backend after it has results. None starts on a spent deadline: one spent before any was
179
+ * asked answers SEARCH_STOPPED, a stopped turn of the first not held. None left: SEARCH_UNAVAILABLE
180
+ * where every backend is off (a lone backend's own answer where it was asked), else the last failure (one that met a
181
+ * limit in its breaker's words), else searchBusy for the shortest wait. */
174
182
  export declare function searchInTurn(backends: readonly Backend[], breakerOf: (name: string) => Breaker, signal?: AbortSignal, boundMs?: number, tries?: Try[]): Promise<Search>;
175
183
  /** `own`, one tool's breaker on a provider, joined with `key`, the provider's breaker across both tools: held while
176
184
  * either holds; a limit whose failure covers the key (Failure.covers) trips both, any other `own` alone. */
package/dist/search.js CHANGED
@@ -1,3 +1,8 @@
1
+ // web_search's one answer shape (Search), its bounds, and searchInTurn: a call asks its backends in order, each behind
2
+ // a breaker of its own. A quota answer turns a backend off until the reset it names, else for the breaker's life; a rate
3
+ // limit holds it for the wait it named (60 s when none), and one naming a wait past 15 minutes turns it off for that
4
+ // wait. A backend that fails, answers no results, is held or is off passes the call to the next.
5
+ import { cutAt } from "./page.js";
1
6
  /** The most of one keyword query a search sends (Parallel's own bound on a query). */
2
7
  export const QUERY_MAX = 200;
3
8
  /** The most of a search's objective, its goal in plain words, a search sends. */
@@ -72,34 +77,37 @@ export function searchBreaker(now = Date.now) {
72
77
  let offKind = "quota";
73
78
  let waitKind = "rate";
74
79
  const off = () => now() < offTill;
80
+ const held = () => {
81
+ if (off())
82
+ return { error: SEARCH_UNAVAILABLE };
83
+ const left = until - now();
84
+ return left > 0 ? busyFor(left) : undefined;
85
+ };
75
86
  return {
76
87
  holding() {
77
88
  if (off())
78
89
  return { kind: offKind, until: offTill };
79
90
  return until > now() ? { kind: waitKind, until } : undefined;
80
91
  },
81
- held() {
82
- if (off())
83
- return { error: SEARCH_UNAVAILABLE };
84
- const left = until - now();
85
- return left > 0 ? busyFor(left) : undefined;
86
- },
92
+ held,
87
93
  off,
88
94
  left: () => Math.max(0, until - now()),
89
- read({ answer, limit }) {
95
+ read({ answer, limit, worded }) {
90
96
  if (!("error" in answer))
91
97
  marked = false;
92
98
  if (!limit)
93
99
  return answer;
94
100
  const at = now();
95
101
  const till = offUntil(limit, at);
96
- // The call that turns search off for a rate limit answers its results if it has any (a merged search's other
97
- // requests), else SEARCH_UNAVAILABLE, never its limit's "try again" words.
102
+ // The call that met a limit answers its results if it has any (a merged search's other requests), else what a call
103
+ // held by it answers (held: SEARCH_UNAVAILABLE, or searchBusy for its wait), never the provider's "answered 429";
104
+ // a provider's own words for the model (worded) stand, but for a rate limit that turns it off ("try again" words).
105
+ const heldOr = (words = !worded) => ("error" in answer && words ? (held() ?? answer) : answer);
98
106
  if (till !== undefined) {
99
107
  if (till >= offTill)
100
108
  offKind = limit.kind;
101
109
  offTill = Math.max(offTill, till);
102
- return limit.kind === "quota" || !("error" in answer) ? answer : { error: SEARCH_UNAVAILABLE };
110
+ return heldOr(limit.kind === "rate" || !worded);
103
111
  }
104
112
  if (limit.kind === "rate" && limit.repeatIsQuota && marked && at >= until) {
105
113
  offTill = Number.POSITIVE_INFINITY;
@@ -110,7 +118,7 @@ export function searchBreaker(now = Date.now) {
110
118
  marked = true;
111
119
  until = Math.max(until, at + waitOf(limit.retryAfter, at));
112
120
  waitKind = limit.kind;
113
- return answer;
121
+ return heldOr();
114
122
  },
115
123
  };
116
124
  }
@@ -140,7 +148,7 @@ export function snippetOf(raw) {
140
148
  const text = raw.replace(/!?\[([^\]]*)\]\([^)\s]*\)/g, "$1").replace(/\s+/g, " ").trim();
141
149
  if (text.length <= SNIPPET_MAX)
142
150
  return text;
143
- const cut = text.slice(0, SNIPPET_MAX - 1);
151
+ const cut = cutAt(text, SNIPPET_MAX - 1);
144
152
  const space = cut.lastIndexOf(" ");
145
153
  return `${(space > SNIPPET_MAX / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
146
154
  }
@@ -161,12 +169,21 @@ export function searchArgs(args) {
161
169
  * leaves Exa what is left of it, never a fresh bound. Firecrawl's own bound inside it (FIRECRAWL_MS, 30 s) leaves Exa
162
170
  * at least the rest. */
163
171
  export const KEYLESS_SEARCH_MS = 60_000;
172
+ /** What a call stopped before any backend was asked answers (searchInTurn): the keyless backends' words for a stop. */
173
+ const SEARCH_STOPPED = "the search was stopped";
174
+ /** Whether a search's answer holds nothing for the model: no results and no short answer of its own (`text`). */
175
+ const emptyAnswer = (answer) => !("error" in answer) && !answer.results.length && !answer.text;
164
176
  /** A call's search through `backends` in turn, each behind its breaker, all under one deadline (`boundMs` or `signal`):
165
- * the first with results answers; none starts on a spent deadline. None left: SEARCH_UNAVAILABLE where every backend is
166
- * off (a lone backend's own answer where it was asked), else the last failure, else searchBusy for the shortest wait. */
177
+ * the first with results (or a short answer of its own) answers; one answering none passes the call on, and the first
178
+ * such answers only when no backend after it has results. None starts on a spent deadline: one spent before any was
179
+ * asked answers SEARCH_STOPPED, a stopped turn of the first not held. None left: SEARCH_UNAVAILABLE
180
+ * where every backend is off (a lone backend's own answer where it was asked), else the last failure (one that met a
181
+ * limit in its breaker's words), else searchBusy for the shortest wait. */
167
182
  export async function searchInTurn(backends, breakerOf, signal, boundMs = KEYLESS_SEARCH_MS, tries) {
168
183
  const deadline = AbortSignal.any([AbortSignal.timeout(boundMs), ...(signal ? [signal] : [])]);
169
184
  let last;
185
+ // The first answer with no results: the call's, if no backend after it has any.
186
+ let empty;
170
187
  for (const backend of backends) {
171
188
  const breaker = breakerOf(backend.name);
172
189
  const held = breaker.held();
@@ -175,16 +192,29 @@ export async function searchInTurn(backends, breakerOf, signal, boundMs = KEYLES
175
192
  tries?.push({ provider: backend.name, outcome: "held", ...(holding && "error" in held ? { failure: failure(holding.kind, "HELD", held.error) } : {}), ms: 0 });
176
193
  continue;
177
194
  }
178
- if (last && deadline.aborted)
179
- break;
195
+ if (deadline.aborted) {
196
+ if (last || empty)
197
+ break;
198
+ // A call stopped before any backend was asked starts none (a paid one would be held, or sent, for nothing): its
199
+ // turn is the stopped one the backend would have answered, in the keyless backends' words.
200
+ tries?.push({ provider: backend.name, outcome: "error", error: SEARCH_STOPPED, failure: failure("infra", "STOPPED", SEARCH_STOPPED), ms: 0 });
201
+ return { error: SEARCH_STOPPED };
202
+ }
180
203
  const started = tries ? performance.now() : 0;
181
204
  const searched = await backend.ask(deadline);
182
205
  const answer = breaker.read(searched);
183
- tries?.push({ provider: backend.name, outcome: "error" in answer ? "error" : "ok", ...("error" in answer ? { error: answer.error, ...(searched.failure ? { failure: searched.failure } : {}) } : {}), ...(searched.limit ? { limit: searched.limit } : {}), ms: Math.round(performance.now() - started) });
184
- if (!("error" in answer))
206
+ const outcome = "error" in answer ? "error" : emptyAnswer(answer) ? "empty" : "ok";
207
+ // The receipt keeps what the provider said; the model reads the breaker's words for a limit.
208
+ tries?.push({ provider: backend.name, outcome, ...("error" in answer ? { error: "error" in searched.answer ? searched.answer.error : answer.error, ...(searched.failure ? { failure: searched.failure } : {}) } : {}), ...(searched.limit ? { limit: searched.limit } : {}), ms: Math.round(performance.now() - started) });
209
+ if (outcome === "ok")
185
210
  return answer;
186
- last = answer;
211
+ if (outcome === "empty")
212
+ empty ??= answer;
213
+ else
214
+ last = answer;
187
215
  }
216
+ if (empty)
217
+ return empty;
188
218
  const breakers = backends.map((backend) => breakerOf(backend.name));
189
219
  if (breakers.every((breaker) => breaker.off()))
190
220
  return backends.length === 1 && last ? last : { error: SEARCH_UNAVAILABLE };
@@ -21,7 +21,7 @@ export const WEB_SEARCH_PARAMETERS = {
21
21
  required: ["objective"],
22
22
  };
23
23
  /** web_fetch's description: one page read cold, a part at a time, and every field it answers. */
24
- export const WEB_FETCH_DESCRIPTION = `Read one web page from a public host, a part at a time. It has no cookies, sign-ins or session: it reads one page cold, so a page behind a sign-in, or one that depends on an earlier page, needs the browser tool, where this run has it. Answers JSON: ok, the final url, the HTTP status, the page's title, text (a part of its readable text as markdown: about max_chars characters from offset, ${count(PAGE_CHARS)} by default, at least ${MAX_CHARS_MIN} and at most ${count(TEXT_CAP)}) and chars (that part's length), the absolute links the page holds (its link targets and the URLs written out in its text, a JSON body's strings and an XML feed's links among them, where an HTML page fetched directly gives its link targets alone; with the part at offset 0; links_omitted counts those its caps left out), and via, what read the page: direct when it was fetched from the host, stopped when the call was stopped before its page arrived, else the name of the reading service the URL was sent to; a service tried ahead that gave no page says why under its own name. A part that is not the whole page says so: truncated is true while more follows, next_offset is where the rest begins, original_chars is the page's whole length where it is known, and a line after the JSON says which characters these are; call again with offset to read on. A page whose HTML is longer than ${count(HTML_READ_CHARS)} characters (scripts and styles aside) is cut before it is read: html_chars gives its whole length on every part, its text is only the start of the page, and the last part's line says it was cut. converted is "text" when the text is the page's plain text, its conversion to markdown having run out of time. A page is read to its first ${count(PAGE_READ_MAX_CHARS)} characters (beyond_read on the last part says it goes on). A page is fetched once a run, at its first call: its later parts come from that read, with no request (where a reading service bills, one read a page). A private or local address, a port other than 80 or 443, or a scheme other than http(s) is refused, never read and never sent to a third party (ok false, with refused saying why); so is a page fetched directly that is not text.`;
24
+ export const WEB_FETCH_DESCRIPTION = `Read one web page from a public host, a part at a time. It has no cookies, sign-ins or session: it reads one page cold, so a page behind a sign-in, or one that depends on an earlier page, needs the browser tool, where this run has it. Answers JSON: ok, the final url, the HTTP status, the page's title, text (a part of its readable text as markdown: about max_chars characters from offset, ${count(PAGE_CHARS)} by default, at least ${MAX_CHARS_MIN} and at most ${count(TEXT_CAP)}) and chars (that part's length), the absolute links the page holds (its link targets and the URLs written out in its text, a JSON body's strings and an XML feed's links among them, where an HTML page fetched directly gives its link targets alone; with the part at offset 0, less those that part's text already writes where a reading service read the page; links_omitted counts those its caps left out), and via, what read the page: direct when it was fetched from the host, stopped when the call was stopped before its page arrived, else the name of the reading service the URL was sent to; a service tried ahead that gave no page says why under its own name. A part that is not the whole page says so: truncated is true while more follows, next_offset is where the rest begins, original_chars is the page's whole length where it is known, and a line after the JSON says which characters these are; call again with offset to read on. Given an objective, it may answer found in place of text and links: the chunks of the whole page most likely to hold what the objective asks for, in page order, each with its offset and relevance (0 to 1), and a sift line says how they were picked or why the objective was not applied. A page whose HTML is longer than ${count(HTML_READ_CHARS)} characters (scripts and styles aside) is cut before it is read: html_chars gives its whole length on every part, its text is only the start of the page, and the last part's line says it was cut. converted is "text" when the text is the page's plain text, its conversion to markdown having run out of time. A page is read to its first ${count(PAGE_READ_MAX_CHARS)} characters (beyond_read on the last part says it goes on). A page is fetched once a run, at its first call: its later parts come from that read, with no request (where a reading service bills, one read a page). A private or local address, a port other than 80 or 443, or a scheme other than http(s) is refused, never read and never sent to a third party (ok false, with refused saying why); so is a page fetched directly that is not text.`;
25
25
  /** web_fetch's parameters: `url` required; `offset`, `max_chars` and `objective` optional. */
26
26
  export const WEB_FETCH_PARAMETERS = {
27
27
  type: "object",
package/dist/web.d.ts CHANGED
@@ -11,7 +11,8 @@ import { type NativeSearch, type WebClient } from "./provider.js";
11
11
  import type { Words } from "./providers/mcp.js";
12
12
  import { type FetchProvider, type KeyedProvider, type ProviderId, type ProviderSettings, type SearchProvider } from "./providers/registry.js";
13
13
  import { type Breaker, type Holding, type Limit, type Search, type SearchBounds, type Try } from "./search.js";
14
- /** What an answer took and cost. `asked`: a search's objective, a fetch's URL; `queries`, a search's keyword queries.
14
+ /** What an answer took and cost. `asked`: a search's objective, a fetch's URL as its page names it (no user name or
15
+ * password); `queries`, a search's keyword queries.
15
16
  * `out` is the answer as the model reads it; `cache` is "hit" when a fetch came from the run's pages. */
16
17
  export type Receipt = {
17
18
  op: "search" | "fetch";
@@ -104,7 +105,6 @@ export type FetchOptions = Part & GuardOptions & {
104
105
  lookingFor?: string;
105
106
  session?: string;
106
107
  };
107
- /** `sift`, only when a decider is given: what it did, for the model to read. */
108
108
  /** A provider a Web's tool asks: its id, how it is reached (`keyed`, on the run's key; `unkeyed`, a keyed provider the
109
109
  * run holds no key for, so never sent; `keyless`, a service's free use; `none`, neither: the model provider's own search
110
110
  * or the guarded direct fetch), and what holds it now (the tool's breaker, else its key's), if anything. */
@@ -134,7 +134,8 @@ export type SearchInput = string | {
134
134
  query?: string;
135
135
  n?: number;
136
136
  };
137
- /** `destinations`: where each tool goes now (Destinations), for a run's start line; never a key. */
137
+ /** `search`'s answer carries `sift` only when a decider is given: what it did, for the model to read. `destinations`:
138
+ * where each tool goes now (Destinations), for a run's start line; never a key. */
138
139
  export type Web = {
139
140
  search(input: SearchInput, options?: SearchOptions): Promise<{
140
141
  answer: Search & Sift;
package/dist/web.js CHANGED
@@ -5,8 +5,8 @@ import { decideFetch, judgePart } from "./decide/fetch.js";
5
5
  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
- import { missesOf, webFetchText, webPart, webRead } from "./fetch.js";
9
- import { unmetered } from "./fees.js";
8
+ import { missesOf, pageKey, sharedRead, webFetchText, webPart, webRead } from "./fetch.js";
9
+ import { 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";
@@ -63,13 +63,15 @@ export function createWeb(config) {
63
63
  * and a page read again is asked about again, as is one whose guard failed. */
64
64
  const pageVerdicts = new WeakMap();
65
65
  const guardOf = (decider, url, read, step) => {
66
- const known = pageVerdicts.get(read);
66
+ // One verdict a page: a read another fragment of its URL shares is that page (sharedRead).
67
+ const page = sharedRead(read);
68
+ const known = pageVerdicts.get(page);
67
69
  // A later caller waits on the check another started only until its own signal stops it; the check goes on.
68
70
  if (known)
69
71
  return guardUntilStopped(known, step.signal);
70
72
  const asked = guardPage(decider, url, read, step);
71
- pageVerdicts.set(read, asked);
72
- void asked.then((verdict) => verdict.wall.error && pageVerdicts.delete(read));
73
+ pageVerdicts.set(page, asked);
74
+ void asked.then((verdict) => verdict.wall.error && pageVerdicts.delete(page));
73
75
  return asked;
74
76
  };
75
77
  /** A receipt's `unsifted`, only in a run with a classifier. */
@@ -107,8 +109,25 @@ export function createWeb(config) {
107
109
  };
108
110
  };
109
111
  const toolBreaker = (tool, id, own, key) => withKeyBreaker(watched(tool, id, own), watched("key", id, key));
110
- // A fee goes on the call's receipt once its request is sent, whatever the cap then books.
111
- const pay = (fee, send) => (config.pay ?? unmetered)(fee, () => (feesOfCall.getStore()?.push(fee), send()));
112
+ // A fee goes on the call's receipt once its request is sent, whatever the cap then books. One that never left (its send
113
+ // answered unsentAnswer, which the cap settles at $0) is $0 on it, saying so, as decisionPay's line for an unbilled
114
+ // request is, once the cap's settle is written: a settle that failed leaves the line at the hold, as the cap keeps it.
115
+ const pay = async (fee, send) => {
116
+ const lines = feesOfCall.getStore();
117
+ let at = -1;
118
+ let unsent;
119
+ let booked = true;
120
+ const answer = await (config.pay ?? unmetered)(fee, async () => {
121
+ if (lines)
122
+ at = lines.push(fee) - 1;
123
+ const response = await send();
124
+ unsent = unsentOf(response);
125
+ return response;
126
+ }, undefined, (landed) => { booked = landed; });
127
+ if (lines && at >= 0 && unsent !== undefined)
128
+ lines[at] = booked ? { ...fee, usd: 0, basis: `not billed (not sent: ${unsent})` } : { ...fee, basis: `${fee.basis}; its settle failed, so the hold stands, not $0 (not sent: ${unsent})` };
129
+ return answer;
130
+ };
112
131
  // Each provider an order names is made once per Web, at its first use, from the run's parts for it: one client a
113
132
  // provider, so a key refused by one tool is refused by both.
114
133
  const runs = new Map();
@@ -166,24 +185,28 @@ export function createWeb(config) {
166
185
  const answer = fitSearch(sifted.answer);
167
186
  const { classifier } = sifted;
168
187
  const said = [asked.objective, asked.query].find((one) => typeof one === "string") ?? "";
188
+ // A copy: a sift this call stopped waiting for may still pay, and its fee is not on this receipt.
189
+ const spent = [...lines];
169
190
  // An empty search's receipt keeps the words it was given.
170
- 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(lines), lines }, ...unsifted(() => searchText(fitSearch(found))) };
191
+ 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))) };
171
192
  return { answer, receipt };
172
193
  },
173
194
  // Only the call's part, resolver, transport, signal, task, objective and session are read: the guard, its bound, the order
174
195
  // and the readers stay the Web's.
175
196
  async fetch(url, { offset, maxChars, task, objective, lookingFor, lookup, fetchImpl, signal, session } = {}) {
176
197
  const asked = typeof url === "string" ? url : "";
198
+ // What a receipt names: the URL as the page names it, with no user name or password (askedUrl).
199
+ const named = askedUrl(url);
177
200
  const lines = [];
178
201
  const tries = [];
179
202
  // A part a call may not ask for is refused before anything is fetched.
180
203
  const problem = partProblem({ offset, maxChars });
181
204
  if (problem) {
182
- const refused = { ok: false, url: askedUrl(asked), status: 0, title: "", text: "", links: [], error: problem };
205
+ const refused = { ok: false, url: named, status: 0, title: "", text: "", links: [], error: problem };
183
206
  const classifier = held ? (await judgePart(held, asked, refused, {})).classifier : "off";
184
- return { answer: refused, receipt: { op: "fetch", asked, provider: null, tries, classifier, ...unjudged, out: outOf(webFetchText(refused)), cost: { usd: 0, lines }, ...unsifted(() => webFetchText(refused)) } };
207
+ return { answer: refused, receipt: { op: "fetch", asked: named, provider: null, tries, classifier, ...unjudged, out: outOf(webFetchText(refused)), cost: { usd: 0, lines }, ...unsifted(() => webFetchText(refused)) } };
185
208
  }
186
- const cached = typeof url === "string" && pages.has(url);
209
+ const cached = typeof url === "string" && pages.has(pageKey(url));
187
210
  const whole = await feesOfCall.run(lines, () => webRead(url, {
188
211
  ...(lookup ? { lookup } : {}),
189
212
  ...(fetchImpl ? { fetchImpl } : {}),
@@ -201,13 +224,13 @@ export function createWeb(config) {
201
224
  const provider = part.ok && part.via !== "stopped" && part.via !== "none" ? part.via : null;
202
225
  const decider = held;
203
226
  const guard = config.pageGuard && decider && whole.ok ? (options) => guardOf(decider, asked, whole, options) : undefined;
204
- const decided = await decideFetch(decider, asked, whole, part, { task, objective: typeof objective === "string" && objective.trim() ? objective : lookingFor, signal, ms: config.bounds?.decideMs, pay: config.pay ?? unmetered, lines, guard });
227
+ const decided = await decideFetch(decider, asked, whole, part, { task, objective: typeof objective === "string" && objective.trim() ? objective : lookingFor, ...(offset === undefined ? {} : { offset }), ...(maxChars === undefined ? {} : { maxChars }), signal, ms: config.bounds?.decideMs, pay: config.pay ?? unmetered, lines, guard });
205
228
  // What the objective found names each provider asked ahead that gave no page, as the part does.
206
229
  const answer = "found" in decided.answer ? { ...decided.answer, ...missesOf(whole) } : decided.answer;
207
230
  const { classifier, guard: verdicts } = decided;
208
231
  // Copies: a read this call stopped waiting for goes on, and its later turns and fees are not on this receipt.
209
232
  const spent = [...lines];
210
- const receipt = { op: "fetch", asked, provider, tries: [...tries], classifier, ...(verdicts ? { wall: verdicts.wall, injection: verdicts.injection } : unjudged), out: outOf(webFetchText(answer)), cost: { usd: usd(spent), lines: spent }, ...(cached ? { cache: "hit" } : {}), ...unsifted(() => webFetchText(part)) };
233
+ const receipt = { op: "fetch", asked: named, provider, tries: [...tries], classifier, ...(verdicts ? { wall: verdicts.wall, injection: verdicts.injection } : unjudged), out: outOf(webFetchText(answer)), cost: { usd: usd(spent), lines: spent }, ...(cached ? { cache: "hit" } : {}), ...unsifted(() => webFetchText(part)) };
211
234
  return { answer, receipt };
212
235
  },
213
236
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-web",
3
- "version": "0.1.0-beta.64",
3
+ "version": "0.1.0-beta.65",
4
4
  "description": "Web search and web fetch for agents: providers asked in an order given as data, a breaker per provider, a per-run page cache read in parts, and a direct fetch through an injected public-host guard.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -46,7 +46,7 @@
46
46
  "undici": "^8.12.2"
47
47
  },
48
48
  "devDependencies": {
49
- "@parcha/pi-browser": "0.1.0-beta.64"
49
+ "@parcha/pi-browser": "0.1.0-beta.65"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",