@edlsh/browse-core 0.4.1 → 0.6.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.
package/dist/schema.js CHANGED
@@ -40,13 +40,14 @@ const askField = z.object({
40
40
  if (field.unit !== undefined && field.type !== "duration")
41
41
  ctx.addIssue({ code: "custom", path: ["unit"], message: "unit is only supported for duration" });
42
42
  });
43
- export const browserParameters = z.object({
44
- action: z.enum([
45
- "start", "status", "close", "open", "back", "forward", "reload", "snapshot", "ask",
46
- "click", "fill", "select", "press", "scroll", "wait", "screenshot", "evaluate",
47
- "tabs", "tab_new", "tab_select", "tab_close", "live_view", "context_create", "cookie_profiles", "cookie_import",
48
- "har_start", "har_stop",
49
- ]),
43
+ const ACTIONS = [
44
+ "start", "status", "close", "open", "back", "forward", "reload", "snapshot", "ask",
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",
47
+ "har_start", "har_stop", "handoff",
48
+ ];
49
+ /** Every action's arguments. A batch step reuses the direct controls' definitions from here instead of redefining them. */
50
+ const browserFields = {
50
51
  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."),
51
52
  cdpUrl: z.url({ protocol: /^(?:https?|wss?)$/ }).refine(value => {
52
53
  if (!URL.canParse(value))
@@ -86,13 +87,82 @@ export const browserParameters = z.object({
86
87
  fullPage: z.boolean().optional().describe("For screenshot; defaults to viewport only."),
87
88
  maxChars: z.number().int().min(1000).max(50_000).optional().describe("Snapshot text limit; default 20000."),
88
89
  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
+ 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."),
89
91
  path: z.string().regex(/^\/.*\.har$/, "path must be an absolute path ending in .har").optional().describe("Only for har_stop: absolute file path for the HAR, e.g. /abs/scratch/capture.har. Default: a new file in the system temp directory."),
90
92
  timeoutMs: z.number().int().min(1).max(120_000).optional().describe("Operation deadline; default 30000 (a fixed wait gets durationMs + 5000). Page waits and navigation time out up to 2s earlier. On the deadline the browser is kept if it still responds."),
91
- }).strict().superRefine((p, ctx) => {
93
+ };
94
+ /** Direct controls a batch step may run. Every other action, including a nested batch, stays a separate call. */
95
+ const BATCH_ACTIONS = ["open", "back", "forward", "reload", "snapshot", "click", "fill", "select", "press", "scroll", "wait", "evaluate"];
96
+ /** A step has no arguments of its own: every field is the direct control's definition above, so it validates the same way. */
97
+ const batchStepFields = z.object({
98
+ action: z.enum(BATCH_ACTIONS, `A batch step must be one of ${BATCH_ACTIONS.join(", ")}; every other action, including a nested batch, is a separate call.`),
99
+ url: browserFields.url.describe("An http or https URL. Required for open."),
100
+ selector: browserFields.selector.describe("Snapshot reference such as @s1:0-24 (preferred), CSS, xpath=... or //..., or text=.... Required for click, fill, and select; for wait, the element to wait for."),
101
+ value: browserFields.value,
102
+ values: browserFields.values,
103
+ key: browserFields.key,
104
+ deltaX: browserFields.deltaX,
105
+ deltaY: browserFields.deltaY,
106
+ x: browserFields.x,
107
+ y: browserFields.y,
108
+ durationMs: browserFields.durationMs,
109
+ loadState: browserFields.loadState,
110
+ state: browserFields.state,
111
+ script: browserFields.script,
112
+ maxChars: browserFields.maxChars,
113
+ }, {
114
+ error: issue => issue.code === "unrecognized_keys"
115
+ ? `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.`
116
+ : undefined,
117
+ }).strict();
118
+ /** The arguments each batch action reads. A step carrying any other would see it silently ignored, so it is rejected. */
119
+ const STEP_ARGUMENTS = {
120
+ open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true },
121
+ click: { selector: true }, fill: { selector: true, value: true }, select: { selector: true, values: true },
122
+ press: { key: true }, scroll: { deltaX: true, deltaY: true, x: true, y: true },
123
+ wait: { durationMs: true, selector: true, loadState: true, state: true }, evaluate: { script: true },
124
+ };
125
+ /** Arguments a direct control cannot run without, for ordinary calls and batch steps alike. */
126
+ const DIRECT_REQUIRED = {
127
+ open: ["url"], fill: ["value"], select: ["values"], press: ["key"], evaluate: ["script"],
128
+ };
129
+ /** Rules a direct control follows whether it runs on its own or as a batch step. */
130
+ function checkDirectArguments(p, ctx) {
131
+ if (p.action === "wait" && [p.durationMs, p.selector, p.loadState].filter(v => v !== undefined).length !== 1) {
132
+ ctx.addIssue({ code: "custom", message: "wait requires exactly one of durationMs, selector, or loadState" });
133
+ }
134
+ if (p.action === "scroll" && p.deltaX === undefined && p.deltaY === undefined) {
135
+ ctx.addIssue({ code: "custom", message: "scroll requires deltaX or deltaY" });
136
+ }
137
+ if (p.key !== undefined && !keyTokens(p.key).every(token => [...token].length === 1 || KEY_NAMES.has(token.toLowerCase()))) {
138
+ ctx.addIssue({ code: "custom", path: ["key"], message: `Unsupported key "${p.key}". Use one character or one of: ${KEY_LIST}, optionally joined with modifiers (Control, Shift, Alt, Meta), e.g. Control+A.` });
139
+ }
140
+ }
141
+ const batchStep = batchStepFields.superRefine((step, ctx) => {
142
+ const takes = STEP_ARGUMENTS[step.action];
143
+ for (const [field, value] of Object.entries(step)) {
144
+ if (field !== "action" && value !== undefined && !Object.hasOwn(takes, field)) {
145
+ ctx.addIssue({ code: "custom", path: [field], message: `${step.action} does not take ${field}; it takes ${Object.keys(takes).join(", ") || "no arguments"}` });
146
+ }
147
+ }
148
+ for (const field of DIRECT_REQUIRED[step.action] ?? []) {
149
+ if (step[field] === undefined)
150
+ ctx.addIssue({ code: "custom", path: [field], message: `${field} is required for ${step.action}` });
151
+ }
152
+ if ((step.action === "click" || step.action === "fill" || step.action === "select") && step.selector === undefined) {
153
+ ctx.addIssue({ code: "custom", path: ["selector"], message: `selector is required for ${step.action}` });
154
+ }
155
+ if (step.action === "wait" && step.state !== undefined && step.selector === undefined) {
156
+ ctx.addIssue({ code: "custom", path: ["state"], message: "state only applies to a wait on a selector" });
157
+ }
158
+ checkDirectArguments(step, ctx);
159
+ });
160
+ const singleCall = z.object({ action: z.enum(ACTIONS), ...browserFields }).strict();
161
+ /** The rules of every action but batch. */
162
+ function checkCall(p, ctx) {
92
163
  const required = {
93
- open: ["url"], fill: ["value"], ask: ["fields"],
94
- select: ["values"], press: ["key"], evaluate: ["script"],
95
- tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"],
164
+ ...DIRECT_REQUIRED, ask: ["fields"],
165
+ tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"], handoff: ["message"],
96
166
  };
97
167
  for (const field of required[p.action] ?? []) {
98
168
  if (p[field] === undefined)
@@ -100,6 +170,8 @@ export const browserParameters = z.object({
100
170
  }
101
171
  if (p.path !== undefined && p.action !== "har_stop")
102
172
  ctx.addIssue({ code: "custom", path: ["path"], message: "path is only supported for har_stop" });
173
+ if (p.message !== undefined && p.action !== "handoff")
174
+ ctx.addIssue({ code: "custom", path: ["message"], message: "message is only supported for handoff" });
103
175
  if (p.fields && (p.action !== "ask" || Object.keys(p.fields).length < 1 || Object.keys(p.fields).length > 20)) {
104
176
  ctx.addIssue({ code: "custom", path: ["fields"], message: "fields is only supported for ask, with 1 to 20 entries" });
105
177
  }
@@ -168,18 +240,44 @@ export const browserParameters = z.object({
168
240
  if (p.browser !== undefined && p.action !== "cookie_import" && p.action !== "cookie_profiles") {
169
241
  ctx.addIssue({ code: "custom", path: ["browser"], message: "browser is only supported for cookie_profiles and cookie_import" });
170
242
  }
171
- if (p.action === "wait" && [p.durationMs, p.selector, p.loadState].filter(v => v !== undefined).length !== 1) {
172
- ctx.addIssue({ code: "custom", message: "wait requires exactly one of durationMs, selector, or loadState" });
173
- }
243
+ checkDirectArguments(p, ctx);
174
244
  // Without timeoutMs the deadline already extends past durationMs.
175
245
  if (p.action === "wait" && p.durationMs !== undefined && p.timeoutMs !== undefined && p.durationMs >= p.timeoutMs) {
176
246
  ctx.addIssue({ code: "custom", message: "durationMs must be shorter than timeoutMs; omit timeoutMs to let it follow durationMs" });
177
247
  }
178
- if (p.action === "scroll" && p.deltaX === undefined && p.deltaY === undefined) {
179
- ctx.addIssue({ code: "custom", message: "scroll requires deltaX or deltaY" });
248
+ }
249
+ /** The browse tool's parameters without batch: what a host that has not adopted batch registers. */
250
+ export const browserParameters = singleCall.superRefine(checkCall);
251
+ /** The only arguments a batch itself takes; everything else belongs inside a step. */
252
+ const BATCH_ARGUMENTS = { action: true, steps: true, tabId: true, timeoutMs: true };
253
+ /**
254
+ * The browse tool's parameters with the batch action. A host opts in by registering this schema, since it owns the
255
+ * prompts and approval rules a batch needs: one call can navigate, act, and run page script.
256
+ */
257
+ export const browserBatchParameters = z.object({
258
+ action: z.enum([...ACTIONS, "batch"]),
259
+ ...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."),
261
+ }).strict().superRefine((p, ctx) => {
262
+ if (p.action !== "batch") {
263
+ if (p.steps !== undefined)
264
+ ctx.addIssue({ code: "custom", path: ["steps"], message: "steps is only supported for batch" });
265
+ // SAFETY: with batch excluded, what is left is exactly a single call's shape.
266
+ checkCall(p, ctx);
267
+ return;
180
268
  }
181
- if (p.key !== undefined && !keyTokens(p.key).every(token => [...token].length === 1 || KEY_NAMES.has(token.toLowerCase()))) {
182
- ctx.addIssue({ code: "custom", path: ["key"], message: `Unsupported key "${p.key}". Use one character or one of: ${KEY_LIST}, optionally joined with modifiers (Control, Shift, Alt, Meta), e.g. Control+A.` });
269
+ if (p.steps === undefined)
270
+ ctx.addIssue({ code: "custom", path: ["steps"], message: "steps is required for batch" });
271
+ for (const [field, value] of Object.entries(p)) {
272
+ if (value !== undefined && !Object.hasOwn(BATCH_ARGUMENTS, field)) {
273
+ ctx.addIssue({ code: "custom", path: [field], message: `${field} is not supported for batch, which takes only steps, tabId, and timeoutMs; put step arguments inside steps` });
274
+ }
275
+ }
276
+ // One deadline covers every step, so fixed waits must leave time for the rest; a lone fixed wait extends its own default instead.
277
+ const fixedWaitMs = (p.steps ?? []).reduce((total, step) => total + (step.action === "wait" ? step.durationMs ?? 0 : 0), 0);
278
+ const deadlineMs = p.timeoutMs ?? 30_000;
279
+ if (fixedWaitMs >= deadlineMs) {
280
+ ctx.addIssue({ code: "custom", path: ["steps"], message: `Fixed waits total ${fixedWaitMs} ms but the batch deadline is ${deadlineMs} ms; keep them shorter, or raise timeoutMs (maximum 120000)` });
183
281
  }
184
282
  });
185
283
  export const aiParameters = z.object({
package/dist/session.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Stagehand } from "@browserbasehq/stagehand";
1
+ import type { Stagehand } from "@browserbasehq/stagehand";
2
2
  import type { AIParams, BrowserParams } from "./schema.ts";
3
3
  import { type CookieProvider } from "./browser-cookies.ts";
4
4
  import { type HostClassify } from "./classifier.ts";
@@ -47,6 +47,14 @@ export interface BrowseConfig {
47
47
  * never reach results), and the URL Stagehand's in-browser extension uses when the browser runs on another machine.
48
48
  */
49
49
  remoteBrowsers?: Record<string, RemoteBrowser>;
50
+ /**
51
+ * The user's own browser, through OpenCode Browse: `command` is the argv that runs `browse mcp`, on this machine or
52
+ * over SSH on the machine with the browser. When set, a local start that names no cdpUrl, endpoint, or headless works
53
+ * in that browser instead of launching one.
54
+ */
55
+ realBrowser?: {
56
+ command: string[];
57
+ };
50
58
  }
51
59
  /** A browser to attach to. extensionCdpUrl is the browser-level DevTools URL the browser itself reaches without headers. */
52
60
  export interface RemoteBrowser {
@@ -108,9 +116,25 @@ export interface ConfigurationContext {
108
116
  }
109
117
  export type ConfigResolver = (context: ConfigurationContext) => BrowseConfig | Promise<BrowseConfig>;
110
118
  export declare function environmentConfig(): BrowseConfig;
119
+ /** How far a batch got. */
120
+ export interface BatchProgress {
121
+ total: number;
122
+ /** Steps confirmed to have completed; absent when a lost reply, deadline, or cancellation leaves that unknown. */
123
+ completed?: number;
124
+ /** Zero-based index of the step that stopped the batch. */
125
+ failedIndex?: number;
126
+ /** True when steps may have run without being confirmed: inspect the page before repeating anything. */
127
+ outcomeUnknown: boolean;
128
+ error?: {
129
+ code: string;
130
+ message: string;
131
+ };
132
+ }
111
133
  export declare class BrowseToolError extends Error {
112
134
  readonly code: string;
113
- constructor(code: string, message: string);
135
+ readonly batch?: BatchProgress | undefined;
136
+ /** `batch` is set on a failed batch call. */
137
+ constructor(code: string, message: string, batch?: BatchProgress | undefined);
114
138
  }
115
139
  export interface BrowserOutput {
116
140
  action: string;
@@ -136,6 +160,8 @@ export interface BrowserOutput {
136
160
  note?: string;
137
161
  /** False when the tab stopped answering right after the action, so its title is unknown. */
138
162
  responsive?: false;
163
+ /** A batch's progress; `data.results` holds one result per completed step. */
164
+ batch?: BatchProgress;
139
165
  }
140
166
  export declare class BrowseSession {
141
167
  private readonly resolveConfig;
@@ -144,6 +170,10 @@ export declare class BrowseSession {
144
170
  private session?;
145
171
  private queue;
146
172
  private active?;
173
+ /** Asks the running batch to stop before its next step. */
174
+ private stopBatch?;
175
+ /** Whether the running batch may have reached the browser, so its steps may have run. */
176
+ private batchSent;
147
177
  private snapshotNumber;
148
178
  private generation;
149
179
  private readonly contextReadyAt;
@@ -154,8 +184,10 @@ export declare class BrowseSession {
154
184
  private readonly cookies;
155
185
  /** This conversation's calls run in the broker that owns its shared browser, until close. */
156
186
  private delegate?;
157
- /** Stagehand's runtime extension, uploaded once per tool instance instead of on every launch. */
158
- private extension?;
187
+ /** This conversation's tabs in the user's real browser, until close. */
188
+ private real?;
189
+ /** Stagehand's runtime extension per Browserbase project, uploaded once and reused across conversations and processes. */
190
+ private readonly extensions;
159
191
  /** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
160
192
  private readonly stagehandModel;
161
193
  private readonly describeInference;
@@ -185,6 +217,21 @@ export declare class BrowseSession {
185
217
  private dispatch;
186
218
  /** The shared browser a call would open, as the broker keys it: an attached browser or a persistent profile; else none. */
187
219
  private sharedKey;
220
+ /** The real-browser session a call would open: a local start that asks for no browser of its own, in a profile that configures one. */
221
+ private realBrowser;
222
+ private inRealBrowser;
223
+ /**
224
+ * ask and JEV in the real browser. They read OpenCode Browse's outline and the page's visible text where a
225
+ * Stagehand browser reads its snapshot tree; the classifiers and their settings are the same.
226
+ */
227
+ private classifyInRealBrowser;
228
+ /**
229
+ * browse_ai in the real browser: act, observe, and extract on the page's outline and text, with the host's own
230
+ * inference. act performs the one action the model chose; a page that offers none is a failed act, not an error.
231
+ */
232
+ private aiInRealBrowser;
233
+ /** Closes this conversation's tabs in the real browser; the browser itself is the user's and stays. */
234
+ private closeReal;
188
235
  /** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
189
236
  private forward;
190
237
  private dropDelegate;
@@ -214,9 +261,11 @@ export declare class BrowseSession {
214
261
  private classifier;
215
262
  /** Refuses visual before any screenshot when the classifier is known to read text only. */
216
263
  private visualAllowed;
217
- /** The viewport as JPEG for a classifier: smaller than PNG, and every image-capable classifier takes it. */
218
- private viewport;
219
264
  private client;
265
+ /**
266
+ * The project's uploaded Stagehand extension: the one the cache file remembers, else a new upload. `fresh` uploads
267
+ * again after the project turned out to have lost the remembered one.
268
+ */
220
269
  private extensionId;
221
270
  private current;
222
271
  private start;
@@ -242,14 +291,31 @@ export declare class BrowseSession {
242
291
  private harStart;
243
292
  private closeOwned;
244
293
  private page;
294
+ /**
295
+ * The tab a call acts on, named by its ID without asking the browser for its tabs: the batch executor finds the live tab
296
+ * itself and reports a closed one. Only a call with no selected tab lists them. In a shared browser, acting on a tab
297
+ * claims it before the request, so no other conversation can take it meanwhile.
298
+ */
299
+ private tab;
300
+ private tabMissing;
245
301
  /**
246
302
  * Runs one operation beside the browser in a single round trip. Stagehand cannot cancel a running batch: on a deadline
247
303
  * or cancellation the browser-side batch stops at its own timeout, and run() checks whether the browser still answers.
248
304
  */
249
305
  private batch;
306
+ /** One direct action as the worker runs it: the domain fence and snapshot refs are settled here, and the worker checks each ref again live. */
307
+ private prepare;
308
+ /** Applies a completed action to the conversation's state (selected tab, snapshot refs) and returns what its result reports. */
309
+ private finish;
250
310
  private direct;
311
+ /**
312
+ * batch: the steps run in order beside the browser in one request, under one deadline. The first failure stops the
313
+ * rest and nothing is rolled back; the result says how many steps completed.
314
+ */
315
+ private sequence;
251
316
  private reference;
252
- private target;
317
+ /** A tab's URL, title, answered dialogs, and document identity, in one bounded request: the action already ran, so a tab that blocks now is reported unresponsive rather than failing. */
318
+ private view;
253
319
  private output;
254
320
  /** A cookie provider call, with its refusals as tool errors. */
255
321
  private fromCookies;
@@ -268,6 +334,12 @@ export declare class BrowseSession {
268
334
  * fresh snapshot; no xpath means it declined to act.
269
335
  */
270
336
  private locate;
337
+ /** Jev's pick among the candidates; a failed request says whether retrying can help. */
338
+ private pick;
339
+ /** What a call reports when Jev declined to act: its best candidates, each with a selector the caller can use as is. */
340
+ private declined;
341
+ /** ask's models for a profile: Workers AI for the values Clairic reads, and the decision classifier for bool and choice. */
342
+ private askModels;
271
343
  private ai;
272
344
  }
273
345
  export {};