@parcha/agentrun-web 0.1.0-beta.73 → 0.1.0-beta.75

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
@@ -188,7 +188,8 @@ The pieces `createWeb` is built from are exported too: `searchInTurn` and `break
188
188
  providers (`exaSearch`, `firecrawlFetch`, `firecrawlScrape`, `firecrawlSearch`, `parallelExtract`, `parallelSearched`)
189
189
  and Parallel's prices and fees (`PARALLEL_EXTRACT_USD`, `PARALLEL_SEARCH_USD`, `PARALLEL_SEARCH_INCLUDED`,
190
190
  `PARALLEL_SEARCH_MODE_USD`, `PARALLEL_SEARCH_RESULT_USD`, `parallelExtractFee`, `parallelSearchFee`, `parallelFeeOf`,
191
- `PaidRefused` and `unmetered`). The package's entry names each export; nothing else in it is API.
191
+ `parallelChargeOf` (an extract charged the URLs Parallel's `usage` says it billed: none for a URL it lists in `errors`,
192
+ the hold when its answer says nothing certain), `PaidRefused` and `unmetered`). The package's entry names each export; nothing else in it is API.
192
193
  `@parcha/agentrun-web/text-urls` holds the link finder alone, for code that only finds the URLs in a text (the
193
194
  console's timeline compiles it from source).
194
195
 
@@ -23,7 +23,7 @@ export type FoundChunk = {
23
23
  text: string;
24
24
  };
25
25
  /** A page as an objective answers it: the chunks most likely to hold what the agent wants from it, in page order. */
26
- export type FoundPage = Pick<Page, "ok" | "url" | "status" | "title" | "original_chars" | "beyond_read"> & Pick<WebPage, "via" | "parallel"> & {
26
+ export type FoundPage = Pick<Page, "ok" | "url" | "status" | "title" | "original_chars" | "beyond_read" | "html_chars" | "cut_bytes"> & Pick<WebPage, "via" | "parallel"> & {
27
27
  found: FoundChunk[];
28
28
  sift: string;
29
29
  };
@@ -61,6 +61,9 @@ export async function findInPage(decider, url, read, need, options, found = deci
61
61
  title: read.title,
62
62
  ...(read.length === undefined ? {} : { original_chars: read.length }),
63
63
  ...(read.beyond ? { beyond_read: true } : {}),
64
+ // The page's text was cut before it was read: its chunks are of the start alone (webFetchText says so).
65
+ ...(read.html_chars === undefined ? {} : { html_chars: read.html_chars }),
66
+ ...(read.cut_bytes === undefined ? {} : { cut_bytes: read.cut_bytes }),
64
67
  found: shown.map((i) => ({ offset: spans[i][0], ...relevanceOf(scored[i].score), text: chunks[i] })),
65
68
  via: read.via,
66
69
  ...(read.parallel ? { parallel: read.parallel } : {}),
package/dist/fees.d.ts CHANGED
@@ -32,6 +32,18 @@ export declare const parallelExtractFee: (urls?: number) => Fee;
32
32
  * default), or its extract's, by the URLs; undefined for an endpoint the web tools do not ask, and for a search whose
33
33
  * mode has no price here (one naming none, or one Parallel added since): never $0, never another mode's price. */
34
34
  export declare function parallelFeeOf(url: string, body: unknown): Fee | undefined;
35
+ /** The URLs a 2xx extract's `usage` says Parallel billed: the sum of its extract SKUs' counts (`sku_extract_*`, one a
36
+ * URL it read), so an empty `usage` is none. Undefined when it says nothing this server can be sure of: no `usage`
37
+ * array, an item that is not a SKU with a whole count, or a SKU other than an extract's. */
38
+ export declare function parallelExtractBilled(json: unknown): number | undefined;
39
+ /** What an answer of `status` to Parallel's `path` held at `fee` is charged, and the receipt's line for it. A 2xx extract
40
+ * is charged the URLs Parallel's `usage` says it billed (parallelExtractBilled), at its list price: Parallel bills no URL
41
+ * it lists in `errors` (its usage is empty for one), so a page it could not read costs nothing. An extract whose usage
42
+ * says nothing certain, or none at all, is charged its fee, as is every other answer: an unknown is never free. */
43
+ export declare function parallelChargeOf(fee: Fee, path: string, json: unknown, status: number): {
44
+ usd: number;
45
+ basis: string;
46
+ };
35
47
  /** Exa's search types priced here (https://exa.ai/pricing, read 2026-11-24): per request, 10 results included. A search
36
48
  * in a type with no price here is never sent. */
37
49
  export type ExaSearchType = "lite" | "instant" | "auto" | "fast" | "deep-lite" | "deep" | "deep-reasoning";
package/dist/fees.js CHANGED
@@ -32,6 +32,39 @@ export function parallelFeeOf(url, body) {
32
32
  return parallelExtractFee(Array.isArray(asked.urls) ? Math.max(1, asked.urls.length) : 1);
33
33
  return undefined;
34
34
  }
35
+ /** The URLs a 2xx extract's `usage` says Parallel billed: the sum of its extract SKUs' counts (`sku_extract_*`, one a
36
+ * URL it read), so an empty `usage` is none. Undefined when it says nothing this server can be sure of: no `usage`
37
+ * array, an item that is not a SKU with a whole count, or a SKU other than an extract's. */
38
+ export function parallelExtractBilled(json) {
39
+ const usage = json?.usage;
40
+ if (!Array.isArray(usage))
41
+ return undefined;
42
+ let urls = 0;
43
+ for (const item of usage) {
44
+ const { name, count } = (item ?? {});
45
+ if (typeof name !== "string" || !name.startsWith("sku_extract_") || typeof count !== "number" || !Number.isInteger(count) || count < 0)
46
+ return undefined;
47
+ urls += count;
48
+ }
49
+ return urls;
50
+ }
51
+ /** What an answer of `status` to Parallel's `path` held at `fee` is charged, and the receipt's line for it. A 2xx extract
52
+ * is charged the URLs Parallel's `usage` says it billed (parallelExtractBilled), at its list price: Parallel bills no URL
53
+ * it lists in `errors` (its usage is empty for one), so a page it could not read costs nothing. An extract whose usage
54
+ * says nothing certain, or none at all, is charged its fee, as is every other answer: an unknown is never free. */
55
+ export function parallelChargeOf(fee, path, json, status) {
56
+ const billed = path === "/v1/extract" && status >= 200 && status < 300 ? parallelExtractBilled(json) : undefined;
57
+ if (billed === undefined)
58
+ return { usd: fee.usd, basis: fee.basis };
59
+ const urls = (n) => `${n} URL${n === 1 ? "" : "s"}`;
60
+ const charged = usd(PARALLEL_EXTRACT_USD * billed);
61
+ // Usage that bills what was held (one URL read, as asked) leaves the receipt's line as it was.
62
+ if (charged === fee.usd)
63
+ return { usd: fee.usd, basis: fee.basis };
64
+ if (charged > fee.usd)
65
+ return { usd: fee.usd, basis: `the hold, ${fee.basis}; Parallel's usage said ${urls(billed)}` };
66
+ return { usd: charged, basis: billed === 0 ? "Parallel's usage billed no URL: it listed each in errors" : `Parallel's usage billed ${urls(billed)}, at its list price` };
67
+ }
35
68
  export const EXA_SEARCH_TYPE_USD = Object.freeze({ lite: 0.004, instant: 0.004, auto: 0.007, fast: 0.007, "deep-lite": 0.012, deep: 0.012, "deep-reasoning": 0.015 });
36
69
  /** Each search result past the 10 a type includes: $1 per 1,000. */
37
70
  export const EXA_SEARCH_RESULT_USD = 0.001;
package/dist/fetch.d.ts CHANGED
@@ -67,5 +67,6 @@ export declare function missesOf(page: object): Partial<Record<AheadProvider, st
67
67
  /** The part (`offset`, `maxChars`) of the page at `url` as a WebPage: webPart of webRead. */
68
68
  export declare function webFetch(url: unknown, { offset, maxChars, ...options }?: WebFetchOptions): Promise<WebPage>;
69
69
  /** A page as the tool `name` answers the model: its JSON, then a line for each provider ahead that gave none saying why
70
- * and what gave the page instead, and one saying where this part is in the page when it is not all of it. */
71
- export declare function webFetchText(page: WebPage | Page | FoundPage, name?: string): string;
70
+ * and what gave the page instead, and one saying where this part is in the page when it is not all of it: of a page
71
+ * some of which web_fetch can't reach, naming `save`, a tool the run has that keeps a URL whole as a file, where given. */
72
+ export declare function webFetchText(page: WebPage | Page | FoundPage, name?: string, save?: string): string;
package/dist/fetch.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { unmetered } from "./fees.js";
2
- import { askedUrl, clip, 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_MAX_BYTES, 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";
@@ -215,21 +215,48 @@ export async function webFetch(url, { offset, maxChars, ...options } = {}) {
215
215
  }
216
216
  /** What the part no part follows says of a page whose HTML readPage cut before it was read (html_chars). */
217
217
  const CUT_LINE = `The page was cut at ${HTML_READ_CHARS.toLocaleString("en-US")} characters of HTML before reading; the rest wasn't read.`;
218
+ /** What the part no part follows says of a page whose body ran past the bytes the direct fetch reads (cut_bytes). */
219
+ const BYTES_LINE = `The page is longer than the ${PAGE_MAX_BYTES / (1024 * 1024)} MiB web_fetch reads, so its text here is only the start; the rest wasn't read.`;
220
+ /** Whether some of `page` is out of web_fetch's reach, as this part shows it: its body or its HTML cut before it was
221
+ * read, its text past PAGE_READ_MAX_CHARS (the last part reached says so; any part, where the whole length is known). */
222
+ const outOfReach = (page) => page.cut_bytes !== undefined || page.html_chars !== undefined || page.beyond_read === true || (page.original_chars ?? 0) > PAGE_READ_MAX_CHARS;
218
223
  /** Where a part of a page is in it, for the model: which characters of how many, and the call that reads on; the end of
219
224
  * the page, or where it was cut before it was read; or that the offset is past it. Nothing for a page read whole, or
220
- * one that was not read. */
221
- function partLine(page, name) {
225
+ * one that was not read. Of a page some of which web_fetch can't reach, it says so on every part that shows it, and
226
+ * names `save` (a tool that keeps a URL whole as a file) where one is given. */
227
+ function partLine(page, name, save) {
228
+ const line = placeLine(page, name);
229
+ if (line === undefined || !save || !outOfReach(page))
230
+ return line;
231
+ return `${line}${saveWords(save)}`;
232
+ }
233
+ /** What an objective's answer (found) says of a page some of which web_fetch can't reach: its chunks are of the part
234
+ * read, and the rest was never searched; naming `save` as partLine does. Nothing for a page read whole. */
235
+ function foundLine(page, save) {
236
+ if (!outOfReach(page))
237
+ return undefined;
238
+ const line = "These chunks are from the start of the page alone: web_fetch didn't read the rest, so it wasn't searched.";
239
+ return save ? `${line}${saveWords(save)}` : line;
240
+ }
241
+ /** The sentence that names `save`, the run's tool that keeps a URL whole as a file. */
242
+ const saveWords = (save) => ` To keep the whole page, save it as a file with ${save} (its url, and a path whose extension names its type, such as page.txt or page.html), then read that file.`;
243
+ /** partLine's place, before any word of `save`. */
244
+ function placeLine(page, name) {
222
245
  if (!page.ok || page.chars === undefined)
223
246
  return undefined;
224
247
  const start = page.offset ?? 0;
225
248
  const end = start + page.chars;
226
- if (page.truncated)
227
- return `Characters ${start}-${end} of ${page.original_chars ?? "a longer page"}: call ${name} again with offset=${page.next_offset ?? end} for the rest.`;
249
+ if (page.truncated) {
250
+ const reach = (page.original_chars ?? 0) > PAGE_READ_MAX_CHARS ? ` (web_fetch reads only its first ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")})` : "";
251
+ return `Characters ${start}-${end} of ${page.original_chars ?? "a longer page"}${reach}: call ${name} again with offset=${page.next_offset ?? end} for the rest.`;
252
+ }
228
253
  // No part follows, and the page was cut before it was read: its text ends at the cut, not at the page's end.
229
254
  if (page.html_chars !== undefined)
230
255
  return CUT_LINE;
231
256
  if (page.beyond_read)
232
257
  return `Characters ${start}-${end}${page.original_chars === undefined ? "" : ` of ${page.original_chars}`}: the page goes on, but web_fetch reads only a page's first ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")} characters.`;
258
+ if (page.cut_bytes !== undefined)
259
+ return BYTES_LINE;
233
260
  if (page.original_chars === undefined)
234
261
  return undefined;
235
262
  if (page.chars === 0)
@@ -244,15 +271,16 @@ function cameBy(page) {
244
271
  return page.ok ? "this one was fetched directly" : "the direct fetch failed too";
245
272
  }
246
273
  /** A page as the tool `name` answers the model: its JSON, then a line for each provider ahead that gave none saying why
247
- * and what gave the page instead, and one saying where this part is in the page when it is not all of it. */
248
- export function webFetchText(page, name = "web_fetch") {
274
+ * and what gave the page instead, and one saying where this part is in the page when it is not all of it: of a page
275
+ * some of which web_fetch can't reach, naming `save`, a tool the run has that keeps a URL whole as a file, where given. */
276
+ export function webFetchText(page, name = "web_fetch", save) {
249
277
  const lines = [JSON.stringify(page)];
250
278
  const came = cameBy(page);
251
279
  for (const [id, why] of Object.entries(missesOf(page))) {
252
280
  if (why)
253
281
  lines.push(`${providerName(id)} gave no page (${why}); ${came}.`);
254
282
  }
255
- const where = "found" in page ? undefined : partLine(page, name);
283
+ const where = "found" in page ? foundLine(page, save) : partLine(page, name, save);
256
284
  if (where)
257
285
  lines.push(where);
258
286
  return lines.join("\n");
package/dist/guard.d.ts CHANGED
@@ -6,16 +6,20 @@ export type GuardOptions = {
6
6
  fetchImpl?: (url: URL, init: Record<string, unknown>) => Promise<Response>;
7
7
  signal?: AbortSignal;
8
8
  };
9
- /** The answer that ended the redirects: its URL, status and type, and its body when it is a 2xx text answer. */
9
+ /** The answer that ended the redirects: its URL, status and type, and its body when it is a 2xx text answer; `cut` when
10
+ * the body is only its first bytes, up to the cap (asked with `cut`), the rest not read. */
10
11
  export type PublicAnswer = {
11
12
  url: string;
12
13
  status: number;
13
14
  contentType: string;
14
15
  body: string | null;
16
+ cut?: true;
15
17
  };
16
- /** The guarded fetch: `maxBytes` its byte cap (the guard's default when not given). */
18
+ /** The guarded fetch: `maxBytes` its byte cap (the guard's default when not given); `cut`, a body over it answered as its
19
+ * first bytes (`cut` on the answer) where the guard would refuse it. A guard that reads no `cut` refuses it as before. */
17
20
  export type PublicFetch = (url: string, options: GuardOptions & {
18
21
  maxBytes?: number;
22
+ cut?: boolean;
19
23
  }) => Promise<PublicAnswer>;
20
24
  /** An HTML page read as text: its title, its text (markdown), its links; `truncated` with `html_chars` (the page's whole
21
25
  * length) when its HTML was cut before it was read (HTML_READ_CHARS), `converted: "text"` when its conversion to
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { type Destination, type Destinations, type FetchOptions, type Hold, type
2
2
  export { type Guard, type GuardOptions, type HtmlRead, type HtmlReader, type PublicAnswer, type PublicCheck, type PublicFetch } from "./guard.js";
3
3
  export { type FetchShape, type NativeSearch, type ProviderParts, type ProviderRun, type ReadFailed, type Reader, type SearchAsk, type SettingsSpec, type WebClient, type WebProvider, defineProvider, holdingWords, readerOf, } from "./provider.js";
4
4
  export { type AheadProvider, type FetchProvider, type KeyedProvider, type ProviderId, type ProviderSettings, type SaidProvider, type SearchProvider, AHEAD, isProviderId, PROVIDERS, providerName, providerOf, SAID, serves, settingsProblemsOf, } from "./providers/registry.js";
5
- export { type ExaSearchType, type Fee, type ParallelSearchMode, type Pay, EXA_CONTENT_USD, EXA_SEARCH_INCLUDED, EXA_SEARCH_RESULT_USD, EXA_SEARCH_TYPE_USD, EXA_SUMMARY_USD, exaFeeOf, FIRECRAWL_CREDIT_USD, FIRECRAWL_JSON_CREDITS, FIRECRAWL_SCRAPE_CREDITS, FIRECRAWL_SEARCH_CREDITS, firecrawlFeeOf, PARALLEL_EXTRACT_USD, PARALLEL_SEARCH_INCLUDED, PARALLEL_SEARCH_MODE_USD, PARALLEL_SEARCH_RESULT_USD, PARALLEL_SEARCH_USD, PaidRefused, parallelExtractFee, parallelFeeOf, parallelSearchFee, unmetered, } from "./fees.js";
5
+ export { type ExaSearchType, type Fee, type ParallelSearchMode, type Pay, EXA_CONTENT_USD, EXA_SEARCH_INCLUDED, EXA_SEARCH_RESULT_USD, EXA_SEARCH_TYPE_USD, EXA_SUMMARY_USD, exaFeeOf, FIRECRAWL_CREDIT_USD, FIRECRAWL_JSON_CREDITS, FIRECRAWL_SCRAPE_CREDITS, FIRECRAWL_SEARCH_CREDITS, firecrawlFeeOf, PARALLEL_EXTRACT_USD, PARALLEL_SEARCH_INCLUDED, PARALLEL_SEARCH_MODE_USD, PARALLEL_SEARCH_RESULT_USD, PARALLEL_SEARCH_USD, PaidRefused, parallelChargeOf, parallelExtractFee, parallelFeeOf, parallelSearchFee, unmetered, } from "./fees.js";
6
6
  export { type Backend, type Breaker, type Failure, type FailureClass, type Hit, type Holding, type Limit, type Search, type SearchBounds, type Searched, type Try, ANSWER_MAX, breakers, CITE, fitSearch, OBJECTIVE_MAX, QUERIES_MAX, QUERY_MAX, RESULTS_DEFAULT, RESULTS_MAX, SEARCH_MAX_CHARS, SNIPPET_MAX, searchArgs, searchBreaker, searchInTurn, searchText, snippetOf, } from "./search.js";
7
7
  export { type FetchTry, type Pages, type Readers, type Via, type WebFetchOptions, type WebLog, type WebPage, type WebRead, type WebUnread, FETCH_ORDER, PAGES_HELD, webFetch, webFetchText, } from "./fetch.js";
8
8
  export { type Page, type Part, type Read, type Unread, askedUrl, clip, HTML_READ_CHARS, LINKS_CAP, LINKS_CHARS, MAX_CHARS_MIN, PAGE_CHARS, PAGE_MAX_BYTES, PAGE_READ_MAX_CHARS, partEnd, partProblem, TEXT_CAP, TITLE_CAP, URL_MAX, } from "./page.js";
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@
8
8
  export { createWeb, destinationsLine, destinationsWords, } from "./web.js";
9
9
  export { defineProvider, holdingWords, readerOf, } from "./provider.js";
10
10
  export { AHEAD, isProviderId, PROVIDERS, providerName, providerOf, SAID, serves, settingsProblemsOf, } from "./providers/registry.js";
11
- export { EXA_CONTENT_USD, EXA_SEARCH_INCLUDED, EXA_SEARCH_RESULT_USD, EXA_SEARCH_TYPE_USD, EXA_SUMMARY_USD, exaFeeOf, FIRECRAWL_CREDIT_USD, FIRECRAWL_JSON_CREDITS, FIRECRAWL_SCRAPE_CREDITS, FIRECRAWL_SEARCH_CREDITS, firecrawlFeeOf, PARALLEL_EXTRACT_USD, PARALLEL_SEARCH_INCLUDED, PARALLEL_SEARCH_MODE_USD, PARALLEL_SEARCH_RESULT_USD, PARALLEL_SEARCH_USD, PaidRefused, parallelExtractFee, parallelFeeOf, parallelSearchFee, unmetered, } from "./fees.js";
11
+ export { EXA_CONTENT_USD, EXA_SEARCH_INCLUDED, EXA_SEARCH_RESULT_USD, EXA_SEARCH_TYPE_USD, EXA_SUMMARY_USD, exaFeeOf, FIRECRAWL_CREDIT_USD, FIRECRAWL_JSON_CREDITS, FIRECRAWL_SCRAPE_CREDITS, FIRECRAWL_SEARCH_CREDITS, firecrawlFeeOf, PARALLEL_EXTRACT_USD, PARALLEL_SEARCH_INCLUDED, PARALLEL_SEARCH_MODE_USD, PARALLEL_SEARCH_RESULT_USD, PARALLEL_SEARCH_USD, PaidRefused, parallelChargeOf, parallelExtractFee, parallelFeeOf, parallelSearchFee, unmetered, } from "./fees.js";
12
12
  export { ANSWER_MAX, breakers, CITE, fitSearch, OBJECTIVE_MAX, QUERIES_MAX, QUERY_MAX, RESULTS_DEFAULT, RESULTS_MAX, SEARCH_MAX_CHARS, SNIPPET_MAX, searchArgs, searchBreaker, searchInTurn, searchText, snippetOf, } from "./search.js";
13
13
  export { FETCH_ORDER, PAGES_HELD, webFetch, webFetchText, } from "./fetch.js";
14
14
  export { askedUrl, clip, HTML_READ_CHARS, LINKS_CAP, LINKS_CHARS, MAX_CHARS_MIN, PAGE_CHARS, PAGE_MAX_BYTES, PAGE_READ_MAX_CHARS, partEnd, partProblem, TEXT_CAP, TITLE_CAP, URL_MAX, } from "./page.js";
package/dist/page.d.ts CHANGED
@@ -5,7 +5,9 @@
5
5
  * first part, how many of the page's links its caps left out. `html_chars`, on every part of a page whose HTML readPage
6
6
  * cut before it was read: the page's whole length in characters. Its text, all its parts together, is then the start of
7
7
  * the page's, so no part gives original_chars, and the last part (no truncated: no part follows) still says the page was
8
- * cut. `converted: "text"` when the text is the page's plain text, its conversion to markdown having run out of time. */
8
+ * cut. `cut_bytes`, on every part of a page whose body ran past PAGE_MAX_BYTES: the bytes of it that were read, its
9
+ * first; its text, all its parts together, is the start of the page's, and the last part says the rest was not read.
10
+ * `converted: "text"` when the text is the page's plain text, its conversion to markdown having run out of time. */
9
11
  export type Page = {
10
12
  ok: boolean;
11
13
  url: string;
@@ -19,6 +21,7 @@ export type Page = {
19
21
  offset?: number;
20
22
  next_offset?: number;
21
23
  html_chars?: number;
24
+ cut_bytes?: number;
22
25
  converted?: "text";
23
26
  links: string[];
24
27
  links_omitted?: number;
@@ -46,7 +49,8 @@ export declare const TIMEOUT_MS = 30000;
46
49
  * without loading a reader where nothing is fetched (web-fetch-direct-cut.test holds the two equal). */
47
50
  export declare const HTML_READ_CHARS = 1000000;
48
51
  /** The most bytes of a page any path reads: the guarded direct fetch's bound (pi-browser's PUBLIC_MAX_BYTES, 5 MiB,
49
- * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. */
52
+ * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. The direct fetch reads a longer
53
+ * page's first PAGE_MAX_BYTES (cut_bytes) and none of the rest. */
50
54
  export declare const PAGE_MAX_BYTES: number;
51
55
  /** `text`'s first `max` UTF-16 units, one fewer where the cut would split a surrogate pair: the one pair-safe cut. */
52
56
  export declare function cutAt(text: string, max: number): string;
@@ -97,7 +101,8 @@ export declare function pageText({ text, beyond, length }: Text, part?: Part): P
97
101
  * left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
98
102
  export declare function linksWithin(links: Iterable<string>): Pick<Page, "links" | "links_omitted">;
99
103
  /** A page read once, before any part of it is taken: its final url, status and title, its Text, the links its first part
100
- * holds (linksWithin), and readPage's `html_chars` and `converted` where it gave them. `written`, where its text writes
104
+ * holds (linksWithin), readPage's `html_chars` and `converted` where it gave them, and `cut_bytes` where the direct
105
+ * fetch read only the body's first bytes. `written`, where its text writes
101
106
  * every link it holds (a reading service's markdown, writtenRead): each link the service's whole answer writes, before
102
107
  * any cap or cut, from which its first part lists only those its own text does not write (unwrittenLinks). */
103
108
  export type Read = {
@@ -108,6 +113,7 @@ export type Read = {
108
113
  links: string[];
109
114
  links_omitted?: number;
110
115
  html_chars?: number;
116
+ cut_bytes?: number;
111
117
  converted?: "text";
112
118
  written?: readonly string[];
113
119
  } & Text;
package/dist/page.js CHANGED
@@ -22,7 +22,8 @@ export const TIMEOUT_MS = 30_000;
22
22
  * without loading a reader where nothing is fetched (web-fetch-direct-cut.test holds the two equal). */
23
23
  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
- * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. */
25
+ * held equal by web-fetch-direct-cut.test), and keyless Firecrawl's scrape's too. The direct fetch reads a longer
26
+ * page's first PAGE_MAX_BYTES (cut_bytes) and none of the rest. */
26
27
  export const PAGE_MAX_BYTES = 5 * 1024 * 1024;
27
28
  /** `text`'s first `max` UTF-16 units, one fewer where the cut would split a surrogate pair: the one pair-safe cut. */
28
29
  export function cutAt(text, max) {
@@ -1,7 +1,7 @@
1
1
  // The guarded direct fetch: one page through the injected public-host guard. A refusal or a failure is a Page with ok
2
2
  // false, never a throw. With no guard nothing is fetched.
3
3
  import { isRefused } from "../guard.js";
4
- import { askedUrl, clip, linksWithin, partOfRead, TIMEOUT_MS, TITLE_CAP, textOf, URL_MAX, withoutCredentials, withoutUserinfo } from "../page.js";
4
+ import { askedUrl, clip, linksWithin, PAGE_MAX_BYTES, partOfRead, TIMEOUT_MS, TITLE_CAP, textOf, URL_MAX, withoutCredentials, withoutUserinfo } from "../page.js";
5
5
  import { defineProvider } from "../provider.js";
6
6
  import { bare } from "../search.js";
7
7
  import { linksOf } from "../text-urls.js";
@@ -33,19 +33,25 @@ async function readTyped(url, guard, options) {
33
33
  return failed("refused", "NO_GUARD", { error: "no public-host guard was given, so nothing is fetched directly" });
34
34
  try {
35
35
  const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(options.signal ? [options.signal] : [])]);
36
- const answer = await guard.fetch(url, { ...options, signal });
36
+ // A body past the guard's cap is read to the cap and answered as the page's start (cut_bytes), never refused whole.
37
+ const answer = await guard.fetch(url, { ...options, signal, cut: true });
37
38
  if (answer.body === null)
38
39
  return failed(answer.status >= 500 ? "infra" : "error", `PAGE_${answer.status}`, { url: clip(withoutCredentials(answer.url), URL_MAX), status: answer.status, error: `the page answered ${answer.status}` });
39
40
  // The caller's stop reaches the read too; the timeout is the network's, and the reader keeps its own deadline.
40
41
  const read = guard.html && /html/i.test(answer.contentType) ? await guard.html(answer.body, answer.url, options.signal ? { signal: options.signal } : {}) : null;
41
42
  const page = read ?? { title: "", text: answer.body, links: linksOf(answer.body) };
43
+ // The guard's cap, which the direct fetch never lowers: pi-browser's PUBLIC_MAX_BYTES, PAGE_MAX_BYTES here.
44
+ const cut = answer.cut ? { cut_bytes: PAGE_MAX_BYTES } : {};
42
45
  return {
43
46
  ok: true,
44
47
  url: clip(withoutCredentials(answer.url), URL_MAX),
45
48
  status: answer.status,
46
49
  title: clip(page.title, TITLE_CAP),
47
- ...textOf(page.text, !read?.truncated),
48
- ...(read?.truncated ? { html_chars: read.html_chars } : {}),
50
+ // A body cut at the cap: its text is the page's start, its length not the page's, and readPage's html_chars, the
51
+ // length of what it was handed, not the page's either.
52
+ ...textOf(page.text, !read?.truncated && !answer.cut),
53
+ ...(read?.truncated && !answer.cut ? { html_chars: read.html_chars } : {}),
54
+ ...cut,
49
55
  ...(read?.converted === "text" ? { converted: "text" } : {}),
50
56
  ...linksWithin(page.links),
51
57
  };
@@ -34,7 +34,7 @@ export type Extract = {
34
34
  read(url: string, signal?: AbortSignal, client?: WebClient): Promise<Read | string>;
35
35
  post(url: string, body: unknown, signal?: AbortSignal): Promise<Response>;
36
36
  };
37
- /** Parallel's extract on `apiKey`: one URL a request, each a billed extract, its full content to the most of a page
37
+ /** Parallel's extract on `apiKey`: one URL a request, each billed as its usage says, its full content to the most of a page
38
38
  * web_fetch reads as the page's text (markdown), its links read from it, status 200 (Parallel answers a page it could
39
39
  * not read in `errors`, with no content), told the read's client (clientFields). */
40
40
  export declare function parallelExtract(apiKey: string, send?: typeof fetch, pay?: Pay, settings?: ParallelSettings): Extract;
@@ -1,6 +1,6 @@
1
1
  // Parallel on the run's key: Extract for web_fetch, Search for web_search. Every request is paid through the injected
2
2
  // Pay at its endpoint's price, and a 401 or 403 stops both for the client's life. Nothing is retried; each ends at 60 s.
3
- import { PARALLEL_SEARCH_MODE_USD, PaidRefused, parallelFeeOf, unmetered } from "../fees.js";
3
+ import { PARALLEL_SEARCH_MODE_USD, PaidRefused, parallelChargeOf, parallelFeeOf, unmetered } from "../fees.js";
4
4
  import { clip, cutAt, markdownRead, PAGE_READ_MAX_CHARS, TITLE_CAP } from "../page.js";
5
5
  import { failed, failure, keyWide, searchArgs, searchFailed, snippetOf } from "../search.js";
6
6
  import { defineProvider, settingsOf } from "../provider.js";
@@ -37,14 +37,15 @@ const clientFields = (client) => ({
37
37
  ...(client.model ? { client_model: client.model } : {}),
38
38
  ...(client.session ? { session_id: client.session.slice(0, SESSION_MAX) } : {}),
39
39
  });
40
- /** Parallel's extract on `apiKey`: one URL a request, each a billed extract, its full content to the most of a page
40
+ /** Parallel's extract on `apiKey`: one URL a request, each billed as its usage says, its full content to the most of a page
41
41
  * web_fetch reads as the page's text (markdown), its links read from it, status 200 (Parallel answers a page it could
42
42
  * not read in `errors`, with no content), told the read's client (clientFields). */
43
43
  export function parallelExtract(apiKey, send = fetch, pay = unmetered, settings = {}) {
44
44
  // One keyed client for both tools (keyed.ts keyedClient): each request paid through `pay` at its endpoint's price
45
45
  // (fees.ts; serve's paid-calls.ts holds it to the run's cap), one with no price, or one the cap refuses, not sent
46
- // (PaidRefused), a stopped call sending nothing and one that never left not billed (paidSend).
47
- const client = keyedClient({ who: "Parallel", base: PARALLEL_API_URL, headers: { "x-api-key": apiKey }, feeOf: (path, body) => parallelFeeOf(`${PARALLEL_API_URL}${path}`, body), timeoutMs: PARALLEL_TIMEOUT_MS, refuseOn: [401, 403] }, send, pay);
46
+ // (PaidRefused), a stopped call sending nothing and one that never left not billed (paidSend). An extract is charged
47
+ // the URLs Parallel's usage says it billed (parallelChargeOf): none for a URL it lists in errors.
48
+ const client = keyedClient({ who: "Parallel", base: PARALLEL_API_URL, headers: { "x-api-key": apiKey }, feeOf: (path, body) => parallelFeeOf(`${PARALLEL_API_URL}${path}`, body), chargeOf: parallelChargeOf, timeoutMs: PARALLEL_TIMEOUT_MS, refuseOn: [401, 403] }, send, pay);
48
49
  const post = async (url, body, signal) => {
49
50
  // It carries the key: a URL not below Parallel's API is never sent, as a request with no price here.
50
51
  if (!url.startsWith(`${PARALLEL_API_URL}/`))
@@ -1,7 +1,7 @@
1
1
  // What a model reads of web_search and web_fetch: each tool's description and its parameters' JSON Schema. One text
2
2
  // whatever provider answers, naming none, so every provider is asked through the same words; which provider answers is
3
3
  // the server's to say elsewhere, never here. AgentRun's server builds both tools from these, and so may any harness.
4
- import { HTML_READ_CHARS, MAX_CHARS_MIN, PAGE_CHARS, PAGE_READ_MAX_CHARS, TEXT_CAP } from "./page.js";
4
+ import { HTML_READ_CHARS, MAX_CHARS_MIN, PAGE_CHARS, PAGE_MAX_BYTES, PAGE_READ_MAX_CHARS, TEXT_CAP } from "./page.js";
5
5
  import { OBJECTIVE_MAX, QUERIES_MAX, QUERY_MAX, RESULTS_DEFAULT, RESULTS_MAX, SNIPPET_MAX } from "./search.js";
6
6
  const count = (n) => n.toLocaleString("en-US");
7
7
  /** web_search's description: what to ask (an objective and a few short keyword queries) and what it answers. */
@@ -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, 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.`;
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 fetched directly whose body is over ${PAGE_MAX_BYTES / (1024 * 1024)} MiB is read to its first ${PAGE_MAX_BYTES / (1024 * 1024)} MiB: cut_bytes on every part says so, its text is only the start of the page, and the last part's line says the rest wasn't read. 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-web",
3
- "version": "0.1.0-beta.73",
3
+ "version": "0.1.0-beta.75",
4
4
  "description": "Web search and web fetch for agents: providers asked in an order given as data, a breaker per provider, a per-run page cache read in parts, and a direct fetch through an injected public-host guard.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -46,7 +46,7 @@
46
46
  "undici": "^8.14.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@parcha/pi-browser": "0.1.0-beta.73"
49
+ "@parcha/pi-browser": "0.1.0-beta.75"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",