@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.
@@ -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";
@@ -29,19 +29,35 @@ const feesOfCall = new AsyncLocalStorage();
29
29
  const usd = (lines) => Math.round(lines.reduce((sum, fee) => sum + fee.usd, 0) * 1e6) / 1e6;
30
30
  const outOf = (text) => ({ bytes: Buffer.byteLength(text), chars: text.length });
31
31
  const unjudged = { wall: { verdict: "unjudged" }, injection: "unjudged" };
32
- /** `shared`, a guard check another call started, or as soon as `signal` stops this call, the page left unjudged as a
33
- * stopped check leaves it (code "aborted"). The shared check is not stopped: another call may still need it. */
34
- function guardUntilStopped(shared, signal) {
35
- if (!signal)
36
- return shared;
37
- const stopped = () => ({ wall: { verdict: "unjudged", error: { code: "aborted", message: String(signal.reason?.message ?? signal.reason).slice(0, 500) } }, injection: "unjudged" });
38
- if (signal.aborted)
39
- return Promise.resolve(stopped());
40
- return new Promise((resolve, reject) => {
41
- const onStop = () => resolve(stopped());
42
- signal.addEventListener("abort", onStop, { once: true });
43
- shared.then((guard) => (signal.removeEventListener("abort", onStop), resolve(guard)), (error) => (signal.removeEventListener("abort", onStop), reject(error)));
44
- });
32
+ /** The page left unjudged as a stopped guard check leaves it (code "aborted"), by `signal`'s reason. */
33
+ const stoppedGuard = (signal) => ({ wall: { verdict: "unjudged", error: { code: "aborted", message: String(signal.reason?.message ?? signal.reason).slice(0, 500) } }, injection: "unjudged" });
34
+ function sharedGuard(ask) {
35
+ const own = new AbortController();
36
+ let waiting = 0;
37
+ let settled = false;
38
+ const verdict = ask(own.signal);
39
+ void verdict.then(() => (settled = true), () => (settled = true));
40
+ return {
41
+ verdict,
42
+ stopped: () => own.signal.aborted,
43
+ wait(signal) {
44
+ if (signal?.aborted)
45
+ return Promise.resolve(stoppedGuard(signal));
46
+ waiting += 1;
47
+ if (!signal)
48
+ return verdict;
49
+ return new Promise((resolve, reject) => {
50
+ const onStop = () => {
51
+ resolve(stoppedGuard(signal));
52
+ waiting -= 1;
53
+ if (waiting === 0 && !settled)
54
+ own.abort(signal.reason);
55
+ };
56
+ signal.addEventListener("abort", onStop, { once: true });
57
+ verdict.then((guard) => (signal.removeEventListener("abort", onStop), resolve(guard)), (error) => (signal.removeEventListener("abort", onStop), reject(error)));
58
+ });
59
+ },
60
+ };
45
61
  }
46
62
  export function createWeb(config) {
47
63
  const problems = settingsProblemsOf(config.settings);
@@ -63,14 +79,20 @@ export function createWeb(config) {
63
79
  * and a page read again is asked about again, as is one whose guard failed. */
64
80
  const pageVerdicts = new WeakMap();
65
81
  const guardOf = (decider, url, read, step) => {
66
- const known = pageVerdicts.get(read);
67
- // A later caller waits on the check another started only until its own signal stops it; the check goes on.
68
- if (known)
69
- return guardUntilStopped(known, step.signal);
70
- const asked = guardPage(decider, url, read, step);
71
- pageVerdicts.set(read, asked);
72
- void asked.then((verdict) => verdict.wall.error && pageVerdicts.delete(read));
73
- return asked;
82
+ // One verdict a page: a read another fragment of its URL shares is that page (sharedRead).
83
+ const page = sharedRead(read);
84
+ const known = pageVerdicts.get(page);
85
+ // A check every waiter stopped is not joined, though it is the page's until its verdict settles: ask anew.
86
+ if (known && !known.stopped())
87
+ return known.wait(step.signal);
88
+ // A call already stopped starts no check.
89
+ if (step.signal?.aborted)
90
+ return Promise.resolve(stoppedGuard(step.signal));
91
+ // The check is the page's, not the caller's: no caller's stop ends it while another call waits on it (sharedGuard).
92
+ const shared = sharedGuard((signal) => guardPage(decider, url, read, { ...step, signal }));
93
+ pageVerdicts.set(page, shared);
94
+ void shared.verdict.then((verdict) => verdict.wall.error && pageVerdicts.get(page) === shared && pageVerdicts.delete(page));
95
+ return shared.wait(step.signal);
74
96
  };
75
97
  /** A receipt's `unsifted`, only in a run with a classifier. */
76
98
  const unsifted = (text) => (config.decider ? { unsifted: text() } : {});
@@ -107,8 +129,28 @@ export function createWeb(config) {
107
129
  };
108
130
  };
109
131
  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()));
132
+ // A fee goes on the call's receipt once its request is sent, whatever the cap then books. One that never left (its send
133
+ // answered unsentAnswer, which the cap settles at $0) is $0 on it, saying so, as decisionPay's line for an unbilled
134
+ // request is, once the cap's settle is written: a settle that failed leaves the line at the hold, as the cap keeps it.
135
+ const pay = async (fee, send, charged, settled) => {
136
+ const lines = feesOfCall.getStore();
137
+ let at = -1;
138
+ let unsent;
139
+ let booked = true;
140
+ const answer = await (config.pay ?? unmetered)(fee, async () => {
141
+ if (lines)
142
+ at = lines.push(fee) - 1;
143
+ const response = await send();
144
+ unsent = unsentOf(response);
145
+ return response;
146
+ }, charged, (landed) => {
147
+ booked = landed;
148
+ settled?.(landed);
149
+ });
150
+ if (lines && at >= 0 && unsent !== undefined)
151
+ lines[at] = booked ? { ...fee, usd: 0, basis: `not billed (not sent: ${unsent})` } : { ...fee, basis: `${fee.basis}; its settle failed, so the hold stands, not $0 (not sent: ${unsent})` };
152
+ return answer;
153
+ };
112
154
  // 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
155
  // provider, so a key refused by one tool is refused by both.
114
156
  const runs = new Map();
@@ -166,24 +208,28 @@ export function createWeb(config) {
166
208
  const answer = fitSearch(sifted.answer);
167
209
  const { classifier } = sifted;
168
210
  const said = [asked.objective, asked.query].find((one) => typeof one === "string") ?? "";
211
+ // A copy: a sift this call stopped waiting for may still pay, and its fee is not on this receipt.
212
+ const spent = [...lines];
169
213
  // 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))) };
214
+ const receipt = { op: "search", asked: ask.objective || said, queries: ask.queries, provider: "error" in answer ? null : answer.provider, tries, classifier, ...unjudged, out: outOf(searchText(answer)), cost: { usd: usd(spent), lines: spent }, ...unsifted(() => searchText(fitSearch(found))) };
171
215
  return { answer, receipt };
172
216
  },
173
217
  // Only the call's part, resolver, transport, signal, task, objective and session are read: the guard, its bound, the order
174
218
  // and the readers stay the Web's.
175
219
  async fetch(url, { offset, maxChars, task, objective, lookingFor, lookup, fetchImpl, signal, session } = {}) {
176
220
  const asked = typeof url === "string" ? url : "";
221
+ // What a receipt names: the URL as the page names it, with no user name or password (askedUrl).
222
+ const named = askedUrl(url);
177
223
  const lines = [];
178
224
  const tries = [];
179
225
  // A part a call may not ask for is refused before anything is fetched.
180
226
  const problem = partProblem({ offset, maxChars });
181
227
  if (problem) {
182
- const refused = { ok: false, url: askedUrl(asked), status: 0, title: "", text: "", links: [], error: problem };
228
+ const refused = { ok: false, url: named, status: 0, title: "", text: "", links: [], error: problem };
183
229
  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)) } };
230
+ 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
231
  }
186
- const cached = typeof url === "string" && pages.has(url);
232
+ const cached = typeof url === "string" && pages.has(pageKey(url));
187
233
  const whole = await feesOfCall.run(lines, () => webRead(url, {
188
234
  ...(lookup ? { lookup } : {}),
189
235
  ...(fetchImpl ? { fetchImpl } : {}),
@@ -201,13 +247,13 @@ export function createWeb(config) {
201
247
  const provider = part.ok && part.via !== "stopped" && part.via !== "none" ? part.via : null;
202
248
  const decider = held;
203
249
  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 });
250
+ 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
251
  // What the objective found names each provider asked ahead that gave no page, as the part does.
206
252
  const answer = "found" in decided.answer ? { ...decided.answer, ...missesOf(whole) } : decided.answer;
207
253
  const { classifier, guard: verdicts } = decided;
208
254
  // Copies: a read this call stopped waiting for goes on, and its later turns and fees are not on this receipt.
209
255
  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)) };
256
+ 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
257
  return { answer, receipt };
212
258
  },
213
259
  };
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.66",
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.66"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",