@parcha/pi-browser 0.1.0-beta.30 → 0.1.0-beta.301

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 (125) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/NOTICE +39 -4
  3. package/README.md +125 -236
  4. package/dist/core/contract.d.ts +17 -5
  5. package/dist/core/contract.js +36 -33
  6. package/dist/core/custody.d.ts +19 -2
  7. package/dist/core/custody.js +28 -6
  8. package/dist/core/downloads.d.ts +44 -3
  9. package/dist/core/downloads.js +94 -58
  10. package/dist/core/driving-guard.d.ts +20 -0
  11. package/dist/core/driving-guard.js +190 -23
  12. package/dist/core/driving.d.ts +56 -2
  13. package/dist/core/driving.js +189 -10
  14. package/dist/core/effects.d.ts +80 -6
  15. package/dist/core/effects.js +374 -41
  16. package/dist/core/evidence.d.ts +1 -1
  17. package/dist/core/failures.d.ts +15 -1
  18. package/dist/core/failures.js +7 -0
  19. package/dist/core/files.d.ts +20 -2
  20. package/dist/core/files.js +161 -10
  21. package/dist/core/host.d.ts +29 -77
  22. package/dist/core/images.d.ts +32 -4
  23. package/dist/core/images.js +81 -16
  24. package/dist/core/lease.d.ts +2 -1
  25. package/dist/core/page-scan.d.ts +81 -2
  26. package/dist/core/page-scan.js +487 -13
  27. package/dist/core/public-fetch.d.ts +70 -9
  28. package/dist/core/public-fetch.js +348 -51
  29. package/dist/core/read-page-worker.js +5 -4
  30. package/dist/core/read-page.d.ts +23 -8
  31. package/dist/core/read-page.js +64 -20
  32. package/dist/core/redact.d.ts +0 -2
  33. package/dist/core/redact.js +0 -32
  34. package/dist/core/session-control.d.ts +0 -2
  35. package/dist/core/session-control.js +0 -5
  36. package/dist/core/tools.d.ts +46 -1
  37. package/dist/core/tools.js +88 -12
  38. package/dist/core/usage.d.ts +4 -3
  39. package/dist/core/usage.js +5 -4
  40. package/dist/core/vault.d.ts +0 -10
  41. package/dist/core/vault.js +0 -13
  42. package/dist/core/web.d.ts +2 -111
  43. package/dist/core/web.js +0 -443
  44. package/dist/driver/cdp.d.ts +6 -0
  45. package/dist/driver/cdp.js +245 -0
  46. package/dist/driver/page-driver.js +110 -7
  47. package/dist/driver/sealed.d.ts +4 -12
  48. package/dist/driver/sealed.js +23 -37
  49. package/dist/driver/stagehand.d.ts +12 -15
  50. package/dist/driver/stagehand.js +21 -17
  51. package/dist/durable/result.d.ts +1 -2
  52. package/dist/durable/result.js +2 -2
  53. package/dist/durable/store.d.ts +17 -3
  54. package/dist/durable/store.js +231 -64
  55. package/dist/durable.d.ts +50 -17
  56. package/dist/durable.js +107 -106
  57. package/dist/index.d.ts +3 -3
  58. package/dist/index.js +5 -3
  59. package/dist/live-view/index.d.ts +4 -1
  60. package/dist/live-view/index.js +5 -0
  61. package/dist/live-view/protocol.d.ts +39 -7
  62. package/dist/live-view/protocol.js +2 -0
  63. package/dist/live-view/provider.d.ts +2 -2
  64. package/dist/live-view/provider.js +2 -2
  65. package/dist/live-view/server.d.ts +55 -2
  66. package/dist/live-view/server.js +282 -35
  67. package/dist/live-view/stream.js +16 -3
  68. package/dist/live-view/viewer.js +106 -13
  69. package/dist/providers/cdp.d.ts +0 -1
  70. package/dist/providers/cdp.js +35 -13
  71. package/dist/providers/chrome-args.d.ts +3 -0
  72. package/dist/providers/chrome-args.js +13 -2
  73. package/dist/providers/profiles.d.ts +1 -15
  74. package/dist/providers/profiles.js +1 -64
  75. package/dist/providers/shared.d.ts +1 -47
  76. package/dist/providers/shared.js +1 -82
  77. package/dist/providers/worker-extension.d.ts +20 -1
  78. package/dist/providers/worker-extension.js +86 -7
  79. package/dist/testing/backend.d.ts +6 -24
  80. package/dist/testing/backend.js +7 -30
  81. package/dist/vault-session.d.ts +4 -7
  82. package/dist/vault-session.js +26 -81
  83. package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
  84. package/dist/vendor/browser-use-pi/ax.js +642 -0
  85. package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
  86. package/dist/vendor/browser-use-pi/cdp.js +106 -0
  87. package/dist/vendor/browser-use-pi/page.d.ts +29 -0
  88. package/dist/vendor/browser-use-pi/page.js +99 -0
  89. package/package.json +15 -46
  90. package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
  91. package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
  92. package/dist/coding-agent-local.d.ts +0 -12
  93. package/dist/coding-agent-local.js +0 -72
  94. package/dist/coding-agent.d.ts +0 -134
  95. package/dist/coding-agent.js +0 -640
  96. package/dist/core/sites.d.ts +0 -33
  97. package/dist/core/sites.js +0 -104
  98. package/dist/driver/extension-worker.d.ts +0 -9
  99. package/dist/driver/extension-worker.js +0 -185
  100. package/dist/durable/web.d.ts +0 -47
  101. package/dist/durable/web.js +0 -41
  102. package/dist/providers/assigned.d.ts +0 -18
  103. package/dist/providers/assigned.js +0 -75
  104. package/dist/providers/browserbase-net.d.ts +0 -12
  105. package/dist/providers/browserbase-net.js +0 -95
  106. package/dist/providers/browserbase.d.ts +0 -169
  107. package/dist/providers/browserbase.js +0 -319
  108. package/dist/providers/kernel.d.ts +0 -58
  109. package/dist/providers/kernel.js +0 -291
  110. package/dist/recorder/credential.d.ts +0 -9
  111. package/dist/recorder/credential.js +0 -49
  112. package/dist/recorder/follow.d.ts +0 -36
  113. package/dist/recorder/follow.js +0 -163
  114. package/dist/recorder/frames.d.ts +0 -87
  115. package/dist/recorder/frames.js +0 -377
  116. package/dist/recorder/index.d.ts +0 -4
  117. package/dist/recorder/index.js +0 -7
  118. package/dist/recorder/jpeg.d.ts +0 -8
  119. package/dist/recorder/jpeg.js +0 -70
  120. package/dist/recorder/track.d.ts +0 -107
  121. package/dist/recorder/track.js +0 -280
  122. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
  123. package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
  124. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  125. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -4,7 +4,10 @@ export type BrowserFailure = {
4
4
  ok: false;
5
5
  code: FailureCode;
6
6
  retryable: boolean;
7
- effect: "none" | "possibly_effected";
7
+ /** `partial`: a run of several actions stopped partway, the first `completed` of them done. */
8
+ effect: "none" | "possibly_effected" | "partial";
9
+ /** With `partial`: how many of the run's actions ran before it stopped. */
10
+ completed?: number;
8
11
  message: string;
9
12
  /** Provider or page text, at most 2,000 characters; redacted before it reaches the model. */
10
13
  detail?: string;
@@ -17,6 +20,17 @@ export type Next = {
17
20
  action: "drive_page" | "other_source" | "browser_relaunch";
18
21
  note: string;
19
22
  };
23
+ /** A run of several actions that stopped partway on an error a call's own handling must still see as it is (a dropped
24
+ * connection, whose driver is let go): the error is passed on as it is, marked with how many of the run's actions ran. */
25
+ export declare const PARTIAL: unique symbol;
26
+ export type PartialRun = {
27
+ completed: number;
28
+ of: number;
29
+ };
30
+ /** The mark PARTIAL left on `error`, if any. */
31
+ export declare const partialOf: (error: unknown) => PartialRun | undefined;
32
+ /** `failure` as a run stopped partway says it: partial, with how many ran, before its own words. */
33
+ export declare const asPartial: (failure: BrowserFailure, partial: PartialRun) => BrowserFailure;
20
34
  export declare const browserFailure: (code: FailureCode, message: string, options?: {
21
35
  retryable?: boolean;
22
36
  effect?: BrowserFailure["effect"];
@@ -5,6 +5,13 @@ export const FAILURE_CODES = Object.freeze([
5
5
  "browser_unavailable", "auth", "timeout", "aborted", "refused", "stale_snapshot", "session_ended",
6
6
  "session_replaced", "effect_unknown", "code_error", "command_failed", "not_content", "blocked", "rate_limited", "waiting_for_human",
7
7
  ]);
8
+ /** A run of several actions that stopped partway on an error a call's own handling must still see as it is (a dropped
9
+ * connection, whose driver is let go): the error is passed on as it is, marked with how many of the run's actions ran. */
10
+ export const PARTIAL = Symbol.for("pi-browser.partial");
11
+ /** The mark PARTIAL left on `error`, if any. */
12
+ export const partialOf = (error) => (error !== null && typeof error === "object" ? error[PARTIAL] : undefined);
13
+ /** `failure` as a run stopped partway says it: partial, with how many ran, before its own words. */
14
+ export const asPartial = (failure, partial) => ({ ...failure, effect: "partial", completed: partial.completed, message: `${partial.completed} of the ${partial.of} actions ran, then this one failed: ${failure.message}` });
8
15
  export const browserFailure = (code, message, options = {}) => ({ ok: false, code, retryable: options.retryable ?? false, effect: options.effect ?? "none", message, ...(options.detail === undefined ? {} : { detail: options.detail }) });
9
16
  /** The vendored facade's refusal texts (vendor/stagehand-facade/contract.ts), copied so the root entry does not load the facade; a test pins
10
17
  * them to the facade's own. */
@@ -1,8 +1,26 @@
1
1
  import type { WorkspaceFiles } from "./host.js";
2
2
  export declare const MAX_UPLOAD_BYTES: number;
3
+ /** The media type browser_upload gives a file named `name`, by its extension; application/octet-stream for one it does
4
+ * not know. */
5
+ export declare const uploadMime: (name: string) => string;
6
+ /** 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
7
+ * then leads (a link on the way) is the reader's or the writer's to check. */
8
+ export declare function workspacePathRefusal(rel: unknown): string | null;
3
9
  /** Files under `root` only: a relative path with no `..`, inside `root` once symlinks resolve, at most `maxBytes`, and
4
- * not one `refuse` names (a host's private files). */
5
- export declare function workspaceFiles(root: string, { maxBytes, refuse }?: {
10
+ * not one `refuse` names (a host's private files). A write takes folders separated by "/" alone and follows no link on
11
+ * the way, the file itself included: it walks from the root one folder at a time, each opened as a folder through no
12
+ * link and held, makes each missing one, and replaces the file whole (a temporary file made beside it, then renamed
13
+ * over the name; a reader sees the old file or the new one).
14
+ *
15
+ * On Linux (`procFd`, default there) every name after the root resolves inside a folder a handle holds, so a folder
16
+ * swapped for a link by another process changes nothing: what is made or written is made in the folders walked.
17
+ * Elsewhere node can only resolve a path again, so before and after each act the folders held are checked: each still
18
+ * there by its path, no link, the same folder (dev and inode); else the write is refused, and the temporary file
19
+ * removed. What remains there is the gap between the last check and the call itself: a folder swapped for a link in
20
+ * it, and put back before the next check, can have that one call (a folder made, an empty temporary file made, or the
21
+ * rename) land through the link; the bytes are written only once the temporary file is confirmed in the folder held. */
22
+ export declare function workspaceFiles(root: string, { maxBytes, refuse, procFd }?: {
6
23
  maxBytes?: number;
7
24
  refuse?: (real: string) => string | null;
25
+ procFd?: boolean;
8
26
  }): WorkspaceFiles;
@@ -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
  }
@@ -86,15 +86,14 @@ export type AttachTarget = {
86
86
  headers?: Record<string, string>;
87
87
  expiresAt?: number;
88
88
  };
89
- extensionId?: string;
89
+ /** The browser's own DevTools URL, which Stagehand's extension inside the browser dials for its own connection; absent, it
90
+ * dials `sdkCdpUrl`. A proxy in front of the driver then carries both, and a drop that cuts both leaves the extension
91
+ * holding a client it can no longer see leave: Stagehand 4.4 then refuses every attach until its worker restarts. */
92
+ extensionCdpUrl?: string;
90
93
  };
91
94
  export type ProviderCaps = {
92
- timeoutModel: "wall-clock" | "inactivity";
93
- maxLifetimeS: number;
94
- survivesDisconnect: boolean;
95
- releaseIsAsync: boolean;
95
+ /** The provider can open a session on a saved sign-in (`SessionSpec.profile`); without it such a session is refused. */
96
96
  profiles: boolean;
97
- extension: "uploaded-per-launch" | "preinstalled" | "loaded-locally";
98
97
  /** Every session attaches to the same browser (an endpoint the host named), so two at once would drive the same pages. */
99
98
  sharedBrowser?: boolean;
100
99
  /** The session settings this provider applies; a setting left out is applied. */
@@ -127,49 +126,16 @@ export type Recording = {
127
126
  startedAt: string | null;
128
127
  durationS: number | null;
129
128
  };
129
+ /** `downloading`: the browser is still writing it; it is listed so the caller can say so, and is not read. */
130
130
  export type RemoteFile = {
131
131
  name: string;
132
132
  sizeBytes: number;
133
133
  modifiedAt: string | null;
134
- };
135
- export type FetchRequest = {
136
- url: string;
137
- format: "markdown" | "raw";
138
- proxies: boolean;
139
- };
140
- export type FetchResult = {
141
- finalUrl: string | null;
142
- statusCode: number | null;
143
- contentType: string | null;
144
- content: string;
145
- usage?: ToolUsage;
146
- };
147
- export type SearchRequest = {
148
- query: string;
149
- n: number;
150
- };
151
- /** `snippet`: an excerpt of the page the search provider chose, when it gives one; web_search bounds it before the model sees it. */
152
- export type SearchHit = {
153
- url: string;
154
- title: string | null;
155
- author?: string | null;
156
- published?: string | null;
157
- snippet?: string | null;
158
- };
159
- export type SearchResult = {
160
- results: SearchHit[];
161
- usage?: ToolUsage;
134
+ downloading?: true;
162
135
  };
163
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). */
164
137
  export type ProviderVault = {
165
138
  kind: "cdp";
166
- } | {
167
- kind: "context";
168
- provider: "browserbase" | "kernel";
169
- /** 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. */
170
- contextIdsInClear: boolean;
171
- /** The context or profile this session runs on, or null. A capability: it goes to the host's vault only. */
172
- contextOf(ref: LeaseRef): string | null;
173
139
  };
174
140
  export interface BrowserProvider {
175
141
  readonly name: string;
@@ -195,10 +161,9 @@ export interface BrowserProvider {
195
161
  list(ref: LeaseRef): Promise<RemoteFile[]>;
196
162
  read(ref: LeaseRef, name: string, maxBytes: number): Promise<AsyncIterable<Uint8Array>>;
197
163
  };
198
- fetch?(request: FetchRequest, signal?: AbortSignal): Promise<FetchResult>;
199
- search?(request: SearchRequest, signal?: AbortSignal): Promise<SearchResult>;
200
164
  }
201
- /** 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. */
202
167
  export interface WorkspaceFiles {
203
168
  resolve(rel: string): Promise<{
204
169
  bytes: Uint8Array;
@@ -207,38 +172,12 @@ export interface WorkspaceFiles {
207
172
  } | {
208
173
  refused: string;
209
174
  }>;
210
- }
211
- /** A site use_website can open: configuration, never model input. */
212
- export type SiteInfo = {
213
- site: string;
214
- title: string;
215
- description: string;
216
- };
217
- /** Runs one child agent that has the browser tools and no use_website, and answers its final text. The adapter supplies
218
- * it: a pi session for the coding agent, a task-owned conversation for pi-durable. */
219
- export type ChildRunner = (task: {
220
- site: string;
221
- requestId: string;
222
- prompt: string;
223
- }, signal: AbortSignal) => Promise<string>;
224
- /** Runs a granted site's task and reports it, idempotent by `requestId`: exactly one of `run` (a task started elsewhere)
225
- * or `report` (the result). A port that runs the child itself uses `ctx.runChild`; a broker ignores it. */
226
- export interface SiteRunPort {
227
- list(signal: AbortSignal): Promise<SiteInfo[]>;
228
- use(input: {
229
- site: string;
230
- requestId: string;
231
- instructions: string;
232
- }, ctx: {
233
- signal: AbortSignal;
234
- runChild: ChildRunner;
235
- }): Promise<{
236
- run: {
237
- id: string;
238
- state: string;
239
- };
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;
240
179
  } | {
241
- report: string;
180
+ refused: string;
242
181
  }>;
243
182
  }
244
183
  export type HandoffOutcome = "done" | "cancelled" | "expired";
@@ -259,7 +198,11 @@ export interface HandoffPort {
259
198
  } | {
260
199
  refused: string;
261
200
  }>;
262
- outcome(interactionId: string, signal: AbortSignal): Promise<"pending" | HandoffOutcome>;
201
+ /** With `reason`: why, in the host's words, for the model (an ask the host ended at its spend cap). */
202
+ outcome(interactionId: string, signal: AbortSignal): Promise<"pending" | HandoffOutcome | {
203
+ outcome: HandoffOutcome;
204
+ reason: string;
205
+ }>;
263
206
  }
264
207
  export type ReleaseReason = "tool" | "idle" | "relaunch" | "close" | "ended" | "lost" | "create_failed";
265
208
  export type SessionRecord = {
@@ -362,6 +305,10 @@ export type SessionsState = {
362
305
  /** Told to the model on its next browser call, then cleared. */
363
306
  notice: string | null;
364
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. */
365
312
  export type InventoryRow = {
366
313
  tag: string;
367
314
  conversationId: number;
@@ -369,6 +316,8 @@ export type InventoryRow = {
369
316
  provider: string;
370
317
  resourceId: string | null;
371
318
  state: SessionRecord["state"];
319
+ owed?: string[];
320
+ made?: Record<string, string>;
372
321
  };
373
322
  export type SessionRow = {
374
323
  conversationId: number;
@@ -407,7 +356,9 @@ export type PriceTable = {
407
356
  };
408
357
  /** One charge of a session's time, as its record bills it: `seconds` and `usd` since the session's last charge, through `at`,
409
358
  * or, `final`, at its release, topped up to the provider's minimum. `state` says whether `usd` is a price (`priced`) or
410
- * 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. */
411
362
  export type SessionCharge = {
412
363
  conversationId: number;
413
364
  tag: string;
@@ -417,6 +368,7 @@ export type SessionCharge = {
417
368
  usd: number;
418
369
  final: boolean;
419
370
  state: PriceState;
371
+ overbookedS?: number;
420
372
  };
421
373
  /** Browserbase list prices as of 2026-10-06: the Developer overage rate, one-minute minimum. */
422
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
  }