@edlsh/browse-core 0.2.2 → 0.4.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 +5 -4
- package/dist/broker-protocol.d.ts +2 -2
- package/dist/browser-cookies.d.ts +28 -0
- package/dist/browser-cookies.js +34 -0
- package/dist/page-operations.d.ts +2 -2
- package/dist/schema.d.ts +35 -35
- package/dist/schema.js +1 -1
- package/dist/session.d.ts +6 -4
- package/dist/session.js +80 -91
- package/package.json +11 -12
package/README.md
CHANGED
|
@@ -15,10 +15,11 @@ const output = await browser.run(browserParameters.parse({ action: "start", back
|
|
|
15
15
|
|
|
16
16
|
- `HostIdentity.name` appears in user-facing messages ("Use the MyHost model…") and names persistent local Chrome profiles `<name> browse` before each launch, so the toolbar avatar shows which harness owns a window. `integration` tags Browserbase session metadata, names the HAR `creator`, and prefixes the default HAR temp directory.
|
|
17
17
|
- `nameChromeProfile(userDataDir, name)` sets that name on a profile the host launches itself; it leaves a profile Chrome holds untouched.
|
|
18
|
+
- `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.
|
|
18
19
|
- `ClientInference` supplies Stagehand's default inference. Without it, unconfigured AI calls use Browserbase Model Gateway.
|
|
19
20
|
- `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
|
|
20
21
|
|
|
21
|
-
Stagehand is pinned to 4.
|
|
22
|
+
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.
|
|
22
23
|
|
|
23
24
|
## Shared browsers
|
|
24
25
|
|
|
@@ -31,11 +32,11 @@ Conversations sharing a browser must agree on its launch options: a `start` aski
|
|
|
31
32
|
## Develop
|
|
32
33
|
|
|
33
34
|
```sh
|
|
34
|
-
bun install
|
|
35
|
-
bun run check
|
|
35
|
+
bun install --frozen-lockfile --ignore-scripts
|
|
36
|
+
bun run check # tests, types, build, package contents
|
|
36
37
|
CHROME_PATH=/path/to/chrome bun run test:local # real local browser
|
|
37
38
|
CHROME_PATH=/path/to/chrome bun run test:shared # two processes on one persistent profile
|
|
38
39
|
bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
|
|
39
40
|
```
|
|
40
41
|
|
|
41
|
-
Releases go through release-please; publishing uses npm trusted publishing from `publish.yml`.
|
|
42
|
+
Releases go through release-please; publishing uses npm trusted publishing from `publish.yml`. See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
@@ -113,9 +113,9 @@ export declare const brokerMessage: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
113
113
|
}>>;
|
|
114
114
|
classifier: z.ZodOptional<z.ZodString>;
|
|
115
115
|
purpose: z.ZodEnum<{
|
|
116
|
+
ai: "ai";
|
|
116
117
|
ask: "ask";
|
|
117
118
|
browser: "browser";
|
|
118
|
-
ai: "ai";
|
|
119
119
|
jev: "jev";
|
|
120
120
|
}>;
|
|
121
121
|
}, z.core.$strip>;
|
|
@@ -169,8 +169,8 @@ export declare const classifyRequest: z.ZodObject<{
|
|
|
169
169
|
}, z.core.$strip>], "type">>;
|
|
170
170
|
images: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
171
171
|
mimeType: z.ZodEnum<{
|
|
172
|
-
"image/png": "image/png";
|
|
173
172
|
"image/jpeg": "image/jpeg";
|
|
173
|
+
"image/png": "image/png";
|
|
174
174
|
}>;
|
|
175
175
|
data: z.ZodString;
|
|
176
176
|
}, z.core.$strip>>>;
|
|
@@ -98,3 +98,31 @@ export declare function readBrowserCookies(source: CookieSource, profile: string
|
|
|
98
98
|
readPassword?: (signal: AbortSignal) => Promise<string>;
|
|
99
99
|
cacheKey?: boolean;
|
|
100
100
|
}): Promise<BrowserCookies>;
|
|
101
|
+
/** One browser and its profiles, as cookie_profiles lists them. */
|
|
102
|
+
export interface CookieBrowser {
|
|
103
|
+
browser: BrowserId;
|
|
104
|
+
name: string;
|
|
105
|
+
profiles: {
|
|
106
|
+
profile: string;
|
|
107
|
+
name?: string;
|
|
108
|
+
}[];
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Where cookie_import and cookie_profiles read cookies. The default reads this Mac's browsers; a host whose browsers are
|
|
112
|
+
* elsewhere (Hermes reading the MacBook's Helium from Linux) supplies its own. Errors it throws reach the agent as written.
|
|
113
|
+
*/
|
|
114
|
+
export interface CookieProvider {
|
|
115
|
+
/** Browsers and profiles cookies can come from, optionally only one browser. */
|
|
116
|
+
list(browser: BrowserId | undefined, signal: AbortSignal): Promise<CookieBrowser[]>;
|
|
117
|
+
/** Profiles holding importable cookies for the domains, most first. */
|
|
118
|
+
find(domains: string[], browser: BrowserId | undefined, signal: AbortSignal): Promise<BrowserProfileMatch[]>;
|
|
119
|
+
/** The profile's unexpired cookies for the domains, decrypted. */
|
|
120
|
+
read(browser: BrowserId, profile: string, domains: string[], signal: AbortSignal): Promise<BrowserCookies>;
|
|
121
|
+
}
|
|
122
|
+
/** A cookie source refusal with a stable code, which the session reports as a tool error. */
|
|
123
|
+
export declare class CookieSourceError extends Error {
|
|
124
|
+
readonly code: string;
|
|
125
|
+
constructor(code: string, message: string);
|
|
126
|
+
}
|
|
127
|
+
/** This Mac's installed browsers; the Keychain key is unlocked once per process and kept in memory. */
|
|
128
|
+
export declare const localCookieProvider: CookieProvider;
|
package/dist/browser-cookies.js
CHANGED
|
@@ -259,3 +259,37 @@ export async function readBrowserCookies(source, profile, domains, signal, optio
|
|
|
259
259
|
key?.fill(0);
|
|
260
260
|
}
|
|
261
261
|
}
|
|
262
|
+
/** Installed supported browsers, optionally only the requested one. */
|
|
263
|
+
async function localSources(browser) {
|
|
264
|
+
const installed = await installedBrowsers();
|
|
265
|
+
const sources = browser ? installed.filter(source => source.browser === browser) : installed;
|
|
266
|
+
if (sources.length)
|
|
267
|
+
return sources;
|
|
268
|
+
const supported = BROWSERS.map(entry => entry.name).join(", ");
|
|
269
|
+
throw new CookieSourceError("browser_not_installed", browser
|
|
270
|
+
? `${BROWSERS.find(entry => entry.id === browser).name} is not installed in /Applications or ~/Applications. Call cookie_profiles to see the installed browsers.`
|
|
271
|
+
: `No supported browser is installed in /Applications or ~/Applications. Supported browsers: ${supported}.`);
|
|
272
|
+
}
|
|
273
|
+
/** A cookie source refusal with a stable code, which the session reports as a tool error. */
|
|
274
|
+
export class CookieSourceError extends Error {
|
|
275
|
+
code;
|
|
276
|
+
constructor(code, message) {
|
|
277
|
+
super(message);
|
|
278
|
+
this.code = code;
|
|
279
|
+
this.name = "CookieSourceError";
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/** This Mac's installed browsers; the Keychain key is unlocked once per process and kept in memory. */
|
|
283
|
+
export const localCookieProvider = {
|
|
284
|
+
async list(browser) {
|
|
285
|
+
return Promise.all((await localSources(browser)).map(async (source) => ({ browser: source.browser, name: source.name,
|
|
286
|
+
profiles: (await listBrowserProfiles(source)).map(({ profile, name }) => name ? { profile, name } : { profile }) })));
|
|
287
|
+
},
|
|
288
|
+
async find(domains, browser, signal) {
|
|
289
|
+
return findBrowserProfiles(domains, signal, await localSources(browser));
|
|
290
|
+
},
|
|
291
|
+
async read(browser, profile, domains, signal) {
|
|
292
|
+
const [source] = await localSources(browser);
|
|
293
|
+
return readBrowserCookies(source, profile, domains, signal, { cacheKey: true });
|
|
294
|
+
},
|
|
295
|
+
};
|
|
@@ -41,9 +41,9 @@ export declare function tabsOperation({ context }: Pick<ExperimentalBatchContext
|
|
|
41
41
|
selectedTabId: string | null;
|
|
42
42
|
readTimeoutMs: number;
|
|
43
43
|
}): Promise<{
|
|
44
|
-
selected: boolean;
|
|
45
|
-
responsive?: boolean | undefined;
|
|
46
44
|
tabId: string;
|
|
47
45
|
url: string;
|
|
48
46
|
title: string | null;
|
|
47
|
+
responsive?: boolean | undefined;
|
|
48
|
+
selected: boolean;
|
|
49
49
|
}[]>;
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
export declare const browserParameters: z.ZodObject<{
|
|
3
3
|
action: z.ZodEnum<{
|
|
4
|
-
fill: "fill";
|
|
5
|
-
status: "status";
|
|
6
|
-
close: "close";
|
|
7
|
-
start: "start";
|
|
8
|
-
open: "open";
|
|
9
|
-
back: "back";
|
|
10
|
-
forward: "forward";
|
|
11
|
-
reload: "reload";
|
|
12
|
-
snapshot: "snapshot";
|
|
13
4
|
ask: "ask";
|
|
5
|
+
back: "back";
|
|
14
6
|
click: "click";
|
|
15
|
-
|
|
16
|
-
press: "press";
|
|
17
|
-
scroll: "scroll";
|
|
18
|
-
wait: "wait";
|
|
19
|
-
screenshot: "screenshot";
|
|
20
|
-
evaluate: "evaluate";
|
|
21
|
-
tabs: "tabs";
|
|
22
|
-
tab_new: "tab_new";
|
|
23
|
-
tab_select: "tab_select";
|
|
24
|
-
tab_close: "tab_close";
|
|
25
|
-
live_view: "live_view";
|
|
7
|
+
close: "close";
|
|
26
8
|
context_create: "context_create";
|
|
27
|
-
cookie_profiles: "cookie_profiles";
|
|
28
9
|
cookie_import: "cookie_import";
|
|
10
|
+
cookie_profiles: "cookie_profiles";
|
|
11
|
+
evaluate: "evaluate";
|
|
12
|
+
fill: "fill";
|
|
13
|
+
forward: "forward";
|
|
29
14
|
har_start: "har_start";
|
|
30
15
|
har_stop: "har_stop";
|
|
16
|
+
live_view: "live_view";
|
|
17
|
+
open: "open";
|
|
18
|
+
press: "press";
|
|
19
|
+
reload: "reload";
|
|
20
|
+
screenshot: "screenshot";
|
|
21
|
+
scroll: "scroll";
|
|
22
|
+
select: "select";
|
|
23
|
+
snapshot: "snapshot";
|
|
24
|
+
start: "start";
|
|
25
|
+
status: "status";
|
|
26
|
+
tab_close: "tab_close";
|
|
27
|
+
tab_new: "tab_new";
|
|
28
|
+
tab_select: "tab_select";
|
|
29
|
+
tabs: "tabs";
|
|
30
|
+
wait: "wait";
|
|
31
31
|
}>;
|
|
32
32
|
backend: z.ZodOptional<z.ZodEnum<{
|
|
33
33
|
browserbase: "browserbase";
|
|
@@ -46,14 +46,14 @@ export declare const browserParameters: z.ZodObject<{
|
|
|
46
46
|
proxyCountry: z.ZodOptional<z.ZodString>;
|
|
47
47
|
name: z.ZodOptional<z.ZodString>;
|
|
48
48
|
browser: z.ZodOptional<z.ZodEnum<{
|
|
49
|
+
arc: "arc";
|
|
50
|
+
brave: "brave";
|
|
49
51
|
chrome: "chrome";
|
|
50
52
|
chromium: "chromium";
|
|
51
|
-
brave: "brave";
|
|
52
53
|
edge: "edge";
|
|
53
|
-
arc: "arc";
|
|
54
|
-
vivaldi: "vivaldi";
|
|
55
|
-
opera: "opera";
|
|
56
54
|
helium: "helium";
|
|
55
|
+
opera: "opera";
|
|
56
|
+
vivaldi: "vivaldi";
|
|
57
57
|
}>>;
|
|
58
58
|
domains: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
59
59
|
profile: z.ZodOptional<z.ZodString>;
|
|
@@ -69,38 +69,38 @@ export declare const browserParameters: z.ZodObject<{
|
|
|
69
69
|
y: z.ZodOptional<z.ZodNumber>;
|
|
70
70
|
durationMs: z.ZodOptional<z.ZodNumber>;
|
|
71
71
|
loadState: z.ZodOptional<z.ZodEnum<{
|
|
72
|
-
load: "load";
|
|
73
72
|
domcontentloaded: "domcontentloaded";
|
|
73
|
+
load: "load";
|
|
74
74
|
networkidle: "networkidle";
|
|
75
75
|
}>>;
|
|
76
76
|
state: z.ZodOptional<z.ZodEnum<{
|
|
77
77
|
attached: "attached";
|
|
78
78
|
detached: "detached";
|
|
79
|
-
visible: "visible";
|
|
80
79
|
hidden: "hidden";
|
|
80
|
+
visible: "visible";
|
|
81
81
|
}>>;
|
|
82
82
|
script: z.ZodOptional<z.ZodString>;
|
|
83
83
|
fullPage: z.ZodOptional<z.ZodBoolean>;
|
|
84
84
|
maxChars: z.ZodOptional<z.ZodNumber>;
|
|
85
85
|
fields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
86
86
|
type: z.ZodEnum<{
|
|
87
|
-
number: "number";
|
|
88
|
-
choice: "choice";
|
|
89
87
|
bool: "bool";
|
|
88
|
+
choice: "choice";
|
|
90
89
|
date: "date";
|
|
91
|
-
text: "text";
|
|
92
90
|
datetime: "datetime";
|
|
93
91
|
duration: "duration";
|
|
92
|
+
number: "number";
|
|
93
|
+
text: "text";
|
|
94
94
|
}>;
|
|
95
95
|
instructions: z.ZodString;
|
|
96
96
|
options: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
97
97
|
unit: z.ZodOptional<z.ZodEnum<{
|
|
98
|
-
seconds: "seconds";
|
|
99
|
-
minutes: "minutes";
|
|
100
|
-
hours: "hours";
|
|
101
98
|
days: "days";
|
|
102
|
-
|
|
99
|
+
hours: "hours";
|
|
100
|
+
minutes: "minutes";
|
|
103
101
|
months: "months";
|
|
102
|
+
seconds: "seconds";
|
|
103
|
+
weeks: "weeks";
|
|
104
104
|
years: "years";
|
|
105
105
|
}>>;
|
|
106
106
|
}, z.core.$strict>>>;
|
|
@@ -110,8 +110,8 @@ export declare const browserParameters: z.ZodObject<{
|
|
|
110
110
|
export declare const aiParameters: z.ZodObject<{
|
|
111
111
|
action: z.ZodEnum<{
|
|
112
112
|
act: "act";
|
|
113
|
-
observe: "observe";
|
|
114
113
|
extract: "extract";
|
|
114
|
+
observe: "observe";
|
|
115
115
|
}>;
|
|
116
116
|
instruction: z.ZodString;
|
|
117
117
|
tabId: z.ZodOptional<z.ZodString>;
|
package/dist/schema.js
CHANGED
|
@@ -55,7 +55,7 @@ export const browserParameters = z.object({
|
|
|
55
55
|
return !url.username && !url.password && !url.hash;
|
|
56
56
|
}, "cdpUrl must be an http(s) or ws(s) endpoint without credentials or a fragment; send credentials in headers").optional().describe("Only for start with backend local. Attach to this explicitly supplied DevTools endpoint, on this machine or another; close disconnects without terminating the browser. Omit to launch an isolated browser."),
|
|
57
57
|
headers: z.record(z.string().regex(/^[A-Za-z0-9-]{1,64}$/), z.string().min(1).max(4096)).optional().describe("Only with cdpUrl: HTTP headers an authenticated DevTools gateway needs, e.g. {\"Authorization\":\"Bearer <token>\"}. Sent only to cdpUrl's host; values never appear in results."),
|
|
58
|
-
extensionCdpUrl: z.url({ protocol: /^wss?$/ }).optional().describe("Only with cdpUrl for a browser on another machine or behind a gateway: the browser-level DevTools WebSocket URL the browser itself reaches without headers, e.g. ws://127.0.0.1:9222/devtools/browser/<id>. Default
|
|
58
|
+
extensionCdpUrl: z.url({ protocol: /^wss?$/ }).optional().describe("Only with cdpUrl for a browser on another machine or behind a gateway: the browser-level DevTools WebSocket URL the browser itself reaches without headers, e.g. ws://127.0.0.1:9222/devtools/browser/<id>. Default: the URL the browser reports."),
|
|
59
59
|
endpoint: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional().describe("Only for start with backend local: attach to the remote browser this profile configures under that name, which supplies its cdpUrl, headers, and extensionCdpUrl."),
|
|
60
60
|
headless: z.boolean().optional().describe("Only for a local launch with start. Default false (visible window); cannot be used with cdpUrl."),
|
|
61
61
|
tabId: z.string().min(1).optional().describe("Target tab ID; defaults to the selected tab. Required for tab_select/tab_close."),
|
package/dist/session.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Stagehand } from "@browserbasehq/stagehand";
|
|
2
2
|
import type { AIParams, BrowserParams } from "./schema.ts";
|
|
3
|
+
import { type CookieProvider } from "./browser-cookies.ts";
|
|
3
4
|
import { type HostClassify } from "./classifier.ts";
|
|
4
5
|
export interface BrowseConfig {
|
|
5
6
|
apiKey?: string;
|
|
@@ -82,6 +83,8 @@ export interface BrowseSessionOptions {
|
|
|
82
83
|
* conversations in other processes can use them at the same time. Default true; the broker turns it off for itself.
|
|
83
84
|
*/
|
|
84
85
|
profileBroker?: boolean;
|
|
86
|
+
/** Where cookie_import and cookie_profiles read cookies; default, this Mac's installed browsers. */
|
|
87
|
+
cookies?: CookieProvider;
|
|
85
88
|
}
|
|
86
89
|
/** A page script that answered a native dialog, as reported in tool output. */
|
|
87
90
|
export interface AnsweredDialog {
|
|
@@ -148,6 +151,7 @@ export declare class BrowseSession {
|
|
|
148
151
|
/** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
|
|
149
152
|
private keepAliveAllowed;
|
|
150
153
|
private readonly profileBroker;
|
|
154
|
+
private readonly cookies;
|
|
151
155
|
/** This conversation's calls run in the broker that owns its shared browser, until close. */
|
|
152
156
|
private delegate?;
|
|
153
157
|
/** Stagehand's runtime extension, uploaded once per tool instance instead of on every launch. */
|
|
@@ -191,8 +195,6 @@ export declare class BrowseSession {
|
|
|
191
195
|
* dropped connection; "ended" once the remote session is gone; "unresponsive" otherwise.
|
|
192
196
|
*/
|
|
193
197
|
private liveness;
|
|
194
|
-
/** Attaches Stagehand to a reconnected browser, first idling the runtime the lost connection left initialized. */
|
|
195
|
-
private attach;
|
|
196
198
|
/**
|
|
197
199
|
* After a deadline or cancellation: keep a browser that still answers, release one that does not. A browser that
|
|
198
200
|
* answers while the action's tab does not is kept, so other tabs and logins survive.
|
|
@@ -249,8 +251,8 @@ export declare class BrowseSession {
|
|
|
249
251
|
private reference;
|
|
250
252
|
private target;
|
|
251
253
|
private output;
|
|
252
|
-
/**
|
|
253
|
-
private
|
|
254
|
+
/** A cookie provider call, with its refusals as tool errors. */
|
|
255
|
+
private fromCookies;
|
|
254
256
|
/** The browser profile to import from: the one given, or the only one with importable cookies for the domains; several leave the choice to the agent's task context. */
|
|
255
257
|
private cookieProfile;
|
|
256
258
|
private browse;
|
package/dist/session.js
CHANGED
|
@@ -14,10 +14,9 @@ import { nameChromeProfile } from "./chrome-profile.js";
|
|
|
14
14
|
import { BrokerConnection } from "./broker-client.js";
|
|
15
15
|
import { randomUUID } from "node:crypto";
|
|
16
16
|
import { pageOperation, tabsOperation } from "./page-operations.js";
|
|
17
|
-
import {
|
|
17
|
+
import { CookieSourceError, localCookieProvider, normalizeCookieDomains } from "./browser-cookies.js";
|
|
18
18
|
import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, pickTarget, treeCandidates } from "./jev.js";
|
|
19
19
|
import { CLEF, classifierName, ClassifierRefusal, classifierSpec, takesImages, VERCEL_JEV, vercelClassifier, WORKERS_AI_JEV, workersAiClassifier } from "./classifier.js";
|
|
20
|
-
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
21
20
|
/** Whether `domain` is `parent` or one of its subdomains. */
|
|
22
21
|
function within(domain, parent) {
|
|
23
22
|
return domain === parent || domain.endsWith(`.${parent}`);
|
|
@@ -178,25 +177,20 @@ function messageOf(error) {
|
|
|
178
177
|
return error instanceof Error ? error.message : String(error);
|
|
179
178
|
}
|
|
180
179
|
/**
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
* runtime's own stagehand.close over a short raw CDP connection, on the same wire Stagehand's client uses
|
|
184
|
-
* (a Runtime.evaluate of __stagehandReceiveFromHost in the extension's service worker). Recheck when upgrading
|
|
185
|
-
* @browserbasehq/stagehand.
|
|
180
|
+
* Stagehand on a browser another client may just have left. The in-browser runtime releases a lost or detached client's
|
|
181
|
+
* instance asynchronously, so a create that arrives first sees it still initialized and is retried.
|
|
186
182
|
*/
|
|
187
|
-
async function
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
.filter(target => target.type === "service_worker" && target.url.startsWith("chrome-extension://") && target.url.includes("service-worker.js"));
|
|
192
|
-
// The reply reaches whichever client is attached next, whose request ids count up from 1: use one it never reaches.
|
|
193
|
-
const close = JSON.stringify(JSON.stringify({ jsonrpc: "2.0", id: Number.MAX_SAFE_INTEGER, method: "stagehand.close", params: {} }));
|
|
194
|
-
for (const worker of workers) {
|
|
195
|
-
const { sessionId } = await send("Target.attachToTarget", { targetId: worker.targetId, flatten: true });
|
|
196
|
-
// Optional call: only the Stagehand runtime defines this receiver.
|
|
197
|
-
await send("Runtime.evaluate", { expression: `void globalThis.__stagehandReceiveFromHost?.(${close}); true`, returnByValue: true }, sessionId);
|
|
183
|
+
async function createStagehand(browser, model, signal) {
|
|
184
|
+
for (let attempt = 0;; attempt++) {
|
|
185
|
+
try {
|
|
186
|
+
return await Stagehand.create({ browser, logging: { level: "off" }, ...model });
|
|
198
187
|
}
|
|
199
|
-
|
|
188
|
+
catch (error) {
|
|
189
|
+
if (attempt >= 4 || !/already initialized/i.test(messageOf(error)))
|
|
190
|
+
throw error;
|
|
191
|
+
await delay(250, undefined, { signal });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
200
194
|
}
|
|
201
195
|
/** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
|
|
202
196
|
async function withRawCdp(connectUrl, signal, use) {
|
|
@@ -248,6 +242,25 @@ async function ensurePageTarget(connectUrl, signal) {
|
|
|
248
242
|
return z.string().parse(targetId);
|
|
249
243
|
});
|
|
250
244
|
}
|
|
245
|
+
/**
|
|
246
|
+
* Lets go of a shared local browser. An attached one is disconnected, which closes Stagehand's instance in it and leaves
|
|
247
|
+
* the browser running for the next client; a launched profile's Chrome is quit so it writes its cookies.
|
|
248
|
+
*/
|
|
249
|
+
async function release(shared) {
|
|
250
|
+
if (shared.guard) {
|
|
251
|
+
try {
|
|
252
|
+
await deadline(shared.browser.disconnect(), 5000);
|
|
253
|
+
}
|
|
254
|
+
finally {
|
|
255
|
+
await shared.guard.close();
|
|
256
|
+
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
await deadline(shared.stagehand?.close() ?? Promise.resolve(), 1500).catch(() => undefined);
|
|
260
|
+
if (shared.quitPort)
|
|
261
|
+
await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
|
|
262
|
+
await deadline(shared.browser.close(), 5000);
|
|
263
|
+
}
|
|
251
264
|
/** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
|
|
252
265
|
function translate(error) {
|
|
253
266
|
if (error instanceof BrowseToolError)
|
|
@@ -259,6 +272,11 @@ function translate(error) {
|
|
|
259
272
|
return new BrowseToolError("tab_missing", "The tab closed or navigated away during the action. List tabs, select one, and take a snapshot.");
|
|
260
273
|
if (/^Connection error\.?$/.test(message))
|
|
261
274
|
return new BrowseToolError("network_error", "Could not reach Browserbase. Retry once; if it persists, check this machine's network.");
|
|
275
|
+
// Stagehand admits one client per browser and refuses a second while the first is connected.
|
|
276
|
+
if (/A Stagehand client is already connected/.test(message))
|
|
277
|
+
return new BrowseToolError("browser_in_use", "Another Stagehand client is connected to this browser, and a browser takes one at a time: a conversation on another machine, or another tool. Close the browser there, then start again.");
|
|
278
|
+
if (/does not support the client watchdog|requires Chrome 137 or later/.test(message))
|
|
279
|
+
return new BrowseToolError("attach_failed", "This browser cannot take this version of Stagehand: it needs Chrome 137 or newer and the Stagehand extension this tool ships. Update the browser and reinstall the extension in it, then start again.");
|
|
262
280
|
// Stagehand's own per-request limit: the tab stopped answering, typically a busy script.
|
|
263
281
|
const rpc = /^RPC response timed out: (\S+)/.exec(message);
|
|
264
282
|
if (rpc)
|
|
@@ -394,6 +412,7 @@ export class BrowseSession {
|
|
|
394
412
|
/** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
|
|
395
413
|
keepAliveAllowed = true;
|
|
396
414
|
profileBroker;
|
|
415
|
+
cookies;
|
|
397
416
|
/** This conversation's calls run in the broker that owns its shared browser, until close. */
|
|
398
417
|
delegate;
|
|
399
418
|
/** Stagehand's runtime extension, uploaded once per tool instance instead of on every launch. */
|
|
@@ -408,6 +427,7 @@ export class BrowseSession {
|
|
|
408
427
|
this.hostClassify = hostClassify;
|
|
409
428
|
this.identity = identity;
|
|
410
429
|
this.profileBroker = options.profileBroker ?? true;
|
|
430
|
+
this.cookies = options.cookies ?? localCookieProvider;
|
|
411
431
|
this.stagehandModel = inference ? { model: { generate: inference.generate } } : {};
|
|
412
432
|
this.describeInference = inference?.describe ?? (async () => "gateway-auto");
|
|
413
433
|
}
|
|
@@ -533,6 +553,10 @@ export class BrowseSession {
|
|
|
533
553
|
if (!this.delegate && !this.session && this.profileBroker && !ai && OPENS_BROWSER.has(params.action)) {
|
|
534
554
|
// SAFETY: only browse actions open a browser, and browse_ai calls were excluded above.
|
|
535
555
|
const key = await this.sharedKey(params, context);
|
|
556
|
+
// The broker reads cookies with its own machine's browsers, not a host's provider.
|
|
557
|
+
if (key && params.action === "cookie_import" && this.cookies !== localCookieProvider) {
|
|
558
|
+
throw new BrowseToolError("unsupported_backend", "This host's cookie source imports into Browserbase sessions only. Start with backend \"browserbase\", then cookie_import.");
|
|
559
|
+
}
|
|
536
560
|
if (key) {
|
|
537
561
|
const connection = await BrokerConnection.for(key);
|
|
538
562
|
const conv = randomUUID();
|
|
@@ -540,6 +564,9 @@ export class BrowseSession {
|
|
|
540
564
|
this.delegate = { conv, owner: this.owner(context), connection };
|
|
541
565
|
}
|
|
542
566
|
}
|
|
567
|
+
if (this.delegate && !ai && params.action === "cookie_import" && this.cookies !== localCookieProvider) {
|
|
568
|
+
throw new BrowseToolError("unsupported_backend", "This host's cookie source imports into Browserbase sessions only. Close, start with backend \"browserbase\", then cookie_import.");
|
|
569
|
+
}
|
|
543
570
|
if (this.delegate)
|
|
544
571
|
return this.forward(params, context, ai);
|
|
545
572
|
const attempt = () => ai ? this.ai(params, context) : this.browse(params, context);
|
|
@@ -610,7 +637,7 @@ export class BrowseSession {
|
|
|
610
637
|
let browser, stagehand;
|
|
611
638
|
try {
|
|
612
639
|
browser = await connectRetrying(() => browserbase.connect({ apiKey: session.config.apiKey, sessionId }), context.signal);
|
|
613
|
-
stagehand = await
|
|
640
|
+
stagehand = await createStagehand(browser, this.stagehandModel, context.signal);
|
|
614
641
|
}
|
|
615
642
|
catch (error) {
|
|
616
643
|
context.signal.throwIfAborted();
|
|
@@ -656,23 +683,6 @@ export class BrowseSession {
|
|
|
656
683
|
}
|
|
657
684
|
}
|
|
658
685
|
}
|
|
659
|
-
/** Attaches Stagehand to a reconnected browser, first idling the runtime the lost connection left initialized. */
|
|
660
|
-
async attach(browser, connectUrl, signal) {
|
|
661
|
-
for (let attempt = 0;; attempt++) {
|
|
662
|
-
try {
|
|
663
|
-
return await Stagehand.create({ browser, logging: { level: "off" }, ...this.stagehandModel });
|
|
664
|
-
}
|
|
665
|
-
catch (error) {
|
|
666
|
-
if (!/already initialized/i.test(messageOf(error)) || !connectUrl || attempt >= 4)
|
|
667
|
-
throw error;
|
|
668
|
-
// The runtime disposes asynchronously; later attempts only wait for it.
|
|
669
|
-
if (attempt === 0)
|
|
670
|
-
await resetStagehandRuntime(connectUrl, signal);
|
|
671
|
-
else
|
|
672
|
-
await delay(250, undefined, { signal });
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
686
|
/**
|
|
677
687
|
* After a deadline or cancellation: keep a browser that still answers, release one that does not. A browser that
|
|
678
688
|
* answers while the action's tab does not is kept, so other tabs and logins survive.
|
|
@@ -905,7 +915,7 @@ export class BrowseSession {
|
|
|
905
915
|
context.signal.throwIfAborted();
|
|
906
916
|
if (this.session !== session)
|
|
907
917
|
throw abortError();
|
|
908
|
-
// The fence goes up before any page loads; Stagehand
|
|
918
|
+
// The fence goes up before any page loads; Stagehand enforces it on every http(s) request the browser makes.
|
|
909
919
|
const [, active] = await Promise.all([browser.context.addInitScript(DIALOG_GUARD), browser.context.activePage(),
|
|
910
920
|
session.domainPolicy ? browser.context.setDomainPolicy(stagehandPolicy(session.domainPolicy)) : undefined]);
|
|
911
921
|
session.tabId = active?.pageId;
|
|
@@ -993,13 +1003,16 @@ export class BrowseSession {
|
|
|
993
1003
|
throw error;
|
|
994
1004
|
return undefined;
|
|
995
1005
|
});
|
|
996
|
-
// Stagehand's in-browser extension
|
|
997
|
-
|
|
1006
|
+
// Stagehand's in-browser extension keeps a connection of its own to the browser, over which it notices a client
|
|
1007
|
+
// that went away. It uses the URL the browser reported, not the guard: a browser elsewhere cannot reach the
|
|
1008
|
+
// guard, and one that ends with this process would take the extension's connection down with the client's.
|
|
1009
|
+
const extensionCdpUrl = attach.extensionCdpUrl ?? opened.browserUrl;
|
|
998
1010
|
try {
|
|
999
|
-
browser = await connectRetrying(() => localBrowser.connect({ cdpUrl: opened.url,
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1011
|
+
browser = await connectRetrying(() => localBrowser.connect({ cdpUrl: opened.url, extensionCdpUrl }), context.signal).catch(error => {
|
|
1012
|
+
const known = translate(error);
|
|
1013
|
+
if (known instanceof BrowseToolError)
|
|
1014
|
+
throw known;
|
|
1015
|
+
throw new BrowseToolError("attach_failed", `Could not attach to the browser: ${messageOf(error).slice(0, 300)} Stagehand's extension must be installed in that browser, and extensionCdpUrl must be a DevTools URL the browser itself reaches without headers.`);
|
|
1003
1016
|
});
|
|
1004
1017
|
}
|
|
1005
1018
|
catch (error) {
|
|
@@ -1033,18 +1046,8 @@ export class BrowseSession {
|
|
|
1033
1046
|
let stagehand;
|
|
1034
1047
|
try {
|
|
1035
1048
|
context.signal.throwIfAborted();
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
stagehand = await Stagehand.create({ browser, logging: { level: "off" }, ...model });
|
|
1039
|
-
}
|
|
1040
|
-
catch (error) {
|
|
1041
|
-
// A client that died while attached leaves the browser's runtime initialized; this process now owns it.
|
|
1042
|
-
if (!guard || attempt > 0 || !/already initialized/i.test(messageOf(error)))
|
|
1043
|
-
throw error;
|
|
1044
|
-
await resetStagehandRuntime(guard.url, context.signal);
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
// The fence goes up before any page loads; Stagehand intercepts every http(s) request in the context.
|
|
1049
|
+
stagehand = await createStagehand(browser, model, context.signal);
|
|
1050
|
+
// The fence goes up before any page loads; Stagehand enforces it on every http(s) request the browser makes.
|
|
1048
1051
|
const [, active] = await Promise.all([browser.context.addInitScript(DIALOG_GUARD), browser.context.activePage(),
|
|
1049
1052
|
domainPolicy ? browser.context.setDomainPolicy(stagehandPolicy(domainPolicy)) : undefined]);
|
|
1050
1053
|
context.signal.throwIfAborted();
|
|
@@ -1055,11 +1058,7 @@ export class BrowseSession {
|
|
|
1055
1058
|
};
|
|
1056
1059
|
}
|
|
1057
1060
|
catch (error) {
|
|
1058
|
-
await
|
|
1059
|
-
if (quitPort)
|
|
1060
|
-
await deadline(quitChrome(quitPort), 5000).catch(() => undefined);
|
|
1061
|
-
await deadline(browser.close(), 5000).catch(() => undefined);
|
|
1062
|
-
await guard?.close();
|
|
1061
|
+
await release({ browser, stagehand, quitPort, guard }).catch(() => undefined);
|
|
1063
1062
|
throw error;
|
|
1064
1063
|
}
|
|
1065
1064
|
}
|
|
@@ -1071,15 +1070,7 @@ export class BrowseSession {
|
|
|
1071
1070
|
if (!shared.closing) {
|
|
1072
1071
|
shared.closing = (async () => {
|
|
1073
1072
|
await before?.().catch(() => undefined);
|
|
1074
|
-
await
|
|
1075
|
-
if (shared.quitPort)
|
|
1076
|
-
await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
|
|
1077
|
-
try {
|
|
1078
|
-
await deadline(shared.browser.close(), 5000);
|
|
1079
|
-
}
|
|
1080
|
-
finally {
|
|
1081
|
-
await shared.guard?.close();
|
|
1082
|
-
}
|
|
1073
|
+
await release(shared);
|
|
1083
1074
|
})();
|
|
1084
1075
|
const settled = shared.closing.catch(() => undefined);
|
|
1085
1076
|
retiringBrowsers.set(shared.key, settled);
|
|
@@ -1364,28 +1355,27 @@ export class BrowseSession {
|
|
|
1364
1355
|
...(data === undefined ? {} : { data }),
|
|
1365
1356
|
};
|
|
1366
1357
|
}
|
|
1367
|
-
/**
|
|
1368
|
-
async
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1358
|
+
/** A cookie provider call, with its refusals as tool errors. */
|
|
1359
|
+
async fromCookies(read) {
|
|
1360
|
+
try {
|
|
1361
|
+
return await read();
|
|
1362
|
+
}
|
|
1363
|
+
catch (error) {
|
|
1364
|
+
if (error instanceof CookieSourceError)
|
|
1365
|
+
throw new BrowseToolError(error.code, error.message);
|
|
1366
|
+
throw error;
|
|
1367
|
+
}
|
|
1377
1368
|
}
|
|
1378
1369
|
/** The browser profile to import from: the one given, or the only one with importable cookies for the domains; several leave the choice to the agent's task context. */
|
|
1379
1370
|
async cookieProfile(p, signal) {
|
|
1380
|
-
const sources = await this.cookieSources(p.browser);
|
|
1381
1371
|
if (p.browser && p.profile)
|
|
1382
|
-
return {
|
|
1383
|
-
const matches = (await
|
|
1372
|
+
return { browser: p.browser, profile: p.profile };
|
|
1373
|
+
const matches = (await this.fromCookies(() => this.cookies.find(p.domains, p.browser, signal))).filter(match => !p.profile || match.profile === p.profile);
|
|
1384
1374
|
if (matches.length === 1)
|
|
1385
|
-
return {
|
|
1386
|
-
const names = sources.map(source => source.name).join(", ");
|
|
1375
|
+
return { browser: matches[0].browser, profile: matches[0].profile };
|
|
1387
1376
|
if (!matches.length) {
|
|
1388
|
-
|
|
1377
|
+
const names = (await this.fromCookies(() => this.cookies.list(p.browser, signal))).map(browser => browser.name).join(", ");
|
|
1378
|
+
throw new BrowseToolError("cookies_not_found", `No ${p.profile ? `${p.profile} profile` : "profile"} in the user's browsers (${names}) has unexpired cookies for these domains, so the user is not signed in there. Ask the user to sign in to the site in their browser for this task and tell you when done, then call cookie_import again and reload. Do not use live_view.`);
|
|
1389
1379
|
}
|
|
1390
1380
|
const listed = matches.map(match => `${match.browser} ${match.profile}${match.name ? ` (${match.name})` : ""}: ${match.cookies} cookies`).join("; ");
|
|
1391
1381
|
throw new BrowseToolError("cookie_profile_ambiguous", `Several browser profiles have cookies for these domains: ${listed}. Retry with browser and profile set to the one matching the task's account or organization; if the task does not say, ask the user which one.`);
|
|
@@ -1395,8 +1385,7 @@ export class BrowseSession {
|
|
|
1395
1385
|
const budget = operationTimeout(p, false);
|
|
1396
1386
|
const pageTimeout = Math.ceil(Math.max(budget - 2_000, budget / 2));
|
|
1397
1387
|
if (p.action === "cookie_profiles") {
|
|
1398
|
-
const browsers = await
|
|
1399
|
-
profiles: (await listBrowserProfiles(source)).map(({ profile, name }) => name ? { profile, name } : { profile }) })));
|
|
1388
|
+
const browsers = await this.fromCookies(() => this.cookies.list(p.browser, context.signal));
|
|
1400
1389
|
return { action: p.action, sessionId: null, data: { browsers } };
|
|
1401
1390
|
}
|
|
1402
1391
|
if (p.action === "status") {
|
|
@@ -1464,8 +1453,8 @@ export class BrowseSession {
|
|
|
1464
1453
|
throw new BrowseToolError("unsupported_backend", "live_view is Browserbase-only. Use the visible local browser window for user hand-off, then take a new snapshot.");
|
|
1465
1454
|
}
|
|
1466
1455
|
if (cookieSource) {
|
|
1467
|
-
const {
|
|
1468
|
-
const imported = await
|
|
1456
|
+
const { browser, profile } = cookieSource;
|
|
1457
|
+
const imported = await this.fromCookies(() => this.cookies.read(browser, profile, p.domains, context.signal));
|
|
1469
1458
|
// Imported values stay redacted from this binding's later output, e.g. evaluate reading document.cookie.
|
|
1470
1459
|
// ponytail: values under 8 characters are too generic to redact without mangling ordinary output.
|
|
1471
1460
|
for (const { value } of imported.cookies)
|
|
@@ -1485,7 +1474,7 @@ export class BrowseSession {
|
|
|
1485
1474
|
session.snapshots.clear();
|
|
1486
1475
|
}
|
|
1487
1476
|
}
|
|
1488
|
-
return this.output(p.action, session, undefined, { browser
|
|
1477
|
+
return this.output(p.action, session, undefined, { browser, profile, domains: imported.domains,
|
|
1489
1478
|
matched: imported.matched, imported: imported.cookies.length, skipped: imported.skipped,
|
|
1490
1479
|
reloadRequired: imported.cookies.length > 0, persistedOnClose: Boolean(session.contextId || session.quitPort || session.shared?.quitPort) });
|
|
1491
1480
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@edlsh/browse-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Host-neutral browser core (Browserbase, local Chrome, remote CDP, Stagehand) shared by omp-browse, pi-browse, and hermes-browse",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"browser",
|
|
@@ -37,10 +37,12 @@
|
|
|
37
37
|
"LICENSE"
|
|
38
38
|
],
|
|
39
39
|
"scripts": {
|
|
40
|
-
"
|
|
40
|
+
"test": "bun test",
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
41
42
|
"build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/node-sqlite.d.ts dist/",
|
|
43
|
+
"check:package": "node scripts/check-package.mjs",
|
|
44
|
+
"check": "bun run test && bun run typecheck && bun run build && bun run check:package",
|
|
42
45
|
"prepublishOnly": "bun run build",
|
|
43
|
-
"test": "bun test",
|
|
44
46
|
"test:local": "bun test/local-browser.integration.ts",
|
|
45
47
|
"test:hosted": "bun test/hosted-browser.integration.ts",
|
|
46
48
|
"test:shared": "bun test/shared-profile.integration.ts"
|
|
@@ -50,18 +52,15 @@
|
|
|
50
52
|
"bun": ">=1.3.14"
|
|
51
53
|
},
|
|
52
54
|
"dependencies": {
|
|
53
|
-
"@browserbasehq/sdk": "2.
|
|
54
|
-
"@browserbasehq/stagehand": "4.
|
|
55
|
-
"tldts": "7.
|
|
56
|
-
"ws": "8.
|
|
57
|
-
"zod": "4.6.
|
|
58
|
-
},
|
|
59
|
-
"overrides": {
|
|
60
|
-
"zod": "4.6.7"
|
|
55
|
+
"@browserbasehq/sdk": "2.26.0",
|
|
56
|
+
"@browserbasehq/stagehand": "4.4.0",
|
|
57
|
+
"tldts": "7.5.1",
|
|
58
|
+
"ws": "8.23.0",
|
|
59
|
+
"zod": "4.6.6"
|
|
61
60
|
},
|
|
62
61
|
"devDependencies": {
|
|
63
62
|
"@types/bun": "1.4.4",
|
|
64
63
|
"@types/ws": "8.18.2",
|
|
65
|
-
"typescript": "
|
|
64
|
+
"typescript": "7.0.2"
|
|
66
65
|
}
|
|
67
66
|
}
|