@edlsh/browse-core 0.7.0 → 0.8.1

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 +103 -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 +10 -4
  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 +5 -4
  22. package/dist/real-browser-client.js +1 -1
  23. package/dist/real-browser-session.d.ts +4 -2
  24. package/dist/real-browser-session.js +47 -21
  25. package/dist/schema.d.ts +36 -0
  26. package/dist/schema.js +37 -10
  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 +152 -352
  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
@@ -0,0 +1,35 @@
1
+ /** Stagehand's single-turn model protocol. The host owns model selection, cancellation, credentials and cost accounting. */
2
+ export function hostModelGenerate(complete) {
3
+ return async (params) => {
4
+ if ("tools" in params && params.tools?.length)
5
+ throw new Error("Stagehand tool calls are not supported on host models.");
6
+ const messages = params.messages.map(message => {
7
+ if (message.role !== "user")
8
+ throw new Error("A host model accepts only single-turn Stagehand requests.");
9
+ const blocks = Array.isArray(message.content) ? message.content : [message.content];
10
+ return { role: "user", content: blocks.map(block => {
11
+ if (block.type === "text")
12
+ return { type: "text", text: block.text };
13
+ if (block.type === "image")
14
+ return { type: "image", mimeType: block.mimeType, data: block.data };
15
+ throw new Error("Unsupported Stagehand content: " + block.type);
16
+ }) };
17
+ });
18
+ const schema = params.responseFormat?.type === "json_schema" ? params.responseFormat.schema : undefined;
19
+ const systemPrompt = params.systemPrompt ? [params.systemPrompt] : [];
20
+ if (schema !== undefined)
21
+ systemPrompt.push("Reply with only one JSON value matching this JSON Schema, with no prose:\n" + JSON.stringify(schema));
22
+ const { text: raw, inputTokens, outputTokens, cachedInputTokens } = await complete({ systemPrompt, messages, temperature: params.temperature });
23
+ const text = raw.trim(), content = { type: "text", text }, usage = { inputTokens, outputTokens, cachedInputTokens, totalTokens: inputTokens + outputTokens };
24
+ if (schema === undefined)
25
+ return { role: "assistant", content, outputFormat: "text", usage };
26
+ let structuredContent;
27
+ try {
28
+ structuredContent = JSON.parse(/^```(?:json)?\s*([\s\S]*?)\s*```$/.exec(text)?.[1] ?? text);
29
+ }
30
+ catch {
31
+ throw new Error("The host model did not return valid JSON for Stagehand.");
32
+ }
33
+ return { role: "assistant", content, outputFormat: "json_schema", structuredContent, usage };
34
+ };
35
+ }
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
@@ -73,7 +73,7 @@ export function outlineCandidates(outline, action) {
73
73
  const depth = indent.length;
74
74
  while (ancestors.length && ancestors.at(-1).depth >= depth)
75
75
  ancestors.pop();
76
- const ref = /(?:^| )ref=(e\d+)/.exec(attributes)?.[1];
76
+ const ref = /(?:^| )ref=(e\d+|(?:f\d+)?a\d+)(?: |$)/.exec(attributes)?.[1];
77
77
  const states = attributes.split(" ").filter(state => state && !state.startsWith("ref="));
78
78
  const text = name ? `${role}: ${name}` : role;
79
79
  // fill needs a text-entry control it may change; select needs a native <select>, which lists its options.
@@ -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: {
@@ -39,11 +39,12 @@ export async function observePage(generate, page, instruction, single) {
39
39
  ? "Return the one next action that carries out the instruction, or no elements when the page offers none."
40
40
  : "Return every element the instruction is about, each with the action a person would take on it.";
41
41
  const reply = await generateJson(generate, `You choose elements on a web page for a browser agent. ${OUTLINE} ${task} Answer with JSON only.`, `${describe(page, instruction)}\n\nOutline:\n${page.outline}`, ACTIONS_SCHEMA);
42
- const refs = new Set(page.outline.match(/\bref=e\d+/g)?.map(ref => ref.slice(4)));
42
+ const refs = new Set(page.outline.match(/\bref=(?:e\d+|(?:f\d+)?a\d+)\b/g)?.map(ref => ref.slice(4)));
43
43
  return (reply.elements ?? []).flatMap(({ ref, description, method, arguments: args }) => {
44
- if (typeof ref !== "string" || !refs.has(ref) || (method !== "click" && method !== "fill" && method !== "select" && method !== "press"))
44
+ const normalized = typeof ref === "string" ? ref.replace(/^@/, "") : "";
45
+ if (!normalized || !refs.has(normalized) || (method !== "click" && method !== "fill" && method !== "select" && method !== "press"))
45
46
  return [];
46
- return [{ selector: ref, description: String(description ?? ""), method, arguments: Array.isArray(args) ? args.map(String) : [] }];
47
+ return [{ selector: normalized, description: String(description ?? ""), method, arguments: Array.isArray(args) ? args.map(String) : [] }];
47
48
  }).slice(0, single ? 1 : undefined);
48
49
  }
49
50
  /** What the page says in answer to an instruction, as JSON matching `schema`; without one, as `{ extraction }`. */
@@ -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;
@@ -19,7 +19,7 @@ export declare class RealBrowserSession {
19
19
  private readonly release;
20
20
  readonly owner: string;
21
21
  private readonly group;
22
- private readonly allowedOrigins?;
22
+ readonly allowedOrigins?: readonly string[] | undefined;
23
23
  /** The tab this conversation's next call acts on. */
24
24
  private tab?;
25
25
  /** Whether this conversation opened a tab, so close has a group to close. */
@@ -33,6 +33,8 @@ export declare class RealBrowserSession {
33
33
  version: string;
34
34
  }, owner: string, group: string, allowedOrigins?: string[]): RealBrowserSession;
35
35
  private constructor();
36
+ /** True once this conversation opened a tab or selected a lent tab; false after a read-only pre-open `tabs` check. */
37
+ get active(): boolean;
36
38
  run(p: BrowserParams, signal: AbortSignal, timeoutMs: number): Promise<BrowserOutput>;
37
39
  /** Reads a tab for ask, JEV, and browse_ai in one script, so the outline, the text, and the viewport are of the same page. */
38
40
  read(tabId: string | undefined, image: boolean, signal: AbortSignal, timeoutMs: number): Promise<RealBrowserPage>;
@@ -1,18 +1,19 @@
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", "force", "value", "values", "key", "script", "fullPage", "durationMs", "loadState", "state", "deltaX", "deltaY", "x", "y", "message", "interactive", "width", "height", "file"];
11
11
  /**
12
- * `el` takes a snapshot ref (e12) or a selector; a bare XPath gets the prefix Playwright-style locators need. `timeout`
13
- * ends a wait for an element or a page before the script's own deadline, whose error would not say what was missing.
12
+ * `el` takes a snapshot ref (`e12`, `@e12`, `a5`, `f2a5`, `@f2a5`) or a selector; a bare XPath gets the prefix
13
+ * Playwright-style locators need. `timeout` ends a wait for an element or a page before the script's own deadline,
14
+ * whose error would not say what was missing.
14
15
  */
15
- const PRELUDE = String.raw `const el = selector => /^e\d+$/.test(selector) ? ref(selector) : page.locator(/^\(*\/\//.test(selector) ? "xpath=" + selector : selector);
16
+ const PRELUDE = String.raw `const el = selector => /^@?(?:e\d+|(?:f\d+)?a\d+)$/.test(selector) ? ref(selector.replace(/^@/, "")) : page.locator(/^\(*\/\//.test(selector) ? "xpath=" + selector : selector);
16
17
  let data, shot, extra;`;
17
18
  /**
18
19
  * What a script hands back. OpenCode Browse returns a string as it is and anything else as JSON, and adds lines of its
@@ -27,14 +28,32 @@ const VIEW = /@@browse-core:([^@]*)@@/;
27
28
  const BODIES = {
28
29
  start: "if (p.url) await page.goto(p.url, { timeout });",
29
30
  open: "await page.goto(p.url, { timeout });",
30
- back: "await page.goBack();",
31
- forward: "await page.goForward();",
32
- reload: "await page.reload();",
31
+ back: "await page.goBack({ timeout });",
32
+ forward: "await page.goForward({ timeout });",
33
+ reload: "await page.reload({ timeout });",
33
34
  // The default of 80 lines hides most of a long page.
34
- snapshot: "data = String(await snapshot({ maxItems: 200 }));",
35
- click: "await el(p.selector).click({ timeout });",
36
- fill: "await el(p.selector).fill(p.value, { timeout });",
37
- select: "data = { selected: await el(p.selector).selectOption(p.values, { timeout }) };",
35
+ snapshot: "data = String(await snapshot({ maxItems: 200, interactive: p.interactive === true }));",
36
+ hover: "await el(p.selector).hover(p.force ? { timeout, force: true } : { timeout });",
37
+ viewport: "await page.setViewportSize({ width: p.width, height: p.height });",
38
+ // The relay's path-based upload would read files on the relay machine. Transfer only the caller-supplied bytes.
39
+ upload: `await el(p.selector).evaluate((node, file) => {
40
+ if (!(node instanceof HTMLInputElement) || node.type !== "file" || node.matches(":disabled")) throw new Error("Expected an enabled file input");
41
+ const transfer = new DataTransfer();
42
+ transfer.items.add(new File([Uint8Array.from(atob(file.base64), ch => ch.charCodeAt(0))], file.name, { type: file.mimeType }));
43
+ node.files = transfer.files;
44
+ node.dispatchEvent(new Event("input", { bubbles: true })); node.dispatchEvent(new Event("change", { bubbles: true }));
45
+ }, p.file, { timeout });`,
46
+ click: "await el(p.selector).click(p.force ? { timeout, force: true } : { timeout });",
47
+ fill: "await el(p.selector).fill(p.value, p.force ? { timeout, force: true } : { timeout });",
48
+ select: `const select = el(p.selector);
49
+ const reason = await select.evaluate((node, wanted) => {
50
+ if (!(node instanceof HTMLSelectElement)) return "Expected a native select";
51
+ if (!node.multiple && new Set(wanted).size > 1) return "Multiple values need a multi-select";
52
+ 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";
53
+ return null;
54
+ }, p.values, { timeout });
55
+ if (reason) throw new Error(reason + ". Nothing was selected.");
56
+ data = { selected: await select.selectOption(p.values, { timeout }) };`,
38
57
  press: "await page.keyboard.press(p.key);",
39
58
  scroll: "await page.mouse.move(p.x ?? 640, p.y ?? 400); await page.mouse.wheel(p.deltaX ?? 0, p.deltaY ?? 0);",
40
59
  wait: `if (p.durationMs !== undefined) await page.waitForTimeout(p.durationMs);
@@ -42,7 +61,7 @@ else if (p.selector !== undefined) await el(p.selector).waitFor({ state: p.state
42
61
  else await page.waitForLoadState(p.loadState, { timeout });`,
43
62
  evaluate: "data = (await page.evaluate(p.script)) ?? null;",
44
63
  screenshot: "shot = await page.screenshot({ fullPage: p.fullPage === true });",
45
- handoff: "data = { handoff: (await handoff(p.message)) ?? null };",
64
+ handoff: "data = { handoff: (await handoff(p.message, { timeoutMs: timeout })) ?? null };",
46
65
  har_start: 'await browse.network({ action: "start" });',
47
66
  };
48
67
  /**
@@ -100,6 +119,10 @@ export class RealBrowserSession {
100
119
  this.group = group;
101
120
  this.allowedOrigins = allowedOrigins;
102
121
  }
122
+ /** True once this conversation opened a tab or selected a lent tab; false after a read-only pre-open `tabs` check. */
123
+ get active() {
124
+ return this.opened || this.tab !== undefined;
125
+ }
103
126
  async run(p, signal, timeoutMs) {
104
127
  if (p.action === "status")
105
128
  return this.output(p.action, { data: { state: this.tab === undefined ? "no_tab" : "running", realBrowser: true, group: this.group } });
@@ -109,13 +132,13 @@ export class RealBrowserSession {
109
132
  }
110
133
  if (p.action === "tabs") {
111
134
  const tabs = await this.list(signal);
112
- return this.output(p.action, { data: { tabs: tabs.map(tab => ({ tabId: String(tab.tab), url: tab.url, title: tab.title, selected: tab.tab === this.tab })) } });
135
+ return this.output(p.action, { data: { tabs: tabs.map(tab => ({ tabId: String(tab.tab), url: tab.url, title: tab.title, selected: tab.tab === this.tab, ...(tab.lent ? { lent: true } : {}) })) } });
113
136
  }
114
137
  if (p.action === "tab_select" || p.action === "tab_close") {
115
138
  const tabs = await this.list(signal);
116
139
  const found = tabs.find(tab => String(tab.tab) === p.tabId);
117
140
  if (!found)
118
- throw new BrowseToolError("tab_missing", "This conversation has no such tab in the real browser. Call tabs to list its tabs.");
141
+ throw new BrowseToolError("tab_missing", "This conversation has no such tab in the real browser, and no lent tab has that ID. Call tabs to list available tabs.");
119
142
  if (p.action === "tab_select") {
120
143
  this.tab = found.tab;
121
144
  return this.output(p.action, { url: found.url, title: found.title });
@@ -151,7 +174,8 @@ export class RealBrowserSession {
151
174
  }
152
175
  if (p.action === "snapshot") {
153
176
  const tree = String(data), limit = p.maxChars ?? 20_000;
154
- data = { tree: tree.slice(0, limit), truncated: tree.length > limit };
177
+ const offset = p.offset ?? 0, end = offset + limit;
178
+ data = { tree: tree.slice(offset, end), truncated: tree.length > end, ...(tree.length > end ? { nextOffset: end } : {}) };
155
179
  }
156
180
  return {
157
181
  ...this.output(p.action, { url: view.url, title: view.title, ...(data === undefined ? {} : { data }) }, tab),
@@ -162,7 +186,7 @@ export class RealBrowserSession {
162
186
  async read(tabId, image, signal, timeoutMs) {
163
187
  const { tab, view, image: shot } = await this.script("read", tabId, { image }, READ, signal, timeoutMs);
164
188
  const { outline, text, values } = view.data;
165
- const controls = outline.replace(/ \[ref=e\d+\]/g, "").replace(/\[ref=e\d+ /g, "[");
189
+ const controls = outline.replace(/ \[ref=(?:e\d+|(?:f\d+)?a\d+)\]/g, "").replace(/\[ref=(?:e\d+|(?:f\d+)?a\d+) /g, "[");
166
190
  const readable = `${text}${values ? `\n\nField values:\n${values}` : ""}\n\nControls:\n${controls}`;
167
191
  return { tabId: String(tab), url: view.url, title: view.title, outline, text: readable, ...(shot ? { image: shot } : {}) };
168
192
  }
@@ -173,9 +197,10 @@ export class RealBrowserSession {
173
197
  throw new BrowseToolError("tab_missing", "No tab is open in the real browser. Call open with a url.");
174
198
  const code = [`const p = ${JSON.stringify(args)}, timeout = ${Math.max(500, timeoutMs - 2000)};`, PRELUDE, body, EPILOGUE].join("\n");
175
199
  const result = await this.client.call("execute", { tab, code, timeoutMs: Math.max(1500, timeoutMs - 1000) }, signal).catch(error => {
176
- // A failed script's message starts with the tab it ran in, which the caller already knows, and ends with where in the script it threw.
177
- if (error instanceof BrowseToolError && error.code === "real_browser_error")
178
- throw new BrowseToolError(error.code, error.message.replace(/^tab: \S+\s+/, "").replace(/\n\s+at .*$/s, ""));
200
+ // Strip the tab header (including `(also used: ...)`) and QuickJS stack frames, while keeping trailing Page/Warnings/Challenge lines.
201
+ if (error instanceof BrowseToolError && error.code === "real_browser_error") {
202
+ throw new BrowseToolError(error.code, error.message.replace(/^tab: [^\n]+\s+/, "").replace(/(?:\n[ \t]+at [^\n]+)+/g, "").trimEnd());
203
+ }
179
204
  throw error;
180
205
  });
181
206
  const encoded = VIEW.exec(result.text)?.[1];
@@ -266,7 +291,8 @@ export class RealBrowserSession {
266
291
  }
267
292
  }
268
293
  async list(signal) {
269
- return JSON.parse((await this.client.call("tabs", { action: "list", group: this.group }, signal)).text).tabs;
294
+ const { tabs } = JSON.parse((await this.client.call("tabs", { action: "list" }, signal)).text);
295
+ return tabs.filter(tab => tab.group === this.group || tab.lent === true);
270
296
  }
271
297
  output(action, view, tab = this.tab) {
272
298
  return { action, sessionId: null, backend: "local", origin: "connected", ...(tab === undefined ? {} : { tabId: String(tab) }), ...view };
package/dist/schema.d.ts CHANGED
@@ -17,6 +17,7 @@ declare const batchStepFields: z.ZodObject<{
17
17
  }>;
18
18
  url: z.ZodOptional<z.ZodURL>;
19
19
  selector: z.ZodOptional<z.ZodString>;
20
+ force: z.ZodOptional<z.ZodBoolean>;
20
21
  value: z.ZodOptional<z.ZodString>;
21
22
  values: z.ZodOptional<z.ZodArray<z.ZodString>>;
22
23
  key: z.ZodOptional<z.ZodString>;
@@ -38,11 +39,21 @@ declare const batchStepFields: z.ZodObject<{
38
39
  }>>;
39
40
  script: z.ZodOptional<z.ZodString>;
40
41
  maxChars: z.ZodOptional<z.ZodNumber>;
42
+ offset: z.ZodOptional<z.ZodNumber>;
43
+ interactive: z.ZodOptional<z.ZodBoolean>;
41
44
  }, z.core.$strict>;
42
45
  /** One validated batch step. It is a flat object, so `{ ...step, tabId }` runs like the same call on its own. */
43
46
  export type BatchStep = z.infer<typeof batchStepFields>;
44
47
  /** The browse tool's parameters without batch: what a host that has not adopted batch registers. */
45
48
  export declare const browserParameters: z.ZodObject<{
49
+ resultId: z.ZodOptional<z.ZodUUID>;
50
+ width: z.ZodOptional<z.ZodNumber>;
51
+ height: z.ZodOptional<z.ZodNumber>;
52
+ file: z.ZodOptional<z.ZodObject<{
53
+ name: z.ZodString;
54
+ mimeType: z.ZodString;
55
+ base64: z.ZodBase64;
56
+ }, z.core.$strict>>;
46
57
  httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
47
58
  backend: z.ZodOptional<z.ZodEnum<{
48
59
  browserbase: "browserbase";
@@ -73,6 +84,7 @@ export declare const browserParameters: z.ZodObject<{
73
84
  domains: z.ZodOptional<z.ZodArray<z.ZodString>>;
74
85
  profile: z.ZodOptional<z.ZodString>;
75
86
  selector: z.ZodOptional<z.ZodString>;
87
+ force: z.ZodOptional<z.ZodBoolean>;
76
88
  target: z.ZodOptional<z.ZodString>;
77
89
  visual: z.ZodOptional<z.ZodBoolean>;
78
90
  value: z.ZodOptional<z.ZodString>;
@@ -96,6 +108,8 @@ export declare const browserParameters: z.ZodObject<{
96
108
  }>>;
97
109
  script: z.ZodOptional<z.ZodString>;
98
110
  fullPage: z.ZodOptional<z.ZodBoolean>;
111
+ offset: z.ZodOptional<z.ZodNumber>;
112
+ interactive: z.ZodOptional<z.ZodBoolean>;
99
113
  maxChars: z.ZodOptional<z.ZodNumber>;
100
114
  fields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
101
115
  type: z.ZodEnum<{
@@ -136,10 +150,12 @@ export declare const browserParameters: z.ZodObject<{
136
150
  handoff: "handoff";
137
151
  har_start: "har_start";
138
152
  har_stop: "har_stop";
153
+ hover: "hover";
139
154
  live_view: "live_view";
140
155
  open: "open";
141
156
  press: "press";
142
157
  reload: "reload";
158
+ result_read: "result_read";
143
159
  screenshot: "screenshot";
144
160
  scroll: "scroll";
145
161
  select: "select";
@@ -150,6 +166,8 @@ export declare const browserParameters: z.ZodObject<{
150
166
  tab_new: "tab_new";
151
167
  tab_select: "tab_select";
152
168
  tabs: "tabs";
169
+ upload: "upload";
170
+ viewport: "viewport";
153
171
  wait: "wait";
154
172
  }>;
155
173
  }, z.core.$strict>;
@@ -158,6 +176,14 @@ export declare const browserParameters: z.ZodObject<{
158
176
  * prompts and approval rules a batch needs: one call can navigate, act, and run page script.
159
177
  */
160
178
  export declare const browserBatchParameters: z.ZodObject<{
179
+ resultId: z.ZodOptional<z.ZodUUID>;
180
+ width: z.ZodOptional<z.ZodNumber>;
181
+ height: z.ZodOptional<z.ZodNumber>;
182
+ file: z.ZodOptional<z.ZodObject<{
183
+ name: z.ZodString;
184
+ mimeType: z.ZodString;
185
+ base64: z.ZodBase64;
186
+ }, z.core.$strict>>;
161
187
  httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
162
188
  backend: z.ZodOptional<z.ZodEnum<{
163
189
  browserbase: "browserbase";
@@ -188,6 +214,7 @@ export declare const browserBatchParameters: z.ZodObject<{
188
214
  domains: z.ZodOptional<z.ZodArray<z.ZodString>>;
189
215
  profile: z.ZodOptional<z.ZodString>;
190
216
  selector: z.ZodOptional<z.ZodString>;
217
+ force: z.ZodOptional<z.ZodBoolean>;
191
218
  target: z.ZodOptional<z.ZodString>;
192
219
  visual: z.ZodOptional<z.ZodBoolean>;
193
220
  value: z.ZodOptional<z.ZodString>;
@@ -211,6 +238,8 @@ export declare const browserBatchParameters: z.ZodObject<{
211
238
  }>>;
212
239
  script: z.ZodOptional<z.ZodString>;
213
240
  fullPage: z.ZodOptional<z.ZodBoolean>;
241
+ offset: z.ZodOptional<z.ZodNumber>;
242
+ interactive: z.ZodOptional<z.ZodBoolean>;
214
243
  maxChars: z.ZodOptional<z.ZodNumber>;
215
244
  fields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
216
245
  type: z.ZodEnum<{
@@ -252,10 +281,12 @@ export declare const browserBatchParameters: z.ZodObject<{
252
281
  handoff: "handoff";
253
282
  har_start: "har_start";
254
283
  har_stop: "har_stop";
284
+ hover: "hover";
255
285
  live_view: "live_view";
256
286
  open: "open";
257
287
  press: "press";
258
288
  reload: "reload";
289
+ result_read: "result_read";
259
290
  screenshot: "screenshot";
260
291
  scroll: "scroll";
261
292
  select: "select";
@@ -266,6 +297,8 @@ export declare const browserBatchParameters: z.ZodObject<{
266
297
  tab_new: "tab_new";
267
298
  tab_select: "tab_select";
268
299
  tabs: "tabs";
300
+ upload: "upload";
301
+ viewport: "viewport";
269
302
  wait: "wait";
270
303
  }>;
271
304
  steps: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -285,6 +318,7 @@ export declare const browserBatchParameters: z.ZodObject<{
285
318
  }>;
286
319
  url: z.ZodOptional<z.ZodURL>;
287
320
  selector: z.ZodOptional<z.ZodString>;
321
+ force: z.ZodOptional<z.ZodBoolean>;
288
322
  value: z.ZodOptional<z.ZodString>;
289
323
  values: z.ZodOptional<z.ZodArray<z.ZodString>>;
290
324
  key: z.ZodOptional<z.ZodString>;
@@ -306,6 +340,8 @@ export declare const browserBatchParameters: z.ZodObject<{
306
340
  }>>;
307
341
  script: z.ZodOptional<z.ZodString>;
308
342
  maxChars: z.ZodOptional<z.ZodNumber>;
343
+ offset: z.ZodOptional<z.ZodNumber>;
344
+ interactive: z.ZodOptional<z.ZodBoolean>;
309
345
  }, z.core.$strict>>>;
310
346
  }, z.core.$strict>;
311
347
  export declare const aiParameters: z.ZodObject<{