@edlsh/browse-core 0.7.0 → 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 (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 +101 -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 +9 -3
  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 +1 -1
  22. package/dist/real-browser-client.js +1 -1
  23. package/dist/real-browser-session.d.ts +1 -1
  24. package/dist/real-browser-session.js +24 -5
  25. package/dist/schema.d.ts +32 -0
  26. package/dist/schema.js +22 -6
  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 +134 -350
  31. package/dist/settings.js +47 -6
  32. package/dist/tool-results.d.ts +28 -0
  33. package/dist/tool-results.js +40 -0
  34. package/extensions/http-auth/README.md +27 -0
  35. package/extensions/http-auth/background.js +85 -0
  36. package/extensions/http-auth/manifest.json +27 -0
  37. package/extensions/http-auth/native/README.md +31 -0
  38. package/extensions/http-auth/native/host.py +97 -0
  39. package/extensions/http-auth/native/install.py +62 -0
  40. package/extensions/http-auth/options.html +25 -0
  41. package/extensions/http-auth/options.js +36 -0
  42. package/extensions/http-auth/origin.js +16 -0
  43. package/package.json +13 -2
@@ -0,0 +1,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. */