@edlsh/browse-core 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/dist/broker-protocol.d.ts +3 -3
- package/dist/chrome-profile.d.ts +9 -0
- package/dist/chrome-profile.js +37 -1
- 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 +0 -2
- package/dist/session.js +53 -70
- package/package.json +11 -12
package/README.md
CHANGED
|
@@ -15,11 +15,12 @@ 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
|
+
- 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.
|
|
18
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.
|
|
19
20
|
- `ClientInference` supplies Stagehand's default inference. Without it, unconfigured AI calls use Browserbase Model Gateway.
|
|
20
21
|
- `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
|
|
21
22
|
|
|
22
|
-
Stagehand is pinned to 4.
|
|
23
|
+
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.
|
|
23
24
|
|
|
24
25
|
## Shared browsers
|
|
25
26
|
|
|
@@ -32,11 +33,11 @@ Conversations sharing a browser must agree on its launch options: a `start` aski
|
|
|
32
33
|
## Develop
|
|
33
34
|
|
|
34
35
|
```sh
|
|
35
|
-
bun install
|
|
36
|
-
bun run check
|
|
36
|
+
bun install --frozen-lockfile --ignore-scripts
|
|
37
|
+
bun run check # tests, types, build, package contents
|
|
37
38
|
CHROME_PATH=/path/to/chrome bun run test:local # real local browser
|
|
38
39
|
CHROME_PATH=/path/to/chrome bun run test:shared # two processes on one persistent profile
|
|
39
40
|
bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
|
|
40
41
|
```
|
|
41
42
|
|
|
42
|
-
Releases go through release-please; publishing uses npm trusted publishing from `publish.yml`.
|
|
43
|
+
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
|
-
browser: "browser";
|
|
117
|
-
ask: "ask";
|
|
118
116
|
ai: "ai";
|
|
117
|
+
ask: "ask";
|
|
118
|
+
browser: "browser";
|
|
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>>>;
|
package/dist/chrome-profile.d.ts
CHANGED
|
@@ -4,3 +4,12 @@
|
|
|
4
4
|
* file is not JSON Chrome would read.
|
|
5
5
|
*/
|
|
6
6
|
export declare function nameChromeProfile(userDataDir: string, name: string): Promise<void>;
|
|
7
|
+
/**
|
|
8
|
+
* Chrome caches an extension's service worker script in the profile and keeps running that copy after the extension's
|
|
9
|
+
* files change, even when the extension is loaded again. A persistent profile would so run the Stagehand extension of
|
|
10
|
+
* the SDK that first launched it, until a newer SDK refuses its protocol. When the bundled extension (its archive)
|
|
11
|
+
* differs from the one the profile last launched with, this drops the profile's service worker storage; Chrome then
|
|
12
|
+
* registers every extension's worker again from its files. Logins and extension data are kept. Skipped while a live
|
|
13
|
+
* Chrome holds the profile.
|
|
14
|
+
*/
|
|
15
|
+
export declare function refreshExtensionWorkers(userDataDir: string, extensionArchive: Uint8Array): Promise<void>;
|
package/dist/chrome-profile.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readFile, readlink, rename, rm, writeFile } from "node:fs/promises";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
/** The JSON files Chrome keeps the default profile's name in; every other key is kept as Chrome wrote it. */
|
|
@@ -50,3 +51,38 @@ export async function nameChromeProfile(userDataDir, name) {
|
|
|
50
51
|
await replace(statePath, { ...state.data, profile: { ...profile, info_cache: { ...cache, Default: { ...entry, name, is_using_default_name: false } } } });
|
|
51
52
|
await replace(preferencesPath, { ...preferences.data, profile: { ...preferences.data.profile, name, using_default_name: false } });
|
|
52
53
|
}
|
|
54
|
+
/** Whether a live Chrome holds the user data dir. SingletonLock links to `<host>-<pid>` and outlives a Chrome that was killed. */
|
|
55
|
+
async function heldByChrome(userDataDir) {
|
|
56
|
+
const holder = await readlink(join(userDataDir, "SingletonLock")).catch(() => undefined);
|
|
57
|
+
if (holder === undefined)
|
|
58
|
+
return false;
|
|
59
|
+
const pid = Number(holder.slice(holder.lastIndexOf("-") + 1));
|
|
60
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
61
|
+
return true;
|
|
62
|
+
try {
|
|
63
|
+
process.kill(pid, 0);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
return error instanceof Error && "code" in error && error.code === "EPERM";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Chrome caches an extension's service worker script in the profile and keeps running that copy after the extension's
|
|
72
|
+
* files change, even when the extension is loaded again. A persistent profile would so run the Stagehand extension of
|
|
73
|
+
* the SDK that first launched it, until a newer SDK refuses its protocol. When the bundled extension (its archive)
|
|
74
|
+
* differs from the one the profile last launched with, this drops the profile's service worker storage; Chrome then
|
|
75
|
+
* registers every extension's worker again from its files. Logins and extension data are kept. Skipped while a live
|
|
76
|
+
* Chrome holds the profile.
|
|
77
|
+
*/
|
|
78
|
+
export async function refreshExtensionWorkers(userDataDir, extensionArchive) {
|
|
79
|
+
if (await heldByChrome(userDataDir))
|
|
80
|
+
return;
|
|
81
|
+
const marker = join(userDataDir, "stagehand-extension.sha256");
|
|
82
|
+
const digest = createHash("sha256").update(extensionArchive).digest("hex");
|
|
83
|
+
if (await readJson(marker) === digest)
|
|
84
|
+
return;
|
|
85
|
+
await rm(join(userDataDir, "Default", "Service Worker"), { recursive: true, force: true });
|
|
86
|
+
await mkdir(userDataDir, { recursive: true, mode: 0o700 });
|
|
87
|
+
await writeFile(marker, digest, { mode: 0o600 });
|
|
88
|
+
}
|
|
@@ -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
|
@@ -195,8 +195,6 @@ export declare class BrowseSession {
|
|
|
195
195
|
* dropped connection; "ended" once the remote session is gone; "unresponsive" otherwise.
|
|
196
196
|
*/
|
|
197
197
|
private liveness;
|
|
198
|
-
/** Attaches Stagehand to a reconnected browser, first idling the runtime the lost connection left initialized. */
|
|
199
|
-
private attach;
|
|
200
198
|
/**
|
|
201
199
|
* After a deadline or cancellation: keep a browser that still answers, release one that does not. A browser that
|
|
202
200
|
* answers while the action's tab does not is kept, so other tabs and logins survive.
|
package/dist/session.js
CHANGED
|
@@ -10,14 +10,13 @@ import { z } from "zod";
|
|
|
10
10
|
import { askNeeds, askPage, DECIDE_TEXT } from "./ask.js";
|
|
11
11
|
import { guardEndpoint } from "./cdp-guard.js";
|
|
12
12
|
import { HarRecorder } from "./har.js";
|
|
13
|
-
import { nameChromeProfile } from "./chrome-profile.js";
|
|
13
|
+
import { nameChromeProfile, refreshExtensionWorkers } 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
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)
|
|
@@ -619,7 +637,7 @@ export class BrowseSession {
|
|
|
619
637
|
let browser, stagehand;
|
|
620
638
|
try {
|
|
621
639
|
browser = await connectRetrying(() => browserbase.connect({ apiKey: session.config.apiKey, sessionId }), context.signal);
|
|
622
|
-
stagehand = await
|
|
640
|
+
stagehand = await createStagehand(browser, this.stagehandModel, context.signal);
|
|
623
641
|
}
|
|
624
642
|
catch (error) {
|
|
625
643
|
context.signal.throwIfAborted();
|
|
@@ -665,23 +683,6 @@ export class BrowseSession {
|
|
|
665
683
|
}
|
|
666
684
|
}
|
|
667
685
|
}
|
|
668
|
-
/** Attaches Stagehand to a reconnected browser, first idling the runtime the lost connection left initialized. */
|
|
669
|
-
async attach(browser, connectUrl, signal) {
|
|
670
|
-
for (let attempt = 0;; attempt++) {
|
|
671
|
-
try {
|
|
672
|
-
return await Stagehand.create({ browser, logging: { level: "off" }, ...this.stagehandModel });
|
|
673
|
-
}
|
|
674
|
-
catch (error) {
|
|
675
|
-
if (!/already initialized/i.test(messageOf(error)) || !connectUrl || attempt >= 4)
|
|
676
|
-
throw error;
|
|
677
|
-
// The runtime disposes asynchronously; later attempts only wait for it.
|
|
678
|
-
if (attempt === 0)
|
|
679
|
-
await resetStagehandRuntime(connectUrl, signal);
|
|
680
|
-
else
|
|
681
|
-
await delay(250, undefined, { signal });
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
686
|
/**
|
|
686
687
|
* After a deadline or cancellation: keep a browser that still answers, release one that does not. A browser that
|
|
687
688
|
* answers while the action's tab does not is kept, so other tabs and logins survive.
|
|
@@ -914,7 +915,7 @@ export class BrowseSession {
|
|
|
914
915
|
context.signal.throwIfAborted();
|
|
915
916
|
if (this.session !== session)
|
|
916
917
|
throw abortError();
|
|
917
|
-
// 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.
|
|
918
919
|
const [, active] = await Promise.all([browser.context.addInitScript(DIALOG_GUARD), browser.context.activePage(),
|
|
919
920
|
session.domainPolicy ? browser.context.setDomainPolicy(stagehandPolicy(session.domainPolicy)) : undefined]);
|
|
920
921
|
session.tabId = active?.pageId;
|
|
@@ -1002,13 +1003,16 @@ export class BrowseSession {
|
|
|
1002
1003
|
throw error;
|
|
1003
1004
|
return undefined;
|
|
1004
1005
|
});
|
|
1005
|
-
// Stagehand's in-browser extension
|
|
1006
|
-
|
|
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;
|
|
1007
1010
|
try {
|
|
1008
|
-
browser = await connectRetrying(() => localBrowser.connect({ cdpUrl: opened.url,
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
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.`);
|
|
1012
1016
|
});
|
|
1013
1017
|
}
|
|
1014
1018
|
catch (error) {
|
|
@@ -1019,6 +1023,7 @@ export class BrowseSession {
|
|
|
1019
1023
|
else {
|
|
1020
1024
|
// The avatar and profile menu then say which harness owns the window; a profile Chrome cannot rename still launches.
|
|
1021
1025
|
await nameChromeProfile(userDataDir, `${this.identity.name} browse`).catch(() => undefined);
|
|
1026
|
+
await refreshExtensionWorkers(userDataDir, await getExtensionArchive());
|
|
1022
1027
|
quitPort = await freePort();
|
|
1023
1028
|
browser = await localBrowser.launch({
|
|
1024
1029
|
headless: p.headless ?? false, viewport: { width: 1280, height: 800 },
|
|
@@ -1042,18 +1047,8 @@ export class BrowseSession {
|
|
|
1042
1047
|
let stagehand;
|
|
1043
1048
|
try {
|
|
1044
1049
|
context.signal.throwIfAborted();
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
stagehand = await Stagehand.create({ browser, logging: { level: "off" }, ...model });
|
|
1048
|
-
}
|
|
1049
|
-
catch (error) {
|
|
1050
|
-
// A client that died while attached leaves the browser's runtime initialized; this process now owns it.
|
|
1051
|
-
if (!guard || attempt > 0 || !/already initialized/i.test(messageOf(error)))
|
|
1052
|
-
throw error;
|
|
1053
|
-
await resetStagehandRuntime(guard.url, context.signal);
|
|
1054
|
-
}
|
|
1055
|
-
}
|
|
1056
|
-
// The fence goes up before any page loads; Stagehand intercepts every http(s) request in the context.
|
|
1050
|
+
stagehand = await createStagehand(browser, model, context.signal);
|
|
1051
|
+
// The fence goes up before any page loads; Stagehand enforces it on every http(s) request the browser makes.
|
|
1057
1052
|
const [, active] = await Promise.all([browser.context.addInitScript(DIALOG_GUARD), browser.context.activePage(),
|
|
1058
1053
|
domainPolicy ? browser.context.setDomainPolicy(stagehandPolicy(domainPolicy)) : undefined]);
|
|
1059
1054
|
context.signal.throwIfAborted();
|
|
@@ -1064,11 +1059,7 @@ export class BrowseSession {
|
|
|
1064
1059
|
};
|
|
1065
1060
|
}
|
|
1066
1061
|
catch (error) {
|
|
1067
|
-
await
|
|
1068
|
-
if (quitPort)
|
|
1069
|
-
await deadline(quitChrome(quitPort), 5000).catch(() => undefined);
|
|
1070
|
-
await deadline(browser.close(), 5000).catch(() => undefined);
|
|
1071
|
-
await guard?.close();
|
|
1062
|
+
await release({ browser, stagehand, quitPort, guard }).catch(() => undefined);
|
|
1072
1063
|
throw error;
|
|
1073
1064
|
}
|
|
1074
1065
|
}
|
|
@@ -1080,15 +1071,7 @@ export class BrowseSession {
|
|
|
1080
1071
|
if (!shared.closing) {
|
|
1081
1072
|
shared.closing = (async () => {
|
|
1082
1073
|
await before?.().catch(() => undefined);
|
|
1083
|
-
await
|
|
1084
|
-
if (shared.quitPort)
|
|
1085
|
-
await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
|
|
1086
|
-
try {
|
|
1087
|
-
await deadline(shared.browser.close(), 5000);
|
|
1088
|
-
}
|
|
1089
|
-
finally {
|
|
1090
|
-
await shared.guard?.close();
|
|
1091
|
-
}
|
|
1074
|
+
await release(shared);
|
|
1092
1075
|
})();
|
|
1093
1076
|
const settled = shared.closing.catch(() => undefined);
|
|
1094
1077
|
retiringBrowsers.set(shared.key, settled);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@edlsh/browse-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
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
|
}
|