@edlsh/browse-core 0.2.0 → 0.2.2
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 +1 -1
- package/dist/session.d.ts +1 -5
- package/dist/session.js +51 -30
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ Stagehand is pinned to 4.3.0 and used unmodified. `overrides` forces zod 4.6.7 b
|
|
|
24
24
|
|
|
25
25
|
New browsers start locally unless the host or the profile's `/browse backend` setting chooses Browserbase.
|
|
26
26
|
|
|
27
|
-
A persistent profile (`localUserDataDir`) and an attached browser (`cdpUrl` or a named endpoint) are shared: any number of conversations, in one process or several (omp, pi, and Hermes at once), drive the same browser without closing it under each other. Stagehand's in-browser runtime admits one client, so the first conversation starts a broker (`dist/broker.js`, one detached process per browser, socket under `$XDG_RUNTIME_DIR` or the temp directory, mode 0600) that owns the browser and runs every conversation's calls on it. Each conversation
|
|
27
|
+
A persistent profile (`localUserDataDir`) and an attached browser (`cdpUrl` or a named endpoint) are shared: any number of conversations, in one process or several (omp, pi, and Hermes at once), drive the same browser without closing it under each other. Stagehand's in-browser runtime admits one client, so the first conversation starts a broker (`dist/broker.js`, one detached process per browser, socket under `$XDG_RUNTIME_DIR` or the temp directory, mode 0600) that owns the browser and runs every conversation's calls on it. Each conversation works in a tab of its own (the launcher takes a launched profile's first tab), with its own refs and selected tab. In an attached browser the user's tabs are left alone unless a conversation selects one by `tabId`. Another conversation's tabs are hidden from `tabs` and `tab_select`, and `har_start` records only its own. A `browse_ai` call runs on the caller's own inference, one call at a time. `close` closes only the caller's tabs. The last conversation to leave quits a launched profile (so its cookies are written) or disconnects from an attached browser, and the broker exits 30 s after its last client.
|
|
28
28
|
|
|
29
29
|
Conversations sharing a browser must agree on its launch options: a `start` asking for a different `headless` mode, or different allowed or blocked domains, gets `shared_browser`. Temporary-profile launches stay private to their conversation. `BrowseSessionOptions.profileBroker: false` keeps shared browsers in-process (the broker uses this for itself).
|
|
30
30
|
|
package/dist/session.d.ts
CHANGED
|
@@ -219,11 +219,7 @@ export declare class BrowseSession {
|
|
|
219
219
|
private current;
|
|
220
220
|
private start;
|
|
221
221
|
private initialize;
|
|
222
|
-
/**
|
|
223
|
-
* Joins the browser this process shares for a persistent profile or an attached browser, opening it first if needed.
|
|
224
|
-
* The launching conversation takes Chrome's first tab and later ones open their own; in an attached browser the
|
|
225
|
-
* user's tabs stay available and a conversation claims one on first use.
|
|
226
|
-
*/
|
|
222
|
+
/** Joins the browser this process shares for a persistent profile or an attached browser, opening it first if needed. */
|
|
227
223
|
private joinShared;
|
|
228
224
|
/** Launches a persistent profile or attaches to a browser, with one Stagehand whose default inference follows the AI turn. */
|
|
229
225
|
private openShared;
|
package/dist/session.js
CHANGED
|
@@ -185,6 +185,21 @@ function messageOf(error) {
|
|
|
185
185
|
* @browserbasehq/stagehand.
|
|
186
186
|
*/
|
|
187
187
|
async function resetStagehandRuntime(connectUrl, signal) {
|
|
188
|
+
await withRawCdp(connectUrl, signal, async (send) => {
|
|
189
|
+
const { targetInfos } = await send("Target.getTargets");
|
|
190
|
+
const workers = targetInfos
|
|
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);
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
|
|
202
|
+
async function withRawCdp(connectUrl, signal, use) {
|
|
188
203
|
const socket = new WebSocket(connectUrl);
|
|
189
204
|
const pending = new Map();
|
|
190
205
|
let nextId = 0;
|
|
@@ -208,26 +223,31 @@ async function resetStagehandRuntime(connectUrl, signal) {
|
|
|
208
223
|
const send = (method, params = {}, sessionId) => {
|
|
209
224
|
const id = ++nextId;
|
|
210
225
|
const reply = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
|
|
211
|
-
socket.send(JSON.stringify({ id, method, params,
|
|
226
|
+
socket.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
|
|
212
227
|
return abortable(Promise.race([reply, closed]), signal);
|
|
213
228
|
};
|
|
214
229
|
try {
|
|
215
230
|
await abortable(Promise.race([new Promise(resolve => socket.addEventListener("open", resolve, { once: true })), closed]), signal);
|
|
216
|
-
|
|
217
|
-
const workers = targetInfos
|
|
218
|
-
.filter(target => target.type === "service_worker" && target.url.startsWith("chrome-extension://") && target.url.includes("service-worker.js"));
|
|
219
|
-
// The reply reaches whichever client is attached next, whose request ids count up from 1: use one it never reaches.
|
|
220
|
-
const close = JSON.stringify(JSON.stringify({ jsonrpc: "2.0", id: Number.MAX_SAFE_INTEGER, method: "stagehand.close", params: {} }));
|
|
221
|
-
for (const worker of workers) {
|
|
222
|
-
const { sessionId } = await send("Target.attachToTarget", { targetId: worker.targetId, flatten: true });
|
|
223
|
-
// Optional call: only the Stagehand runtime defines this receiver.
|
|
224
|
-
await send("Runtime.evaluate", { expression: `void globalThis.__stagehandReceiveFromHost?.(${close}); true`, returnByValue: true }, sessionId);
|
|
225
|
-
}
|
|
231
|
+
return await use(send);
|
|
226
232
|
}
|
|
227
233
|
finally {
|
|
228
234
|
socket.close();
|
|
229
235
|
}
|
|
230
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Opens a window with a blank tab in a running browser that has no tab, and returns its id; else undefined. macOS
|
|
239
|
+
* Chrome keeps running after its last window closes, and in that state no client can create a tab, so Stagehand cannot
|
|
240
|
+
* attach. The tab belongs to whoever attaches, whose close removes it again.
|
|
241
|
+
*/
|
|
242
|
+
async function ensurePageTarget(connectUrl, signal) {
|
|
243
|
+
return withRawCdp(connectUrl, signal, async (send) => {
|
|
244
|
+
const { targetInfos } = await send("Target.getTargets");
|
|
245
|
+
if (targetInfos.some(target => target.type === "page"))
|
|
246
|
+
return undefined;
|
|
247
|
+
const { targetId } = await send("Target.createTarget", { url: "about:blank", newWindow: true });
|
|
248
|
+
return z.string().parse(targetId);
|
|
249
|
+
});
|
|
250
|
+
}
|
|
231
251
|
/** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
|
|
232
252
|
function translate(error) {
|
|
233
253
|
if (error instanceof BrowseToolError)
|
|
@@ -896,11 +916,7 @@ export class BrowseSession {
|
|
|
896
916
|
throw error;
|
|
897
917
|
}
|
|
898
918
|
}
|
|
899
|
-
/**
|
|
900
|
-
* Joins the browser this process shares for a persistent profile or an attached browser, opening it first if needed.
|
|
901
|
-
* The launching conversation takes Chrome's first tab and later ones open their own; in an attached browser the
|
|
902
|
-
* user's tabs stay available and a conversation claims one on first use.
|
|
903
|
-
*/
|
|
919
|
+
/** Joins the browser this process shares for a persistent profile or an attached browser, opening it first if needed. */
|
|
904
920
|
async joinShared(context, config, p, domainPolicy, attach, userDataDir) {
|
|
905
921
|
const key = attach ? `attach:${attach.cdpUrl}` : `launch:${userDataDir}`;
|
|
906
922
|
let shared;
|
|
@@ -938,19 +954,14 @@ export class BrowseSession {
|
|
|
938
954
|
endpoint: shared.endpoint, headless: shared.headless, debugPort: shared.debugPort, snapshots: new Map(), keepAlive: false,
|
|
939
955
|
domainPolicy: shared.domainPolicy, shared, ownedTabs: new Set(), createdTabs: new Set(),
|
|
940
956
|
};
|
|
957
|
+
// Every conversation works in a tab of its own, which close removes: the launcher takes Chrome's first tab, and
|
|
958
|
+
// in an attached browser the user's tabs stay untouched unless a conversation selects one by id.
|
|
941
959
|
const first = shared.firstTab;
|
|
942
960
|
shared.firstTab = undefined;
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
session.tabId = tab;
|
|
948
|
-
}
|
|
949
|
-
else {
|
|
950
|
-
const active = await shared.browser.context.activePage();
|
|
951
|
-
if (active && !this.ownedByOther(session, active.pageId))
|
|
952
|
-
session.tabId = active.pageId;
|
|
953
|
-
}
|
|
961
|
+
const tab = first ?? (await shared.browser.context.newPage("about:blank")).pageId;
|
|
962
|
+
session.ownedTabs.add(tab);
|
|
963
|
+
session.createdTabs.add(tab);
|
|
964
|
+
session.tabId = tab;
|
|
954
965
|
shared.users.add(session);
|
|
955
966
|
this.session = session;
|
|
956
967
|
return session;
|
|
@@ -967,6 +978,8 @@ export class BrowseSession {
|
|
|
967
978
|
let browser;
|
|
968
979
|
let guard;
|
|
969
980
|
let quitPort;
|
|
981
|
+
/** A tab opened in an attached browser that had none; the first conversation takes it as its own. */
|
|
982
|
+
let createdTab;
|
|
970
983
|
if (attach) {
|
|
971
984
|
// Stagehand's close() would send Browser.close to an attached browser: connect through a guard that drops it.
|
|
972
985
|
const opened = await guardEndpoint(attach.cdpUrl, context.signal, attach.headers).catch(error => {
|
|
@@ -975,6 +988,11 @@ export class BrowseSession {
|
|
|
975
988
|
throw new BrowseToolError("attach_failed", `Could not reach the DevTools endpoint: ${messageOf(error).slice(0, 200)}. Check cdpUrl and any headers it needs.`);
|
|
976
989
|
});
|
|
977
990
|
guard = opened;
|
|
991
|
+
createdTab = await ensurePageTarget(opened.url, context.signal).catch(error => {
|
|
992
|
+
if (context.signal.aborted)
|
|
993
|
+
throw error;
|
|
994
|
+
return undefined;
|
|
995
|
+
});
|
|
978
996
|
// Stagehand's in-browser extension would follow the client to the loopback guard, which a browser elsewhere cannot reach.
|
|
979
997
|
const extensionCdpUrl = attach.extensionCdpUrl ?? (!LOOPBACK.has(new URL(attach.cdpUrl).hostname) ? opened.browserUrl : undefined);
|
|
980
998
|
try {
|
|
@@ -1032,7 +1050,7 @@ export class BrowseSession {
|
|
|
1032
1050
|
context.signal.throwIfAborted();
|
|
1033
1051
|
return {
|
|
1034
1052
|
key, browser, stagehand, quitPort, debugPort: quitPort, guard, cdpUrl: attach?.cdpUrl, endpoint: p.endpoint,
|
|
1035
|
-
headless: attach ? undefined : p.headless ?? false, domainPolicy, users: new Set(), closedTabs: new Set(), firstTab: attach ?
|
|
1053
|
+
headless: attach ? undefined : p.headless ?? false, domainPolicy, users: new Set(), closedTabs: new Set(), firstTab: attach ? createdTab : active?.pageId,
|
|
1036
1054
|
inference, aiTurn: Promise.resolve(),
|
|
1037
1055
|
};
|
|
1038
1056
|
}
|
|
@@ -1204,9 +1222,12 @@ export class BrowseSession {
|
|
|
1204
1222
|
async page(session, tabId) {
|
|
1205
1223
|
const pages = await this.visiblePages(session);
|
|
1206
1224
|
const id = tabId ?? session.tabId;
|
|
1207
|
-
|
|
1225
|
+
// In a shared browser only a tab chosen by id is taken over; no conversation drifts into the user's or a closed one.
|
|
1226
|
+
const page = id ? pages.find(page => page.pageId === id) : pages.find(page => session.ownedTabs.has(page.pageId)) ?? (session.shared ? undefined : pages[0]);
|
|
1208
1227
|
if (!page) {
|
|
1209
|
-
throw new BrowseToolError("tab_missing",
|
|
1228
|
+
throw new BrowseToolError("tab_missing", session.shared
|
|
1229
|
+
? "This conversation has no tab here, or the target tab is closed or another conversation's. Open one with tab_new, or select one of the listed tabs by tabId."
|
|
1230
|
+
: "The target tab is closed or missing. List tabs, select an existing tab, or create a new one.");
|
|
1210
1231
|
}
|
|
1211
1232
|
if (!session.tabId)
|
|
1212
1233
|
session.tabId = page.pageId;
|
package/package.json
CHANGED