@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/README.md CHANGED
@@ -17,6 +17,8 @@ const output = await browser.run(browserParameters.parse({ action: "start", back
17
17
  - `nameChromeProfile(userDataDir, name)` sets that name on a profile the host launches itself; it leaves a profile Chrome holds untouched.
18
18
  - A persistent profile's cached extension service workers are dropped before a launch whenever the bundled Stagehand extension changed, because Chrome otherwise keeps running the worker of the SDK that first launched the profile. Logins and extension data are kept.
19
19
  - `BrowseSessionOptions.cookies` takes a `CookieProvider` (`list`, `find`, `read`) that `cookie_profiles` and `cookie_import` read through; the default, `localCookieProvider`, reads this Mac's installed browsers. A host whose user's browsers are on another machine supplies its own (hermes-browse reads the MacBook's Helium through a cookie service). Imports with a custom provider go into Browserbase or private launches only, since shared browsers run in a broker that reads its own machine's browsers.
20
+ - A hosted start uploads the Stagehand extension to the Browserbase project once and remembers its ID in `$XDG_CACHE_HOME/browse-core/browserbase-extensions.json` (`~/.cache` without `XDG_CACHE_HOME`), keyed by a hash of the API key and project; later conversations and processes reuse it, and an SDK upgrade replaces it. The extension stays in the project. A remembered extension the project no longer has is uploaded again.
21
+ - `browserBatchParameters` is `browserParameters` plus the `batch` action: 1 to 20 known steps (`open`, `back`, `forward`, `reload`, `snapshot`, `click`, `fill`, `select`, `press`, `scroll`, `wait`, `evaluate`) run in order on one tab, in one request, under one deadline. The first failure stops the rest; the result's `batch` reports `total`, `completed`, `failedIndex`, and `outcomeUnknown`, and a failed call's `BrowseToolError` carries the same. A batch whose first step is `open` starts a browser when none is running. A host opts in by registering this schema, because it owns the prompts and approval rules one call that navigates, acts, and runs page script needs; `browserParameters` stays without batch.
20
22
  - `ClientInference` supplies Stagehand's default inference. Without it, unconfigured AI calls use Browserbase Model Gateway.
21
23
  - `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
22
24
 
@@ -30,6 +32,20 @@ A persistent profile (`localUserDataDir`) and an attached browser (`cdpUrl` or a
30
32
 
31
33
  Conversations sharing a browser must agree on its launch options: a `start` asking for a different `headless` mode, or different allowed or blocked domains, gets `shared_browser`. Temporary-profile launches stay private to their conversation. `BrowseSessionOptions.profileBroker: false` keeps shared browsers in-process (the broker uses this for itself).
32
34
 
35
+ ## The user's real browser
36
+
37
+ A profile whose config sets `realBrowser.command` works in the user's own browser through [OpenCode Browse](https://opencode.ai/product/browse) instead of launching one: a local `start` that names no `cdpUrl`, `endpoint`, or `headless` goes there. `command` is the argv that runs OpenCode Browse's MCP server, `["/path/to/browse", "mcp"]` on the machine with the browser or the same behind `ssh` from another one. The browser needs OpenCode Browse's extension, paired once.
38
+
39
+ Each conversation's tabs open in the background in a tab group of its own, and `close` closes that group; the browser and the person's tabs stay. `snapshot` returns OpenCode Browse's outline, whose refs (`e12`) the other actions take as `selector`, alongside CSS, `xpath=`, and `text=` selectors. `handoff` gives the selected tab to the person with a message and returns once they click Continue (ten minutes by default).
40
+
41
+ Stagehand cannot attach to this browser, so what it does elsewhere runs here on the outline and the page's visible text:
42
+
43
+ - `target` and `ask` use the same classifiers and settings.
44
+ - `browse_ai` runs act, observe, and extract on the host's own inference (the `generate` a host lends Stagehand); a host that lends none gets `configuration`. act performs one action.
45
+ - `har_start` and `har_stop` write OpenCode Browse's network capture of the selected tab. It redacts credentials, leaves out the bodies of pages, scripts, styles, and images, and holds at most 1000 requests.
46
+
47
+ `live_view`, `cookie_import`, and saved contexts stay Browserbase's. Blocked domains cannot be enforced here and refuse the start; allowed domains become the tabs' allowed origins. `headless: true`, `cdpUrl`, and `endpoint` still launch or attach a Chrome of this tool's own.
48
+
33
49
  ## Develop
34
50
 
35
51
  ```sh
@@ -38,6 +54,7 @@ bun run check # tests, types, build, package
38
54
  CHROME_PATH=/path/to/chrome bun run test:local # real local browser
39
55
  CHROME_PATH=/path/to/chrome bun run test:shared # two processes on one persistent profile
40
56
  bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
57
+ CHROME_PATH=/path/to/chrome bun run benchmark # call latency, requests per call, and result sizes; BENCH_BACKEND=attach|browserbase
41
58
  ```
42
59
 
43
60
  Releases go through release-please; publishing uses npm trusted publishing from `publish.yml`. See [CONTRIBUTING.md](CONTRIBUTING.md).
package/dist/ask.d.ts CHANGED
@@ -5,11 +5,15 @@ export declare const EXTRACT_MODEL = "@cf/cloudflare/clairic";
5
5
  export declare const MAX_TEXT = 100000;
6
6
  /** Clef Flash reads 24,576 tokens: about 72k characters of page text leaves room for the questions. */
7
7
  export declare const DECIDE_TEXT: Record<string, number>;
8
- export interface PageState {
8
+ /** A page as ask reads it: a Stagehand snapshot tree, or text a browser without one supplies ready to read. */
9
+ export type PageState = {
9
10
  url: string;
10
11
  title: string;
12
+ } & ({
11
13
  tree: string;
12
- }
14
+ } | {
15
+ text: string;
16
+ });
13
17
  /** bool answers carry the probability of yes; other answers carry the model's confidence. */
14
18
  export type Answer = {
15
19
  value: boolean;
package/dist/ask.js CHANGED
@@ -70,7 +70,7 @@ async function extractValues(cloudflare, input, signal) {
70
70
  * answers bool and choice questions; when a call needs both, they run in parallel.
71
71
  */
72
72
  export async function askPage(models, page, fields, signal) {
73
- const full = pageText(page.tree);
73
+ const full = "text" in page ? page.text : pageText(page.tree);
74
74
  const decideLimit = Math.min(models.decideText ?? MAX_TEXT, MAX_TEXT);
75
75
  const entries = Object.entries(fields);
76
76
  const decide = entries.filter(([, field]) => Object.hasOwn(DECISIONS, field.type));
@@ -14,6 +14,8 @@ export declare class BrokerConnection {
14
14
  private readonly runs;
15
15
  private readonly conversations;
16
16
  private hello;
17
+ /** What the broker said it can do; one started by an older version says nothing. */
18
+ private features;
17
19
  private nextId;
18
20
  private buffer;
19
21
  private ended;
@@ -14,7 +14,7 @@ const CONNECT_TIMEOUT_MS = 15_000;
14
14
  const CANCEL_GRACE_MS = 15_000;
15
15
  function errorOf(body) {
16
16
  if (body.code)
17
- return new BrowseToolError(body.code, body.message);
17
+ return new BrowseToolError(body.code, body.message, body.batch);
18
18
  return Object.assign(new Error(body.message), { name: body.name });
19
19
  }
20
20
  const encodedOutput = z.looseObject({ action: z.string(), sessionId: z.string().nullable(), image: z.string().optional() });
@@ -61,6 +61,8 @@ export class BrokerConnection {
61
61
  runs = new Map();
62
62
  conversations = new Map();
63
63
  hello = Promise.withResolvers();
64
+ /** What the broker said it can do; one started by an older version says nothing. */
65
+ features = [];
64
66
  nextId = 1;
65
67
  buffer = "";
66
68
  ended = false;
@@ -140,6 +142,7 @@ export class BrokerConnection {
140
142
  receive(message) {
141
143
  switch (message.t) {
142
144
  case "hello":
145
+ this.features = message.features ?? [];
143
146
  this.hello.resolve(message.protocol);
144
147
  return;
145
148
  case "result": {
@@ -214,6 +217,9 @@ export class BrokerConnection {
214
217
  async run(conv, params, context, ai, defaultBackend, signal) {
215
218
  if (this.ended)
216
219
  throw new BrowseToolError("session_lost", "The shared browser service stopped. Start again.");
220
+ if (params.action === "batch" && !this.features.includes("batch")) {
221
+ throw new BrowseToolError("broker_version", "The shared browser service for this browser was started by an older browse version, which cannot run a batch. Send the steps as separate calls, or close the browser in every other conversation using it and start again.", { total: params.steps?.length ?? 0, completed: 0, outcomeUnknown: false });
222
+ }
217
223
  const id = this.nextId++;
218
224
  const waiter = Promise.withResolvers();
219
225
  this.runs.set(id, waiter);
@@ -8,6 +8,16 @@ declare const errorBody: z.ZodObject<{
8
8
  code: z.ZodOptional<z.ZodString>;
9
9
  name: z.ZodString;
10
10
  message: z.ZodString;
11
+ batch: z.ZodOptional<z.ZodObject<{
12
+ total: z.ZodNumber;
13
+ completed: z.ZodOptional<z.ZodNumber>;
14
+ failedIndex: z.ZodOptional<z.ZodNumber>;
15
+ outcomeUnknown: z.ZodBoolean;
16
+ error: z.ZodOptional<z.ZodObject<{
17
+ code: z.ZodString;
18
+ message: z.ZodString;
19
+ }, z.core.$strip>>;
20
+ }, z.core.$strip>>;
11
21
  }, z.core.$strip>;
12
22
  export type ErrorBody = z.infer<typeof errorBody>;
13
23
  /** The part of a conversation's context that crosses to the broker; the signal stays with the caller. */
@@ -74,12 +84,25 @@ export declare const clientMessage: z.ZodUnion<readonly [z.ZodObject<{
74
84
  code: z.ZodOptional<z.ZodString>;
75
85
  name: z.ZodString;
76
86
  message: z.ZodString;
87
+ batch: z.ZodOptional<z.ZodObject<{
88
+ total: z.ZodNumber;
89
+ completed: z.ZodOptional<z.ZodNumber>;
90
+ failedIndex: z.ZodOptional<z.ZodNumber>;
91
+ outcomeUnknown: z.ZodBoolean;
92
+ error: z.ZodOptional<z.ZodObject<{
93
+ code: z.ZodString;
94
+ message: z.ZodString;
95
+ }, z.core.$strip>>;
96
+ }, z.core.$strip>>;
77
97
  }, z.core.$strip>;
78
98
  }, z.core.$strip>]>;
79
99
  export type ClientMessage = z.infer<typeof clientMessage>;
100
+ /** What a broker can do beyond its protocol's first release; one started by an older version names none. */
101
+ export declare const BROKER_FEATURES: string[];
80
102
  export declare const brokerMessage: z.ZodUnion<readonly [z.ZodObject<{
81
103
  t: z.ZodLiteral<"hello">;
82
104
  protocol: z.ZodNumber;
105
+ features: z.ZodOptional<z.ZodArray<z.ZodString>>;
83
106
  }, z.core.$strip>, z.ZodObject<{
84
107
  t: z.ZodLiteral<"result">;
85
108
  id: z.ZodNumber;
@@ -93,6 +116,16 @@ export declare const brokerMessage: z.ZodUnion<readonly [z.ZodObject<{
93
116
  code: z.ZodOptional<z.ZodString>;
94
117
  name: z.ZodString;
95
118
  message: z.ZodString;
119
+ batch: z.ZodOptional<z.ZodObject<{
120
+ total: z.ZodNumber;
121
+ completed: z.ZodOptional<z.ZodNumber>;
122
+ failedIndex: z.ZodOptional<z.ZodNumber>;
123
+ outcomeUnknown: z.ZodBoolean;
124
+ error: z.ZodOptional<z.ZodObject<{
125
+ code: z.ZodString;
126
+ message: z.ZodString;
127
+ }, z.core.$strip>>;
128
+ }, z.core.$strip>>;
96
129
  }, z.core.$strip>;
97
130
  }, z.core.$strip>, z.ZodObject<{
98
131
  t: z.ZodLiteral<"released">;
@@ -7,7 +7,12 @@ import { z } from "zod";
7
7
  /** Bumped on any incompatible message change; a client never talks to a broker of another protocol. */
8
8
  export const BROKER_PROTOCOL = 1;
9
9
  const json = z.json();
10
- const errorBody = z.object({ code: z.string().optional(), name: z.string(), message: z.string() });
10
+ /** A failed batch's progress, as BatchProgress in session.ts. */
11
+ const batchProgress = z.object({
12
+ total: z.number().int(), completed: z.number().int().optional(), failedIndex: z.number().int().optional(), outcomeUnknown: z.boolean(),
13
+ error: z.object({ code: z.string(), message: z.string() }).optional(),
14
+ });
15
+ const errorBody = z.object({ code: z.string().optional(), name: z.string(), message: z.string(), batch: batchProgress.optional() });
11
16
  /** The part of a conversation's context that crosses to the broker; the signal stays with the caller. */
12
17
  const runContext = z.object({
13
18
  sessionId: z.string(), profile: z.string(), cwd: z.string(),
@@ -26,8 +31,10 @@ export const clientMessage = z.union([
26
31
  z.object({ t: z.literal("answer"), cb: z.number().int(), ok: z.literal(true), value: json }),
27
32
  z.object({ t: z.literal("answer"), cb: z.number().int(), ok: z.literal(false), error: errorBody }),
28
33
  ]);
34
+ /** What a broker can do beyond its protocol's first release; one started by an older version names none. */
35
+ export const BROKER_FEATURES = ["batch"];
29
36
  export const brokerMessage = z.union([
30
- z.object({ t: z.literal("hello"), protocol: z.number().int() }),
37
+ z.object({ t: z.literal("hello"), protocol: z.number().int(), features: z.array(z.string()).optional() }),
31
38
  z.object({ t: z.literal("result"), id: z.number().int(), ok: z.literal(true), output: json }),
32
39
  z.object({ t: z.literal("result"), id: z.number().int(), ok: z.literal(false), error: errorBody }),
33
40
  z.object({ t: z.literal("released"), id: z.number().int() }),
@@ -72,6 +79,9 @@ export function errorBodyOf(cause) {
72
79
  const body = { name: cause.name, message: cause.message };
73
80
  if (code?.success)
74
81
  body.code = code.data;
82
+ const batch = "batch" in cause ? batchProgress.safeParse(cause.batch) : undefined;
83
+ if (batch?.success)
84
+ body.batch = batch.data;
75
85
  return body;
76
86
  }
77
87
  /**
package/dist/broker.js CHANGED
@@ -4,8 +4,8 @@
4
4
  // it exits once no client has been connected for a while, after the last conversation released the browser.
5
5
  import { chmodSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { createServer } from "node:net";
7
- import { BROKER_PROTOCOL, browseConfig, classifyAnswers, clientMessage, errorBodyOf, } from "./broker-protocol.js";
8
- import { aiParameters, browserParameters } from "./schema.js";
7
+ import { BROKER_FEATURES, BROKER_PROTOCOL, browseConfig, classifyAnswers, clientMessage, errorBodyOf, } from "./broker-protocol.js";
8
+ import { aiParameters, browserBatchParameters } from "./schema.js";
9
9
  import { BrowseSession } from "./session.js";
10
10
  const IDLE_EXIT_MS = 30_000;
11
11
  const socketPath = process.argv[2];
@@ -86,7 +86,7 @@ class Connection {
86
86
  async handle(message) {
87
87
  switch (message.t) {
88
88
  case "hello":
89
- this.send({ t: "hello", protocol: BROKER_PROTOCOL });
89
+ this.send({ t: "hello", protocol: BROKER_PROTOCOL, features: BROKER_FEATURES });
90
90
  return;
91
91
  case "open":
92
92
  if (!this.sessions.has(message.conv))
@@ -102,7 +102,7 @@ class Connection {
102
102
  this.controllers.set(message.id, controller);
103
103
  try {
104
104
  session.defaultBackend = message.defaultBackend;
105
- const params = message.ai ? aiParameters.parse(message.params) : browserParameters.parse(message.params);
105
+ const params = message.ai ? aiParameters.parse(message.params) : browserBatchParameters.parse(message.params);
106
106
  const output = await session.run(params, message.context, controller.signal, message.ai);
107
107
  this.send({ t: "result", id: message.id, ok: true, output: encodeOutput(output) });
108
108
  }
package/dist/cdp-guard.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { once } from "node:events";
2
2
  import { createServer } from "node:http";
3
- import WebSocket, { WebSocketServer } from "ws";
4
3
  /** Browser-level commands that would end or crash a browser we only attached to. */
5
4
  const BLOCKED = new Set(["Browser.close", "Browser.crash", "Browser.crashGpuProcess"]);
6
5
  /** Screenshots and full snapshots exceed ws's 100 MiB default only in extreme pages; keep a generous ceiling. */
@@ -39,16 +38,18 @@ async function browserWebSocketUrl(cdpUrl, headers, signal) {
39
38
  export async function guardEndpoint(cdpUrl, signal, headers = {}) {
40
39
  const { reported, reachable: upstreamUrl } = await browserWebSocketUrl(cdpUrl, headers, signal);
41
40
  const server = createServer((_request, response) => { response.writeHead(404).end(); });
41
+ // Loaded on first attach, so hosts that never attach to a browser do not pay for it at startup.
42
+ const ws = await import("ws");
42
43
  const sockets = new Set();
43
- const wss = new WebSocketServer({ server, maxPayload: MAX_PAYLOAD, perMessageDeflate: false });
44
+ const wss = new ws.WebSocketServer({ server, maxPayload: MAX_PAYLOAD, perMessageDeflate: false });
44
45
  wss.on("connection", client => {
45
- const upstream = new WebSocket(upstreamUrl, { maxPayload: MAX_PAYLOAD, perMessageDeflate: false, headers });
46
+ const upstream = new ws.default(upstreamUrl, { maxPayload: MAX_PAYLOAD, perMessageDeflate: false, headers });
46
47
  sockets.add(client).add(upstream);
47
48
  const pending = [];
48
49
  const end = () => {
49
50
  for (const socket of [client, upstream]) {
50
51
  sockets.delete(socket);
51
- if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)
52
+ if (socket.readyState === ws.default.OPEN || socket.readyState === ws.default.CONNECTING)
52
53
  socket.terminate();
53
54
  }
54
55
  };
@@ -56,7 +57,7 @@ export async function guardEndpoint(cdpUrl, signal, headers = {}) {
56
57
  upstream.on("close", end).on("error", end);
57
58
  upstream.on("open", () => { for (const data of pending.splice(0))
58
59
  upstream.send(data, { binary: false }); });
59
- upstream.on("message", (data, binary) => { if (client.readyState === WebSocket.OPEN)
60
+ upstream.on("message", (data, binary) => { if (client.readyState === ws.default.OPEN)
60
61
  client.send(data, { binary }); });
61
62
  client.on("message", data => {
62
63
  const text = data.toString();
@@ -72,9 +73,9 @@ export async function guardEndpoint(cdpUrl, signal, headers = {}) {
72
73
  return;
73
74
  }
74
75
  }
75
- if (upstream.readyState === WebSocket.OPEN)
76
+ if (upstream.readyState === ws.default.OPEN)
76
77
  upstream.send(text);
77
- else if (upstream.readyState === WebSocket.CONNECTING)
78
+ else if (upstream.readyState === ws.default.CONNECTING)
78
79
  pending.push(data);
79
80
  });
80
81
  });
@@ -0,0 +1,23 @@
1
+ /** The cache file: under XDG_CACHE_HOME, else ~/.cache. It holds extension IDs and hashes, never a key. */
2
+ export declare function extensionCachePath(): string;
3
+ /** Names a Browserbase project in the cache without storing its API key. */
4
+ export declare function extensionCacheKey(apiKey: string, projectId: string): string;
5
+ export interface ExtensionProvision {
6
+ path: string;
7
+ key: string;
8
+ /** The extension archive bundled with the installed SDK. */
9
+ archive: Uint8Array;
10
+ upload(): Promise<string>;
11
+ /** Deletes an extension this cache replaced; failures are ignored. */
12
+ remove(id: string): Promise<unknown>;
13
+ /** The cached extension turned out to be gone from the project: upload again. */
14
+ fresh?: boolean;
15
+ }
16
+ /**
17
+ * The project's extension ID for this archive: the cached one, or a new upload that replaces it. An upload from another
18
+ * SDK version is deleted once replaced. Two processes that upload at the same moment leave one extra extension behind.
19
+ */
20
+ export declare function provisionExtension(options: ExtensionProvision): Promise<{
21
+ id: string;
22
+ cached: boolean;
23
+ }>;
@@ -0,0 +1,48 @@
1
+ // Remembers the Stagehand extension uploaded to a Browserbase project, so conversations and processes reuse one upload.
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { z } from "zod";
7
+ /** Per project: the uploaded extension's ID and the digest of the archive it was uploaded from. */
8
+ const cache = z.record(z.string(), z.object({ id: z.string().min(1), archive: z.string().min(1) }));
9
+ /** The cache file: under XDG_CACHE_HOME, else ~/.cache. It holds extension IDs and hashes, never a key. */
10
+ export function extensionCachePath() {
11
+ return join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "browse-core", "browserbase-extensions.json");
12
+ }
13
+ /** Names a Browserbase project in the cache without storing its API key. */
14
+ export function extensionCacheKey(apiKey, projectId) {
15
+ return createHash("sha256").update(`${apiKey}\n${projectId}`).digest("hex");
16
+ }
17
+ /** A missing or unreadable cache is an empty one: the next upload rewrites it. */
18
+ async function load(path) {
19
+ try {
20
+ return cache.parse(JSON.parse(await readFile(path, "utf8")));
21
+ }
22
+ catch {
23
+ return {};
24
+ }
25
+ }
26
+ async function store(path, entries) {
27
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
28
+ // Rename into place so another process reading the cache never sees a partial file.
29
+ const partial = `${path}.${process.pid}.tmp`;
30
+ await writeFile(partial, `${JSON.stringify(entries, null, 2)}\n`, { mode: 0o600 });
31
+ await rename(partial, path);
32
+ }
33
+ /**
34
+ * The project's extension ID for this archive: the cached one, or a new upload that replaces it. An upload from another
35
+ * SDK version is deleted once replaced. Two processes that upload at the same moment leave one extra extension behind.
36
+ */
37
+ export async function provisionExtension(options) {
38
+ const archive = createHash("sha256").update(options.archive).digest("hex");
39
+ const entries = await load(options.path);
40
+ const known = entries[options.key];
41
+ if (known && known.archive === archive && !options.fresh)
42
+ return { id: known.id, cached: true };
43
+ const id = await options.upload();
44
+ await store(options.path, { ...await load(options.path), [options.key]: { id, archive } }).catch(() => undefined);
45
+ if (known && !options.fresh)
46
+ void options.remove(known.id).catch(() => undefined);
47
+ return { id, cached: false };
48
+ }
package/dist/har.d.ts CHANGED
@@ -8,6 +8,44 @@ export interface HarSummary {
8
8
  /** HAR has no place for traffic still in flight at stop; it is dropped. */
9
9
  unfinished: number;
10
10
  }
11
+ type NameValue = {
12
+ name: string;
13
+ value: string;
14
+ };
15
+ interface CapturedBody {
16
+ size?: number;
17
+ mimeType?: string;
18
+ text?: string;
19
+ omitted?: boolean;
20
+ }
21
+ /** A tab's traffic as OpenCode Browse's network capture returns it at stop. */
22
+ export interface NetworkCapture {
23
+ failureCount?: number;
24
+ droppedEntryCount?: number;
25
+ exchanges: {
26
+ startedDateTime: string;
27
+ durationMs?: number;
28
+ request: {
29
+ method: string;
30
+ url: string;
31
+ headers?: NameValue[];
32
+ body?: CapturedBody;
33
+ };
34
+ response?: {
35
+ status: number;
36
+ statusText?: string;
37
+ headers?: NameValue[];
38
+ body?: CapturedBody;
39
+ };
40
+ }[];
41
+ }
42
+ /**
43
+ * Writes OpenCode Browse's capture of one tab as HAR 1.2 (mode 0600). The capture arrives with credentials redacted
44
+ * and without the bodies of HTML, scripts, styles, and images, so the file holds less than a HarRecorder's does.
45
+ */
46
+ export declare function writeCaptureHar(capture: NetworkCapture, path: string, creator: string): Promise<HarSummary & {
47
+ dropped: number;
48
+ }>;
11
49
  /**
12
50
  * Records the network traffic of every tab in one browser as HAR 1.2, over its own DevTools connection to the browser
13
51
  * target. Request headers include Cookie and response headers Set-Cookie (from the ExtraInfo events), and request and
@@ -48,3 +86,4 @@ export declare class HarRecorder {
48
86
  private finish;
49
87
  private entry;
50
88
  }
89
+ export {};
package/dist/har.js CHANGED
@@ -3,6 +3,38 @@ import { dirname } from "node:path";
3
3
  // Stagehand 4.3 forwards only console events from CDP, so network capture uses its own connection to the browser target.
4
4
  /** A response body larger than this (base64 or text characters) is left out of the HAR and counted instead. */
5
5
  const MAX_BODY_CHARS = 5_000_000;
6
+ /**
7
+ * Writes OpenCode Browse's capture of one tab as HAR 1.2 (mode 0600). The capture arrives with credentials redacted
8
+ * and without the bodies of HTML, scripts, styles, and images, so the file holds less than a HarRecorder's does.
9
+ */
10
+ export async function writeCaptureHar(capture, path, creator) {
11
+ const exchanges = capture.exchanges.filter(exchange => /^(?:https?|wss?):/.test(exchange.request.url));
12
+ const entries = exchanges.map(({ startedDateTime, durationMs = 0, request, response }) => ({
13
+ startedDateTime, time: durationMs,
14
+ request: {
15
+ method: request.method, url: request.url, httpVersion: "",
16
+ // HTTP/2 pseudo-headers repeat the method and URL.
17
+ headers: (request.headers ?? []).filter(header => !header.name.startsWith(":")),
18
+ queryString: URL.canParse(request.url) ? [...new URL(request.url).searchParams].map(([name, value]) => ({ name, value })) : [],
19
+ cookies: [], headersSize: -1, bodySize: request.body?.size ?? 0,
20
+ ...(request.body?.text === undefined ? {} : { postData: { mimeType: request.body.mimeType ?? "", text: request.body.text } }),
21
+ },
22
+ response: {
23
+ status: response?.status ?? 0, statusText: response?.statusText ?? "", httpVersion: "", headers: response?.headers ?? [], cookies: [],
24
+ content: { size: response?.body?.size ?? 0, mimeType: response?.body?.mimeType ?? "", ...(response?.body?.text === undefined ? {} : { text: response.body.text }) },
25
+ redirectURL: "", headersSize: -1, bodySize: -1,
26
+ },
27
+ cache: {}, timings: { send: 0, wait: durationMs, receive: 0 },
28
+ }));
29
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
30
+ await writeFile(path, JSON.stringify({ log: { version: "1.2", creator: { name: creator, version: "1" }, pages: [], entries } }), { mode: 0o600 });
31
+ await chmod(path, 0o600);
32
+ const hosts = [...new Set(exchanges.map(exchange => URL.canParse(exchange.request.url) ? new URL(exchange.request.url).host : "").filter(Boolean))];
33
+ return {
34
+ path, entries: entries.length, tabs: 1, hosts: hosts.slice(0, 30), failed: capture.failureCount ?? 0,
35
+ bodiesOmitted: exchanges.filter(exchange => exchange.response?.body?.omitted).length, unfinished: 0, dropped: capture.droppedEntryCount ?? 0,
36
+ };
37
+ }
6
38
  /** CDP header objects join repeated headers with newlines; HAR lists each value. */
7
39
  function headerList(headers) {
8
40
  return Object.entries(headers).flatMap(([name, value]) => String(value).split("\n").map(line => ({ name, value: line })));
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from "./schema.ts";
3
3
  export * from "./settings.ts";
4
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
5
  export * from "./cdp-guard.ts";
6
+ export * from "./real-browser-client.ts";
6
7
  export * from "./chrome-profile.ts";
7
8
  export * from "./har.ts";
8
9
  export * from "./page-operations.ts";
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ export * from "./settings.js";
5
5
  // ask.ts and classifier.ts both name a type Answer; the hosts use the classifier's.
6
6
  export { EXTRACT_MODEL, MAX_TEXT, DECIDE_TEXT, askNeeds, pageText, askPage } from "./ask.js";
7
7
  export * from "./cdp-guard.js";
8
+ export * from "./real-browser-client.js";
8
9
  export * from "./chrome-profile.js";
9
10
  export * from "./har.js";
10
11
  export * from "./page-operations.js";
package/dist/jev.d.ts CHANGED
@@ -30,6 +30,11 @@ export interface JevPick {
30
30
  * also carry their adjacent siblings' text, where visible labels such as "checkbox 1" usually live.
31
31
  */
32
32
  export declare function treeCandidates(tree: string): Candidate[];
33
+ /**
34
+ * Targetable lines of an OpenCode Browse outline (`- button "Save" [ref=e12 disabled]`) that `action` can operate on.
35
+ * Labels keep the element's states and carry up to two named ancestors, as treeCandidates' do.
36
+ */
37
+ export declare function outlineCandidates(outline: string, action: string): Candidate[];
33
38
  /** Whether `action` can operate on the element at `xpath`: fill needs a text-entry control, select a native <select>. */
34
39
  export declare function fitsAction(action: string, candidate: Candidate, xpath: string): boolean;
35
40
  /** Tournament over Jev's per-choice option limit; the final round decides whether the pick is confident enough to act. */
package/dist/jev.js CHANGED
@@ -58,6 +58,37 @@ export function treeCandidates(tree) {
58
58
  });
59
59
  return candidates;
60
60
  }
61
+ /**
62
+ * Targetable lines of an OpenCode Browse outline (`- button "Save" [ref=e12 disabled]`) that `action` can operate on.
63
+ * Labels keep the element's states and carry up to two named ancestors, as treeCandidates' do.
64
+ */
65
+ export function outlineCandidates(outline, action) {
66
+ const candidates = [];
67
+ const ancestors = [];
68
+ for (const line of outline.split("\n")) {
69
+ const match = /^(\s*)- ([\w-]+)(?: "((?:[^"\\]|\\.)*)")?(?: \[([^\]]*)\])?/.exec(line);
70
+ if (!match)
71
+ continue;
72
+ const [, indent, role, name = "", attributes = ""] = match;
73
+ const depth = indent.length;
74
+ while (ancestors.length && ancestors.at(-1).depth >= depth)
75
+ ancestors.pop();
76
+ const ref = /(?:^| )ref=(e\d+)/.exec(attributes)?.[1];
77
+ const states = attributes.split(" ").filter(state => state && !state.startsWith("ref="));
78
+ const text = name ? `${role}: ${name}` : role;
79
+ // fill needs a text-entry control it may change; select needs a native <select>, which lists its options.
80
+ const fits = action === "fill" ? Object.hasOwn(FILLABLE, role) && !states.includes("readonly") && !states.includes("options")
81
+ : action === "select" ? states.includes("options")
82
+ : true;
83
+ if (ref && fits && !states.includes("disabled")) {
84
+ const context = ancestors.flatMap(a => a.label ? [a.label] : []).slice(-2);
85
+ const label = `${text}${states.length ? ` [${states.join(" ")}]` : ""}${context.length ? ` (in ${context.join(" > ")})` : ""}`;
86
+ candidates.push({ ref, label: label.slice(0, 240), role: role });
87
+ }
88
+ ancestors.push({ depth, label: name ? text.slice(0, 80) : undefined });
89
+ }
90
+ return candidates;
91
+ }
61
92
  /** Whether `action` can operate on the element at `xpath`: fill needs a text-entry control, select a native <select>. */
62
93
  export function fitsAction(action, candidate, xpath) {
63
94
  // Stagehand xpath steps are tagName[n]; the last one is the element's own tag.
@@ -1,7 +1,7 @@
1
- import type { ExperimentalBatchContext, SnapshotResult } from "@browserbasehq/stagehand";
1
+ import type { ExperimentalBatchContext } from "@browserbasehq/stagehand";
2
2
  import type { AnsweredDialog } from "./session.ts";
3
3
  export interface PageOperation {
4
- action: "snapshot" | "click" | "fill" | "select" | "press" | "scroll" | "evaluate" | "tab_select";
4
+ action: "start" | "open" | "back" | "forward" | "reload" | "wait" | "snapshot" | "click" | "fill" | "select" | "press" | "scroll" | "evaluate" | "screenshot" | "tab_select";
5
5
  selector?: string;
6
6
  nth?: number;
7
7
  /** Snapshot ref to verify before acting: the tab URL, the ref ID (frame ordinal and backend node), and its XPath. */
@@ -18,8 +18,28 @@ export interface PageOperation {
18
18
  y?: number;
19
19
  deltaX?: number;
20
20
  deltaY?: number;
21
+ url?: string;
22
+ durationMs?: number;
23
+ loadState?: "load" | "domcontentloaded" | "networkidle";
24
+ state?: "attached" | "detached" | "visible" | "hidden";
25
+ fullPage?: boolean;
26
+ /** The browser has a domain policy: a navigation that ends on Chrome's error page was refused by it. */
27
+ fenced?: boolean;
28
+ /** Deadline for page-level waits and navigation, a little under the operation's own so a clean timeout wins. */
29
+ pageTimeoutMs: number;
30
+ /** For snapshot: the version its refs carry, and how much of the tree the caller shows. */
31
+ snapshot?: {
32
+ version: string;
33
+ maxChars: number;
34
+ };
21
35
  readTimeoutMs: number;
22
36
  }
37
+ /** The part of a snapshot its caller uses: the tree cut to size with versioned refs, and the XPath of each ref in it. */
38
+ export interface PageSnapshot {
39
+ tree: string;
40
+ truncated: boolean;
41
+ refs: Record<string, string>;
42
+ }
23
43
  export interface PageOperationResult {
24
44
  tabId: string;
25
45
  url: string;
@@ -27,15 +47,82 @@ export interface PageOperationResult {
27
47
  dialogs?: AnsweredDialog[];
28
48
  responsive?: false;
29
49
  value?: unknown;
30
- snapshot?: SnapshotResult;
50
+ snapshot?: PageSnapshot;
31
51
  snapshotUrl?: string;
52
+ navigation?: {
53
+ httpStatus?: number;
54
+ };
55
+ /** A screenshot as base64 PNG. */
56
+ image?: string;
32
57
  error?: {
33
58
  code: string;
34
59
  message: string;
35
60
  };
36
61
  }
62
+ /** A batch: steps run in order on one tab under one deadline. */
63
+ export interface PageBatchInput {
64
+ id: string;
65
+ steps: PageOperation[];
66
+ timeoutMs: number;
67
+ }
68
+ /** The steps that completed, in order, and the step that stopped the batch, if one did. */
69
+ export interface PageBatchResult {
70
+ results: PageOperationResult[];
71
+ /** outcomeUnknown: the SDK threw after the step may already have acted. */
72
+ failure?: {
73
+ index: number;
74
+ code: string;
75
+ message: string;
76
+ outcomeUnknown: boolean;
77
+ };
78
+ }
79
+ /**
80
+ * Asks a running batch to stop before its next step. A request of its own, since the worker runs it while the batch waits
81
+ * on a step. Serialized into the worker: no outside dependencies.
82
+ */
83
+ export declare function cancelPageBatch(_context: ExperimentalBatchContext, input: {
84
+ id: string;
85
+ ttlMs: number;
86
+ }): Promise<boolean>;
37
87
  /** Serialized into the worker: executable dependencies must stay inside this function. */
38
- export declare function pageOperation({ page, context }: ExperimentalBatchContext, input: PageOperation): Promise<PageOperationResult>;
88
+ export declare function pageOperation(context: ExperimentalBatchContext, input: PageOperation): Promise<PageOperationResult>;
89
+ export declare function pageOperation(context: ExperimentalBatchContext, input: PageBatchInput): Promise<PageBatchResult>;
90
+ /** What a result says about its tab after an action that ran outside pageOperation. */
91
+ export interface PageView {
92
+ tabId: string;
93
+ url: string;
94
+ title: string | null;
95
+ dialogs?: AnsweredDialog[];
96
+ responsive?: false;
97
+ origin: number | null;
98
+ }
99
+ /**
100
+ * Reads a tab's URL, title, answered dialogs, and document identity in one request. The main-thread read is bounded, so
101
+ * a blocked tab is reported unresponsive instead of failing. Serialized into the worker: no outside dependencies.
102
+ */
103
+ export declare function viewOperation({ page }: ExperimentalBatchContext, input: {
104
+ readTimeoutMs: number;
105
+ }): Promise<PageView>;
106
+ export interface PageRead {
107
+ tabId: string;
108
+ url: string;
109
+ title: string;
110
+ /** The document's performance.timeOrigin; null while a navigation leaves the tab without a document to ask. */
111
+ origin: number | null;
112
+ tree: string;
113
+ /** XPaths of the tree's non-text nodes, by unversioned ref. */
114
+ refs?: Record<string, string>;
115
+ /** The viewport as base64 JPEG. */
116
+ image?: string;
117
+ }
118
+ /**
119
+ * Reads a page for ask and JEV in one request: the snapshot tree, optionally the XPaths of the nodes a target can name
120
+ * and the viewport. Serialized into the worker: executable dependencies must stay inside this function.
121
+ */
122
+ export declare function readOperation({ page }: ExperimentalBatchContext, input: {
123
+ refs: boolean;
124
+ image: boolean;
125
+ }): Promise<PageRead>;
39
126
  /** Context-only reads share one transport request; keep the same bounded title behavior for blocked tabs. */
40
127
  export declare function tabsOperation({ context }: Pick<ExperimentalBatchContext, "context">, input: {
41
128
  selectedTabId: string | null;