@edlsh/browse-core 0.6.4 → 0.8.0

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 (49) hide show
  1. package/README.md +23 -2
  2. package/dist/broker-client.d.ts +4 -2
  3. package/dist/broker-client.js +12 -6
  4. package/dist/broker-protocol.d.ts +3 -2
  5. package/dist/broker-protocol.js +11 -7
  6. package/dist/broker.js +12 -12
  7. package/dist/cdp-connection.d.ts +18 -0
  8. package/dist/cdp-connection.js +59 -0
  9. package/dist/config.d.ts +101 -0
  10. package/dist/config.js +78 -0
  11. package/dist/contexts.d.ts +10 -0
  12. package/dist/contexts.js +27 -0
  13. package/dist/errors.d.ts +29 -0
  14. package/dist/errors.js +83 -0
  15. package/dist/har.d.ts +1 -6
  16. package/dist/har.js +16 -56
  17. package/dist/host-model.d.ts +24 -0
  18. package/dist/host-model.js +35 -0
  19. package/dist/http-auth.d.ts +14 -0
  20. package/dist/http-auth.js +114 -0
  21. package/dist/index.d.ts +10 -13
  22. package/dist/index.js +11 -15
  23. package/dist/jev.js +9 -3
  24. package/dist/page-operations.d.ts +11 -1
  25. package/dist/page-operations.js +62 -11
  26. package/dist/real-browser-ai.d.ts +1 -1
  27. package/dist/real-browser-ai.js +1 -1
  28. package/dist/real-browser-client.js +1 -1
  29. package/dist/real-browser-session.d.ts +1 -1
  30. package/dist/real-browser-session.js +24 -5
  31. package/dist/schema.d.ts +34 -0
  32. package/dist/schema.js +29 -6
  33. package/dist/session-runtime.d.ts +42 -0
  34. package/dist/session-runtime.js +144 -0
  35. package/dist/session.d.ts +29 -108
  36. package/dist/session.js +189 -364
  37. package/dist/settings.js +47 -6
  38. package/dist/tool-results.d.ts +28 -0
  39. package/dist/tool-results.js +40 -0
  40. package/extensions/http-auth/README.md +27 -0
  41. package/extensions/http-auth/background.js +85 -0
  42. package/extensions/http-auth/manifest.json +27 -0
  43. package/extensions/http-auth/native/README.md +31 -0
  44. package/extensions/http-auth/native/host.py +97 -0
  45. package/extensions/http-auth/native/install.py +62 -0
  46. package/extensions/http-auth/options.html +25 -0
  47. package/extensions/http-auth/options.js +36 -0
  48. package/extensions/http-auth/origin.js +16 -0
  49. package/package.json +14 -2
@@ -53,7 +53,7 @@ export async function pageOperation({ page, context }, input) {
53
53
  batches.delete(input.id);
54
54
  }
55
55
  async function execute(input) {
56
- const control = input.action === "click" || input.action === "fill" || input.action === "select";
56
+ const control = ["click", "fill", "select", "hover", "upload"].includes(input.action);
57
57
  const base = control ? page.locator(input.selector) : undefined;
58
58
  const locator = input.nth === undefined ? base : base.nth(input.nth);
59
59
  /** A tab's first history entry, before any page: about:blank, or Stagehand's own start page for tabs it opens. */
@@ -89,16 +89,34 @@ export async function pageOperation({ page, context }, input) {
89
89
  return String.fromCodePoint(Number(name.slice(1)));
90
90
  return entities[name.toLowerCase()] ?? entity;
91
91
  });
92
- const options = [...html.matchAll(/<option\b([^>]*)>([\s\S]*?)<\/option>/gi)].map(([, attributes, inner]) => {
92
+ // Check the same selector in its target frame. A positional selector that might include single-selects is not safe for multiple values.
93
+ if (new Set(input.values).size > 1) {
94
+ const parts = input.selector.split(/\s+>>\s+/);
95
+ const leaf = parts.pop();
96
+ const multi = /^(?:xpath=|\/\/)/.test(leaf) ? "xpath=" + leaf.replace(/^xpath=/, "") + "[self::select and @multiple]"
97
+ : leaf.startsWith("text=") ? undefined : ":is(" + leaf.replace(/^css=/, "") + "):is(select[multiple])";
98
+ if (!multi || await page.locator([...parts, multi].join(" >> ")).count() !== count) {
99
+ return failure("single_select", "Multiple values need a native multi-select. Nothing was selected.");
100
+ }
101
+ }
102
+ let disabledGroup = false;
103
+ const options = [...html.matchAll(/<(\/?optgroup)\b((?:"[^"]*"|[^">])*)>|<option\b((?:"[^"]*"|[^">])*)>([\s\S]*?)<\/option>/gi)].flatMap(([, group, groupAttrs, attributes, inner]) => {
104
+ if (group) {
105
+ disabledGroup = group.toLowerCase() === "optgroup" && /\sdisabled(?:=|\s|$)/i.test(groupAttrs);
106
+ return [];
107
+ }
93
108
  const attribute = (name) => {
94
109
  const found = new RegExp(`\\s${name}="([^"]*)"`, "i").exec(attributes);
95
110
  return found ? decode(found[1]) : undefined;
96
111
  };
97
112
  const text = decode(inner.replace(/<[^>]*>/g, "")).replace(/[ \t\n\f\r]+/g, " ").trim();
98
- return { value: (attribute("value") ?? text).trim(), label: (attribute("label") || text).trim() };
113
+ return [{ value: (attribute("value") ?? text).trim(), label: (attribute("label") || text).trim(), disabled: disabledGroup || attribute("disabled") !== undefined }];
99
114
  });
100
115
  if (!options.length)
101
116
  return failure("not_select", "select works only on a native <select> element with options. For a custom dropdown, click it and then click the option.");
117
+ if (input.values.some(value => options.some(o => o.disabled && (o.value === value.trim() || o.label === value.trim())))) {
118
+ return failure("option_disabled", "A requested option or its optgroup is disabled. Nothing was selected.");
119
+ }
102
120
  const missing = input.values.filter(value => !options.some(option => option.value === value.trim() || option.label === value.trim()));
103
121
  if (missing.length)
104
122
  return failure("option_not_found", `No option matches ${JSON.stringify(missing)}; nothing was selected. `
@@ -168,18 +186,46 @@ export async function pageOperation({ page, context }, input) {
168
186
  }
169
187
  case "snapshot": {
170
188
  // A full result carries an XPath for every DOM node, over a megabyte on a large page: return only what is shown.
171
- const [fresh, at] = await Promise.all([page.snapshot({ includeIframes: true }), page.url()]);
172
- const { version, maxChars } = input.snapshot;
173
- const full = fresh.formattedTree.replace(/\[(\d+-\d+)\]/g, `[${version}:$1]`);
174
- const tree = full.slice(0, maxChars);
189
+ const [fresh, documentUrl] = await Promise.all([page.snapshot({ includeIframes: true }), page.url()]);
190
+ const { version, maxChars, interactive, offset = 0 } = input.snapshot;
191
+ const control = /^\s*\[\d+-\d+\] (button|link|textbox|searchbox|combobox|listbox|select|option|checkbox|radio|switch|slider|spinbutton|menuitem(?:checkbox|radio)?|tab|treeitem|date|datetime|inputtime)\b/i;
192
+ const full = interactive ? fresh.formattedTree.split("\n").filter(line => control.test(line)).join("\n") : fresh.formattedTree;
193
+ // Cursor counts source characters, not prefixes such as s9/s10, whose lengths can change between calls.
194
+ let at = Math.min(offset, full.length), tree = "";
195
+ const pattern = /\[(\d+-\d+)\]/g;
196
+ pattern.lastIndex = at;
197
+ for (;;) {
198
+ const match = pattern.exec(full);
199
+ const end = Math.min(match?.index ?? full.length, at + maxChars - tree.length);
200
+ tree += full.slice(at, end);
201
+ at = end;
202
+ if (!match || at < match.index)
203
+ break;
204
+ const token = "[" + version + ":" + match[1] + "]";
205
+ if (tree.length + token.length > maxChars)
206
+ break;
207
+ tree += token;
208
+ at = pattern.lastIndex;
209
+ }
175
210
  const refs = {};
176
211
  for (const [, id] of tree.matchAll(/\[s\d+:(\d+-\d+)\]/g)) {
177
212
  const xpath = fresh.xpathMap[id];
178
213
  if (xpath)
179
214
  refs[id] = xpath;
180
215
  }
181
- snapshot = { tree, truncated: full.length > maxChars, refs };
182
- snapshotUrl = at;
216
+ snapshot = { tree, truncated: at < full.length, ...(at < full.length ? { nextOffset: at } : {}), refs };
217
+ snapshotUrl = documentUrl;
218
+ break;
219
+ }
220
+ case "viewport":
221
+ await page.setViewportSize(input.width, input.height);
222
+ break;
223
+ case "hover":
224
+ await locator.hover();
225
+ break;
226
+ case "upload": {
227
+ const { name, mimeType, base64 } = input.file;
228
+ await locator.setInputFiles({ name, mimeType, buffer: Uint8Array.from(atob(base64), c => c.charCodeAt(0)) });
183
229
  break;
184
230
  }
185
231
  case "click":
@@ -195,9 +241,14 @@ export async function pageOperation({ page, context }, input) {
195
241
  value = selected;
196
242
  break;
197
243
  }
198
- case "press":
199
- await page.keyPress(input.key);
244
+ case "press": {
245
+ const key = input.key;
246
+ if ([...key].length === 1 || /^(space|spacebar)$/i.test(key))
247
+ await page.type([...key].length === 1 ? key : " ");
248
+ else
249
+ await page.keyPress(key);
200
250
  break;
251
+ }
201
252
  case "scroll":
202
253
  await page.scroll(input.x ?? 640, input.y ?? 400, input.deltaX ?? 0, input.deltaY ?? 0);
203
254
  break;
@@ -1,5 +1,5 @@
1
1
  import type { RealBrowserPage } from "./real-browser-session.ts";
2
- import { type ClientGenerate } from "./session.ts";
2
+ import type { ClientGenerate } from "./session.ts";
3
3
  /** One thing to do to one element, in the shape Stagehand's observe returns: `selector` is a snapshot ref. */
4
4
  export interface PageAction {
5
5
  selector: string;
@@ -1,5 +1,5 @@
1
1
  import { MAX_TEXT } from "./ask.js";
2
- import { BrowseToolError } from "./session.js";
2
+ import { BrowseToolError } from "./errors.js";
3
3
  const ACTIONS_SCHEMA = {
4
4
  type: "object", additionalProperties: false, required: ["elements"],
5
5
  properties: {
@@ -1,7 +1,7 @@
1
1
  // The user's real browser, driven through OpenCode Browse: its MCP server (`browse mcp`) and its browser extension.
2
2
  import { spawn } from "node:child_process";
3
3
  import { createInterface } from "node:readline";
4
- import { BrowseToolError } from "./session.js";
4
+ import { BrowseToolError } from "./errors.js";
5
5
  /** The newest MCP revision this client speaks; the server answers with the one it chose. */
6
6
  const MCP_PROTOCOL = "2025-06-18";
7
7
  /** A server silent this long is not coming: an SSH hop to a sleeping machine, or a command that waits for input. */
@@ -1,6 +1,6 @@
1
1
  import type { NetworkCapture } from "./har.ts";
2
2
  import type { BrowserParams } from "./schema.ts";
3
- import { type BrowserOutput } from "./session.ts";
3
+ import type { BrowserOutput } from "./session.ts";
4
4
  export interface RealBrowserPage {
5
5
  tabId: string;
6
6
  url: string;
@@ -1,13 +1,13 @@
1
1
  // One conversation's tabs in the user's real browser, driven through OpenCode Browse (see real-browser-client.ts).
2
2
  import { RealBrowserClient } from "./real-browser-client.js";
3
- import { BrowseToolError } from "./session.js";
3
+ import { BrowseToolError } from "./errors.js";
4
4
  /** One client per command for the conversations using it; the last to close ends its process, so a host can exit. */
5
5
  const clients = new Map();
6
6
  function toTab(tabId) {
7
7
  return /^\d+$/.test(tabId) ? Number(tabId) : tabId;
8
8
  }
9
9
  /** The arguments a script reads from `p`. */
10
- const ARGUMENTS = ["url", "selector", "value", "values", "key", "script", "fullPage", "durationMs", "loadState", "state", "deltaX", "deltaY", "x", "y", "message"];
10
+ const ARGUMENTS = ["url", "selector", "value", "values", "key", "script", "fullPage", "durationMs", "loadState", "state", "deltaX", "deltaY", "x", "y", "message", "interactive", "width", "height", "file"];
11
11
  /**
12
12
  * `el` takes a snapshot ref (e12) or a selector; a bare XPath gets the prefix Playwright-style locators need. `timeout`
13
13
  * ends a wait for an element or a page before the script's own deadline, whose error would not say what was missing.
@@ -31,10 +31,28 @@ const BODIES = {
31
31
  forward: "await page.goForward();",
32
32
  reload: "await page.reload();",
33
33
  // The default of 80 lines hides most of a long page.
34
- snapshot: "data = String(await snapshot({ maxItems: 200 }));",
34
+ snapshot: "data = String(await snapshot({ maxItems: 200, interactive: p.interactive === true }));",
35
+ hover: "await el(p.selector).hover({ timeout });",
36
+ viewport: "await page.setViewportSize({ width: p.width, height: p.height });",
37
+ // The relay's path-based upload would read files on the relay machine. Transfer only the caller-supplied bytes.
38
+ upload: `await el(p.selector).evaluate((node, file) => {
39
+ if (!(node instanceof HTMLInputElement) || node.type !== "file" || node.matches(":disabled")) throw new Error("Expected an enabled file input");
40
+ const transfer = new DataTransfer();
41
+ transfer.items.add(new File([Uint8Array.from(atob(file.base64), ch => ch.charCodeAt(0))], file.name, { type: file.mimeType }));
42
+ node.files = transfer.files;
43
+ node.dispatchEvent(new Event("input", { bubbles: true })); node.dispatchEvent(new Event("change", { bubbles: true }));
44
+ }, p.file);`,
35
45
  click: "await el(p.selector).click({ timeout });",
36
46
  fill: "await el(p.selector).fill(p.value, { timeout });",
37
- select: "data = { selected: await el(p.selector).selectOption(p.values, { timeout }) };",
47
+ select: `const select = el(p.selector);
48
+ const reason = await select.evaluate((node, wanted) => {
49
+ if (!(node instanceof HTMLSelectElement)) return "Expected a native select";
50
+ if (!node.multiple && new Set(wanted).size > 1) return "Multiple values need a multi-select";
51
+ if (node.disabled || Array.from(node.options).some(o => o.matches(":disabled") && wanted.some(v => v === o.value || v === o.label))) return "A requested option is disabled";
52
+ return null;
53
+ }, p.values);
54
+ if (reason) throw new Error(reason + ". Nothing was selected.");
55
+ data = { selected: await select.selectOption(p.values, { timeout }) };`,
38
56
  press: "await page.keyboard.press(p.key);",
39
57
  scroll: "await page.mouse.move(p.x ?? 640, p.y ?? 400); await page.mouse.wheel(p.deltaX ?? 0, p.deltaY ?? 0);",
40
58
  wait: `if (p.durationMs !== undefined) await page.waitForTimeout(p.durationMs);
@@ -151,7 +169,8 @@ export class RealBrowserSession {
151
169
  }
152
170
  if (p.action === "snapshot") {
153
171
  const tree = String(data), limit = p.maxChars ?? 20_000;
154
- data = { tree: tree.slice(0, limit), truncated: tree.length > limit };
172
+ const offset = p.offset ?? 0, end = offset + limit;
173
+ data = { tree: tree.slice(offset, end), truncated: tree.length > end, ...(tree.length > end ? { nextOffset: end } : {}) };
155
174
  }
156
175
  return {
157
176
  ...this.output(p.action, { url: view.url, title: view.title, ...(data === undefined ? {} : { data }) }, tab),
package/dist/schema.d.ts CHANGED
@@ -38,11 +38,22 @@ declare const batchStepFields: z.ZodObject<{
38
38
  }>>;
39
39
  script: z.ZodOptional<z.ZodString>;
40
40
  maxChars: z.ZodOptional<z.ZodNumber>;
41
+ offset: z.ZodOptional<z.ZodNumber>;
42
+ interactive: z.ZodOptional<z.ZodBoolean>;
41
43
  }, z.core.$strict>;
42
44
  /** One validated batch step. It is a flat object, so `{ ...step, tabId }` runs like the same call on its own. */
43
45
  export type BatchStep = z.infer<typeof batchStepFields>;
44
46
  /** The browse tool's parameters without batch: what a host that has not adopted batch registers. */
45
47
  export declare const browserParameters: z.ZodObject<{
48
+ resultId: z.ZodOptional<z.ZodUUID>;
49
+ width: z.ZodOptional<z.ZodNumber>;
50
+ height: z.ZodOptional<z.ZodNumber>;
51
+ file: z.ZodOptional<z.ZodObject<{
52
+ name: z.ZodString;
53
+ mimeType: z.ZodString;
54
+ base64: z.ZodBase64;
55
+ }, z.core.$strict>>;
56
+ httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
46
57
  backend: z.ZodOptional<z.ZodEnum<{
47
58
  browserbase: "browserbase";
48
59
  local: "local";
@@ -95,6 +106,8 @@ export declare const browserParameters: z.ZodObject<{
95
106
  }>>;
96
107
  script: z.ZodOptional<z.ZodString>;
97
108
  fullPage: z.ZodOptional<z.ZodBoolean>;
109
+ offset: z.ZodOptional<z.ZodNumber>;
110
+ interactive: z.ZodOptional<z.ZodBoolean>;
98
111
  maxChars: z.ZodOptional<z.ZodNumber>;
99
112
  fields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
100
113
  type: z.ZodEnum<{
@@ -135,10 +148,12 @@ export declare const browserParameters: z.ZodObject<{
135
148
  handoff: "handoff";
136
149
  har_start: "har_start";
137
150
  har_stop: "har_stop";
151
+ hover: "hover";
138
152
  live_view: "live_view";
139
153
  open: "open";
140
154
  press: "press";
141
155
  reload: "reload";
156
+ result_read: "result_read";
142
157
  screenshot: "screenshot";
143
158
  scroll: "scroll";
144
159
  select: "select";
@@ -149,6 +164,8 @@ export declare const browserParameters: z.ZodObject<{
149
164
  tab_new: "tab_new";
150
165
  tab_select: "tab_select";
151
166
  tabs: "tabs";
167
+ upload: "upload";
168
+ viewport: "viewport";
152
169
  wait: "wait";
153
170
  }>;
154
171
  }, z.core.$strict>;
@@ -157,6 +174,15 @@ export declare const browserParameters: z.ZodObject<{
157
174
  * prompts and approval rules a batch needs: one call can navigate, act, and run page script.
158
175
  */
159
176
  export declare const browserBatchParameters: z.ZodObject<{
177
+ resultId: z.ZodOptional<z.ZodUUID>;
178
+ width: z.ZodOptional<z.ZodNumber>;
179
+ height: z.ZodOptional<z.ZodNumber>;
180
+ file: z.ZodOptional<z.ZodObject<{
181
+ name: z.ZodString;
182
+ mimeType: z.ZodString;
183
+ base64: z.ZodBase64;
184
+ }, z.core.$strict>>;
185
+ httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
160
186
  backend: z.ZodOptional<z.ZodEnum<{
161
187
  browserbase: "browserbase";
162
188
  local: "local";
@@ -209,6 +235,8 @@ export declare const browserBatchParameters: z.ZodObject<{
209
235
  }>>;
210
236
  script: z.ZodOptional<z.ZodString>;
211
237
  fullPage: z.ZodOptional<z.ZodBoolean>;
238
+ offset: z.ZodOptional<z.ZodNumber>;
239
+ interactive: z.ZodOptional<z.ZodBoolean>;
212
240
  maxChars: z.ZodOptional<z.ZodNumber>;
213
241
  fields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
214
242
  type: z.ZodEnum<{
@@ -250,10 +278,12 @@ export declare const browserBatchParameters: z.ZodObject<{
250
278
  handoff: "handoff";
251
279
  har_start: "har_start";
252
280
  har_stop: "har_stop";
281
+ hover: "hover";
253
282
  live_view: "live_view";
254
283
  open: "open";
255
284
  press: "press";
256
285
  reload: "reload";
286
+ result_read: "result_read";
257
287
  screenshot: "screenshot";
258
288
  scroll: "scroll";
259
289
  select: "select";
@@ -264,6 +294,8 @@ export declare const browserBatchParameters: z.ZodObject<{
264
294
  tab_new: "tab_new";
265
295
  tab_select: "tab_select";
266
296
  tabs: "tabs";
297
+ upload: "upload";
298
+ viewport: "viewport";
267
299
  wait: "wait";
268
300
  }>;
269
301
  steps: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -304,6 +336,8 @@ export declare const browserBatchParameters: z.ZodObject<{
304
336
  }>>;
305
337
  script: z.ZodOptional<z.ZodString>;
306
338
  maxChars: z.ZodOptional<z.ZodNumber>;
339
+ offset: z.ZodOptional<z.ZodNumber>;
340
+ interactive: z.ZodOptional<z.ZodBoolean>;
307
341
  }, z.core.$strict>>>;
308
342
  }, z.core.$strict>;
309
343
  export declare const aiParameters: z.ZodObject<{
package/dist/schema.js CHANGED
@@ -43,11 +43,18 @@ const askField = z.object({
43
43
  const ACTIONS = [
44
44
  "start", "status", "close", "open", "back", "forward", "reload", "snapshot", "ask",
45
45
  "click", "fill", "select", "press", "scroll", "wait", "screenshot", "evaluate",
46
- "tabs", "tab_new", "tab_select", "tab_close", "live_view", "context_create", "cookie_profiles", "cookie_import",
46
+ "tabs", "tab_new", "tab_select", "tab_close", "hover", "upload", "viewport", "result_read", "live_view", "context_create", "cookie_profiles", "cookie_import",
47
47
  "har_start", "har_stop", "handoff",
48
48
  ];
49
49
  /** Every action's arguments. A batch step reuses the direct controls' definitions from here instead of redefining them. */
50
50
  const browserFields = {
51
+ resultId: z.uuid().optional().describe("For result_read: ID of this conversation's most recent oversized tool result. Read the redacted JSON in chunks without rerunning the action."),
52
+ width: z.number().int().min(1).max(8192).optional().describe("Only for viewport: CSS pixel width."),
53
+ height: z.number().int().min(1).max(8192).optional().describe("Only for viewport: CSS pixel height."),
54
+ file: z.object({ name: z.string().min(1).max(255).regex(/^[^/\\\x00-\x1f\x7f]+$/).refine(n => n !== "." && n !== ".."),
55
+ mimeType: z.string().regex(/^[\w.+-]+\/[\w.+-]+$/).max(127), base64: z.base64().max(256 * 1024) }).strict().optional()
56
+ .describe("Only for upload: one file supplied inline, up to 192 KiB decoded. No filesystem paths. Attach only content authorized by the user."),
57
+ httpAuth: z.literal(true).optional().describe("Start a fresh isolated browser that answers HTTP Basic authentication challenges for the origin configured by the user. Requires an explicit local or browserbase backend."),
51
58
  backend: z.enum(["browserbase", "local"]).optional().describe("Only for start. Default local (or the profile's /browse backend setting); choose browserbase for clean-slate isolation, proxyCountry, a saved contextId, or at the user's request. Close before changing backends."),
52
59
  cdpUrl: z.url({ protocol: /^(?:https?|wss?)$/ }).refine(value => {
53
60
  if (!URL.canParse(value))
@@ -85,6 +92,8 @@ const browserFields = {
85
92
  state: z.enum(["attached", "detached", "visible", "hidden"]).optional().describe("Selector state for wait; default visible."),
86
93
  script: z.string().min(1).optional().describe("JavaScript expression evaluated in the browser page, required for evaluate. No local filesystem or process access."),
87
94
  fullPage: z.boolean().optional().describe("For screenshot; defaults to viewport only."),
95
+ offset: z.number().int().nonnegative().optional().describe("For snapshot or result_read: resume at nextOffset (or 0). For a snapshot keep the same interactive setting."),
96
+ interactive: z.boolean().optional().describe("Only for snapshot: list controls instead of the full outline."),
88
97
  maxChars: z.number().int().min(1000).max(50_000).optional().describe("Snapshot text limit; default 20000."),
89
98
  fields: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/), askField).optional().describe("Required for ask: 1 to 20 named questions about the selected page. text, number, date, datetime, and duration read a value (null when the page does not say); bool answers yes/no; choice picks one of options."),
90
99
  message: z.string().trim().min(1).max(500).optional().describe("Required for handoff: what only the person can do in the selected tab, e.g. sign in or approve the 2FA prompt. The call returns once they click Continue. Only in the user's real browser."),
@@ -109,7 +118,7 @@ const batchStepFields = z.object({
109
118
  loadState: browserFields.loadState,
110
119
  state: browserFields.state,
111
120
  script: browserFields.script,
112
- maxChars: browserFields.maxChars,
121
+ maxChars: browserFields.maxChars, offset: browserFields.offset, interactive: browserFields.interactive,
113
122
  }, {
114
123
  error: issue => issue.code === "unrecognized_keys"
115
124
  ? `A batch step does not accept ${issue.keys.join(", ")}. Set tabId and timeoutMs on the batch, address elements by selector (no JEV target), and give each step only its action's arguments.`
@@ -117,7 +126,7 @@ const batchStepFields = z.object({
117
126
  }).strict();
118
127
  /** The arguments each batch action reads. A step carrying any other would see it silently ignored, so it is rejected. */
119
128
  const STEP_ARGUMENTS = {
120
- open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true },
129
+ open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true, offset: true, interactive: true },
121
130
  click: { selector: true }, fill: { selector: true, value: true }, select: { selector: true, values: true },
122
131
  press: { key: true }, scroll: { deltaX: true, deltaY: true, x: true, y: true },
123
132
  wait: { durationMs: true, selector: true, loadState: true, state: true }, evaluate: { script: true },
@@ -161,13 +170,21 @@ const singleCall = z.object({ action: z.enum(ACTIONS), ...browserFields }).stric
161
170
  /** The rules of every action but batch. */
162
171
  function checkCall(p, ctx) {
163
172
  const required = {
164
- ...DIRECT_REQUIRED, ask: ["fields"],
173
+ ...DIRECT_REQUIRED, ask: ["fields"], hover: ["selector"], upload: ["selector", "file"], viewport: ["width", "height"], result_read: ["resultId"],
165
174
  tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"], handoff: ["message"],
166
175
  };
167
176
  for (const field of required[p.action] ?? []) {
168
177
  if (p[field] === undefined)
169
178
  ctx.addIssue({ code: "custom", path: [field], message: `${field} is required for ${p.action}` });
170
179
  }
180
+ if (p.action !== "viewport" && (p.width !== undefined || p.height !== undefined))
181
+ ctx.addIssue({ code: "custom", message: "width and height are only supported for viewport" });
182
+ if (p.action !== "upload" && p.file !== undefined)
183
+ ctx.addIssue({ code: "custom", message: "file is only supported for upload" });
184
+ if ((p.offset !== undefined && p.action !== "result_read" || p.interactive !== undefined) && p.action !== "snapshot")
185
+ ctx.addIssue({ code: "custom", message: "offset is supported for snapshot and result_read; interactive only for snapshot" });
186
+ if (p.resultId !== undefined && p.action !== "result_read")
187
+ ctx.addIssue({ code: "custom", message: "resultId is only supported for result_read" });
171
188
  if (p.path !== undefined && p.action !== "har_stop")
172
189
  ctx.addIssue({ code: "custom", path: ["path"], message: "path is only supported for har_stop" });
173
190
  if (p.message !== undefined && p.action !== "handoff")
@@ -176,6 +193,12 @@ function checkCall(p, ctx) {
176
193
  ctx.addIssue({ code: "custom", path: ["fields"], message: "fields is only supported for ask, with 1 to 20 entries" });
177
194
  }
178
195
  const attach = p.cdpUrl !== undefined || p.endpoint !== undefined;
196
+ if (p.httpAuth && p.url && URL.canParse(p.url) && (new URL(p.url).username || new URL(p.url).password)) {
197
+ ctx.addIssue({ code: "custom", path: ["url"], message: "Use a URL without credentials when starting HTTP authentication" });
198
+ }
199
+ if (p.httpAuth && (p.action !== "start" || !p.backend || attach || p.contextId)) {
200
+ ctx.addIssue({ code: "custom", path: ["httpAuth"], message: "httpAuth requires start with an explicit backend and a fresh browser, without an endpoint, cdpUrl or contextId" });
201
+ }
179
202
  if (p.action !== "start" && (p.backend !== undefined || attach || p.headless !== undefined || p.headers !== undefined || p.extensionCdpUrl !== undefined)) {
180
203
  ctx.addIssue({ code: "custom", message: "backend, cdpUrl, endpoint, headers, extensionCdpUrl, and headless are only supported for start" });
181
204
  }
@@ -257,7 +280,7 @@ const BATCH_ARGUMENTS = { action: true, steps: true, tabId: true, timeoutMs: tru
257
280
  export const browserBatchParameters = z.object({
258
281
  action: z.enum([...ACTIONS, "batch"]),
259
282
  ...browserFields,
260
- steps: z.array(batchStep).min(1, "A batch needs at least one step").max(20, "A batch takes at most 20 steps; split a longer sequence into several batches").optional().describe("Only for batch: 1 to 20 steps run in order on one tab, in one request, with one timeoutMs for all of them. Use it when every step is already known and none needs an earlier result. Each step is an action (open, back, forward, reload, snapshot, click, fill, select, press, scroll, wait, evaluate) with only that action's arguments: no per-step tabId or timeoutMs (set them on the batch), no target, no nested batch. A batch whose first step is open starts a browser when none is running. The first failure stops the rest and nothing is rolled back. After a click, press, evaluate, navigation, or snapshot step, refs from before the batch stop working: use literal selectors, or end the batch with a snapshot."),
283
+ steps: z.array(batchStep).min(1, "A batch needs at least one step").max(20, "A batch takes at most 20 steps; split a longer sequence into several batches").optional().describe("Only for batch: 1 to 20 steps run in order on one tab, in one tool call, with one timeoutMs for all of them. Use it when every step is already known and none needs an earlier result. Each step is an action (open, back, forward, reload, snapshot, click, fill, select, press, scroll, wait, evaluate) with only that action's arguments: no per-step tabId or timeoutMs (set them on the batch), no target, no nested batch. A batch whose first step is open starts a browser when none is running. The first failure stops the rest and nothing is rolled back. After a click, press, evaluate, navigation, or snapshot step, refs from before the batch stop working: use literal selectors, or end the batch with a snapshot."),
261
284
  }).strict().superRefine((p, ctx) => {
262
285
  if (p.action !== "batch") {
263
286
  if (p.steps !== undefined)
@@ -285,7 +308,7 @@ export const aiParameters = z.object({
285
308
  instruction: z.string().trim().min(1).describe("One bounded task on the selected page. act may change the website."),
286
309
  tabId: z.string().min(1).optional(),
287
310
  schema: z.record(z.string(), z.unknown()).optional().describe("Optional JSON Schema for extract; unsupported schemas are rejected before the model call."),
288
- timeoutMs: z.number().int().min(1).max(120_000).optional().describe("Default 120000. Timeout closes the owned browser; actions are never replayed automatically."),
311
+ timeoutMs: z.number().int().min(1).max(120_000).optional().describe("Default 120000. On timeout, an already-sent action may have completed. A responsive browser is kept; inspect the page before retrying."),
289
312
  }).strict().superRefine((p, ctx) => {
290
313
  if (p.schema && p.action !== "extract")
291
314
  ctx.addIssue({ code: "custom", path: ["schema"], message: "schema is only supported for extract" });
@@ -0,0 +1,42 @@
1
+ import type { Stagehand, StagehandBrowser } from "@browserbasehq/stagehand";
2
+ import type { GuardedEndpoint } from "./cdp-guard.ts";
3
+ import type { ClientGenerate } from "./session.ts";
4
+ export declare const stagehandSdk: () => Promise<typeof import("@browserbasehq/stagehand")>;
5
+ export declare function freePort(): Promise<number>;
6
+ /**
7
+ * Stagehand ends a launched Chrome with SIGTERM to its whole process group, which kills the network service before it
8
+ * writes cookies to disk. Browser.close shuts Chrome down in order; waiting for its process to exit means Stagehand's
9
+ * close then has nothing left to signal, so a persistent profile keeps its logins.
10
+ */
11
+ export declare function quitChrome(port: number): Promise<void>;
12
+ /** Reloading Stagehand's extension can replace its service worker between discovery and attachment; attaching again then succeeds. */
13
+ export declare function connectRetrying<T>(connect: () => Promise<T>, signal: AbortSignal): Promise<T>;
14
+ /**
15
+ * Stagehand on a browser another client may just have left. The in-browser runtime releases a lost or detached client's
16
+ * instance asynchronously, so a create that arrives first sees it still initialized and is retried.
17
+ */
18
+ export declare function createStagehand(browser: StagehandBrowser, model: {
19
+ model?: {
20
+ generate: ClientGenerate;
21
+ };
22
+ }, signal: AbortSignal): Promise<Stagehand>;
23
+ type RawCdpSend = (method: string, params?: Record<string, unknown>, sessionId?: string) => Promise<any>;
24
+ /** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
25
+ export declare function withRawCdp<T>(connectUrl: string, signal: AbortSignal, use: (send: RawCdpSend) => Promise<T>): Promise<T>;
26
+ /**
27
+ * Opens a window with a blank tab in a running browser that has no tab, and returns its id; else undefined. macOS
28
+ * Chrome keeps running after its last window closes, and in that state no client can create a tab, so Stagehand cannot
29
+ * attach. The tab belongs to whoever attaches, whose close removes it again.
30
+ */
31
+ export declare function ensurePageTarget(connectUrl: string, signal: AbortSignal): Promise<string | undefined>;
32
+ /**
33
+ * Lets go of a shared local browser. An attached one is disconnected, which closes Stagehand's instance in it and leaves
34
+ * the browser running for the next client; a launched profile's Chrome is quit so it writes its cookies.
35
+ */
36
+ export declare function release(shared: {
37
+ browser: StagehandBrowser;
38
+ stagehand?: Stagehand;
39
+ quitPort?: number;
40
+ guard?: GuardedEndpoint;
41
+ }): Promise<void>;
42
+ export {};
@@ -0,0 +1,144 @@
1
+ import { once } from "node:events";
2
+ import { createServer } from "node:net";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { z } from "zod";
5
+ import { abortable, deadline, messageOf } from "./errors.js";
6
+ export const stagehandSdk = () => import("@browserbasehq/stagehand");
7
+ export async function freePort() {
8
+ const server = createServer().listen(0, "127.0.0.1");
9
+ await once(server, "listening");
10
+ const { port } = server.address();
11
+ await new Promise(resolve => server.close(resolve));
12
+ return port;
13
+ }
14
+ /**
15
+ * Stagehand ends a launched Chrome with SIGTERM to its whole process group, which kills the network service before it
16
+ * writes cookies to disk. Browser.close shuts Chrome down in order; waiting for its process to exit means Stagehand's
17
+ * close then has nothing left to signal, so a persistent profile keeps its logins.
18
+ */
19
+ export async function quitChrome(port) {
20
+ const version = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
21
+ const socket = new WebSocket((await version.json()).webSocketDebuggerUrl);
22
+ let pid;
23
+ socket.addEventListener("message", event => {
24
+ const reply = JSON.parse(String(event.data));
25
+ if (reply.id === 1)
26
+ pid = reply.result?.processInfo?.find(entry => entry.type === "browser")?.id;
27
+ });
28
+ const closed = once(socket, "close");
29
+ socket.addEventListener("open", () => {
30
+ socket.send(JSON.stringify({ id: 1, method: "SystemInfo.getProcessInfo" }));
31
+ socket.send(JSON.stringify({ id: 2, method: "Browser.close" }));
32
+ }, { once: true });
33
+ await closed;
34
+ // The endpoint closes before Chrome finishes writing the profile.
35
+ for (let i = 0; pid && i < 200 && running(pid); i++)
36
+ await delay(20);
37
+ }
38
+ /** Reloading Stagehand's extension can replace its service worker between discovery and attachment; attaching again then succeeds. */
39
+ export async function connectRetrying(connect, signal) {
40
+ for (let attempt = 0;; attempt++) {
41
+ try {
42
+ return await connect();
43
+ }
44
+ catch (error) {
45
+ if (attempt >= 3 || !/No target with given id found/.test(messageOf(error)))
46
+ throw error;
47
+ await delay(100, undefined, { signal });
48
+ }
49
+ }
50
+ }
51
+ function running(pid) {
52
+ try {
53
+ process.kill(pid, 0);
54
+ return true;
55
+ }
56
+ catch (error) {
57
+ return error.code === "EPERM";
58
+ }
59
+ }
60
+ /**
61
+ * Stagehand on a browser another client may just have left. The in-browser runtime releases a lost or detached client's
62
+ * instance asynchronously, so a create that arrives first sees it still initialized and is retried.
63
+ */
64
+ export async function createStagehand(browser, model, signal) {
65
+ for (let attempt = 0;; attempt++) {
66
+ try {
67
+ return await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...model });
68
+ }
69
+ catch (error) {
70
+ if (attempt >= 4 || !/already initialized/i.test(messageOf(error)))
71
+ throw error;
72
+ await delay(250, undefined, { signal });
73
+ }
74
+ }
75
+ }
76
+ /** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
77
+ export async function withRawCdp(connectUrl, signal, use) {
78
+ const socket = new WebSocket(connectUrl);
79
+ const pending = new Map();
80
+ let nextId = 0;
81
+ const closed = new Promise((_, reject) => {
82
+ const fail = () => reject(new Error("CDP connection closed"));
83
+ socket.addEventListener("close", fail);
84
+ socket.addEventListener("error", fail);
85
+ });
86
+ closed.catch(() => undefined);
87
+ socket.addEventListener("message", event => {
88
+ const message = JSON.parse(String(event.data));
89
+ const entry = pending.get(message.id);
90
+ if (!entry)
91
+ return;
92
+ pending.delete(message.id);
93
+ if (message.error)
94
+ entry.reject(new Error(message.error.message));
95
+ else
96
+ entry.resolve(message.result);
97
+ });
98
+ const send = (method, params = {}, sessionId) => {
99
+ const id = ++nextId;
100
+ const reply = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
101
+ socket.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
102
+ return abortable(Promise.race([reply, closed]), signal);
103
+ };
104
+ try {
105
+ await abortable(Promise.race([new Promise(resolve => socket.addEventListener("open", resolve, { once: true })), closed]), signal);
106
+ return await use(send);
107
+ }
108
+ finally {
109
+ socket.close();
110
+ }
111
+ }
112
+ /**
113
+ * Opens a window with a blank tab in a running browser that has no tab, and returns its id; else undefined. macOS
114
+ * Chrome keeps running after its last window closes, and in that state no client can create a tab, so Stagehand cannot
115
+ * attach. The tab belongs to whoever attaches, whose close removes it again.
116
+ */
117
+ export async function ensurePageTarget(connectUrl, signal) {
118
+ return withRawCdp(connectUrl, signal, async (send) => {
119
+ const { targetInfos } = await send("Target.getTargets");
120
+ if (targetInfos.some(target => target.type === "page"))
121
+ return undefined;
122
+ const { targetId } = await send("Target.createTarget", { url: "about:blank", newWindow: true });
123
+ return z.string().parse(targetId);
124
+ });
125
+ }
126
+ /**
127
+ * Lets go of a shared local browser. An attached one is disconnected, which closes Stagehand's instance in it and leaves
128
+ * the browser running for the next client; a launched profile's Chrome is quit so it writes its cookies.
129
+ */
130
+ export async function release(shared) {
131
+ if (shared.guard) {
132
+ try {
133
+ await deadline(shared.browser.disconnect(), 5000);
134
+ }
135
+ finally {
136
+ await shared.guard.close();
137
+ }
138
+ return;
139
+ }
140
+ await deadline(shared.stagehand?.close() ?? Promise.resolve(), 1500).catch(() => undefined);
141
+ if (shared.quitPort)
142
+ await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
143
+ await deadline(shared.browser.close(), 5000);
144
+ }