@parcha/pi-browser 0.1.0-beta.34 → 0.1.0-beta.341

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/NOTICE +6 -1
  3. package/README.md +70 -60
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +12 -30
  6. package/dist/core/custody.d.ts +6 -0
  7. package/dist/core/custody.js +15 -3
  8. package/dist/core/downloads.d.ts +37 -3
  9. package/dist/core/downloads.js +81 -57
  10. package/dist/core/driving-guard.d.ts +1 -1
  11. package/dist/core/driving-guard.js +1 -1
  12. package/dist/core/evidence.d.ts +1 -1
  13. package/dist/core/files.d.ts +20 -2
  14. package/dist/core/files.js +161 -10
  15. package/dist/core/host.d.ts +18 -75
  16. package/dist/core/images.d.ts +32 -4
  17. package/dist/core/images.js +81 -16
  18. package/dist/core/lease.d.ts +2 -1
  19. package/dist/core/page-scan.d.ts +81 -2
  20. package/dist/core/page-scan.js +487 -13
  21. package/dist/core/public-fetch.d.ts +70 -9
  22. package/dist/core/public-fetch.js +348 -51
  23. package/dist/core/read-page-worker.js +5 -4
  24. package/dist/core/read-page.d.ts +23 -8
  25. package/dist/core/read-page.js +64 -20
  26. package/dist/core/redact.d.ts +0 -2
  27. package/dist/core/redact.js +0 -32
  28. package/dist/core/session-control.d.ts +0 -2
  29. package/dist/core/session-control.js +0 -5
  30. package/dist/core/tools.d.ts +23 -1
  31. package/dist/core/tools.js +46 -4
  32. package/dist/core/usage.d.ts +4 -3
  33. package/dist/core/usage.js +5 -4
  34. package/dist/core/vault.d.ts +0 -10
  35. package/dist/core/vault.js +0 -13
  36. package/dist/core/web.d.ts +2 -111
  37. package/dist/core/web.js +0 -443
  38. package/dist/driver/cdp.js +3 -3
  39. package/dist/driver/page-driver.js +7 -3
  40. package/dist/driver/stagehand.d.ts +3 -1
  41. package/dist/driver/stagehand.js +4 -2
  42. package/dist/durable/store.d.ts +14 -3
  43. package/dist/durable/store.js +204 -51
  44. package/dist/durable.d.ts +32 -16
  45. package/dist/durable.js +68 -95
  46. package/dist/index.d.ts +3 -3
  47. package/dist/index.js +5 -3
  48. package/dist/live-view/index.d.ts +3 -1
  49. package/dist/live-view/index.js +4 -0
  50. package/dist/live-view/protocol.d.ts +1 -1
  51. package/dist/live-view/server.d.ts +30 -0
  52. package/dist/live-view/server.js +152 -25
  53. package/dist/providers/cdp.js +2 -2
  54. package/dist/providers/profiles.d.ts +1 -15
  55. package/dist/providers/profiles.js +1 -64
  56. package/dist/providers/shared.d.ts +1 -47
  57. package/dist/providers/shared.js +1 -82
  58. package/dist/providers/worker-extension.d.ts +14 -1
  59. package/dist/providers/worker-extension.js +69 -3
  60. package/dist/testing/backend.d.ts +6 -24
  61. package/dist/testing/backend.js +7 -30
  62. package/dist/vault-session.d.ts +4 -7
  63. package/dist/vault-session.js +26 -81
  64. package/dist/vendor/browser-use-pi/page.d.ts +3 -12
  65. package/dist/vendor/browser-use-pi/page.js +6 -19
  66. package/package.json +9 -22
  67. package/dist/core/sites.d.ts +0 -33
  68. package/dist/core/sites.js +0 -104
  69. package/dist/durable/web.d.ts +0 -47
  70. package/dist/durable/web.js +0 -41
  71. package/dist/providers/browserbase-net.d.ts +0 -12
  72. package/dist/providers/browserbase-net.js +0 -95
  73. package/dist/providers/browserbase.d.ts +0 -169
  74. package/dist/providers/browserbase.js +0 -319
  75. package/dist/providers/kernel.d.ts +0 -58
  76. package/dist/providers/kernel.js +0 -291
  77. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  78. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -1,61 +1,93 @@
1
1
  // A fetched HTML page read as its title, its text and its links, without ever holding the event loop. The host's tools
2
2
  // run in the run's own process, so a read that holds the loop holds the run's heartbeat with it, and a run whose
3
3
  // heartbeat lapses is fenced: go.dev/dl, 3.15 MB of tables, held it past 240 s in one markdown conversion. So one linear
4
- // pass drops the blocks that hold no readable text (page-scan.ts); what is left is cut at READ_MAX_CHARS (the page is
4
+ // pass drops the blocks that hold no readable text, and another the elements the page hides from everyone (page-scan.ts:
5
+ // a help pop-up until its link is clicked is not the page's text); what is left is cut at READ_MAX_CHARS (the page is
5
6
  // then `truncated`, and `html_chars` is its whole length); and a worker thread converts that to markdown, in pieces
6
7
  // small enough that the converter stays linear (page-markdown.ts), within a deadline. A worker that has not answered by
7
8
  // then, or that fails, is stopped, and the text is the page's plain text, read on the loop in steps that yield it
8
- // (`converted: "text"`). browser_read's markdown (htmlMarkdown) goes through the same worker, which drops, picks and
9
- // cuts the live page's HTML itself, since that HTML has no bound; its fallback is the browser's own text.
9
+ // (`converted: "text"`); a worker that ran out of memory is not: the read is refused (PageReadOutOfMemory), since what
10
+ // filled the worker's heap would fill the run's own. The links resolved are bounded (READ_LINKS_MAX and
11
+ // READ_LINKS_MAX_CHARS, page-scan.ts). browser_read's markdown (htmlMarkdown) goes through the same worker, which drops,
12
+ // picks and cuts the live page's HTML itself, since that HTML has no bound; its fallback is the browser's own text.
10
13
  import { setImmediate as yieldToLoop } from "node:timers/promises";
11
14
  import { Worker } from "node:worker_threads";
12
15
  import { decodeEntities } from "./entities.js";
13
- import { cutHtml, InertDrop, PageScan } from "./page-scan.js";
16
+ import { cutHtml, HiddenDrop, InertDrop, pageHidingOf, PageScan } from "./page-scan.js";
17
+ export { READ_LINKS_MAX, READ_LINKS_MAX_CHARS } from "./page-scan.js";
14
18
  /** The most of a page's HTML that is read, counted once its script, style, svg, noscript and template blocks and its
15
19
  * comments are dropped. A million characters of go.dev/dl converts in about 0.8 s on a busy 48-core host and gives
16
20
  * 590,000 characters of markdown, ten times the 60,000 one web_fetch answer carries. */
17
21
  export const READ_MAX_CHARS = 1_000_000;
18
22
  /** How long the worker has for the markdown by default: six times what READ_MAX_CHARS of tables took. */
19
23
  export const READ_DEADLINE_MS = 5_000;
24
+ /** The worker's heap by default, in MB (`heapMb`). */
25
+ export const READ_WORKER_HEAP_MB = 1024;
26
+ /** The least heap a worker is given, in MB: one of a few MB fails while it starts, and takes its whole process down. */
27
+ const WORKER_HEAP_MIN_MB = 16;
20
28
  /** `n` with its digits in groups of three ("3,154,060"): Intl's first use costs tens of milliseconds on the loop. */
21
29
  export const thousands = (n) => String(n).replace(/\B(?=(\d{3})+$)/g, ",");
22
30
  /** How much of the page one step of the plain-text scan reads before it yields the loop. */
23
31
  const STEP_CHARS = 32_768;
32
+ /** The worker ran out of its heap (Node's ERR_WORKER_OUT_OF_MEMORY). */
33
+ const OUT_OF_MEMORY = Symbol("out of memory");
34
+ /** readPage's refusal of a page whose read filled the worker's heap: it is not read again on the caller's thread. */
35
+ export class PageReadOutOfMemory extends Error {
36
+ heapMb;
37
+ name = "PageReadOutOfMemory";
38
+ code = "PAGE_READ_OUT_OF_MEMORY";
39
+ constructor(heapMb) {
40
+ super(`the page was not read: reading it filled the reader's ${heapMb} MB heap`);
41
+ this.heapMb = heapMb;
42
+ }
43
+ }
24
44
  /**
25
45
  * An HTML page's title, its text as markdown, and the absolute http(s) URLs it links to (resolved against its
26
46
  * `<base href>` or `url`), each once, in page order. The event loop is never held for longer than one linear step of a
27
- * bounded part of the page (see the file's head and PageRead). Rejects only with `signal`'s reason.
47
+ * bounded part of the page (see the file's head and PageRead). Rejects with `signal`'s reason, or with
48
+ * PageReadOutOfMemory when the worker ran out of memory (the page is then not read on this thread).
28
49
  */
29
- export async function readPage(html, url, { deadlineMs = READ_DEADLINE_MS, signal } = {}) {
50
+ export async function readPage(html, url, { deadlineMs = READ_DEADLINE_MS, heapMb = READ_WORKER_HEAP_MB, signal } = {}) {
30
51
  signal?.throwIfAborted();
31
- const kept = await dropOnLoop(html, signal);
52
+ // What the page hides from everyone who reads it (a help pop-up until its link is clicked, a closed dialog) is not
53
+ // its text: what its own live style elements declare is read from those the inert drop took out.
54
+ const inert = new InertDrop(html);
55
+ await stepsOnLoop(inert, signal);
56
+ const kept = await dropHiddenOnLoop(inert.result(), pageHidingOf(inert.styles()), signal);
32
57
  const read = cutHtml(kept, READ_MAX_CHARS);
33
58
  const cut = read.length < kept.length ? { truncated: true, html_chars: html.length } : {};
34
59
  await yieldToLoop();
35
60
  signal?.throwIfAborted();
36
- const markdown = await inWorker({ html: read, url }, deadlineMs, signal);
61
+ const markdown = await inWorker({ html: read, url }, deadlineMs, heapMb, signal);
62
+ if (markdown === OUT_OF_MEMORY)
63
+ throw new PageReadOutOfMemory(Math.max(WORKER_HEAP_MIN_MB, heapMb));
37
64
  if (markdown)
38
- return { title: markdown.title ?? "", text: markdown.text, links: markdown.links ?? [], converted: "markdown", ...cut };
65
+ return { title: markdown.title ?? "", text: markdown.text, links: markdown.links ?? [], ...(markdown.links_truncated ? { links_truncated: true } : {}), converted: "markdown", ...cut };
39
66
  return { ...(await plainRead(read, url, signal)), converted: "text", ...cut };
40
67
  }
41
68
  /**
42
69
  * `html`'s markdown, made in the worker within `deadlineMs` (default READ_DEADLINE_MS): of its first article, else its
43
70
  * main, else its body element when `main` (mainOf), once its inert blocks are dropped, cut at READ_MAX_CHARS (then
44
- * `truncated`, and `html_chars` is the page's whole length). Null when the worker has not answered in time, failed, or
45
- * could not start. The event loop does no more than hand the worker the page. Rejects only with `signal`'s reason.
71
+ * `truncated`, and `html_chars` is the page's whole length). Null when the worker has not answered in time, failed (ran
72
+ * out of memory included), or could not start. The event loop does no more than hand the worker the page. Rejects only
73
+ * with `signal`'s reason.
46
74
  */
47
- export async function htmlMarkdown(html, { main = false, deadlineMs = READ_DEADLINE_MS, signal } = {}) {
75
+ export async function htmlMarkdown(html, { main = false, deadlineMs = READ_DEADLINE_MS, heapMb = READ_WORKER_HEAP_MB, signal } = {}) {
48
76
  signal?.throwIfAborted();
49
- const answer = await inWorker({ html, main, max: READ_MAX_CHARS }, deadlineMs, signal);
50
- return answer && { text: answer.text, ...(answer.truncated ? { truncated: true, html_chars: answer.html_chars } : {}) };
77
+ const answer = await inWorker({ html, main, max: READ_MAX_CHARS }, deadlineMs, heapMb, signal);
78
+ // Out of memory too: the caller's fallback is the browser's own text, never this HTML read on its thread.
79
+ if (!answer || answer === OUT_OF_MEMORY)
80
+ return null;
81
+ return { text: answer.text, ...(answer.truncated ? { truncated: true, html_chars: answer.html_chars } : {}) };
51
82
  }
52
- /** The worker's answer to `job`, or null when it has not answered within `deadlineMs`, failed, or could not start. */
53
- function inWorker(job, deadlineMs, signal) {
83
+ /** The worker's answer to `job`, OUT_OF_MEMORY when it ran out of its `heapMb` heap, or null when it has not answered
84
+ * within `deadlineMs`, failed otherwise, or could not start. */
85
+ function inWorker(job, deadlineMs, heapMb, signal) {
54
86
  return new Promise((resolve, reject) => {
55
87
  let worker;
56
88
  // execArgv: none of the host's own flags (a test runner's --import, say) reach the worker.
57
89
  try {
58
- worker = new Worker(new URL("./read-page-worker.js", import.meta.url), { workerData: job, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 1024 } });
90
+ worker = new Worker(new URL("./read-page-worker.js", import.meta.url), { workerData: job, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: Math.max(WORKER_HEAP_MIN_MB, heapMb) } });
59
91
  }
60
92
  catch {
61
93
  resolve(null);
@@ -71,17 +103,28 @@ function inWorker(job, deadlineMs, signal) {
71
103
  const timer = setTimeout(() => settle(() => resolve(null)), deadlineMs);
72
104
  signal?.addEventListener("abort", onAbort, { once: true });
73
105
  worker.once("message", (answer) => settle(() => resolve(typeof answer?.text === "string" ? answer : null)));
74
- worker.once("error", () => settle(() => resolve(null)));
106
+ worker.once("error", (error) => settle(() => resolve(error?.code === "ERR_WORKER_OUT_OF_MEMORY" ? OUT_OF_MEMORY : null)));
75
107
  worker.once("exit", () => settle(() => resolve(null)));
76
108
  });
77
109
  }
78
110
  /** `html` without its inert blocks (InertDrop), STEP_CHARS at a time with the loop yielded between steps. */
79
111
  export async function dropOnLoop(html, signal) {
80
112
  const drop = new InertDrop(html);
81
- while (!drop.step(STEP_CHARS)) {
113
+ await stepsOnLoop(drop, signal);
114
+ return drop.result();
115
+ }
116
+ /** Runs `pass` STEP_CHARS at a time, the loop yielded between steps, to its end. */
117
+ async function stepsOnLoop(pass, signal) {
118
+ while (!pass.step(STEP_CHARS)) {
82
119
  await yieldToLoop();
83
120
  signal?.throwIfAborted();
84
121
  }
122
+ }
123
+ /** `html` without the elements it hides from everyone (HiddenDrop), with `page` what its own live styles declare
124
+ * (pageHidingOf), STEP_CHARS at a time with the loop yielded between steps. */
125
+ async function dropHiddenOnLoop(html, page, signal) {
126
+ const drop = new HiddenDrop(html, page, decodeEntities);
127
+ await stepsOnLoop(drop, signal);
85
128
  return drop.result();
86
129
  }
87
130
  /** `html`'s plain text, title and links, scanned STEP_CHARS at a time with the loop yielded between steps. */
@@ -92,5 +135,6 @@ async function plainRead(html, url, signal) {
92
135
  await yieldToLoop();
93
136
  signal?.throwIfAborted();
94
137
  }
95
- return scan.result();
138
+ const { title, text, links, linksCut } = scan.result();
139
+ return { title, text, links, ...(linksCut ? { links_truncated: true } : {}) };
96
140
  }
@@ -16,7 +16,5 @@ export declare function redactContent<T extends {
16
16
  /** A live view as the host receives it, on every channel (`onSession`, a handoff's `request`): the viewer's own URLs stay
17
17
  * whole, since the host needs their token; a browsed page's URL and title are scrubbed, since its query can carry a credential. */
18
18
  export declare function hostLiveView(view: LiveView, redact: Redact): LiveView;
19
- /** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
20
- export declare function scrubFetchedUrl(raw: string, requested: string, redact: Redact): string;
21
19
  /** Every string inside `value`, object keys included, passed through `redact`. */
22
20
  export declare function redactDeep<T>(value: T, redact: Redact): T;
@@ -47,38 +47,6 @@ export function redactContent(content, redact) {
47
47
  export function hostLiveView(view, redact) {
48
48
  return { ...view, pages: view.pages.map((page) => ({ ...page, url: page.url === null ? null : scrubPageUrl(page.url, redact), title: page.title === null ? null : redact(page.title) })) };
49
49
  }
50
- /** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
51
- export function scrubFetchedUrl(raw, requested, redact) {
52
- let url, asked;
53
- try {
54
- url = new URL(raw);
55
- }
56
- catch {
57
- return redact(raw);
58
- }
59
- if (url.protocol !== "http:" && url.protocol !== "https:")
60
- return redact(raw);
61
- try {
62
- asked = new URL(requested);
63
- }
64
- catch {
65
- return scrubPageUrl(raw, redact);
66
- }
67
- const decoded = (text) => { try {
68
- return decodeURIComponent(text.replace(/\+/g, " "));
69
- }
70
- catch {
71
- return text;
72
- } };
73
- const pairsOf = (search) => search.slice(1).split("&").filter(Boolean).map((pair) => {
74
- const at = pair.indexOf("=");
75
- return at < 0 ? { pair, key: pair, value: "" } : { pair, key: pair.slice(0, at), value: pair.slice(at + 1) };
76
- });
77
- const sent = new Set(pairsOf(asked.search).map(({ key, value }) => `${decoded(key)}\0${decoded(value)}`));
78
- const query = pairsOf(url.search).map(({ pair, key, value }) => (sent.has(`${decoded(key)}\0${decoded(value)}`) ? pair : `${key}=${REDACTED}`));
79
- const fragment = url.hash && url.hash === asked.hash ? url.hash : "";
80
- return redact(`${url.protocol}//${url.host}${url.pathname}${query.length ? `?${query.join("&")}` : ""}${fragment}`);
81
- }
82
50
  /** Every string inside `value`, object keys included, passed through `redact`. */
83
51
  export function redactDeep(value, redact) {
84
52
  if (typeof value === "string")
@@ -23,5 +23,3 @@ export declare function idleTracker<K = string>(options: {
23
23
  /** Every environment variable that holds a provider key: each redactor in either adapter scrubs their values. */
24
24
  export declare const PROVIDER_KEY_ENV: readonly string[];
25
25
  export declare const providerKeyValues: (env: NodeJS.ProcessEnv, host?: () => readonly string[]) => string[];
26
- /** Runs one at a time, in arrival order: each starts once the one before it has settled, however that one ended. */
27
- export declare function oneAtATime(): <T>(run: () => Promise<T>) => Promise<T>;
@@ -73,8 +73,3 @@ export function idleTracker(options) {
73
73
  /** Every environment variable that holds a provider key: each redactor in either adapter scrubs their values. */
74
74
  export const PROVIDER_KEY_ENV = Object.freeze(["BROWSERBASE_API_KEY", "BB_API_KEY", "KERNEL_API_KEY"]);
75
75
  export const providerKeyValues = (env, host) => [...PROVIDER_KEY_ENV.map((name) => env[name] ?? "").filter(Boolean), ...(host?.() ?? [])];
76
- /** Runs one at a time, in arrival order: each starts once the one before it has settled, however that one ended. */
77
- export function oneAtATime() {
78
- let turn = Promise.resolve();
79
- return (run) => { const mine = turn.then(run, run); turn = mine.catch(() => undefined); return mine; };
80
- }
@@ -1,6 +1,7 @@
1
1
  import { type BrowserDriver, type CustodyPort, type ToolOutput } from "./custody.js";
2
2
  import { type EvidenceSink } from "./evidence.js";
3
3
  import type { Decisions } from "./decisions.js";
4
+ import { type DownloadsWorkspace } from "./downloads.js";
4
5
  import type { WorkspaceFiles } from "./host.js";
5
6
  import { type RepeatGuard } from "./guard.js";
6
7
  import { type Locate } from "./clip.js";
@@ -92,7 +93,7 @@ export type ToolCall = {
92
93
  redact: Redact;
93
94
  evidence: EvidenceSink;
94
95
  classifyPage?: Decisions["classifyPage"];
95
- workspace?: string;
96
+ workspace?: DownloadsWorkspace;
96
97
  files?: WorkspaceFiles;
97
98
  };
98
99
  export type ToolImpl<D extends BrowserDriver = BrowserDriver, A = unknown> = (args: A, port: CustodyPort<D>, call: ToolCall) => Promise<ToolOutput>;
@@ -118,6 +119,7 @@ export type BrowserToolArgs = {
118
119
  };
119
120
  id?: string;
120
121
  selector?: string;
122
+ save_as?: string;
121
123
  };
122
124
  browser_read: {
123
125
  what?: (typeof WHATS)[number];
@@ -157,6 +159,26 @@ type Lost = {
157
159
  /** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
158
160
  * them): they were not sent, so the model may send them again. */
159
161
  export declare const lostRequests: (lost: readonly Lost[]) => string;
162
+ /** Where a screenshot's `save_as` saves it and in which format, or why it is refused: a path relative to the workspace
163
+ * (workspacePathRefusal), its folders separated by "/" alone (as computer_screenshot's save_as), naming a .png, .jpg
164
+ * or .jpeg file, whose format agrees with `type` when it is given. A .png name asks for a PNG; a .jpg name leaves the
165
+ * capture as it was asked (a JPEG unless type says png, which is refused). */
166
+ export declare function savePlanOf(given: unknown, type: "png" | "jpeg" | undefined): {
167
+ path: string;
168
+ format: "png" | "jpeg";
169
+ } | {
170
+ refused: string;
171
+ };
172
+ /** What became of a screenshot's save_as: saved at `path`, or not, with the reason in a word and in a sentence. */
173
+ export type SaveOutcome = {
174
+ path: string;
175
+ saved: true;
176
+ } | {
177
+ path: string;
178
+ saved: false;
179
+ reason: "format_changed" | "refused";
180
+ message: string;
181
+ };
160
182
  export declare function pageTools({ guards, reconnect: timings, readDeadlineMs }?: {
161
183
  /** Each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
162
184
  guards?: Map<number, RepeatGuard>;
@@ -3,6 +3,7 @@ import { BrowserFailureError, FenceRefusal, refusedError, loadedNoPage, passedTh
3
3
  import { defaultInline } from "./evidence.js";
4
4
  import { fetchDownloads } from "./downloads.js";
5
5
  import { asPartial, browserFailure, classifyBrowserError, partialOf, transportFactOf } from "./failures.js";
6
+ import { workspacePathRefusal } from "./files.js";
6
7
  import { createRepeatGuard } from "./guard.js";
7
8
  import { regionOf } from "./clip.js";
8
9
  import { captureWithinBudget } from "./images.js";
@@ -69,6 +70,35 @@ const lostOf = (error) => (error !== null && typeof error === "object" ? (error[
69
70
  /** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
70
71
  * them): they were not sent, so the model may send them again. */
71
72
  export const lostRequests = (lost) => `The browser lost ${lost.length === 1 ? "a request" : `${lost.length} requests`} your page made before ${lost.length === 1 ? "the request" : "they"} left the browser: ${lost.map((r) => `${r.method} ${r.url}`).join(", ")}. Chrome's network service restarted while ${lost.length === 1 ? "it was" : "they were"} on ${lost.length === 1 ? "its" : "their"} way, so ${lost.length === 1 ? "the request was" : "the requests were"} not sent. Make ${lost.length === 1 ? "it" : "them"} again if you still need ${lost.length === 1 ? "it" : "them"}.`;
73
+ /** Where a screenshot's `save_as` saves it and in which format, or why it is refused: a path relative to the workspace
74
+ * (workspacePathRefusal), its folders separated by "/" alone (as computer_screenshot's save_as), naming a .png, .jpg
75
+ * or .jpeg file, whose format agrees with `type` when it is given. A .png name asks for a PNG; a .jpg name leaves the
76
+ * capture as it was asked (a JPEG unless type says png, which is refused). */
77
+ export function savePlanOf(given, type) {
78
+ const bad = workspacePathRefusal(given);
79
+ if (bad)
80
+ return { refused: `save_as: ${bad}` };
81
+ // One separator, so the path the run's gate reads is the path written: a backslash is refused, never read as a "/".
82
+ if (given.includes("\\"))
83
+ return { refused: `save_as separates folders with "/", never a backslash: not ${JSON.stringify(given)}` };
84
+ const path = given.split("/").filter((part) => part !== "" && part !== ".").join("/");
85
+ const format = /\.png$/i.test(path) ? "png" : /\.jpe?g$/i.test(path) ? "jpeg" : null;
86
+ if (!format || /(^|\/)\.(png|jpe?g)$/i.test(path))
87
+ return { refused: `save_as names a .png, .jpg or .jpeg file: not ${JSON.stringify(given)}` };
88
+ if (type !== undefined && type !== format)
89
+ return { refused: `save_as ${JSON.stringify(given)} names a ${format === "png" ? "PNG" : "JPEG"} file, and type asks for ${type === "png" ? "a PNG" : "a JPEG"}: give a name that matches type, or leave type out` };
90
+ return { path, format };
91
+ }
92
+ /** The capture's own bytes (the ones filed as evidence) written at the plan's path through the host's write, unless the
93
+ * capture came back in another format than the name says (a PNG over the size budget is retaken as a JPEG): a file
94
+ * whose bytes are not what its name says is never written. */
95
+ async function saveCapture(plan, taken, bytes, write) {
96
+ if (taken !== plan.format) {
97
+ return { path: plan.path, saved: false, reason: "format_changed", message: `the ${plan.format === "png" ? "PNG" : "JPEG"} was over the size budget and was taken as a ${taken === "png" ? "PNG" : "JPEG"}, so it was not saved as ${plan.path}; save a .${taken === "png" ? "png" : "jpg"} name, or capture a smaller region (clip, id or selector)` };
98
+ }
99
+ const out = await write(plan.path, bytes).catch((error) => ({ refused: `${plan.path} could not be written: ${error?.message ?? String(error)}` }));
100
+ return "refused" in out ? { path: plan.path, saved: false, reason: "refused", message: out.refused } : { path: out.path, saved: true };
101
+ }
72
102
  /** A read of a browser that has loaded no page yet: it is fresh, and the next step is to navigate, to the replaced
73
103
  * session's last page when there is one. */
74
104
  function freshBrowser(replaced) {
@@ -412,8 +442,16 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
412
442
  });
413
443
  },
414
444
  screenshot: (args, port, call) => {
415
- const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, ...requested } = args ?? {};
445
+ const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, save_as: saveAs, ...asks } = args ?? {};
416
446
  const ask = typeof asked === "string" && asked.trim() ? asked.trim() : undefined;
447
+ // A save_as is checked before any browser call, so a refused one captures and files nothing.
448
+ const plan = saveAs === undefined ? undefined : savePlanOf(saveAs, asks.type);
449
+ if (plan && "refused" in plan)
450
+ return Promise.resolve(text(browserFailure("refused", plan.refused), true));
451
+ const write = call.files?.write?.bind(call.files);
452
+ if (plan && !write)
453
+ return Promise.resolve(text(browserFailure("refused", "This host gives the browser no workspace to save a screenshot into."), true));
454
+ const requested = plan?.format === "png" ? { ...asks, type: "png" } : asks;
417
455
  return perform("screenshot", args ?? {}, port, call, "read", async (s, news) => {
418
456
  // A region goes through the same capture as the whole page, so whatever guards a capture guards a clipped one.
419
457
  const region = await regionOf({ clip: wantedClip, id: wantedId, selector: wantedSelector, fullPage: requested.fullPage }, s.driver.locate?.bind(s.driver));
@@ -421,10 +459,14 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
421
459
  const url = pageUrl(call, await s.driver.url());
422
460
  const receipt = await file(s, call, { tool: "screenshot", args: region ? { ...requested, clip: region.clip, ...region.of } : requested, status: "ok", facts: { final_url: url }, body: Buffer.from(shot.data, "base64"), ext: shot.size.type === "png" ? "png" : "jpg" });
423
461
  const first = shot.adjusted?.first;
424
- const adjusted = shot.adjusted && `adjusted: the first capture${first ? ` (${first.width}x${first.height})` : ""} was over the ${shot.adjusted.why === "long_edge" ? "2,000 px long edge" : "size"} budget; this is ${region ? "the clip" : "the viewport"} at ${shot.size.width}x${shot.size.height}`;
425
- const lines = [news, `url: ${url}`, `evidence: ${receipt.path ?? "(not filed)"}`, adjusted].filter(Boolean).join("\n");
462
+ const over = shot.adjusted?.why === "long_edge" ? "was over the 2,000 px long edge budget" : shot.adjusted?.why === "base64_bytes" ? "was over the size budget" : "could not be measured";
463
+ const taken = shot.options.clip ? "the clip" : shot.options.fullPage ? "the full page" : "the viewport";
464
+ const scaled = shot.options.scale !== undefined && shot.options.scale < 1 ? ", scaled down" : "";
465
+ const adjusted = shot.adjusted && `adjusted: the first capture${first ? ` (${first.width}x${first.height})` : ""} ${over}; this is ${taken} at ${shot.size.width}x${shot.size.height}${scaled}`;
466
+ const saved = plan && write ? await saveCapture(plan, shot.size.type, Buffer.from(shot.data, "base64"), write) : undefined;
467
+ const lines = [news, `url: ${url}`, `evidence: ${receipt.path ?? "(not filed)"}`, adjusted, saved && (saved.saved ? `saved: ${saved.path}` : `not saved: ${saved.message}`)].filter(Boolean).join("\n");
426
468
  const media = { kind: "screenshot", path: receipt.bodyPath, mime: shot.mimeType, bytes: Buffer.from(shot.data, "base64").byteLength, width: shot.size.width, height: shot.size.height, ...(region ? { clip: region.clip, ...region.of } : {}), ...(ask ? { ask } : {}) };
427
- return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256, media } };
469
+ return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256, media, ...(saved ? { save_as: saved } : {}) } };
428
470
  });
429
471
  },
430
472
  browser_read: (args, port, call) => {
@@ -7,15 +7,16 @@ export declare function sessionPrice(raw: string | null | undefined): {
7
7
  /** List prices with the host's overrides on top; an override of `null` is a deliberate gap. */
8
8
  export declare const resolvePrices: (overrides?: Partial<PriceTable>) => PriceTable;
9
9
  export declare const toolUsage: (usd: number, state?: PriceState) => ToolUsage;
10
- export declare const fetchUsage: (prices: PriceTable, proxied: boolean) => ToolUsage;
11
- export declare const searchUsage: (prices: PriceTable) => ToolUsage;
12
10
  type Spent = SessionRecord["spent"];
13
11
  export declare const startSpent: (createdAt: string) => Spent;
14
12
  /** The record after a charge, with its list-priced dollars: the ones it already held plus this charge's when the price was the list's. `after` is what `sessionCharge` returned. */
15
13
  export declare function withEstimate(before: Spent, after: Spent, listPriced: boolean): Spent;
16
- /** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing. */
14
+ /** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing. A
15
+ * charge through an `at` before the record's `chargedThrough` bills no time (an earlier charge billed past it), and says
16
+ * by how much in `overbookedS`. */
17
17
  export declare function sessionCharge(spent: Spent, at: string, prices: PriceTable, state?: PriceState, final?: boolean): {
18
18
  spent: Spent;
19
19
  usage: ToolUsage;
20
+ overbookedS?: number;
20
21
  };
21
22
  export {};
@@ -17,8 +17,6 @@ export const toolUsage = (usd, state = "priced") => ({
17
17
  usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: usd } },
18
18
  state,
19
19
  });
20
- export const fetchUsage = (prices, proxied) => toolUsage(proxied ? prices.fetchProxiedUsd : prices.fetchUsd);
21
- export const searchUsage = (prices) => toolUsage(prices.searchUsd);
22
20
  /** Integer picodollars, so a bill reads as its decimal amount (0.002, not 0.0019999999999999996). */
23
21
  const PICO = 1e12;
24
22
  const HOUR_MS = 3600000n;
@@ -29,7 +27,9 @@ export function withEstimate(before, after, listPriced) {
29
27
  const estimated = Math.round(((before.estimatedUsd ?? 0) + (listPriced ? added : 0)) * PICO) / PICO;
30
28
  return estimated > 0 ? { ...after, estimatedUsd: estimated } : after;
31
29
  }
32
- /** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing. */
30
+ /** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing. A
31
+ * charge through an `at` before the record's `chargedThrough` bills no time (an earlier charge billed past it), and says
32
+ * by how much in `overbookedS`. */
33
33
  export function sessionCharge(spent, at, prices, state = "priced", final = false) {
34
34
  if (spent.final)
35
35
  return { spent, usage: toolUsage(0, state === "invalid" ? "invalid" : prices.sessionUsdPerHour === null || state !== "priced" ? "unpriced" : "priced") };
@@ -37,6 +37,7 @@ export function sessionCharge(spent, at, prices, state = "priced", final = false
37
37
  // 59.99999999999999 s.
38
38
  const before = Math.round(spent.seconds * 1000);
39
39
  const elapsed = Math.max(0, Date.parse(at) - Date.parse(spent.chargedThrough));
40
+ const overbooked = Math.max(0, Date.parse(spent.chargedThrough) - Date.parse(at));
40
41
  const charged = elapsed + (final ? Math.max(0, Math.round(prices.sessionMinimumS * 1000) - (before + elapsed)) : 0);
41
42
  const price = prices.sessionUsdPerHour;
42
43
  const priced = price !== null && state === "priced";
@@ -46,5 +47,5 @@ export function sessionCharge(spent, at, prices, state = "priced", final = false
46
47
  const picos = Number(owed / HOUR_MS);
47
48
  const carry = Number(owed % HOUR_MS);
48
49
  const gap = priced ? "priced" : state === "invalid" ? "invalid" : "unpriced";
49
- return { spent: { seconds: (before + charged) / 1000, usd: (Math.round(spent.usd * PICO) + picos) / PICO, chargedThrough: elapsed > 0 ? at : spent.chargedThrough, ...(final ? { final: true } : {}), ...(carry ? { carry } : {}) }, usage: toolUsage(picos / PICO, gap) };
50
+ return { spent: { seconds: (before + charged) / 1000, usd: (Math.round(spent.usd * PICO) + picos) / PICO, chargedThrough: elapsed > 0 ? at : spent.chargedThrough, ...(final ? { final: true } : {}), ...(carry ? { carry } : {}) }, usage: toolUsage(picos / PICO, gap), ...(overbooked > 0 ? { overbookedS: overbooked / 1000 } : {}) };
50
51
  }
@@ -19,17 +19,7 @@ export type CapturedState = {
19
19
  /** Only cookies the allowed origins would be sent (see `cookieKept`). Partitioned cookies are not kept. */
20
20
  cookies: VaultCookie[];
21
21
  localStorage: Record<string, Record<string, string>>;
22
- }
23
- /** `origins`: the origins the context was captured for. A context holds a whole browser profile, so it is restored only for a request that covers EVERY one of them (`coversEveryOrigin`); one that records none is refused. */
24
- | {
25
- kind: "provider-context";
26
- capturedAt: string;
27
- provider: "browserbase" | "kernel";
28
- contextId: string;
29
- origins?: string[];
30
22
  };
31
- /** Whether `requested` includes every origin in `saved` (as scheme://host[:port], any order): a provider context is all-or-nothing, so a request for some of its origins would bring back the others' sign-ins. */
32
- export declare function coversEveryOrigin(requested: readonly string[], saved: readonly string[] | undefined): boolean;
33
23
  export interface SessionVaultPort {
34
24
  /** At release and at the end of a handoff, and, for a context a new session made, right after the create (so a restart still finds it). The host supplied the origins; nothing outside them was captured.
35
25
  * A capture has a deadline (20 s) after which nothing more is read or written, but a write already handed to this port cannot be recalled: ignore one whose `capturedAt` is older than the one you hold. */
@@ -11,19 +11,6 @@ export function clampSessionCookieAgeMs(requested) {
11
11
  throw new RangeError("the session-cookie age cap is a positive number of milliseconds");
12
12
  return Math.min(requested, MAX_SESSION_COOKIE_AGE_MS);
13
13
  }
14
- /** Whether `requested` includes every origin in `saved` (as scheme://host[:port], any order): a provider context is all-or-nothing, so a request for some of its origins would bring back the others' sign-ins. */
15
- export function coversEveryOrigin(requested, saved) {
16
- if (!saved || saved.length === 0)
17
- return false;
18
- const origin = (value) => { try {
19
- return new URL(value).origin;
20
- }
21
- catch {
22
- return null;
23
- } };
24
- const have = new Set(requested.map(origin));
25
- return saved.every((value) => { const o = origin(value); return o !== null && have.has(o); });
26
- }
27
14
  const SESSION_KEY = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
28
15
  /** The host's allowed origins, each `scheme://host[:port]` of http or https, normalised and de-duplicated; anything else is refused. */
29
16
  export function vaultOrigins(origins) {
@@ -1,107 +1,10 @@
1
- import type { Decisions, PageVerdict, WallClass } from "./decisions.js";
2
- import { type EvidenceSink } from "./evidence.js";
3
- import { type BrowserFailure, type Next } from "./failures.js";
4
- import { type FetchRequest, type FetchResult, type PriceTable, type SearchRequest, type SearchResult } from "./host.js";
5
- export declare const WEB_SEARCH_QUERY_MAX = 200;
6
- export declare const WEB_SEARCH_RESULTS_MAX = 25;
7
- export declare const WEB_SEARCH_RESULTS_DEFAULT = 10;
8
- /** A provider's excerpt with markdown links reduced to their text and whitespace collapsed, clipped at a word boundary;
9
- * null when it has no text. A link inside a page is the page's lead, not the hit's, and its URL only spends the bound. */
10
- export declare function boundSnippet(raw: unknown): string | null;
1
+ import type { PageVerdict, WallClass } from "./decisions.js";
2
+ import type { BrowserFailure, Next } from "./failures.js";
11
3
  /** Over 507 recorded pages, ordinary pages scored up to 0.66 and a page with a spliced instruction 0.98. */
12
4
  export declare const INJECTION_THRESHOLD = 0.75;
13
- /** A search answer's snippets are page text the model has not read through a fetch, so each hit that carries one is judged like a page
14
- * before the model sees it. At most this many judgments run at once, and the whole screen is held to this long. */
15
- export declare const SNIPPET_SCREEN_CONCURRENCY = 5;
16
- export declare const SNIPPET_SCREEN_TIMEOUT_MS = 30000;
17
- /** The largest PDF handed to the host's `pdf.text`; a larger one is named and left to `format: "raw"`. */
18
- export declare const PDF_TEXT_MAX_BYTES: number;
19
- export declare const PDF_TEXT_TIMEOUT_MS = 120000;
20
- /** Told the calling conversation's scope, so a host can hold it to what that conversation may use. `available`, when
21
- * given, says whether that conversation can reach it at all: a backup it answers false for is neither tried nor named
22
- * among the sources tried. */
23
- export type WebBackup = {
24
- name: string;
25
- available?(scope: {
26
- label: string;
27
- proxies: boolean;
28
- }): boolean;
29
- fetch(url: string, signal?: AbortSignal, scope?: {
30
- label: string;
31
- proxies: boolean;
32
- }): Promise<string>;
33
- };
34
- /** A search the host tries before the provider's own, in order: one that throws hands the call to the next, and the
35
- * provider's own search answers last. Its answer is priced at the usage it reports, else at the list search price.
36
- * `available`, when given, is asked at each call: a source it answers false for is neither tried nor named as a
37
- * failure (one that has learned it is not served this run). */
38
- export type SearchSource = {
39
- name: string;
40
- available?(): boolean;
41
- search(request: SearchRequest, signal?: AbortSignal): Promise<SearchResult>;
42
- };
43
- /** A reader the host tries before the provider's own fetch for a markdown read, in order, with `available` as for a
44
- * `SearchSource`. One that throws, or answers no content or an HTTP error status, hands the call to the next; its
45
- * failure is never the call's own, which stays the provider's. A page it answers is filed exactly as the provider's
46
- * is, under `via: <name>_fetch`, and is priced at the usage it reports, else at the list fetch price. */
47
- export type FetchSource = {
48
- name: string;
49
- available?(): boolean;
50
- fetch(request: FetchRequest, signal?: AbortSignal): Promise<FetchResult>;
51
- };
52
- export type RenderedPage = {
53
- finalUrl: string | null;
54
- statusCode: number | null;
55
- contentType: string | null;
56
- content: string;
57
- extractor?: "readability-md" | "inner-text";
58
- usd?: number;
59
- };
60
- export type WebToolsOptions = {
61
- /** `via` is `<name>_fetch` and `<name>_search`. */
62
- name: string;
63
- fetch?: (request: FetchRequest, signal?: AbortSignal) => Promise<FetchResult>;
64
- search?: (request: SearchRequest, signal?: AbortSignal) => Promise<SearchResult>;
65
- /** See `SearchSource`. */
66
- searchSources?: readonly SearchSource[];
67
- /** See `FetchSource`. */
68
- fetchSources?: readonly FetchSource[];
69
- evidence: EvidenceSink;
70
- scope(conversation: string | number): {
71
- label: string;
72
- proxies: boolean;
73
- } | Promise<{
74
- label: string;
75
- proxies: boolean;
76
- }>;
77
- prices?: Partial<PriceTable>;
78
- redact?: {
79
- values: () => readonly string[];
80
- };
81
- backups?: readonly WebBackup[];
82
- classifyPage?: Decisions["classifyPage"];
83
- render?: {
84
- enabled: boolean;
85
- read(url: string, signal?: AbortSignal): Promise<RenderedPage>;
86
- };
87
- /** Text of a PDF the provider would not convert to markdown; null or blank is a PDF with no readable text. */
88
- pdf?: {
89
- text(bytes: Uint8Array, url: string, signal: AbortSignal): Promise<string | null>;
90
- maxBytes?: number;
91
- timeoutMs?: number;
92
- };
93
- /** How long the screening of a search answer's snippets may take in all; default `SNIPPET_SCREEN_TIMEOUT_MS`. */
94
- snippetScreenMs?: number;
95
- };
96
5
  export type WebFailure = BrowserFailure & {
97
6
  wall?: WallClass;
98
7
  };
99
- export type WebOutcome = {
100
- text: string;
101
- isError: boolean;
102
- details: Record<string, unknown>;
103
- usd: number;
104
- };
105
8
  export declare const WALLS: Record<WallClass, {
106
9
  code: "blocked" | "not_content";
107
10
  what: string;
@@ -112,15 +15,3 @@ export declare function wallFailure(subject: string, wall: WallClass, detail?: s
112
15
  /** The line before a page the model reads: an injection over the threshold first, whatever the wall; then a page not screened, an unjudged
113
16
  * wall or a score that is not a finite number. */
114
17
  export declare function pageNotice(verdict: PageVerdict | null | undefined): string;
115
- export declare function filedBody(result: string): string;
116
- export type WebTools = {
117
- fetch(conversation: string | number, args: {
118
- url?: unknown;
119
- format?: unknown;
120
- }, signal?: AbortSignal): Promise<WebOutcome>;
121
- search(conversation: string | number, args: {
122
- query?: unknown;
123
- n?: unknown;
124
- }, signal?: AbortSignal): Promise<WebOutcome>;
125
- };
126
- export declare function createWebTools(options: WebToolsOptions): WebTools;