@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
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 => {
@@ -71,7 +77,8 @@ const browserFields = {
71
77
  browser: z.enum(BROWSER_IDS).optional().describe("For cookie_profiles and cookie_import: limit to this installed browser. Omit to consider every installed supported browser."),
72
78
  domains: z.array(z.string().min(1).max(255)).min(1).max(20).optional().describe("Required for cookie_import. Explicit bare domains, e.g. github.com, plus the identity provider the sign-in redirects to, e.g. microsoftonline.com; includes their subdomains. Never import unrelated domains."),
73
79
  profile: z.string().regex(/^(?:Default|Profile [0-9]+)$/).optional().describe("Browser profile folder for cookie_import, e.g. Profile 1. Omit to use the only profile with cookies for the domains; set it (with browser) when several match. Discover names with cookie_profiles."),
74
- selector: z.string().min(1).optional().describe("Snapshot reference such as @s1:0-24 (preferred), CSS, xpath=... or //..., or text=.... (xpath)[n] picks the nth match. `>>` enters an iframe; Playwright-only syntax (:has-text(), >> nth=) is unsupported. Required for click/fill/select unless target is used."),
80
+ selector: z.string().min(1).optional().describe("Snapshot reference (preferred: e12 or @e12 in the user's real browser; @s1:0-24 in launched/hosted browsers), CSS, xpath=... or //..., or text=.... (xpath)[n] picks the nth match. `>>` enters an iframe; Playwright-only syntax (:has-text(), >> nth=) is unsupported. Required for click/fill/select unless target is used."),
81
+ force: z.boolean().optional().describe("Only for click, hover, and fill: bypass pointer/actionability hit-testing when a benign page overlay blocks the element (used by the user's real browser)."),
75
82
  target: z.string().trim().min(1).max(500).optional().describe("JEV mode only (/browse jev on): plain-language element description for click/fill/select, used instead of selector."),
76
83
  visual: z.boolean().optional().describe("With target or ask: also send a viewport screenshot to the classifier, for elements and states that labels and page text do not convey (icon-only buttons, canvas, colors). ask uses it for bool and choice fields only. Needs an image-capable classifier; Jev on Vercel AI Gateway is text-only."),
77
84
  value: z.string().optional().describe("Text for fill; may be empty to clear the input."),
@@ -86,11 +93,13 @@ const browserFields = {
86
93
  state: z.enum(["attached", "detached", "visible", "hidden"]).optional().describe("Selector state for wait; default visible."),
87
94
  script: z.string().min(1).optional().describe("JavaScript expression evaluated in the browser page, required for evaluate. No local filesystem or process access."),
88
95
  fullPage: z.boolean().optional().describe("For screenshot; defaults to viewport only."),
96
+ 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."),
97
+ interactive: z.boolean().optional().describe("Only for snapshot: list controls instead of the full outline."),
89
98
  maxChars: z.number().int().min(1000).max(50_000).optional().describe("Snapshot text limit; default 20000."),
90
99
  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
100
  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."),
92
101
  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."),
93
- 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."),
102
+ timeoutMs: z.number().int().min(1).max(600_000).optional().describe("Operation deadline; default 30000 (fixed wait: durationMs + 5000; handoff: default 600000, maximum 600000; other actions: maximum 120000). Page waits and navigation time out up to 2s earlier. On the deadline the browser is kept if it still responds."),
94
103
  };
95
104
  /** Direct controls a batch step may run. Every other action, including a nested batch, stays a separate call. */
96
105
  const BATCH_ACTIONS = ["open", "back", "forward", "reload", "snapshot", "click", "fill", "select", "press", "scroll", "wait", "evaluate"];
@@ -98,7 +107,8 @@ const BATCH_ACTIONS = ["open", "back", "forward", "reload", "snapshot", "click",
98
107
  const batchStepFields = z.object({
99
108
  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.`),
100
109
  url: browserFields.url.describe("An http or https URL. Required for open."),
101
- 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."),
110
+ selector: browserFields.selector.describe("Snapshot reference (preferred: e12 or @e12 in the user's real browser; @s1:0-24 in launched/hosted browsers), CSS, xpath=... or //..., or text=.... Required for click, fill, and select; for wait, the element to wait for."),
111
+ force: browserFields.force,
102
112
  value: browserFields.value,
103
113
  values: browserFields.values,
104
114
  key: browserFields.key,
@@ -110,7 +120,7 @@ const batchStepFields = z.object({
110
120
  loadState: browserFields.loadState,
111
121
  state: browserFields.state,
112
122
  script: browserFields.script,
113
- maxChars: browserFields.maxChars,
123
+ maxChars: browserFields.maxChars, offset: browserFields.offset, interactive: browserFields.interactive,
114
124
  }, {
115
125
  error: issue => issue.code === "unrecognized_keys"
116
126
  ? `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,8 +128,8 @@ const batchStepFields = z.object({
118
128
  }).strict();
119
129
  /** The arguments each batch action reads. A step carrying any other would see it silently ignored, so it is rejected. */
120
130
  const STEP_ARGUMENTS = {
121
- open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true },
122
- click: { selector: true }, fill: { selector: true, value: true }, select: { selector: true, values: true },
131
+ open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true, offset: true, interactive: true },
132
+ click: { selector: true, force: true }, fill: { selector: true, value: true, force: true }, select: { selector: true, values: true },
123
133
  press: { key: true }, scroll: { deltaX: true, deltaY: true, x: true, y: true },
124
134
  wait: { durationMs: true, selector: true, loadState: true, state: true }, evaluate: { script: true },
125
135
  };
@@ -162,13 +172,21 @@ const singleCall = z.object({ action: z.enum(ACTIONS), ...browserFields }).stric
162
172
  /** The rules of every action but batch. */
163
173
  function checkCall(p, ctx) {
164
174
  const required = {
165
- ...DIRECT_REQUIRED, ask: ["fields"],
175
+ ...DIRECT_REQUIRED, ask: ["fields"], hover: ["selector"], upload: ["selector", "file"], viewport: ["width", "height"], result_read: ["resultId"],
166
176
  tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"], handoff: ["message"],
167
177
  };
168
178
  for (const field of required[p.action] ?? []) {
169
179
  if (p[field] === undefined)
170
180
  ctx.addIssue({ code: "custom", path: [field], message: `${field} is required for ${p.action}` });
171
181
  }
182
+ if (p.action !== "viewport" && (p.width !== undefined || p.height !== undefined))
183
+ ctx.addIssue({ code: "custom", message: "width and height are only supported for viewport" });
184
+ if (p.action !== "upload" && p.file !== undefined)
185
+ ctx.addIssue({ code: "custom", message: "file is only supported for upload" });
186
+ if ((p.offset !== undefined && p.action !== "result_read" || p.interactive !== undefined) && p.action !== "snapshot")
187
+ ctx.addIssue({ code: "custom", message: "offset is supported for snapshot and result_read; interactive only for snapshot" });
188
+ if (p.resultId !== undefined && p.action !== "result_read")
189
+ ctx.addIssue({ code: "custom", message: "resultId is only supported for result_read" });
172
190
  if (p.path !== undefined && p.action !== "har_stop")
173
191
  ctx.addIssue({ code: "custom", path: ["path"], message: "path is only supported for har_stop" });
174
192
  if (p.message !== undefined && p.action !== "handoff")
@@ -247,6 +265,12 @@ function checkCall(p, ctx) {
247
265
  if (p.browser !== undefined && p.action !== "cookie_import" && p.action !== "cookie_profiles") {
248
266
  ctx.addIssue({ code: "custom", path: ["browser"], message: "browser is only supported for cookie_profiles and cookie_import" });
249
267
  }
268
+ if (p.force !== undefined && p.action !== "click" && p.action !== "hover" && p.action !== "fill") {
269
+ ctx.addIssue({ code: "custom", path: ["force"], message: "force is only supported for click, hover, and fill" });
270
+ }
271
+ if (p.timeoutMs !== undefined && p.action !== "handoff" && p.timeoutMs > 120_000) {
272
+ ctx.addIssue({ code: "custom", path: ["timeoutMs"], message: "timeoutMs must be at most 120000 for this action (handoff allows up to 600000)" });
273
+ }
250
274
  checkDirectArguments(p, ctx);
251
275
  // Without timeoutMs the deadline already extends past durationMs.
252
276
  if (p.action === "wait" && p.durationMs !== undefined && p.timeoutMs !== undefined && p.durationMs >= p.timeoutMs) {
@@ -264,7 +288,7 @@ const BATCH_ARGUMENTS = { action: true, steps: true, tabId: true, timeoutMs: tru
264
288
  export const browserBatchParameters = z.object({
265
289
  action: z.enum([...ACTIONS, "batch"]),
266
290
  ...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."),
291
+ 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
292
  }).strict().superRefine((p, ctx) => {
269
293
  if (p.action !== "batch") {
270
294
  if (p.steps !== undefined)
@@ -275,6 +299,9 @@ export const browserBatchParameters = z.object({
275
299
  }
276
300
  if (p.steps === undefined)
277
301
  ctx.addIssue({ code: "custom", path: ["steps"], message: "steps is required for batch" });
302
+ if (p.timeoutMs !== undefined && p.timeoutMs > 120_000) {
303
+ ctx.addIssue({ code: "custom", path: ["timeoutMs"], message: "timeoutMs must be at most 120000 for batch" });
304
+ }
278
305
  for (const [field, value] of Object.entries(p)) {
279
306
  if (value !== undefined && !Object.hasOwn(BATCH_ARGUMENTS, field)) {
280
307
  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` });
@@ -292,7 +319,7 @@ export const aiParameters = z.object({
292
319
  instruction: z.string().trim().min(1).describe("One bounded task on the selected page. act may change the website."),
293
320
  tabId: z.string().min(1).optional(),
294
321
  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."),
322
+ 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
323
  }).strict().superRefine((p, ctx) => {
297
324
  if (p.schema && p.action !== "extract")
298
325
  ctx.addIssue({ code: "custom", path: ["schema"], message: "schema is only supported for extract" });
@@ -0,0 +1,42 @@
1
+ import type { Stagehand, StagehandBrowser } from "@browserbasehq/stagehand";
2
+ import type { GuardedEndpoint } from "./cdp-guard.ts";
3
+ import type { ClientGenerate } from "./session.ts";
4
+ export declare const stagehandSdk: () => Promise<typeof import("@browserbasehq/stagehand")>;
5
+ export declare function freePort(): Promise<number>;
6
+ /**
7
+ * Stagehand ends a launched Chrome with SIGTERM to its whole process group, which kills the network service before it
8
+ * writes cookies to disk. Browser.close shuts Chrome down in order; waiting for its process to exit means Stagehand's
9
+ * close then has nothing left to signal, so a persistent profile keeps its logins.
10
+ */
11
+ export declare function quitChrome(port: number): Promise<void>;
12
+ /** Reloading Stagehand's extension can replace its service worker between discovery and attachment; attaching again then succeeds. */
13
+ export declare function connectRetrying<T>(connect: () => Promise<T>, signal: AbortSignal): Promise<T>;
14
+ /**
15
+ * Stagehand on a browser another client may just have left. The in-browser runtime releases a lost or detached client's
16
+ * instance asynchronously, so a create that arrives first sees it still initialized and is retried.
17
+ */
18
+ export declare function createStagehand(browser: StagehandBrowser, model: {
19
+ model?: {
20
+ generate: ClientGenerate;
21
+ };
22
+ }, signal: AbortSignal): Promise<Stagehand>;
23
+ type RawCdpSend = (method: string, params?: Record<string, unknown>, sessionId?: string) => Promise<any>;
24
+ /** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
25
+ export declare function withRawCdp<T>(connectUrl: string, signal: AbortSignal, use: (send: RawCdpSend) => Promise<T>): Promise<T>;
26
+ /**
27
+ * Opens a window with a blank tab in a running browser that has no tab, and returns its id; else undefined. macOS
28
+ * Chrome keeps running after its last window closes, and in that state no client can create a tab, so Stagehand cannot
29
+ * attach. The tab belongs to whoever attaches, whose close removes it again.
30
+ */
31
+ export declare function ensurePageTarget(connectUrl: string, signal: AbortSignal): Promise<string | undefined>;
32
+ /**
33
+ * Lets go of a shared local browser. An attached one is disconnected, which closes Stagehand's instance in it and leaves
34
+ * the browser running for the next client; a launched profile's Chrome is quit so it writes its cookies.
35
+ */
36
+ export declare function release(shared: {
37
+ browser: StagehandBrowser;
38
+ stagehand?: Stagehand;
39
+ quitPort?: number;
40
+ guard?: GuardedEndpoint;
41
+ }): Promise<void>;
42
+ export {};
@@ -0,0 +1,144 @@
1
+ import { once } from "node:events";
2
+ import { createServer } from "node:net";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { z } from "zod";
5
+ import { abortable, deadline, messageOf } from "./errors.js";
6
+ export const stagehandSdk = () => import("@browserbasehq/stagehand");
7
+ export async function freePort() {
8
+ const server = createServer().listen(0, "127.0.0.1");
9
+ await once(server, "listening");
10
+ const { port } = server.address();
11
+ await new Promise(resolve => server.close(resolve));
12
+ return port;
13
+ }
14
+ /**
15
+ * Stagehand ends a launched Chrome with SIGTERM to its whole process group, which kills the network service before it
16
+ * writes cookies to disk. Browser.close shuts Chrome down in order; waiting for its process to exit means Stagehand's
17
+ * close then has nothing left to signal, so a persistent profile keeps its logins.
18
+ */
19
+ export async function quitChrome(port) {
20
+ const version = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
21
+ const socket = new WebSocket((await version.json()).webSocketDebuggerUrl);
22
+ let pid;
23
+ socket.addEventListener("message", event => {
24
+ const reply = JSON.parse(String(event.data));
25
+ if (reply.id === 1)
26
+ pid = reply.result?.processInfo?.find(entry => entry.type === "browser")?.id;
27
+ });
28
+ const closed = once(socket, "close");
29
+ socket.addEventListener("open", () => {
30
+ socket.send(JSON.stringify({ id: 1, method: "SystemInfo.getProcessInfo" }));
31
+ socket.send(JSON.stringify({ id: 2, method: "Browser.close" }));
32
+ }, { once: true });
33
+ await closed;
34
+ // The endpoint closes before Chrome finishes writing the profile.
35
+ for (let i = 0; pid && i < 200 && running(pid); i++)
36
+ await delay(20);
37
+ }
38
+ /** Reloading Stagehand's extension can replace its service worker between discovery and attachment; attaching again then succeeds. */
39
+ export async function connectRetrying(connect, signal) {
40
+ for (let attempt = 0;; attempt++) {
41
+ try {
42
+ return await connect();
43
+ }
44
+ catch (error) {
45
+ if (attempt >= 3 || !/No target with given id found/.test(messageOf(error)))
46
+ throw error;
47
+ await delay(100, undefined, { signal });
48
+ }
49
+ }
50
+ }
51
+ function running(pid) {
52
+ try {
53
+ process.kill(pid, 0);
54
+ return true;
55
+ }
56
+ catch (error) {
57
+ return error.code === "EPERM";
58
+ }
59
+ }
60
+ /**
61
+ * Stagehand on a browser another client may just have left. The in-browser runtime releases a lost or detached client's
62
+ * instance asynchronously, so a create that arrives first sees it still initialized and is retried.
63
+ */
64
+ export async function createStagehand(browser, model, signal) {
65
+ for (let attempt = 0;; attempt++) {
66
+ try {
67
+ return await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...model });
68
+ }
69
+ catch (error) {
70
+ if (attempt >= 4 || !/already initialized/i.test(messageOf(error)))
71
+ throw error;
72
+ await delay(250, undefined, { signal });
73
+ }
74
+ }
75
+ }
76
+ /** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
77
+ export async function withRawCdp(connectUrl, signal, use) {
78
+ const socket = new WebSocket(connectUrl);
79
+ const pending = new Map();
80
+ let nextId = 0;
81
+ const closed = new Promise((_, reject) => {
82
+ const fail = () => reject(new Error("CDP connection closed"));
83
+ socket.addEventListener("close", fail);
84
+ socket.addEventListener("error", fail);
85
+ });
86
+ closed.catch(() => undefined);
87
+ socket.addEventListener("message", event => {
88
+ const message = JSON.parse(String(event.data));
89
+ const entry = pending.get(message.id);
90
+ if (!entry)
91
+ return;
92
+ pending.delete(message.id);
93
+ if (message.error)
94
+ entry.reject(new Error(message.error.message));
95
+ else
96
+ entry.resolve(message.result);
97
+ });
98
+ const send = (method, params = {}, sessionId) => {
99
+ const id = ++nextId;
100
+ const reply = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
101
+ socket.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
102
+ return abortable(Promise.race([reply, closed]), signal);
103
+ };
104
+ try {
105
+ await abortable(Promise.race([new Promise(resolve => socket.addEventListener("open", resolve, { once: true })), closed]), signal);
106
+ return await use(send);
107
+ }
108
+ finally {
109
+ socket.close();
110
+ }
111
+ }
112
+ /**
113
+ * Opens a window with a blank tab in a running browser that has no tab, and returns its id; else undefined. macOS
114
+ * Chrome keeps running after its last window closes, and in that state no client can create a tab, so Stagehand cannot
115
+ * attach. The tab belongs to whoever attaches, whose close removes it again.
116
+ */
117
+ export async function ensurePageTarget(connectUrl, signal) {
118
+ return withRawCdp(connectUrl, signal, async (send) => {
119
+ const { targetInfos } = await send("Target.getTargets");
120
+ if (targetInfos.some(target => target.type === "page"))
121
+ return undefined;
122
+ const { targetId } = await send("Target.createTarget", { url: "about:blank", newWindow: true });
123
+ return z.string().parse(targetId);
124
+ });
125
+ }
126
+ /**
127
+ * Lets go of a shared local browser. An attached one is disconnected, which closes Stagehand's instance in it and leaves
128
+ * the browser running for the next client; a launched profile's Chrome is quit so it writes its cookies.
129
+ */
130
+ export async function release(shared) {
131
+ if (shared.guard) {
132
+ try {
133
+ await deadline(shared.browser.disconnect(), 5000);
134
+ }
135
+ finally {
136
+ await shared.guard.close();
137
+ }
138
+ return;
139
+ }
140
+ await deadline(shared.stagehand?.close() ?? Promise.resolve(), 1500).catch(() => undefined);
141
+ if (shared.quitPort)
142
+ await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
143
+ await deadline(shared.browser.close(), 5000);
144
+ }
package/dist/session.d.ts CHANGED
@@ -1,82 +1,10 @@
1
+ import { type BatchProgress } from "./errors.ts";
2
+ import { type ConfigResolver, type ConfigurationContext } from "./config.ts";
1
3
  import type { Stagehand } from "@browserbasehq/stagehand";
4
+ import { z } from "zod";
2
5
  import type { AIParams, BrowserParams } from "./schema.ts";
3
- import { type HttpAuth } from "./http-auth.ts";
4
6
  import { type CookieProvider } from "./browser-cookies.ts";
5
7
  import { type HostClassify } from "./classifier.ts";
6
- export interface BrowseConfig {
7
- /** One exact origin and its credentials, resolved for an explicit isolated HTTP-auth start. */
8
- httpAuth?: HttpAuth;
9
- /** Allow this profile to read the initial URL's exact origin from the locally installed native helper. */
10
- httpAuthStore?: {
11
- hosted?: boolean;
12
- origin?: string;
13
- };
14
- apiKey?: string;
15
- projectId?: string;
16
- model?: string;
17
- modelApiKey?: string;
18
- /** Vercel AI Gateway key for JEV's default classifier; resolvers should load it only for purpose "jev". */
19
- jevApiKey?: string;
20
- /**
21
- * Classifier for JEV targeting: absent or `vercel` (Jev on Vercel AI Gateway), `workers-ai` (Jev 1.14 on Workers AI)
22
- * or `workers-ai/<model>`, or a host classifier as `<provider>/<id>`.
23
- */
24
- jevModel?: string;
25
- /** Classifier for ask's bool and choice fields: absent is Clef on Workers AI; takes the same values as jevModel. */
26
- askModel?: string;
27
- /**
28
- * Cloudflare account and Workers AI token for ask, and for JEV on Workers AI; resolvers should load the token only for
29
- * purposes "ask" and "jev".
30
- */
31
- cloudflareAccountId?: string;
32
- cloudflareApiKey?: string;
33
- /** Optional profile-specific file containing only saved-context identifiers. */
34
- contextHistoryPath?: string;
35
- /** Browserbase region for new sessions; validated against the SDK's regions. Absent uses Browserbase's default (us-west-2). */
36
- region?: string;
37
- /**
38
- * Chrome user data directory for local launches, so logins and installed extensions persist across launches. Absent
39
- * launches a temporary profile that close deletes. Only one browser can use the directory at a time.
40
- */
41
- localUserDataDir?: string;
42
- /** Chrome or Chromium executable for local launches; absent uses CHROME_PATH or Stagehand's discovery of an installed Chrome. */
43
- localExecutablePath?: string;
44
- /**
45
- * Bare domains, each with its subdomains, that this profile's browsers may reach; every other http(s) request fails,
46
- * page resources included. A start can narrow the list, never widen it.
47
- */
48
- allowedDomains?: string[];
49
- /** Bare domains, each with its subdomains, that this profile's browsers never reach; a start can add more. */
50
- blockedDomains?: string[];
51
- /** Browserbase navigation policy for hosted sessions (browserSettings.riskPolicyId); the project must enforce policies. */
52
- navigationPolicyId?: string;
53
- /**
54
- * Browsers start can attach to by name (endpoint): a DevTools URL, headers for an authenticated gateway (secrets that
55
- * never reach results), and the URL Stagehand's in-browser extension uses when the browser runs on another machine.
56
- */
57
- remoteBrowsers?: Record<string, RemoteBrowser>;
58
- /**
59
- * The user's own browser, through OpenCode Browse: `command` is the argv that runs `browse mcp`, on this machine or
60
- * over SSH on the machine with the browser. When set, a local start that names no cdpUrl, endpoint, or headless works
61
- * in that browser instead of launching one.
62
- */
63
- realBrowser?: {
64
- command: string[];
65
- };
66
- }
67
- /** A browser to attach to. extensionCdpUrl is the browser-level DevTools URL the browser itself reaches without headers. */
68
- export interface RemoteBrowser {
69
- cdpUrl: string;
70
- headers?: Record<string, string>;
71
- extensionCdpUrl?: string;
72
- }
73
- /** A browser's domain fence as bare domains, each covering its subdomains. */
74
- export interface DomainLists {
75
- allowedDomains?: string[];
76
- blockedDomains?: string[];
77
- }
78
- /** The profile's domain lists, narrowed by start: start's allowed domains must fall inside the profile's, and blocked ones add up. */
79
- export declare function domainLists(config: BrowseConfig, start: Pick<BrowserParams, "allowedDomains" | "blockedDomains">): DomainLists | undefined;
80
8
  type StagehandModel = NonNullable<NonNullable<Parameters<typeof Stagehand.create>[0]>["model"]>;
81
9
  /** Stagehand's bring-your-own-LLM callback: default inference for act/observe/extract when no model is configured. */
82
10
  export type ClientGenerate = Extract<StagehandModel, {
@@ -84,8 +12,9 @@ export type ClientGenerate = Extract<StagehandModel, {
84
12
  }>["generate"];
85
13
  /** Stagehand's default inference when no Stagehand model is configured. */
86
14
  export interface ClientInference {
87
- generate: ClientGenerate;
88
- /** Names the model `generate` runs now, for status. */
15
+ /** Default for AI runs. Hosts that supply a provider for each run can omit this method. */
16
+ generate?(params: Parameters<ClientGenerate>[0], signal: AbortSignal): ReturnType<ClientGenerate>;
17
+ /** Names the host model for status. */
89
18
  describe: () => Promise<string>;
90
19
  }
91
20
  /** The host running the core: `name` appears in messages, `integration` in Browserbase metadata, HAR files, and temp paths. */
@@ -108,44 +37,6 @@ export interface AnsweredDialog {
108
37
  message: string;
109
38
  answer: "ok" | "cancel";
110
39
  }
111
- export interface ConfigurationContext {
112
- /** Resolve origin credentials for an explicitly requested isolated launch. */
113
- httpAuth?: true;
114
- sessionId: string;
115
- profile: string;
116
- cwd: string;
117
- signal: AbortSignal;
118
- purpose: "browser" | "ai" | "jev" | "ask";
119
- /** Selected browser backend; local controls do not need Browserbase credentials. */
120
- backend?: "browserbase" | "local";
121
- /**
122
- * For purposes "jev" and "ask", the classifier chosen with /browse jev-model or ask-model. It replaces the returned jevModel or askModel,
123
- * so load the credentials it needs.
124
- */
125
- classifier?: string;
126
- }
127
- export type ConfigResolver = (context: ConfigurationContext) => BrowseConfig | Promise<BrowseConfig>;
128
- export declare function environmentConfig(scope?: Pick<ConfigurationContext, "httpAuth">): BrowseConfig;
129
- /** How far a batch got. */
130
- export interface BatchProgress {
131
- total: number;
132
- /** Steps confirmed to have completed; absent when a lost reply, deadline, or cancellation leaves that unknown. */
133
- completed?: number;
134
- /** Zero-based index of the step that stopped the batch. */
135
- failedIndex?: number;
136
- /** True when steps may have run without being confirmed: inspect the page before repeating anything. */
137
- outcomeUnknown: boolean;
138
- error?: {
139
- code: string;
140
- message: string;
141
- };
142
- }
143
- export declare class BrowseToolError extends Error {
144
- readonly code: string;
145
- readonly batch?: BatchProgress | undefined;
146
- /** `batch` is set on a failed batch call. */
147
- constructor(code: string, message: string, batch?: BatchProgress | undefined);
148
- }
149
40
  export interface BrowserOutput {
150
41
  action: string;
151
42
  sessionId: string | null;
@@ -187,6 +78,7 @@ export declare class BrowseSession {
187
78
  private snapshotNumber;
188
79
  private generation;
189
80
  private readonly contextReadyAt;
81
+ private readonly results;
190
82
  private readonly secrets;
191
83
  /** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
192
84
  private keepAliveAllowed;
@@ -200,21 +92,37 @@ export declare class BrowseSession {
200
92
  private readonly extensions;
201
93
  /** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
202
94
  private readonly stagehandModel;
95
+ private readonly aiOwner;
203
96
  private readonly describeInference;
97
+ private readonly defaultGenerate;
204
98
  /** Backend for a start, open, tab_new, or cookie_import that names none while no browser is open: the profile's /browse backend setting, else the loader's default, else local. */
205
99
  defaultBackend: "browserbase" | "local";
206
100
  constructor(resolveConfig?: ConfigResolver, inference?: ClientInference, hostClassify?: HostClassify | undefined, identity?: HostIdentity, options?: BrowseSessionOptions);
101
+ /** Host-facing output. Keep raw run() available for SDK consumers and the broker. */
102
+ encodeResult(output: BrowserOutput, scope: Pick<ConfigurationContext, "profile" | "sessionId">): {
103
+ json: string;
104
+ metadata: Record<string, z.JSONType>;
105
+ image: Uint8Array<ArrayBufferLike> | undefined;
106
+ isError: boolean;
107
+ };
108
+ encodeError(cause: unknown): {
109
+ json: string;
110
+ metadata: Record<string, z.JSONType>;
111
+ isError: true;
112
+ image: undefined;
113
+ };
207
114
  redact(text: string): string;
208
115
  /**
209
116
  * Queues one operation behind this conversation's earlier ones. `ai` marks a browse_ai call; as a function it runs
210
117
  * once the call reaches the front of the queue, so per-call state such as the inference model belongs to the running call.
211
118
  */
212
- run(params: BrowserParams | AIParams, context: Omit<ConfigurationContext, "signal" | "purpose">, signal?: AbortSignal, ai?: boolean | (() => void)): Promise<BrowserOutput>;
119
+ run(params: BrowserParams | AIParams, context: Omit<ConfigurationContext, "signal" | "purpose">, signal?: AbortSignal, ai?: boolean | ((signal: AbortSignal) => ClientGenerate | void)): Promise<BrowserOutput>;
213
120
  shutdown(): Promise<void>;
214
121
  /** Which credentials resolve for this profile. Starts no browser and leaves the session alone. */
215
122
  readiness(context: Omit<ConfigurationContext, "signal" | "purpose">, signal: AbortSignal): Promise<{
216
123
  credentials: boolean;
217
124
  region: string;
125
+ regionValid: boolean;
218
126
  aiModel: string | undefined;
219
127
  jevModel: string;
220
128
  jevKey: boolean;
@@ -319,6 +227,8 @@ export declare class BrowseSession {
319
227
  private prepare;
320
228
  /** Applies a completed action to the conversation's state (selected tab, snapshot refs) and returns what its result reports. */
321
229
  private finish;
230
+ /** Stagehand 4.4 keyPress loses printable Shift key metadata. Send this chord through the selected tab's DevTools target. */
231
+ private shiftedKey;
322
232
  private direct;
323
233
  /**
324
234
  * batch: the steps run in order beside the browser in one request, under one deadline. The first failure stops the
@@ -342,8 +252,7 @@ export declare class BrowseSession {
342
252
  */
343
253
  private ask;
344
254
  /**
345
- * JEV mode: a classifier (Jev unless jevModel names another) picks the element for a plain-language target from a
346
- * fresh snapshot; no xpath means it declined to act.
255
+ * JEV mode: a classifier (Jev unless jevModel names another) picks a versioned snapshot ref. The worker must still verify it after inference.
347
256
  */
348
257
  private locate;
349
258
  /** Jev's pick among the candidates; a failed request says whether retrying can help. */