@edlsh/browse-core 0.7.0 → 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 (43) hide show
  1. package/README.md +8 -2
  2. package/dist/broker-client.d.ts +4 -2
  3. package/dist/broker-client.js +10 -5
  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/config.d.ts +101 -0
  8. package/dist/config.js +78 -0
  9. package/dist/contexts.d.ts +10 -0
  10. package/dist/contexts.js +27 -0
  11. package/dist/errors.d.ts +29 -0
  12. package/dist/errors.js +83 -0
  13. package/dist/host-model.d.ts +24 -0
  14. package/dist/host-model.js +35 -0
  15. package/dist/index.d.ts +10 -13
  16. package/dist/index.js +11 -15
  17. package/dist/jev.js +9 -3
  18. package/dist/page-operations.d.ts +11 -1
  19. package/dist/page-operations.js +62 -11
  20. package/dist/real-browser-ai.d.ts +1 -1
  21. package/dist/real-browser-ai.js +1 -1
  22. package/dist/real-browser-client.js +1 -1
  23. package/dist/real-browser-session.d.ts +1 -1
  24. package/dist/real-browser-session.js +24 -5
  25. package/dist/schema.d.ts +32 -0
  26. package/dist/schema.js +22 -6
  27. package/dist/session-runtime.d.ts +42 -0
  28. package/dist/session-runtime.js +144 -0
  29. package/dist/session.d.ts +27 -118
  30. package/dist/session.js +134 -350
  31. package/dist/settings.js +47 -6
  32. package/dist/tool-results.d.ts +28 -0
  33. package/dist/tool-results.js +40 -0
  34. package/extensions/http-auth/README.md +27 -0
  35. package/extensions/http-auth/background.js +85 -0
  36. package/extensions/http-auth/manifest.json +27 -0
  37. package/extensions/http-auth/native/README.md +31 -0
  38. package/extensions/http-auth/native/host.py +97 -0
  39. package/extensions/http-auth/native/install.py +62 -0
  40. package/extensions/http-auth/options.html +25 -0
  41. package/extensions/http-auth/options.js +36 -0
  42. package/extensions/http-auth/origin.js +16 -0
  43. package/package.json +13 -2
package/dist/index.d.ts CHANGED
@@ -1,13 +1,10 @@
1
- export * from "./session.ts";
2
- export * from "./schema.ts";
3
- export * from "./settings.ts";
4
- export { EXTRACT_MODEL, MAX_TEXT, DECIDE_TEXT, askNeeds, pageText, askPage, type PageState, type Answer as AskAnswer, type AskResult, type AskModels } from "./ask.ts";
5
- export * from "./cdp-guard.ts";
6
- export * from "./real-browser-client.ts";
7
- export * from "./chrome-profile.ts";
8
- export * from "./har.ts";
9
- export * from "./page-operations.ts";
10
- export * from "./browser-cookies.ts";
11
- export * from "./jev.ts";
12
- export * from "./classifier.ts";
13
- export * from "./command.ts";
1
+ export { BrowseSession, type BrowserOutput, type BrowseSessionOptions, type HostIdentity, type ClientGenerate, type ClientInference } from "./session.ts";
2
+ export { environmentConfig, type BrowseConfig, type ConfigurationContext, type ConfigResolver, type RemoteBrowser, type DomainLists } from "./config.ts";
3
+ export { BrowseToolError, type BatchProgress } from "./errors.ts";
4
+ export { browserParameters, browserBatchParameters, aiParameters, type AIParams, type BrowserParams, type BatchStep, type AskFields } from "./schema.ts";
5
+ export { hostModelGenerate, type HostModelRequest, type HostModelReply } from "./host-model.ts";
6
+ export { nameChromeProfile } from "./chrome-profile.ts";
7
+ export { BROWSER_IDS, localCookieProvider, normalizeCookieDomains, CookieSourceError, type BrowserId, type BrowserCookies, type BrowserProfileMatch, type CookieProvider, type CookieBrowser } from "./browser-cookies.ts";
8
+ export { classifierSpec, ClassifierRefusal, workersAiClassifier, vercelClassifier, type Answer, type ClassifyRequest, type HostClassify } from "./classifier.ts";
9
+ export { SETTINGS_FILE, CONVERSATION_MODEL, DEFAULT_CLASSIFIER, ROLE_KEYS, readSettings, writeSetting, modelRef, roleChoice, classifierOptions, type ModelOption, type ModelRole, type ClassifierInfo, type BrowseSettings } from "./settings.ts";
10
+ export { SETTINGS, SETTING_SUMMARY, USAGE, parseBrowseCommand, browseCompletions, type BrowseCommand, type CompletionSource, type CompletionItem } from "./command.ts";
package/dist/index.js CHANGED
@@ -1,15 +1,11 @@
1
- // Host-neutral browser core shared by omp-browse, pi-browse, and hermes-browse.
2
- export * from "./session.js";
3
- export * from "./schema.js";
4
- export * from "./settings.js";
5
- // ask.ts and classifier.ts both name a type Answer; the hosts use the classifier's.
6
- export { EXTRACT_MODEL, MAX_TEXT, DECIDE_TEXT, askNeeds, pageText, askPage } from "./ask.js";
7
- export * from "./cdp-guard.js";
8
- export * from "./real-browser-client.js";
9
- export * from "./chrome-profile.js";
10
- export * from "./har.js";
11
- export * from "./page-operations.js";
12
- export * from "./browser-cookies.js";
13
- export * from "./jev.js";
14
- export * from "./classifier.js";
15
- export * from "./command.js";
1
+ // Host integration surface. Serialized worker callbacks and transport internals are not public APIs.
2
+ export { BrowseSession } from "./session.js";
3
+ export { environmentConfig } from "./config.js";
4
+ export { BrowseToolError } from "./errors.js";
5
+ export { browserParameters, browserBatchParameters, aiParameters } from "./schema.js";
6
+ export { hostModelGenerate } from "./host-model.js";
7
+ export { nameChromeProfile } from "./chrome-profile.js";
8
+ export { BROWSER_IDS, localCookieProvider, normalizeCookieDomains, CookieSourceError } from "./browser-cookies.js";
9
+ export { classifierSpec, ClassifierRefusal, workersAiClassifier, vercelClassifier } from "./classifier.js";
10
+ export { SETTINGS_FILE, CONVERSATION_MODEL, DEFAULT_CLASSIFIER, ROLE_KEYS, readSettings, writeSetting, modelRef, roleChoice, classifierOptions } from "./settings.js";
11
+ export { SETTINGS, SETTING_SUMMARY, USAGE, parseBrowseCommand, browseCompletions } from "./command.js";
package/dist/jev.js CHANGED
@@ -94,7 +94,8 @@ export function fitsAction(action, candidate, xpath) {
94
94
  // Stagehand xpath steps are tagName[n]; the last one is the element's own tag.
95
95
  const tag = /(?:^|\/)([\w-]+)\[\d+\]$/.exec(xpath)?.[1].toLowerCase();
96
96
  if (action === "fill")
97
- return tag === "input" || tag === "textarea" || Object.hasOwn(FILLABLE, candidate.role);
97
+ return tag === "textarea" || (tag !== "select" && Object.hasOwn(FILLABLE, candidate.role))
98
+ || (tag === "input" && ["Date", "DateTime", "InputTime", "week", "month"].includes(candidate.role));
98
99
  if (action === "select")
99
100
  return tag === "select";
100
101
  return true;
@@ -119,8 +120,13 @@ export async function pickTarget(candidates, state, choose, signal) {
119
120
  }
120
121
  const won = answers.flatMap((answer, i) => chunks[i].filter(c => c.ref === answer.choice).map(chosen => ({ chosen, confidence: answer.confidence })));
121
122
  // Every chunk answered NONE; report how sure the least-sure chunk was.
122
- if (!won.length)
123
- return { none: true, confidence: Math.min(...answers.map(a => a.confidence)), ranked: [] };
123
+ if (!won.length) {
124
+ const confidence = Math.min(...answers.map(a => a.confidence));
125
+ const none = confidence >= JEV_MIN_CONFIDENCE;
126
+ const ranked = none ? [] : chunks.flatMap((chunk, i) => chunk.map(c => ({ ...c, probability: answers[i].probabilities[c.ref] ?? 0 })))
127
+ .sort((a, b) => b.probability - a.probability).slice(0, 5);
128
+ return { none, confidence, ranked };
129
+ }
124
130
  // A lone confident winner would face only itself in another round; take it without the extra request.
125
131
  if (won.length === 1 && won[0].confidence >= JEV_MIN_CONFIDENCE)
126
132
  return { ...won[0], none: false, ranked: [] };
@@ -1,7 +1,14 @@
1
1
  import type { ExperimentalBatchContext } from "@browserbasehq/stagehand";
2
2
  import type { AnsweredDialog } from "./session.ts";
3
3
  export interface PageOperation {
4
- action: "start" | "open" | "back" | "forward" | "reload" | "wait" | "snapshot" | "click" | "fill" | "select" | "press" | "scroll" | "evaluate" | "screenshot" | "tab_select";
4
+ action: "start" | "open" | "back" | "forward" | "reload" | "wait" | "snapshot" | "click" | "fill" | "select" | "press" | "scroll" | "evaluate" | "screenshot" | "tab_select" | "hover" | "upload" | "viewport";
5
+ width?: number;
6
+ height?: number;
7
+ file?: {
8
+ name: string;
9
+ mimeType: string;
10
+ base64: string;
11
+ };
5
12
  selector?: string;
6
13
  nth?: number;
7
14
  /** Snapshot ref to verify before acting: the tab URL, the ref ID (frame ordinal and backend node), and its XPath. */
@@ -31,6 +38,8 @@ export interface PageOperation {
31
38
  snapshot?: {
32
39
  version: string;
33
40
  maxChars: number;
41
+ offset?: number;
42
+ interactive?: boolean;
34
43
  };
35
44
  readTimeoutMs: number;
36
45
  }
@@ -38,6 +47,7 @@ export interface PageOperation {
38
47
  export interface PageSnapshot {
39
48
  tree: string;
40
49
  truncated: boolean;
50
+ nextOffset?: number;
41
51
  refs: Record<string, string>;
42
52
  }
43
53
  export interface PageOperationResult {
@@ -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,21 @@ 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>>;
46
56
  httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
47
57
  backend: z.ZodOptional<z.ZodEnum<{
48
58
  browserbase: "browserbase";
@@ -96,6 +106,8 @@ export declare const browserParameters: z.ZodObject<{
96
106
  }>>;
97
107
  script: z.ZodOptional<z.ZodString>;
98
108
  fullPage: z.ZodOptional<z.ZodBoolean>;
109
+ offset: z.ZodOptional<z.ZodNumber>;
110
+ interactive: z.ZodOptional<z.ZodBoolean>;
99
111
  maxChars: z.ZodOptional<z.ZodNumber>;
100
112
  fields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
101
113
  type: z.ZodEnum<{
@@ -136,10 +148,12 @@ export declare const browserParameters: z.ZodObject<{
136
148
  handoff: "handoff";
137
149
  har_start: "har_start";
138
150
  har_stop: "har_stop";
151
+ hover: "hover";
139
152
  live_view: "live_view";
140
153
  open: "open";
141
154
  press: "press";
142
155
  reload: "reload";
156
+ result_read: "result_read";
143
157
  screenshot: "screenshot";
144
158
  scroll: "scroll";
145
159
  select: "select";
@@ -150,6 +164,8 @@ export declare const browserParameters: z.ZodObject<{
150
164
  tab_new: "tab_new";
151
165
  tab_select: "tab_select";
152
166
  tabs: "tabs";
167
+ upload: "upload";
168
+ viewport: "viewport";
153
169
  wait: "wait";
154
170
  }>;
155
171
  }, z.core.$strict>;
@@ -158,6 +174,14 @@ export declare const browserParameters: z.ZodObject<{
158
174
  * prompts and approval rules a batch needs: one call can navigate, act, and run page script.
159
175
  */
160
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>>;
161
185
  httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
162
186
  backend: z.ZodOptional<z.ZodEnum<{
163
187
  browserbase: "browserbase";
@@ -211,6 +235,8 @@ export declare const browserBatchParameters: z.ZodObject<{
211
235
  }>>;
212
236
  script: z.ZodOptional<z.ZodString>;
213
237
  fullPage: z.ZodOptional<z.ZodBoolean>;
238
+ offset: z.ZodOptional<z.ZodNumber>;
239
+ interactive: z.ZodOptional<z.ZodBoolean>;
214
240
  maxChars: z.ZodOptional<z.ZodNumber>;
215
241
  fields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
216
242
  type: z.ZodEnum<{
@@ -252,10 +278,12 @@ export declare const browserBatchParameters: z.ZodObject<{
252
278
  handoff: "handoff";
253
279
  har_start: "har_start";
254
280
  har_stop: "har_stop";
281
+ hover: "hover";
255
282
  live_view: "live_view";
256
283
  open: "open";
257
284
  press: "press";
258
285
  reload: "reload";
286
+ result_read: "result_read";
259
287
  screenshot: "screenshot";
260
288
  scroll: "scroll";
261
289
  select: "select";
@@ -266,6 +294,8 @@ export declare const browserBatchParameters: z.ZodObject<{
266
294
  tab_new: "tab_new";
267
295
  tab_select: "tab_select";
268
296
  tabs: "tabs";
297
+ upload: "upload";
298
+ viewport: "viewport";
269
299
  wait: "wait";
270
300
  }>;
271
301
  steps: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -306,6 +336,8 @@ export declare const browserBatchParameters: z.ZodObject<{
306
336
  }>>;
307
337
  script: z.ZodOptional<z.ZodString>;
308
338
  maxChars: z.ZodOptional<z.ZodNumber>;
339
+ offset: z.ZodOptional<z.ZodNumber>;
340
+ interactive: z.ZodOptional<z.ZodBoolean>;
309
341
  }, z.core.$strict>>>;
310
342
  }, z.core.$strict>;
311
343
  export declare const aiParameters: z.ZodObject<{
package/dist/schema.js CHANGED
@@ -43,11 +43,17 @@ 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."),
51
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."),
52
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."),
53
59
  cdpUrl: z.url({ protocol: /^(?:https?|wss?)$/ }).refine(value => {
@@ -86,6 +92,8 @@ const browserFields = {
86
92
  state: z.enum(["attached", "detached", "visible", "hidden"]).optional().describe("Selector state for wait; default visible."),
87
93
  script: z.string().min(1).optional().describe("JavaScript expression evaluated in the browser page, required for evaluate. No local filesystem or process access."),
88
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."),
89
97
  maxChars: z.number().int().min(1000).max(50_000).optional().describe("Snapshot text limit; default 20000."),
90
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."),
91
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."),
@@ -110,7 +118,7 @@ const batchStepFields = z.object({
110
118
  loadState: browserFields.loadState,
111
119
  state: browserFields.state,
112
120
  script: browserFields.script,
113
- maxChars: browserFields.maxChars,
121
+ maxChars: browserFields.maxChars, offset: browserFields.offset, interactive: browserFields.interactive,
114
122
  }, {
115
123
  error: issue => issue.code === "unrecognized_keys"
116
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.`
@@ -118,7 +126,7 @@ const batchStepFields = z.object({
118
126
  }).strict();
119
127
  /** The arguments each batch action reads. A step carrying any other would see it silently ignored, so it is rejected. */
120
128
  const STEP_ARGUMENTS = {
121
- open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true },
129
+ open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true, offset: true, interactive: true },
122
130
  click: { selector: true }, fill: { selector: true, value: true }, select: { selector: true, values: true },
123
131
  press: { key: true }, scroll: { deltaX: true, deltaY: true, x: true, y: true },
124
132
  wait: { durationMs: true, selector: true, loadState: true, state: true }, evaluate: { script: true },
@@ -162,13 +170,21 @@ const singleCall = z.object({ action: z.enum(ACTIONS), ...browserFields }).stric
162
170
  /** The rules of every action but batch. */
163
171
  function checkCall(p, ctx) {
164
172
  const required = {
165
- ...DIRECT_REQUIRED, ask: ["fields"],
173
+ ...DIRECT_REQUIRED, ask: ["fields"], hover: ["selector"], upload: ["selector", "file"], viewport: ["width", "height"], result_read: ["resultId"],
166
174
  tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"], handoff: ["message"],
167
175
  };
168
176
  for (const field of required[p.action] ?? []) {
169
177
  if (p[field] === undefined)
170
178
  ctx.addIssue({ code: "custom", path: [field], message: `${field} is required for ${p.action}` });
171
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" });
172
188
  if (p.path !== undefined && p.action !== "har_stop")
173
189
  ctx.addIssue({ code: "custom", path: ["path"], message: "path is only supported for har_stop" });
174
190
  if (p.message !== undefined && p.action !== "handoff")
@@ -264,7 +280,7 @@ const BATCH_ARGUMENTS = { action: true, steps: true, tabId: true, timeoutMs: tru
264
280
  export const browserBatchParameters = z.object({
265
281
  action: z.enum([...ACTIONS, "batch"]),
266
282
  ...browserFields,
267
- 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."),
268
284
  }).strict().superRefine((p, ctx) => {
269
285
  if (p.action !== "batch") {
270
286
  if (p.steps !== undefined)
@@ -292,7 +308,7 @@ export const aiParameters = z.object({
292
308
  instruction: z.string().trim().min(1).describe("One bounded task on the selected page. act may change the website."),
293
309
  tabId: z.string().min(1).optional(),
294
310
  schema: z.record(z.string(), z.unknown()).optional().describe("Optional JSON Schema for extract; unsupported schemas are rejected before the model call."),
295
- 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."),
296
312
  }).strict().superRefine((p, ctx) => {
297
313
  if (p.schema && p.action !== "extract")
298
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 {};