@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,5 +1,6 @@
1
1
  import { constants } from "node:fs";
2
- import { open, readlink, realpath, stat } from "node:fs/promises";
2
+ import { lstat, mkdir, open, readlink, realpath, rename, rm, stat } from "node:fs/promises";
3
+ import { randomBytes } from "node:crypto";
3
4
  import path from "node:path";
4
5
  export const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
5
6
  const MIME = {
@@ -9,6 +10,9 @@ const MIME = {
9
10
  ".svg": "image/svg+xml", ".txt": "text/plain", ".webp": "image/webp", ".xls": "application/vnd.ms-excel",
10
11
  ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xml": "application/xml", ".zip": "application/zip",
11
12
  };
13
+ /** The media type browser_upload gives a file named `name`, by its extension; application/octet-stream for one it does
14
+ * not know. */
15
+ export const uploadMime = (name) => MIME[path.extname(name).toLowerCase()] ?? "application/octet-stream";
12
16
  // Where the opened file really is, so a parent directory swapped for a symlink after the check is caught.
13
17
  async function openedPath(handle, checked) {
14
18
  if (process.platform === "linux")
@@ -16,17 +20,41 @@ async function openedPath(handle, checked) {
16
20
  const [opened, now] = await Promise.all([handle.stat(), stat(checked).catch(() => null)]);
17
21
  return now && opened.dev === now.dev && opened.ino === now.ino ? realpath(checked).catch(() => null) : null;
18
22
  }
23
+ /** Why `rel` is no path of a file in a workspace, or null when it is one: a relative path with no `..` segment. Where it
24
+ * then leads (a link on the way) is the reader's or the writer's to check. */
25
+ export function workspacePathRefusal(rel) {
26
+ if (typeof rel !== "string" || !rel.trim() || rel.includes("\0"))
27
+ return "path must name a file in the workspace";
28
+ if (path.isAbsolute(rel) || path.win32.isAbsolute(rel))
29
+ return `${rel} is absolute; give a path relative to the workspace`;
30
+ if (rel.split(/[\\/]/).includes(".."))
31
+ return `${rel} contains '..'; give a path inside the workspace`;
32
+ return null;
33
+ }
34
+ const DIR_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
35
+ const errno = (error) => error?.code;
36
+ /** A write's refusal, carried out of the walk. */
37
+ class Refused extends Error {
38
+ }
19
39
  /** Files under `root` only: a relative path with no `..`, inside `root` once symlinks resolve, at most `maxBytes`, and
20
- * not one `refuse` names (a host's private files). */
21
- export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse } = {}) {
40
+ * not one `refuse` names (a host's private files). A write takes folders separated by "/" alone and follows no link on
41
+ * the way, the file itself included: it walks from the root one folder at a time, each opened as a folder through no
42
+ * link and held, makes each missing one, and replaces the file whole (a temporary file made beside it, then renamed
43
+ * over the name; a reader sees the old file or the new one).
44
+ *
45
+ * On Linux (`procFd`, default there) every name after the root resolves inside a folder a handle holds, so a folder
46
+ * swapped for a link by another process changes nothing: what is made or written is made in the folders walked.
47
+ * Elsewhere node can only resolve a path again, so before and after each act the folders held are checked: each still
48
+ * there by its path, no link, the same folder (dev and inode); else the write is refused, and the temporary file
49
+ * removed. What remains there is the gap between the last check and the call itself: a folder swapped for a link in
50
+ * it, and put back before the next check, can have that one call (a folder made, an empty temporary file made, or the
51
+ * rename) land through the link; the bytes are written only once the temporary file is confirmed in the folder held. */
52
+ export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse, procFd = process.platform === "linux" } = {}) {
22
53
  return {
23
54
  async resolve(rel) {
24
- if (typeof rel !== "string" || !rel.trim() || rel.includes("\0"))
25
- return { refused: "path must name a file in the workspace" };
26
- if (path.isAbsolute(rel) || path.win32.isAbsolute(rel))
27
- return { refused: `${rel} is absolute; give a path relative to the workspace` };
28
- if (rel.split(/[\\/]/).includes(".."))
29
- return { refused: `${rel} contains '..'; give a path inside the workspace` };
55
+ const bad = workspacePathRefusal(rel);
56
+ if (bad)
57
+ return { refused: bad };
30
58
  let base;
31
59
  try {
32
60
  base = await realpath(root);
@@ -64,11 +92,134 @@ export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse } = {
64
92
  ;
65
93
  if (size !== info.size)
66
94
  return { refused: `${rel} changed while it was read; try again` };
67
- return { bytes: new Uint8Array(buffer.subarray(0, size)), name: path.basename(where), mime: MIME[path.extname(where).toLowerCase()] ?? "application/octet-stream" };
95
+ return { bytes: new Uint8Array(buffer.subarray(0, size)), name: path.basename(where), mime: uploadMime(where) };
68
96
  }
69
97
  finally {
70
98
  await handle.close();
71
99
  }
72
100
  },
101
+ async write(rel, bytes) {
102
+ const bad = workspacePathRefusal(rel);
103
+ if (bad)
104
+ return { refused: bad };
105
+ if (rel.includes("\\"))
106
+ return { refused: `${rel}: folders are separated by "/", never a backslash` };
107
+ const parts = rel.split("/").filter((part) => part !== "" && part !== ".");
108
+ const name = parts.pop();
109
+ if (!name)
110
+ return { refused: "path must name a file in the workspace" };
111
+ let base;
112
+ try {
113
+ base = await realpath(root);
114
+ }
115
+ catch {
116
+ return { refused: "the workspace does not exist" };
117
+ }
118
+ const held = [];
119
+ const at = (dir, child) => (procFd ? `/proc/self/fd/${dir.handle.fd}/${child}` : path.join(dir.abs, child));
120
+ const outside = () => new Refused(`${rel} resolves outside the workspace, or a link is on the way to it, and a write follows none`);
121
+ // Off /proc/self/fd: every folder held is still there by its path, through no link, the same folder.
122
+ const confirm = async () => {
123
+ if (procFd)
124
+ return;
125
+ for (const dir of held.slice(1)) {
126
+ const now = await lstat(dir.abs).catch(() => null);
127
+ if (!now?.isDirectory() || now.dev !== dir.dev || now.ino !== dir.ino)
128
+ throw outside();
129
+ }
130
+ };
131
+ const hold = async (handle, abs) => {
132
+ const info = await handle.stat().catch(async (error) => { await handle.close(); throw error; });
133
+ const dir = { handle, abs, dev: info.dev, ino: info.ino };
134
+ held.push(dir);
135
+ return dir;
136
+ };
137
+ const enter = async (dir, index) => {
138
+ const part = parts[index];
139
+ for (let made = false;;) {
140
+ try {
141
+ const handle = await open(at(dir, part), DIR_FLAGS);
142
+ const next = await hold(handle, path.join(dir.abs, part));
143
+ await confirm();
144
+ return next;
145
+ }
146
+ catch (error) {
147
+ if (error instanceof Refused)
148
+ throw error;
149
+ const code = errno(error);
150
+ if (code === "ENOENT" && !made) {
151
+ made = true;
152
+ await confirm();
153
+ await mkdir(at(dir, part)).catch((making) => { if (making.code !== "EEXIST")
154
+ throw making; });
155
+ await confirm();
156
+ continue;
157
+ }
158
+ const there = await lstat(at(dir, part)).catch(() => null);
159
+ if (code === "ELOOP" || there?.isSymbolicLink())
160
+ throw new Refused(`${rel}: a link is on the way to it, and a write follows none`);
161
+ if (code === "ENOTDIR" || there)
162
+ throw new Refused(`${rel}: ${parts.slice(0, index + 1).join("/")} is not a directory`);
163
+ throw error;
164
+ }
165
+ }
166
+ };
167
+ let temp = null;
168
+ let tempIn = null;
169
+ let placed = false;
170
+ try {
171
+ let dir = await hold(await open(base, DIR_FLAGS), base);
172
+ for (let index = 0; index < parts.length; index++)
173
+ dir = await enter(dir, index);
174
+ const target = path.join(dir.abs, name);
175
+ await confirm();
176
+ const there = await lstat(at(dir, name)).catch(() => null);
177
+ await confirm();
178
+ if (there?.isSymbolicLink())
179
+ return { refused: `${rel} is a link, and a write follows none` };
180
+ if (there && !there.isFile())
181
+ return { refused: `${rel} is not a regular file` };
182
+ const vetoed = refuse?.(target);
183
+ if (vetoed)
184
+ return { refused: `${rel}: ${vetoed}` };
185
+ // Not built from the name, as serve's workspace writes are not: a name the folder takes may leave no room for more.
186
+ const tempName = `.workspace-${randomBytes(8).toString("hex")}.tmp`;
187
+ const handle = await open(at(dir, tempName), constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o666).catch(() => null);
188
+ if (!handle)
189
+ return { refused: `${rel} cannot be written` };
190
+ temp = tempName;
191
+ tempIn = dir;
192
+ try {
193
+ // The file just made is the one at its name in the folder held, before any byte is written to it.
194
+ await confirm();
195
+ const [made, named] = await Promise.all([handle.stat(), lstat(at(dir, tempName)).catch(() => null)]);
196
+ if (!named || named.dev !== made.dev || named.ino !== made.ino)
197
+ throw outside();
198
+ await confirm();
199
+ await handle.writeFile(bytes);
200
+ await handle.sync();
201
+ }
202
+ finally {
203
+ await handle.close();
204
+ }
205
+ await confirm();
206
+ // A rename replaces whatever is at the name, a link swapped in included, and never writes through it; one that
207
+ // resolves through a folder swapped since the check finds no temporary file there, and fails.
208
+ await rename(at(dir, tempName), at(dir, name));
209
+ placed = true;
210
+ await dir.handle.sync();
211
+ return { path: [...parts, name].join("/") };
212
+ }
213
+ catch (error) {
214
+ if (error instanceof Refused)
215
+ return { refused: error.message };
216
+ return { refused: `${rel} cannot be written` };
217
+ }
218
+ finally {
219
+ if (!placed && temp && tempIn)
220
+ await rm(at(tempIn, temp), { force: true }).catch(() => undefined);
221
+ await Promise.all(held.map((dir) => dir.handle.close().catch(() => undefined)));
222
+ }
223
+ },
73
224
  };
74
225
  }
@@ -92,12 +92,8 @@ export type AttachTarget = {
92
92
  extensionCdpUrl?: string;
93
93
  };
94
94
  export type ProviderCaps = {
95
- timeoutModel: "wall-clock" | "inactivity";
96
- maxLifetimeS: number;
97
- survivesDisconnect: boolean;
98
- releaseIsAsync: boolean;
95
+ /** The provider can open a session on a saved sign-in (`SessionSpec.profile`); without it such a session is refused. */
99
96
  profiles: boolean;
100
- extension: "uploaded-per-launch" | "preinstalled" | "loaded-locally";
101
97
  /** Every session attaches to the same browser (an endpoint the host named), so two at once would drive the same pages. */
102
98
  sharedBrowser?: boolean;
103
99
  /** The session settings this provider applies; a setting left out is applied. */
@@ -137,44 +133,9 @@ export type RemoteFile = {
137
133
  modifiedAt: string | null;
138
134
  downloading?: true;
139
135
  };
140
- export type FetchRequest = {
141
- url: string;
142
- format: "markdown" | "raw";
143
- proxies: boolean;
144
- };
145
- export type FetchResult = {
146
- finalUrl: string | null;
147
- statusCode: number | null;
148
- contentType: string | null;
149
- content: string;
150
- usage?: ToolUsage;
151
- };
152
- export type SearchRequest = {
153
- query: string;
154
- n: number;
155
- };
156
- /** `snippet`: an excerpt of the page the search provider chose, when it gives one; web_search bounds it before the model sees it. */
157
- export type SearchHit = {
158
- url: string;
159
- title: string | null;
160
- author?: string | null;
161
- published?: string | null;
162
- snippet?: string | null;
163
- };
164
- export type SearchResult = {
165
- results: SearchHit[];
166
- usage?: ToolUsage;
167
- };
168
136
  /** What a session vault may keep of this provider's sessions. Absent: nothing (a browser the package cannot read, or one the host shares). */
169
137
  export type ProviderVault = {
170
138
  kind: "cdp";
171
- } | {
172
- kind: "context";
173
- provider: "browserbase" | "kernel";
174
- /** True when this provider writes the context ids it makes to a clear file: a vault refuses such a provider, so an id never lands outside it. */
175
- contextIdsInClear: boolean;
176
- /** The context or profile this session runs on, or null. A capability: it goes to the host's vault only. */
177
- contextOf(ref: LeaseRef): string | null;
178
139
  };
179
140
  export interface BrowserProvider {
180
141
  readonly name: string;
@@ -200,10 +161,9 @@ export interface BrowserProvider {
200
161
  list(ref: LeaseRef): Promise<RemoteFile[]>;
201
162
  read(ref: LeaseRef, name: string, maxBytes: number): Promise<AsyncIterable<Uint8Array>>;
202
163
  };
203
- fetch?(request: FetchRequest, signal?: AbortSignal): Promise<FetchResult>;
204
- search?(request: SearchRequest, signal?: AbortSignal): Promise<SearchResult>;
205
164
  }
206
- /** The host owns the file boundary for `browser_upload`: a path the model names is resolved here or refused. */
165
+ /** The host owns the file boundary for `browser_upload` and a screenshot's `save_as`: a path the model names is resolved
166
+ * or written here, or refused. */
207
167
  export interface WorkspaceFiles {
208
168
  resolve(rel: string): Promise<{
209
169
  bytes: Uint8Array;
@@ -212,38 +172,12 @@ export interface WorkspaceFiles {
212
172
  } | {
213
173
  refused: string;
214
174
  }>;
215
- }
216
- /** A site use_website can open: configuration, never model input. */
217
- export type SiteInfo = {
218
- site: string;
219
- title: string;
220
- description: string;
221
- };
222
- /** Runs one child agent that has the browser tools and no use_website, and answers its final text. The durable adapter
223
- * supplies it: a task-owned conversation. */
224
- export type ChildRunner = (task: {
225
- site: string;
226
- requestId: string;
227
- prompt: string;
228
- }, signal: AbortSignal) => Promise<string>;
229
- /** Runs a granted site's task and reports it, idempotent by `requestId`: exactly one of `run` (a task started elsewhere)
230
- * or `report` (the result). A port that runs the child itself uses `ctx.runChild`; a broker ignores it. */
231
- export interface SiteRunPort {
232
- list(signal: AbortSignal): Promise<SiteInfo[]>;
233
- use(input: {
234
- site: string;
235
- requestId: string;
236
- instructions: string;
237
- }, ctx: {
238
- signal: AbortSignal;
239
- runChild: ChildRunner;
240
- }): Promise<{
241
- run: {
242
- id: string;
243
- state: string;
244
- };
175
+ /** File `rel` made or replaced with `bytes`, its parent directories made, as the host's own file-write tool writes one;
176
+ * `path` is where it went, relative to the workspace. Absent: the host saves no screenshot. */
177
+ write?(rel: string, bytes: Uint8Array): Promise<{
178
+ path: string;
245
179
  } | {
246
- report: string;
180
+ refused: string;
247
181
  }>;
248
182
  }
249
183
  export type HandoffOutcome = "done" | "cancelled" | "expired";
@@ -371,6 +305,10 @@ export type SessionsState = {
371
305
  /** Told to the model on its next browser call, then cleared. */
372
306
  notice: string | null;
373
307
  };
308
+ /** `owed`: sessions besides the row's own that a release by its tag sent a stop to (or is about to), and that no raced
309
+ * call has told yet; each stays until a status read confirms its stop and it is told. `made`: when the provider made each
310
+ * session its tag lookup found (LeaseRef.madeAt), by id, saved before any stop is sent to it, until it is told: a stopped
311
+ * session is listed by no later lookup, and a raced call hands its host this time. */
374
312
  export type InventoryRow = {
375
313
  tag: string;
376
314
  conversationId: number;
@@ -378,6 +316,8 @@ export type InventoryRow = {
378
316
  provider: string;
379
317
  resourceId: string | null;
380
318
  state: SessionRecord["state"];
319
+ owed?: string[];
320
+ made?: Record<string, string>;
381
321
  };
382
322
  export type SessionRow = {
383
323
  conversationId: number;
@@ -416,7 +356,9 @@ export type PriceTable = {
416
356
  };
417
357
  /** One charge of a session's time, as its record bills it: `seconds` and `usd` since the session's last charge, through `at`,
418
358
  * or, `final`, at its release, topped up to the provider's minimum. `state` says whether `usd` is a price (`priced`) or
419
- * the time went unpriced (`unpriced`, `invalid`: `usd` is 0 and is no charge). */
359
+ * the time went unpriced (`unpriced`, `invalid`: `usd` is 0 and is no charge). `overbookedS`: an earlier charge billed
360
+ * the session through a later time than this one's `at` (a charge taken while its release was under way, the release
361
+ * confirmed before it), by that many seconds; this one bills none of it again. Absent: none. */
420
362
  export type SessionCharge = {
421
363
  conversationId: number;
422
364
  tag: string;
@@ -426,6 +368,7 @@ export type SessionCharge = {
426
368
  usd: number;
427
369
  final: boolean;
428
370
  state: PriceState;
371
+ overbookedS?: number;
429
372
  };
430
373
  /** Browserbase list prices as of 2026-10-06: the Developer overage rate, one-minute minimum. */
431
374
  export declare const LIST_PRICES: PriceTable;
@@ -1,5 +1,8 @@
1
1
  export declare const SCREENSHOT_MAX_EDGE_PX = 2000;
2
2
  export declare const SCREENSHOT_MAX_BASE64_BYTES = 900000;
3
+ /** A full page shrunk to the long edge that would be narrower than this (its short edge) is unreadable: the viewport is
4
+ * taken in its place. */
5
+ export declare const SCREENSHOT_MIN_SHORT_EDGE_PX = 600;
3
6
  export type ImageSize = {
4
7
  type: "png" | "jpeg";
5
8
  width: number;
@@ -13,12 +16,13 @@ export type Clip = {
13
16
  width: number;
14
17
  height: number;
15
18
  };
16
- /** `scale: "css"` takes one image pixel per CSS pixel, so a high-density display does not double the size. `clip` captures that region alone. */
19
+ /** `clip` captures that region alone, `fullPage` the whole document. `scale` is the image's size as a share of the
20
+ * browser's own capture of the same region (its device pixels): 0.5 is half as wide and half as high; absent, 1. */
17
21
  export type ScreenshotOptions = {
18
22
  fullPage?: boolean;
19
23
  type?: "png" | "jpeg";
20
24
  quality?: number;
21
- scale?: "css" | "device";
25
+ scale?: number;
22
26
  clip?: Clip;
23
27
  };
24
28
  export type Capture = (options: ScreenshotOptions) => Promise<{
@@ -31,14 +35,38 @@ export type BudgetedScreenshot = {
31
35
  size: ImageSize;
32
36
  options: ScreenshotOptions;
33
37
  adjusted: {
34
- why: "long_edge" | "base64_bytes";
38
+ why: "long_edge" | "base64_bytes" | "unreadable";
35
39
  first: ImageSize | null;
36
40
  } | null;
37
41
  };
42
+ /** What CDP's Page.getLayoutMetrics says of a page, in CSS pixels: where the viewport is scrolled to and its size, and
43
+ * the whole document's size. */
44
+ export type Layout = {
45
+ cssVisualViewport: {
46
+ pageX: number;
47
+ pageY: number;
48
+ clientWidth: number;
49
+ clientHeight: number;
50
+ };
51
+ cssContentSize: {
52
+ width: number;
53
+ height: number;
54
+ };
55
+ };
56
+ /** CDP's Page.captureScreenshot parameters for `options` on a page laid out as `layout`. Chrome scales a clip alone, its
57
+ * image `clip.scale` times its device pixels: a clip (from the viewport) is moved to the document, a full page is the
58
+ * document's clip captured beyond the viewport, and a scaled viewport is the viewport's own clip. */
59
+ export declare function captureParams(options: ScreenshotOptions, layout: Layout): Record<string, unknown>;
38
60
  export declare class ScreenshotBudgetError extends Error {
39
61
  name: string;
40
62
  }
41
- /** Over budget, retakes as a viewport JPEG at CSS scale, quality 40, 25, 10 (of the same clip, when there is one); throws ScreenshotBudgetError. */
63
+ /**
64
+ * A capture as requested, held to the budget. Over the long edge, the same region is retaken scaled to fit it (a full
65
+ * page that would come out narrower than SCREENSHOT_MIN_SHORT_EDGE_PX is the viewport instead, itself scaled to fit);
66
+ * over the byte budget, as a JPEG at quality 40, 25 and 10 (at most the requested quality), then smaller still. A capture
67
+ * whose size cannot be read is retaken once as a viewport JPEG. Throws ScreenshotBudgetError only when no capture it can
68
+ * measure is made, or none fits within MAX_CAPTURES.
69
+ */
42
70
  export declare function captureWithinBudget(capture: Capture, requested: ScreenshotOptions, budget?: {
43
71
  maxEdgePx: number;
44
72
  maxBase64Bytes: number;
@@ -1,7 +1,11 @@
1
1
  // Tool images are stored verbatim and resent on every later request, and routes reject oversize ones: a capture is held
2
- // to a long edge and a base64 size.
2
+ // to a long edge and a base64 size, by shrinking its pixels and then its JPEG quality, never by failing while a capture
3
+ // can be made.
3
4
  export const SCREENSHOT_MAX_EDGE_PX = 2_000;
4
5
  export const SCREENSHOT_MAX_BASE64_BYTES = 900_000;
6
+ /** A full page shrunk to the long edge that would be narrower than this (its short edge) is unreadable: the viewport is
7
+ * taken in its place. */
8
+ export const SCREENSHOT_MIN_SHORT_EDGE_PX = 600;
5
9
  const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
6
10
  /** JPEG start-of-frame markers; C4 (DHT), C8 (JPG) and CC (DAC) are not frames. */
7
11
  const JPEG_SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
@@ -34,27 +38,88 @@ export function imageSize(bytes) {
34
38
  }
35
39
  return null;
36
40
  }
41
+ /** CDP's Page.captureScreenshot parameters for `options` on a page laid out as `layout`. Chrome scales a clip alone, its
42
+ * image `clip.scale` times its device pixels: a clip (from the viewport) is moved to the document, a full page is the
43
+ * document's clip captured beyond the viewport, and a scaled viewport is the viewport's own clip. */
44
+ export function captureParams(options, layout) {
45
+ const format = options.type ?? "png";
46
+ const scale = options.scale ?? 1;
47
+ const view = layout.cssVisualViewport;
48
+ const region = options.clip ? { ...options.clip, x: options.clip.x + view.pageX, y: options.clip.y + view.pageY }
49
+ : options.fullPage ? { x: 0, y: 0, width: Math.ceil(layout.cssContentSize.width), height: Math.ceil(layout.cssContentSize.height) }
50
+ : scale !== 1 ? { x: view.pageX, y: view.pageY, width: view.clientWidth, height: view.clientHeight }
51
+ : null;
52
+ return {
53
+ format,
54
+ // CDP takes a quality for jpeg only, and only as an integer.
55
+ ...(format === "jpeg" && options.quality !== undefined ? { quality: Math.round(options.quality) } : {}),
56
+ ...(options.fullPage && !options.clip ? { captureBeyondViewport: true } : {}),
57
+ ...(region ? { clip: { ...region, scale } } : {}),
58
+ };
59
+ }
37
60
  export class ScreenshotBudgetError extends Error {
38
61
  name = "ScreenshotBudgetError";
39
62
  }
40
- /** Over budget, retakes as a viewport JPEG at CSS scale, quality 40, 25, 10 (of the same clip, when there is one); throws ScreenshotBudgetError. */
63
+ /** The most captures one screenshot takes before it gives up. */
64
+ const MAX_CAPTURES = 12;
65
+ const QUALITIES = [40, 25, 10];
66
+ /**
67
+ * A capture as requested, held to the budget. Over the long edge, the same region is retaken scaled to fit it (a full
68
+ * page that would come out narrower than SCREENSHOT_MIN_SHORT_EDGE_PX is the viewport instead, itself scaled to fit);
69
+ * over the byte budget, as a JPEG at quality 40, 25 and 10 (at most the requested quality), then smaller still. A capture
70
+ * whose size cannot be read is retaken once as a viewport JPEG. Throws ScreenshotBudgetError only when no capture it can
71
+ * measure is made, or none fits within MAX_CAPTURES.
72
+ */
41
73
  export async function captureWithinBudget(capture, requested, budget = { maxEdgePx: SCREENSHOT_MAX_EDGE_PX, maxBase64Bytes: SCREENSHOT_MAX_BASE64_BYTES }) {
42
74
  const ceiling = requested.type === "png" ? 40 : (requested.quality ?? 40);
43
- const ladder = [
44
- { fullPage: requested.fullPage ?? false, type: requested.type ?? "jpeg", ...(requested.type === "png" ? {} : { quality: requested.quality ?? 40 }), ...(requested.scale ? { scale: requested.scale } : {}), ...(requested.clip ? { clip: requested.clip } : {}) },
45
- ...[40, 25, 10].map((quality) => ({ fullPage: false, type: "jpeg", quality: Math.min(ceiling, quality), scale: "css", ...(requested.clip ? { clip: requested.clip } : {}) })),
46
- ];
47
- const key = (o) => `${o.fullPage}:${o.type}:${o.quality}:${o.scale}:${o.clip ? `${o.clip.x},${o.clip.y},${o.clip.width},${o.clip.height}` : ""}`;
48
- const attempts = ladder.filter((o, i) => ladder.findIndex((other) => key(other) === key(o)) === i);
49
- let adjusted = null;
50
- for (const options of attempts) {
75
+ // The clip and the scale asked are kept on every capture; a retake only scales further down.
76
+ const clip = { ...(requested.clip ? { clip: requested.clip } : {}), ...(requested.scale === undefined ? {} : { scale: requested.scale }) };
77
+ let taken = 0;
78
+ const take = async (options) => {
79
+ taken += 1;
51
80
  const image = await capture(options);
52
81
  const size = imageSize(Buffer.from(image.data, "base64"));
53
- const why = size === null || Math.max(size.width, size.height) > budget.maxEdgePx ? "long_edge"
54
- : Buffer.byteLength(image.data, "utf8") > budget.maxBase64Bytes ? "base64_bytes" : null;
55
- if (why === null && size)
56
- return { data: image.data, mimeType: image.mimeType, size, options, adjusted };
57
- adjusted ??= { why: why ?? "long_edge", first: size };
82
+ const why = size === null ? "unreadable"
83
+ : Math.max(size.width, size.height) > budget.maxEdgePx ? "long_edge"
84
+ : Buffer.byteLength(image.data, "utf8") > budget.maxBase64Bytes ? "base64_bytes" : null;
85
+ return { image, size, why, options };
86
+ };
87
+ const fit = (size) => budget.maxEdgePx / Math.max(size.width, size.height);
88
+ const viewport = (options) => ({ fullPage: false, type: "jpeg", quality: Math.min(ceiling, options.type === "jpeg" ? options.quality ?? 40 : 40), ...clip });
89
+ let shot = await take({ fullPage: requested.fullPage ?? false, type: requested.type ?? "jpeg", ...(requested.type === "png" ? {} : { quality: ceiling }), ...clip });
90
+ const adjusted = shot.why === null ? null : { why: shot.why, first: shot.size };
91
+ if (shot.why === "unreadable")
92
+ shot = await take(viewport(shot.options));
93
+ // A full page that fits only narrower than a page can be read: the viewport, which the steps below fit.
94
+ if (shot.why === "long_edge" && shot.options.fullPage && shot.size && Math.min(shot.size.width, shot.size.height) * fit(shot.size) < SCREENSHOT_MIN_SHORT_EDGE_PX) {
95
+ shot = await take(viewport(shot.options));
96
+ }
97
+ while (shot.why !== null) {
98
+ if (shot.why === "unreadable" || !shot.size)
99
+ throw new ScreenshotBudgetError("The browser's capture is not a PNG or JPEG whose size can be read, and a viewport JPEG retake is not either.");
100
+ if (taken >= MAX_CAPTURES)
101
+ throw new ScreenshotBudgetError(`No capture fits ${budget.maxEdgePx} px on its long edge and ${budget.maxBase64Bytes} base64 bytes after ${taken} captures; the last was ${shot.size.width}x${shot.size.height}.`);
102
+ const { options, size } = shot;
103
+ const scale = options.scale ?? 1;
104
+ let next;
105
+ if (shot.why === "long_edge") {
106
+ next = { ...options, scale: scale * fit(size) };
107
+ }
108
+ else {
109
+ const quality = options.type === "png" ? undefined : options.quality ?? 40;
110
+ const lower = QUALITIES.map((q) => Math.min(ceiling, q)).find((q) => quality === undefined || q < quality);
111
+ // Its bytes go roughly with its area: a scale that takes them to nine tenths of the budget.
112
+ const smaller = scale * Math.min(0.9, 0.9 * Math.sqrt(budget.maxBase64Bytes / Buffer.byteLength(shot.image.data, "utf8")));
113
+ next = lower !== undefined ? { ...options, type: "jpeg", quality: lower } : { ...options, scale: smaller };
114
+ }
115
+ shot = await take(next);
116
+ // A driver that does not take the scale asked (Stagehand's, past one image pixel per CSS pixel): a full page is the
117
+ // viewport instead, and anything else is as small as this browser makes it.
118
+ if ((next.scale ?? 1) < scale && shot.size && Math.max(shot.size.width, shot.size.height) >= Math.max(size.width, size.height)) {
119
+ if (!options.fullPage)
120
+ throw new ScreenshotBudgetError(`The browser does not take this capture smaller than ${shot.size.width}x${shot.size.height}, which is over ${budget.maxEdgePx} px on its long edge or ${budget.maxBase64Bytes} base64 bytes.`);
121
+ shot = await take(viewport(options));
122
+ }
58
123
  }
59
- throw new ScreenshotBudgetError(`The screenshot stays over ${budget.maxEdgePx} px on its long edge or ${budget.maxBase64Bytes} base64 bytes after viewport JPEG retakes at CSS scale and quality 40, 25 and 10.`);
124
+ return { data: shot.image.data, mimeType: shot.image.mimeType, size: shot.size, options: shot.options, adjusted };
60
125
  }
@@ -5,7 +5,8 @@ export type ResourceStatus = "pending" | "running" | "stopped" | "gone";
5
5
  * `id`. */
6
6
  export type LeaseRef = {
7
7
  readonly id: string;
8
- readonly tag: string;
8
+ readonly tag: string; /** When the provider made the session (an ISO time), where its tag lookup (findByTag) says. */
9
+ readonly madeAt?: string;
9
10
  };
10
11
  /** Each change is one commit, and a provider call sits between two commits, never inside one. `lost` ends custody of a
11
12
  * resource the provider no longer answers for and that was never confirmed released. */