@edlsh/browse-core 0.6.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +23 -2
  2. package/dist/broker-client.d.ts +4 -2
  3. package/dist/broker-client.js +12 -6
  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/cdp-connection.d.ts +18 -0
  8. package/dist/cdp-connection.js +59 -0
  9. package/dist/config.d.ts +101 -0
  10. package/dist/config.js +78 -0
  11. package/dist/contexts.d.ts +10 -0
  12. package/dist/contexts.js +27 -0
  13. package/dist/errors.d.ts +29 -0
  14. package/dist/errors.js +83 -0
  15. package/dist/har.d.ts +1 -6
  16. package/dist/har.js +16 -56
  17. package/dist/host-model.d.ts +24 -0
  18. package/dist/host-model.js +35 -0
  19. package/dist/http-auth.d.ts +14 -0
  20. package/dist/http-auth.js +114 -0
  21. package/dist/index.d.ts +10 -13
  22. package/dist/index.js +11 -15
  23. package/dist/jev.js +9 -3
  24. package/dist/page-operations.d.ts +11 -1
  25. package/dist/page-operations.js +62 -11
  26. package/dist/real-browser-ai.d.ts +1 -1
  27. package/dist/real-browser-ai.js +1 -1
  28. package/dist/real-browser-client.js +1 -1
  29. package/dist/real-browser-session.d.ts +1 -1
  30. package/dist/real-browser-session.js +24 -5
  31. package/dist/schema.d.ts +34 -0
  32. package/dist/schema.js +29 -6
  33. package/dist/session-runtime.d.ts +42 -0
  34. package/dist/session-runtime.js +144 -0
  35. package/dist/session.d.ts +29 -108
  36. package/dist/session.js +189 -364
  37. package/dist/settings.js +47 -6
  38. package/dist/tool-results.d.ts +28 -0
  39. package/dist/tool-results.js +40 -0
  40. package/extensions/http-auth/README.md +27 -0
  41. package/extensions/http-auth/background.js +85 -0
  42. package/extensions/http-auth/manifest.json +27 -0
  43. package/extensions/http-auth/native/README.md +31 -0
  44. package/extensions/http-auth/native/host.py +97 -0
  45. package/extensions/http-auth/native/install.py +62 -0
  46. package/extensions/http-auth/options.html +25 -0
  47. package/extensions/http-auth/options.js +36 -0
  48. package/extensions/http-auth/origin.js +16 -0
  49. package/package.json +14 -2
package/README.md CHANGED
@@ -18,12 +18,32 @@ const output = await browser.run(browserParameters.parse({ action: "start", back
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
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.
22
- - `ClientInference` supplies Stagehand's default inference. Without it, unconfigured AI calls use Browserbase Model Gateway.
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 under one deadline. Stagehand normally executes them in one browser request. A shifted printable key uses tab-scoped DevTools input because Stagehand 4.4 drops its keydown metadata; that batch and real-browser batches can take several round trips. 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.
22
+ - `ClientInference.describe` names the host model for status. Supply `ClientInference.generate` for a session-wide provider, or pass a provider factory to `browser.run(params, context, signal, providerFactory)` for each AI call. The factory receives that call’s abort signal. Hosted sessions without a host model use Browserbase Model Gateway.
23
23
  - `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
24
24
 
25
25
  Stagehand is pinned to 4.4.0 and used unmodified. zod is pinned to 4.6.6, the exact version Stagehand pins, so one copy is installed; a second copy fails the typecheck on the schema passed to `stagehand.extract`. An attached browser needs Chrome 137 or newer and the Stagehand extension shipped with 4.4.0. Run both real-browser suites before upgrading Stagehand.
26
26
 
27
+ **Saved context ownership:** a hosted context must match the remote project and profile prefix and have a local creation record for this integration, profile and project. The registry is the configured history file or a private file under the user state directory. Older untagged records are not proof of origin: create a new context. A context returned with `historySaved: false` cannot be reused until the registry is writable and a new context is created.
28
+
29
+ **Tool results:** hosts call `encodeResult` or `encodeError` before rendering. For a large reply, use `result_read(resultId, offset)` to retrieve redacted JSON in chunks without replaying an action. Only the latest large reply is held in memory, and close or shutdown discards it.
30
+
31
+ ## HTTP sign-in in a managed browser
32
+
33
+ Start an isolated browser for a site that uses a browser-native username and password prompt.
34
+
35
+ ```js
36
+ { action: "start", backend: "local", httpAuth: true, url: "https://example.com/" }
37
+ ```
38
+
39
+ The package includes the companion and native helper under `extensions/http-auth/`. To install the resolver explicitly, run `python3 node_modules/@edlsh/browse-core/extensions/http-auth/native/install.py managed`; installing the npm package does not register or run it. See the companion README there for desktop registration.
40
+
41
+ Enable the installed browser credential helper with `BROWSE_HTTP_AUTH_USE_STORE=true`. The helper looks up the starting URL's exact origin in the user's private credential mapping. Set `BROWSE_HTTP_AUTH_ORIGIN` to restrict this profile's lookups to one origin. Alternatively, supply `BROWSE_HTTP_AUTH_ORIGIN`, `BROWSE_HTTP_AUTH_USERNAME` and `BROWSE_HTTP_AUTH_PASSWORD` through the host's configured secrets manager. Keep these values out of tool arguments. Custom host resolvers receive `scope.httpAuth === true` at this start and may return profile-specific `httpAuthStore: {}` or `httpAuth: {origin, username, password}`.
42
+
43
+ The browser answers a server's HTTP Basic challenge at that scheme, host and port. Authentication requires HTTPS or loopback HTTP. Closing the browser discards its auth cache. An authenticated start uses a fresh profile even where the host normally shares a persistent profile. HAR capture is unavailable during this session.
44
+
45
+ For a fresh Browserbase session, choose `backend: "browserbase"` and grant the host permission with `BROWSE_HTTP_AUTH_HOSTED=true` or `hosted: true` in the selected credential configuration. Browserbase processes the credentials for that session. The launch disables session logging, recording and keep-alive.
46
+
27
47
  ## Shared browsers
28
48
 
29
49
  New browsers start locally unless the host or the profile's `/browse backend` setting chooses Browserbase.
@@ -51,6 +71,7 @@ Stagehand cannot attach to this browser, so what it does elsewhere runs here on
51
71
  ```sh
52
72
  bun install --frozen-lockfile --ignore-scripts
53
73
  bun run check # tests, types, build, package contents
74
+ CHROME_PATH=/path/to/chrome bun run test:http-auth # local HTTP Basic challenge, exact origin and rejected credentials
54
75
  CHROME_PATH=/path/to/chrome bun run test:local # real local browser
55
76
  CHROME_PATH=/path/to/chrome bun run test:shared # two processes on one persistent profile
56
77
  bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
@@ -1,6 +1,7 @@
1
1
  import { type RunContext } from "./broker-protocol.ts";
2
2
  import type { HostClassify } from "./classifier.ts";
3
- import { type BrowserOutput, type ClientGenerate, type ConfigResolver, type HostIdentity } from "./session.ts";
3
+ import type { ConfigResolver } from "./config.ts";
4
+ import type { BrowserOutput, ClientGenerate, HostIdentity } from "./session.ts";
4
5
  import type { AIParams, BrowserParams } from "./schema.ts";
5
6
  /** What a conversation in this process lends the broker. */
6
7
  export interface BrokerHandlers {
@@ -11,6 +12,7 @@ export interface BrokerHandlers {
11
12
  export declare class BrokerConnection {
12
13
  private readonly socket;
13
14
  private readonly socketPath;
15
+ private readonly inferenceRuns;
14
16
  private readonly runs;
15
17
  private readonly conversations;
16
18
  private hello;
@@ -35,7 +37,7 @@ export declare class BrokerConnection {
35
37
  /** Opens a conversation in the broker; its calls then run on the shared browser. */
36
38
  openConversation(conv: string, identity: HostIdentity, handlers: BrokerHandlers): void;
37
39
  /** Runs one call in the broker. A cancel is passed on, and the broker's own account of the outcome awaited briefly. */
38
- run(conv: string, params: BrowserParams | AIParams, context: RunContext, ai: boolean, defaultBackend: "browserbase" | "local", signal: AbortSignal): Promise<BrowserOutput>;
40
+ run(conv: string, params: BrowserParams | AIParams, context: RunContext, ai: boolean, defaultBackend: "browserbase" | "local", signal: AbortSignal, generate?: ClientGenerate): Promise<BrowserOutput>;
39
41
  /** Ends a conversation in the broker: its tabs close, and the browser goes with the last conversation. */
40
42
  closeConversation(conv: string): Promise<void>;
41
43
  }
@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { setTimeout as delay } from "node:timers/promises";
9
9
  import { z } from "zod";
10
10
  import { BROKER_PROTOCOL, brokerMessage, brokerSocketPath, classifyRequest, errorBodyOf, } from "./broker-protocol.js";
11
- import { BrowseToolError } from "./session.js";
11
+ import { BrowseToolError } from "./errors.js";
12
12
  const CONNECT_TIMEOUT_MS = 15_000;
13
13
  /** After a cancel, how long a call still waits for the broker's own account of what happened. */
14
14
  const CANCEL_GRACE_MS = 15_000;
@@ -58,6 +58,7 @@ const connections = new Map();
58
58
  export class BrokerConnection {
59
59
  socket;
60
60
  socketPath;
61
+ inferenceRuns = new Map();
61
62
  runs = new Map();
62
63
  conversations = new Map();
63
64
  hello = Promise.withResolvers();
@@ -174,13 +175,15 @@ export class BrokerConnection {
174
175
  throw new Error("The conversation this request belongs to has ended.");
175
176
  let value;
176
177
  if (request.kind === "config") {
177
- value = await handlers.resolveConfig({ ...request.context, signal: AbortSignal.timeout(60_000) });
178
+ const { httpAuth: _privateCredentials, httpAuthStore: _privateCredentialStore, ...sharedConfig } = await handlers.resolveConfig({ ...request.context, signal: AbortSignal.timeout(60_000) });
179
+ value = sharedConfig;
178
180
  }
179
181
  else if (request.kind === "generate") {
180
- if (!handlers.generate)
181
- throw new Error("This conversation has no Stagehand inference to lend.");
182
+ const run = this.inferenceRuns.get(request.runId);
183
+ if (!run || run.conv !== conv)
184
+ throw new Error("This browser model call has ended.");
182
185
  // SAFETY: the broker forwards Stagehand's own generate() parameters, unchanged apart from the JSON round trip.
183
- value = await handlers.generate(request.params);
186
+ value = await run.generate(request.params);
184
187
  }
185
188
  else {
186
189
  if (!handlers.classify)
@@ -214,7 +217,7 @@ export class BrokerConnection {
214
217
  this.send({ t: "open", conv, identity, inference: Boolean(handlers.generate), classify: Boolean(handlers.classify) });
215
218
  }
216
219
  /** Runs one call in the broker. A cancel is passed on, and the broker's own account of the outcome awaited briefly. */
217
- async run(conv, params, context, ai, defaultBackend, signal) {
220
+ async run(conv, params, context, ai, defaultBackend, signal, generate) {
218
221
  if (this.ended)
219
222
  throw new BrowseToolError("session_lost", "The shared browser service stopped. Start again.");
220
223
  if (params.action === "batch" && !this.features.includes("batch")) {
@@ -223,6 +226,8 @@ export class BrokerConnection {
223
226
  const id = this.nextId++;
224
227
  const waiter = Promise.withResolvers();
225
228
  this.runs.set(id, waiter);
229
+ if (generate)
230
+ this.inferenceRuns.set(id, { conv, generate });
226
231
  this.hold();
227
232
  const onAbort = () => {
228
233
  this.send({ t: "cancel", id });
@@ -235,6 +240,7 @@ export class BrokerConnection {
235
240
  }
236
241
  finally {
237
242
  signal.removeEventListener("abort", onAbort);
243
+ this.inferenceRuns.delete(id);
238
244
  this.runs.delete(id);
239
245
  this.release();
240
246
  }
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  /** Bumped on any incompatible message change; a client never talks to a broker of another protocol. */
3
- export declare const BROKER_PROTOCOL = 1;
3
+ export declare const BROKER_PROTOCOL = 2;
4
4
  declare const json: z.ZodJSONSchema;
5
5
  /** A JSON value as it crosses the socket. */
6
6
  export type Json = z.infer<typeof json>;
@@ -154,6 +154,7 @@ export declare const brokerMessage: z.ZodUnion<readonly [z.ZodObject<{
154
154
  }, z.core.$strip>;
155
155
  }, z.core.$strip>, z.ZodObject<{
156
156
  kind: z.ZodLiteral<"generate">;
157
+ runId: z.ZodNumber;
157
158
  params: z.ZodJSONSchema;
158
159
  }, z.core.$strip>, z.ZodObject<{
159
160
  kind: z.ZodLiteral<"classify">;
@@ -218,7 +219,7 @@ export declare const classifyAnswers: z.ZodRecord<z.ZodString, z.ZodDiscriminate
218
219
  probability: z.ZodNumber;
219
220
  }, z.core.$strip>], "type">>;
220
221
  /** An error as it crosses the socket: a tool error keeps its code, an abort its name. */
221
- export declare function errorBodyOf(cause: unknown): ErrorBody;
222
+ export declare function errorBodyOf(cause: unknown, redact?: (value: string) => string): ErrorBody;
222
223
  /**
223
224
  * The broker's socket for one shared browser key. In the user's runtime or temp directory (0700), named by a hash of the
224
225
  * key, since a profile path can exceed the 104-byte socket path limit.
@@ -5,7 +5,8 @@ import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { z } from "zod";
7
7
  /** Bumped on any incompatible message change; a client never talks to a broker of another protocol. */
8
- export const BROKER_PROTOCOL = 1;
8
+ // Older brokers return unredacted results. Do not silently share their browser.
9
+ export const BROKER_PROTOCOL = 2;
9
10
  const json = z.json();
10
11
  /** A failed batch's progress, as BatchProgress in session.ts. */
11
12
  const batchProgress = z.object({
@@ -42,7 +43,7 @@ export const brokerMessage = z.union([
42
43
  t: z.literal("ask"), cb: z.number().int(), conv: z.string(),
43
44
  request: z.discriminatedUnion("kind", [
44
45
  z.object({ kind: z.literal("config"), context: runContext.extend({ purpose: z.enum(["browser", "ai", "jev", "ask"]) }) }),
45
- z.object({ kind: z.literal("generate"), params: json }),
46
+ z.object({ kind: z.literal("generate"), runId: z.number().int(), params: json }),
46
47
  z.object({ kind: z.literal("classify"), model: z.string(), request: json }),
47
48
  ]),
48
49
  }),
@@ -72,16 +73,19 @@ export const classifyAnswers = z.record(z.string(), z.discriminatedUnion("type",
72
73
  z.object({ type: z.literal("bool"), probability: z.number() }),
73
74
  ]));
74
75
  /** An error as it crosses the socket: a tool error keeps its code, an abort its name. */
75
- export function errorBodyOf(cause) {
76
+ export function errorBodyOf(cause, redact = (value) => value) {
76
77
  if (!(cause instanceof Error))
77
- return { name: "Error", message: String(cause) };
78
+ return { name: "Error", message: redact(String(cause)) };
78
79
  const code = "code" in cause && cause.name !== "AbortError" ? z.string().safeParse(cause.code) : undefined;
79
- const body = { name: cause.name, message: cause.message };
80
+ const body = { name: redact(cause.name), message: redact(cause.message) };
80
81
  if (code?.success)
81
- body.code = code.data;
82
+ body.code = redact(code.data);
82
83
  const batch = "batch" in cause ? batchProgress.safeParse(cause.batch) : undefined;
83
- if (batch?.success)
84
+ if (batch?.success) {
84
85
  body.batch = batch.data;
86
+ if (body.batch.error)
87
+ body.batch.error = { code: redact(body.batch.error.code), message: redact(body.batch.error.message) };
88
+ }
85
89
  return body;
86
90
  }
87
91
  /**
package/dist/broker.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { chmodSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { createServer } from "node:net";
7
7
  import { BROKER_FEATURES, BROKER_PROTOCOL, browseConfig, classifyAnswers, clientMessage, errorBodyOf, } from "./broker-protocol.js";
8
+ import { redactMetadata } from "./tool-results.js";
8
9
  import { aiParameters, browserBatchParameters } from "./schema.js";
9
10
  import { BrowseSession } from "./session.js";
10
11
  const IDLE_EXIT_MS = 30_000;
@@ -22,10 +23,10 @@ function armIdle() {
22
23
  idle = setTimeout(() => void stop(), IDLE_EXIT_MS);
23
24
  }
24
25
  /** A BrowserOutput as JSON: the image as base64, BigInt (cookie timestamps) as strings. */
25
- function encodeOutput(output) {
26
+ function encodeOutput(output, redact) {
26
27
  const { image, ...rest } = output;
27
- const text = JSON.stringify({ ...rest, image: image ? Buffer.from(image).toString("base64") : undefined }, (_key, value) => value?.constructor === BigInt ? String(value) : value);
28
- return JSON.parse(text);
28
+ return { ...redactMetadata(rest, redact),
29
+ ...(image ? { image: Buffer.from(image).toString("base64") } : {}) };
29
30
  }
30
31
  class Connection {
31
32
  socket;
@@ -76,12 +77,7 @@ class Connection {
76
77
  }
77
78
  open(message) {
78
79
  const { conv } = message;
79
- const generate = async (params) => {
80
- const value = await this.ask(conv, { kind: "generate", params: JSON.parse(JSON.stringify(params)) });
81
- // SAFETY: the client returns its own Stagehand generate() result, unchanged apart from the JSON round trip.
82
- return value;
83
- };
84
- return new BrowseSession(async ({ signal: _signal, ...context }) => browseConfig.parse(await this.ask(conv, { kind: "config", context })), message.inference ? { generate, describe: async () => "host model" } : undefined, message.classify ? async (model, request) => classifyAnswers.parse(await this.ask(conv, { kind: "classify", model, request: JSON.parse(JSON.stringify(request)) })) : undefined, message.identity, { profileBroker: false });
80
+ return new BrowseSession(async ({ signal: _signal, ...context }) => browseConfig.parse(await this.ask(conv, { kind: "config", context })), message.inference ? { describe: async () => "host model" } : undefined, message.classify ? async (model, request) => classifyAnswers.parse(await this.ask(conv, { kind: "classify", model, request: JSON.parse(JSON.stringify(request)) })) : undefined, message.identity, { profileBroker: false });
85
81
  }
86
82
  async handle(message) {
87
83
  switch (message.t) {
@@ -103,11 +99,15 @@ class Connection {
103
99
  try {
104
100
  session.defaultBackend = message.defaultBackend;
105
101
  const params = message.ai ? aiParameters.parse(message.params) : browserBatchParameters.parse(message.params);
106
- const output = await session.run(params, message.context, controller.signal, message.ai);
107
- this.send({ t: "result", id: message.id, ok: true, output: encodeOutput(output) });
102
+ const output = await session.run(params, message.context, controller.signal, message.ai && (() => async (args) => {
103
+ // Correlate callbacks to the originating run, not the conversation's latest model.
104
+ const value = await this.ask(message.conv, { kind: "generate", runId: message.id, params: JSON.parse(JSON.stringify(args)) });
105
+ return value;
106
+ }));
107
+ this.send({ t: "result", id: message.id, ok: true, output: encodeOutput(output, text => session.redact(text)) });
108
108
  }
109
109
  catch (error) {
110
- this.send({ t: "result", id: message.id, ok: false, error: errorBodyOf(error) });
110
+ this.send({ t: "result", id: message.id, ok: false, error: errorBodyOf(error, text => session.redact(text)) });
111
111
  }
112
112
  finally {
113
113
  this.controllers.delete(message.id);
@@ -0,0 +1,18 @@
1
+ /** A flattened browser DevTools connection. Responses resolve the command that sent them. */
2
+ export interface CdpEvent {
3
+ method: string;
4
+ params: any;
5
+ sessionId?: string;
6
+ }
7
+ export declare class CdpConnection {
8
+ private readonly socket;
9
+ private nextId;
10
+ private readonly pending;
11
+ onEvent?: (event: CdpEvent) => void;
12
+ private constructor();
13
+ static open(url: string, signal: AbortSignal): Promise<CdpConnection>;
14
+ get closed(): boolean;
15
+ send(method: string, params?: Record<string, unknown>, sessionId?: string): Promise<any>;
16
+ private rejectPending;
17
+ close(): void;
18
+ }
@@ -0,0 +1,59 @@
1
+ export class CdpConnection {
2
+ socket;
3
+ nextId = 0;
4
+ pending = new Map();
5
+ onEvent;
6
+ constructor(socket) {
7
+ this.socket = socket;
8
+ socket.addEventListener("message", event => {
9
+ const message = JSON.parse(String(event.data));
10
+ if (message.id === undefined) {
11
+ this.onEvent?.(message);
12
+ return;
13
+ }
14
+ const reply = this.pending.get(message.id);
15
+ if (!reply)
16
+ return;
17
+ this.pending.delete(message.id);
18
+ if (message.error)
19
+ reply.reject(new Error(message.error.message));
20
+ else
21
+ reply.resolve(message.result);
22
+ });
23
+ socket.addEventListener("close", () => this.rejectPending());
24
+ }
25
+ static async open(url, signal) {
26
+ signal.throwIfAborted();
27
+ const socket = new WebSocket(url);
28
+ const client = new CdpConnection(socket);
29
+ const abort = () => client.close();
30
+ try {
31
+ signal.addEventListener("abort", abort, { once: true });
32
+ await new Promise((resolve, reject) => {
33
+ socket.addEventListener("open", () => resolve(), { once: true });
34
+ socket.addEventListener("error", () => reject(new Error("Could not open a DevTools connection.")), { once: true });
35
+ socket.addEventListener("close", () => reject(new Error("DevTools connection closed.")), { once: true });
36
+ });
37
+ signal.throwIfAborted();
38
+ return client;
39
+ }
40
+ finally {
41
+ signal.removeEventListener("abort", abort);
42
+ }
43
+ }
44
+ get closed() { return this.socket.readyState !== this.socket.OPEN; }
45
+ send(method, params = {}, sessionId) {
46
+ if (this.closed)
47
+ return Promise.reject(new Error("DevTools connection closed."));
48
+ const id = ++this.nextId;
49
+ const result = new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
50
+ this.socket.send(JSON.stringify({ id, method, params, sessionId }));
51
+ return result;
52
+ }
53
+ rejectPending() {
54
+ for (const { reject } of this.pending.values())
55
+ reject(new Error("DevTools connection closed."));
56
+ this.pending.clear();
57
+ }
58
+ close() { this.socket.close(); this.rejectPending(); }
59
+ }
@@ -0,0 +1,101 @@
1
+ import type { BrowserParams } from "./schema.ts";
2
+ import type { HttpAuth } from "./http-auth.ts";
3
+ export interface BrowseConfig {
4
+ /** One exact origin and its credentials, resolved for an explicit isolated HTTP-auth start. */
5
+ httpAuth?: HttpAuth;
6
+ /** Allow this profile to read the initial URL's exact origin from the locally installed native helper. */
7
+ httpAuthStore?: {
8
+ hosted?: boolean;
9
+ origin?: string;
10
+ };
11
+ apiKey?: string;
12
+ projectId?: string;
13
+ model?: string;
14
+ modelApiKey?: string;
15
+ /** Vercel AI Gateway key for JEV's default classifier; resolvers should load it only for purpose "jev". */
16
+ jevApiKey?: string;
17
+ /**
18
+ * Classifier for JEV targeting: absent or `vercel` (Jev on Vercel AI Gateway), `workers-ai` (Jev 1.14 on Workers AI)
19
+ * or `workers-ai/<model>`, or a host classifier as `<provider>/<id>`.
20
+ */
21
+ jevModel?: string;
22
+ /** Classifier for ask's bool and choice fields: absent is Clef on Workers AI; takes the same values as jevModel. */
23
+ askModel?: string;
24
+ /**
25
+ * Cloudflare account and Workers AI token for ask, and for JEV on Workers AI; resolvers should load the token only for
26
+ * purposes "ask" and "jev".
27
+ */
28
+ cloudflareAccountId?: string;
29
+ cloudflareApiKey?: string;
30
+ /** Optional profile-specific file containing only saved-context identifiers. */
31
+ contextHistoryPath?: string;
32
+ /** Browserbase region for new sessions; validated against the SDK's regions. Absent uses Browserbase's default (us-west-2). */
33
+ region?: string;
34
+ /**
35
+ * Chrome user data directory for local launches, so logins and installed extensions persist across launches. Absent
36
+ * launches a temporary profile that close deletes. Only one browser can use the directory at a time.
37
+ */
38
+ localUserDataDir?: string;
39
+ /** Chrome or Chromium executable for local launches; absent uses CHROME_PATH or Stagehand's discovery of an installed Chrome. */
40
+ localExecutablePath?: string;
41
+ /**
42
+ * Bare domains, each with its subdomains, that this profile's browsers may reach; every other http(s) request fails,
43
+ * page resources included. A start can narrow the list, never widen it.
44
+ */
45
+ allowedDomains?: string[];
46
+ /** Bare domains, each with its subdomains, that this profile's browsers never reach; a start can add more. */
47
+ blockedDomains?: string[];
48
+ /** Browserbase navigation policy for hosted sessions (browserSettings.riskPolicyId); the project must enforce policies. */
49
+ navigationPolicyId?: string;
50
+ /**
51
+ * Browsers start can attach to by name (endpoint): a DevTools URL, headers for an authenticated gateway (secrets that
52
+ * never reach results), and the URL Stagehand's in-browser extension uses when the browser runs on another machine.
53
+ */
54
+ remoteBrowsers?: Record<string, RemoteBrowser>;
55
+ /**
56
+ * The user's own browser, through OpenCode Browse: `command` is the argv that runs `browse mcp`, on this machine or
57
+ * over SSH on the machine with the browser. When set, a local start that names no cdpUrl, endpoint, or headless works
58
+ * in that browser instead of launching one.
59
+ */
60
+ realBrowser?: {
61
+ command: string[];
62
+ };
63
+ }
64
+ /** A browser to attach to. extensionCdpUrl is the browser-level DevTools URL the browser itself reaches without headers. */
65
+ export interface RemoteBrowser {
66
+ cdpUrl: string;
67
+ headers?: Record<string, string>;
68
+ extensionCdpUrl?: string;
69
+ }
70
+ /** A browser's domain fence as bare domains, each covering its subdomains. */
71
+ export interface DomainLists {
72
+ allowedDomains?: string[];
73
+ blockedDomains?: string[];
74
+ }
75
+ /** The profile's domain lists, narrowed by start: start's allowed domains must fall inside the profile's, and blocked ones add up. */
76
+ export declare function domainLists(config: BrowseConfig, start: Pick<BrowserParams, "allowedDomains" | "blockedDomains">): DomainLists | undefined;
77
+ /** Why the fence refuses a URL's host, or undefined when it lets the URL through. */
78
+ export declare function fenced(url: string, lists: DomainLists | undefined): string | undefined;
79
+ /** Stagehand matches exact hosts and `*.` subdomains, so each bare domain becomes both. */
80
+ export declare function stagehandPolicy(lists: DomainLists): {
81
+ allowedDomains?: string[] | undefined;
82
+ blockedDomains?: string[] | undefined;
83
+ };
84
+ export interface ConfigurationContext {
85
+ /** Resolve origin credentials for an explicitly requested isolated launch. */
86
+ httpAuth?: true;
87
+ sessionId: string;
88
+ profile: string;
89
+ cwd: string;
90
+ signal: AbortSignal;
91
+ purpose: "browser" | "ai" | "jev" | "ask";
92
+ /** Selected browser backend; local controls do not need Browserbase credentials. */
93
+ backend?: "browserbase" | "local";
94
+ /**
95
+ * For purposes "jev" and "ask", the classifier chosen with /browse jev-model or ask-model. It replaces the returned jevModel or askModel,
96
+ * so load the credentials it needs.
97
+ */
98
+ classifier?: string;
99
+ }
100
+ export type ConfigResolver = (context: ConfigurationContext) => BrowseConfig | Promise<BrowseConfig>;
101
+ export declare function environmentConfig(scope?: Pick<ConfigurationContext, "httpAuth">): BrowseConfig;
package/dist/config.js ADDED
@@ -0,0 +1,78 @@
1
+ import { normalizeCookieDomains } from "./browser-cookies.js";
2
+ import { BrowseToolError, messageOf } from "./errors.js";
3
+ /** Whether `domain` is `parent` or one of its subdomains. */
4
+ function within(domain, parent) {
5
+ return domain === parent || domain.endsWith(`.${parent}`);
6
+ }
7
+ /** The profile's domain lists, narrowed by start: start's allowed domains must fall inside the profile's, and blocked ones add up. */
8
+ export function domainLists(config, start) {
9
+ const normalize = (domains, setting) => {
10
+ if (!domains?.length)
11
+ return undefined;
12
+ try {
13
+ return normalizeCookieDomains(domains);
14
+ }
15
+ catch (error) {
16
+ throw new BrowseToolError("configuration", `${setting}: ${messageOf(error)}`);
17
+ }
18
+ };
19
+ const profileAllowed = normalize(config.allowedDomains, "the profile's allowedDomains");
20
+ const startAllowed = normalize(start.allowedDomains, "allowedDomains");
21
+ if (profileAllowed && startAllowed) {
22
+ const outside = startAllowed.filter(domain => !profileAllowed.some(parent => within(domain, parent)));
23
+ if (outside.length)
24
+ throw new BrowseToolError("domain_policy_widened", `allowedDomains can only narrow this profile's allowed domains (${profileAllowed.join(", ")}); ${outside.join(", ")} is outside them.`);
25
+ }
26
+ const allowedDomains = startAllowed ?? profileAllowed;
27
+ const blockedDomains = [...new Set([...normalize(config.blockedDomains, "the profile's blockedDomains") ?? [], ...normalize(start.blockedDomains, "blockedDomains") ?? []])];
28
+ if (!allowedDomains && !blockedDomains.length)
29
+ return undefined;
30
+ return { ...(allowedDomains ? { allowedDomains } : {}), ...(blockedDomains.length ? { blockedDomains } : {}) };
31
+ }
32
+ /** Why the fence refuses a URL's host, or undefined when it lets the URL through. */
33
+ export function fenced(url, lists) {
34
+ if (!lists || !URL.canParse(url))
35
+ return undefined;
36
+ const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
37
+ if (lists.blockedDomains?.some(domain => within(host, domain)))
38
+ return `${host} is in this browser's blocked domains (${lists.blockedDomains.join(", ")})`;
39
+ if (lists.allowedDomains && !lists.allowedDomains.some(domain => within(host, domain)))
40
+ return `${host} is outside this browser's allowed domains (${lists.allowedDomains.join(", ")})`;
41
+ return undefined;
42
+ }
43
+ /** Stagehand matches exact hosts and `*.` subdomains, so each bare domain becomes both. */
44
+ export function stagehandPolicy(lists) {
45
+ const patterns = (domains) => domains.flatMap(domain => [domain, `*.${domain}`]);
46
+ return {
47
+ ...(lists.allowedDomains ? { allowedDomains: patterns(lists.allowedDomains) } : {}),
48
+ ...(lists.blockedDomains ? { blockedDomains: patterns(lists.blockedDomains) } : {}),
49
+ };
50
+ }
51
+ /** A comma- or space-separated domain list from the environment; empty counts as unset. */
52
+ function domainList(value) {
53
+ const domains = value?.split(/[\s,]+/).filter(Boolean);
54
+ return domains?.length ? domains : undefined;
55
+ }
56
+ export function environmentConfig(scope) {
57
+ return {
58
+ ...(scope?.httpAuth && (process.env.BROWSE_HTTP_AUTH_USERNAME || process.env.BROWSE_HTTP_AUTH_PASSWORD) ? { httpAuth: {
59
+ origin: process.env.BROWSE_HTTP_AUTH_ORIGIN ?? "", username: process.env.BROWSE_HTTP_AUTH_USERNAME ?? "",
60
+ password: process.env.BROWSE_HTTP_AUTH_PASSWORD ?? "", hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true",
61
+ } } : {}),
62
+ ...(scope?.httpAuth && process.env.BROWSE_HTTP_AUTH_USE_STORE === "true"
63
+ ? { httpAuthStore: { hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true", origin: process.env.BROWSE_HTTP_AUTH_ORIGIN } } : {}),
64
+ apiKey: process.env.BROWSERBASE_API_KEY ?? "",
65
+ projectId: process.env.BROWSERBASE_PROJECT_ID ?? "",
66
+ model: process.env.STAGEHAND_MODEL,
67
+ modelApiKey: process.env.STAGEHAND_MODEL_API_KEY,
68
+ jevApiKey: process.env.AI_GATEWAY_API_KEY,
69
+ cloudflareAccountId: process.env.CLOUDFLARE_ACCOUNT_ID,
70
+ cloudflareApiKey: process.env.CLOUDFLARE_API_KEY,
71
+ region: process.env.BROWSERBASE_REGION,
72
+ allowedDomains: domainList(process.env.BROWSE_ALLOWED_DOMAINS),
73
+ blockedDomains: domainList(process.env.BROWSE_BLOCKED_DOMAINS),
74
+ navigationPolicyId: process.env.BROWSERBASE_NAVIGATION_POLICY_ID,
75
+ jevModel: process.env.BROWSE_JEV_MODEL,
76
+ askModel: process.env.BROWSE_ASK_MODEL,
77
+ };
78
+ }
@@ -0,0 +1,10 @@
1
+ interface ContextRecord {
2
+ contextId: string;
3
+ integration: string;
4
+ projectId: string;
5
+ profile: string;
6
+ }
7
+ export declare function contextRegistry(path: string | undefined, integration: string): string;
8
+ export declare function rememberContext(path: string, record: ContextRecord): Promise<void>;
9
+ export declare function knownContext(path: string, expected: ContextRecord): Promise<boolean>;
10
+ export {};
@@ -0,0 +1,27 @@
1
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ export function contextRegistry(path, integration) {
6
+ return path ?? join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "browse-core", createHash("sha256").update(integration).digest("hex"), "contexts.jsonl");
7
+ }
8
+ export async function rememberContext(path, record) {
9
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
10
+ await appendFile(path, JSON.stringify(record) + "\n", { mode: 0o600 });
11
+ }
12
+ export async function knownContext(path, expected) {
13
+ try {
14
+ return (await readFile(path, "utf8")).split("\n").some(line => {
15
+ try {
16
+ const record = JSON.parse(line);
17
+ return Object.entries(expected).every(([k, value]) => record[k] === value);
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ });
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
@@ -0,0 +1,29 @@
1
+ /** How far a batch got. */
2
+ export interface BatchProgress {
3
+ total: number;
4
+ /** Steps confirmed to have completed; absent when a lost reply, deadline, or cancellation leaves that unknown. */
5
+ completed?: number;
6
+ /** Zero-based index of the step that stopped the batch. */
7
+ failedIndex?: number;
8
+ /** True when steps may have run without being confirmed: inspect the page before repeating anything. */
9
+ outcomeUnknown: boolean;
10
+ error?: {
11
+ code: string;
12
+ message: string;
13
+ };
14
+ }
15
+ export declare class BrowseToolError extends Error {
16
+ readonly code: string;
17
+ readonly batch?: BatchProgress | undefined;
18
+ /** `batch` is set on a failed batch call. */
19
+ constructor(code: string, message: string, batch?: BatchProgress | undefined);
20
+ }
21
+ /** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
22
+ export declare function scriptError(message: string): BrowseToolError | undefined;
23
+ export declare function messageOf(error: unknown): string;
24
+ /** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
25
+ export declare function translate(error: unknown): unknown;
26
+ export declare function abortError(message?: string): BrowseToolError;
27
+ /** Stops waiting immediately; the caller is responsible for closing the remote browser. */
28
+ export declare function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
29
+ export declare function deadline<T>(promise: Promise<T>, ms: number): Promise<T>;