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

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) });
@@ -5,6 +5,7 @@ import { askedUrl, clip, linksWithin, partOfRead, TIMEOUT_MS, TITLE_CAP, textOf,
5
5
  import { defineProvider } from "../provider.js";
6
6
  import { bare } from "../search.js";
7
7
  import { linksOf } from "../text-urls.js";
8
+ import { thrownFailure } from "./keyed.js";
8
9
  /** The page at `url`, read once through `guard`'s fetch (an HTML page through its reader), or why it was not. `options`
9
10
  * are the guard's resolver and fetch, for a test; a signal ends it early. */
10
11
  export async function readDirect(url, guard, options = {}) {
@@ -54,7 +55,8 @@ async function readTyped(url, guard, options) {
54
55
  const message = withoutUserinfo(error?.message ?? String(error));
55
56
  if (isRefused(error))
56
57
  return failed("refused", "GUARD", { refused: message });
57
- return failed("infra", error?.name === "TimeoutError" ? "TIMEOUT" : "CONNECT", { error: message });
58
+ // Typed as every provider types a thrown failure (thrownFailure); the page says what the error said, whole.
59
+ return failed("infra", thrownFailure(error, { who: "the direct fetch", what: "fetch", signal: options.signal }).failure.code, { error: message });
58
60
  }
59
61
  }
60
62
  /** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
@@ -2,9 +2,10 @@
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
+ import { thrownFailure } from "./keyed.js";
8
9
  import { callTool, RATE_LIMITED, sleep, textBlocks } from "./mcp.js";
9
10
  export const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
10
11
  export const EXA_SEARCH_TOOL = "web_search_exa";
@@ -19,7 +20,7 @@ const SAID_MAX = 120;
19
20
  function exaSaid(text) {
20
21
  const line = text.split("\n").map((part) => part.trim()).find(Boolean) ?? "";
21
22
  const sentence = /^.*?[.!?](?=\s|$)/.exec(line)?.[0] ?? line;
22
- const short = sentence.length <= SAID_MAX ? sentence : `${sentence.slice(0, SAID_MAX - 1).replace(/\s+\S*$/, "")}…`;
23
+ const short = sentence.length <= SAID_MAX ? sentence : `${cutAt(sentence, SAID_MAX - 1).replace(/\s+\S*$/, "")}…`;
23
24
  return short ? `Free web search failed. Exa said: "${short}"` : "Free web search failed: Exa gave no answer";
24
25
  }
25
26
  /** The `_meta` key Exa's MCP server marks a tool result reporting its free limit with (isError as well). */
@@ -76,6 +77,9 @@ function searchOf(called, { objective, queries, n }, rateLimited) {
76
77
  if (!Array.isArray(result?.content) || result.isError === true)
77
78
  return typed("error", "FAILED", { error: exaSaid(said) });
78
79
  const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
80
+ // Text that names no result this server reads is a failure, never an answer of no results: the call goes on.
81
+ if (!hits.length && said.trim())
82
+ return typed("error", "UNREADABLE", { error: "Exa's search answered no results this server reads" });
79
83
  return { provider: "exa-keyless", objective, queries, results: hits.slice(0, n) };
80
84
  }
81
85
  /** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
@@ -98,10 +102,7 @@ async function searchTyped(ask, { send, signal, pause = sleep, words = {} }) {
98
102
  return await once();
99
103
  }
100
104
  catch (error) {
101
- const name = error?.name;
102
- if (name === "TimeoutError")
103
- return typed("infra", "TIMEOUT", { error: "Exa's search did not answer within 60 s" });
104
- return name === "AbortError" ? typed("infra", "STOPPED", { error: "the search was stopped" }) : typed("infra", "CONNECT", { error: `Exa's search failed: ${String(error?.message ?? error).slice(0, 300)}` });
105
+ return thrownFailure(error, { who: "Exa", what: "search", signal, timeout: "Exa's search did not answer within 60 s", stopped: "the search was stopped", failedWith: (said) => `Exa's search failed: ${said}` });
105
106
  }
106
107
  finally {
107
108
  await own?.close().catch(() => undefined);
@@ -123,6 +124,7 @@ export const exaKeyless = defineProvider({ id: "exa-keyless", label: "Exa", keyl
123
124
  if (!("failure" in found))
124
125
  return { answer: found };
125
126
  const limit = "limit" in found ? exaLimitOf(found) : undefined;
126
- return { answer: { error: found.error }, failure: found.failure, ...(limit ? { limit } : {}) };
127
+ // Its limit's words (RATE_LIMITED, or the caller's) are the model's: the breaker passes them on (Searched.worded).
128
+ return { answer: { error: found.error }, failure: found.failure, ...(limit ? { limit, worded: true } : {}) };
127
129
  },
128
130
  }));
@@ -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
  });