@edlsh/browse-core 0.1.0 → 0.2.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 +11 -1
- package/dist/broker-client.d.ts +39 -0
- package/dist/broker-client.js +254 -0
- package/dist/broker-protocol.d.ts +194 -0
- package/dist/broker-protocol.js +90 -0
- package/dist/broker.d.ts +1 -0
- package/dist/broker.js +225 -0
- package/dist/chrome-profile.d.ts +6 -0
- package/dist/chrome-profile.js +52 -0
- package/dist/har.d.ts +8 -2
- package/dist/har.js +19 -6
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/schema.js +1 -1
- package/dist/session.d.ts +38 -2
- package/dist/session.js +344 -62
- package/package.json +3 -2
package/dist/session.js
CHANGED
|
@@ -10,6 +10,9 @@ 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";
|
|
14
|
+
import { BrokerConnection } from "./broker-client.js";
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
13
16
|
import { pageOperation, tabsOperation } from "./page-operations.js";
|
|
14
17
|
import { BROWSERS, findBrowserProfiles, installedBrowsers, listBrowserProfiles, normalizeCookieDomains, readBrowserCookies } from "./browser-cookies.js";
|
|
15
18
|
import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, pickTarget, treeCandidates } from "./jev.js";
|
|
@@ -68,6 +71,8 @@ const REGIONS = ["us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1"];
|
|
|
68
71
|
const JEV_DEFAULT = { service: "vercel", model: VERCEL_JEV };
|
|
69
72
|
/** ask's bool and choice classifier unless askModel names another: Clef on Workers AI. */
|
|
70
73
|
const ASK_DEFAULT = { service: "workers-ai", model: CLEF };
|
|
74
|
+
/** Actions that open a browser when none is open. */
|
|
75
|
+
const OPENS_BROWSER = new Set(["start", "open", "tab_new", "cookie_import", "har_start"]);
|
|
71
76
|
/** Hard cap on a remote session's life. close and the host's session shutdown release it sooner; this bounds a leak after a crash. */
|
|
72
77
|
const SESSION_LIFETIME_SECONDS = 3600;
|
|
73
78
|
/** Stagehand's errors once the transport to the remote browser is gone. */
|
|
@@ -304,6 +309,10 @@ export class BrowseToolError extends Error {
|
|
|
304
309
|
this.code = code;
|
|
305
310
|
}
|
|
306
311
|
}
|
|
312
|
+
/** Shared browsers by key (`launch:<userDataDir>` or `attach:<cdpUrl>`), for every BrowseSession in this process. */
|
|
313
|
+
const sharedBrowsers = new Map();
|
|
314
|
+
/** A shared browser still quitting; a new launch of the same profile waits for Chrome to release it. */
|
|
315
|
+
const retiringBrowsers = new Map();
|
|
307
316
|
function abortError(message = "Operation cancelled.") {
|
|
308
317
|
return new BrowseToolError("cancelled", message);
|
|
309
318
|
}
|
|
@@ -364,17 +373,21 @@ export class BrowseSession {
|
|
|
364
373
|
secrets = new Set();
|
|
365
374
|
/** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
|
|
366
375
|
keepAliveAllowed = true;
|
|
376
|
+
profileBroker;
|
|
377
|
+
/** This conversation's calls run in the broker that owns its shared browser, until close. */
|
|
378
|
+
delegate;
|
|
367
379
|
/** Stagehand's runtime extension, uploaded once per tool instance instead of on every launch. */
|
|
368
380
|
extension;
|
|
369
381
|
/** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
|
|
370
382
|
stagehandModel;
|
|
371
383
|
describeInference;
|
|
372
|
-
/** 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. */
|
|
373
|
-
defaultBackend = "
|
|
374
|
-
constructor(resolveConfig = environmentConfig, inference, hostClassify, identity = { name: "Host", integration: "browse-core" }) {
|
|
384
|
+
/** 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. */
|
|
385
|
+
defaultBackend = "local";
|
|
386
|
+
constructor(resolveConfig = environmentConfig, inference, hostClassify, identity = { name: "Host", integration: "browse-core" }, options = {}) {
|
|
375
387
|
this.resolveConfig = resolveConfig;
|
|
376
388
|
this.hostClassify = hostClassify;
|
|
377
389
|
this.identity = identity;
|
|
390
|
+
this.profileBroker = options.profileBroker ?? true;
|
|
378
391
|
this.stagehandModel = inference ? { model: { generate: inference.generate } } : {};
|
|
379
392
|
this.describeInference = inference?.describe ?? (async () => "gateway-auto");
|
|
380
393
|
}
|
|
@@ -411,6 +424,8 @@ export class BrowseSession {
|
|
|
411
424
|
try {
|
|
412
425
|
if (this.session && this.session.owner !== this.owner(scope))
|
|
413
426
|
await this.closeOwned();
|
|
427
|
+
if (this.delegate && this.delegate.owner !== this.owner(scope))
|
|
428
|
+
await this.dropDelegate();
|
|
414
429
|
controller.signal.throwIfAborted();
|
|
415
430
|
return await abortable(this.dispatch(params, scope, isAi), controller.signal);
|
|
416
431
|
}
|
|
@@ -420,6 +435,9 @@ export class BrowseSession {
|
|
|
420
435
|
if (!controller.signal.aborted || generation !== this.generation)
|
|
421
436
|
throw error;
|
|
422
437
|
const timedOut = error instanceof BrowseToolError && error.code === "timeout";
|
|
438
|
+
// The broker keeps or releases a shared browser by its own deadline; only the outcome here is unknown.
|
|
439
|
+
if (this.delegate)
|
|
440
|
+
throw new BrowseToolError(timedOut ? "timeout" : "cancelled", `${timedOut ? "Operation timed out" : "Operation cancelled"}; the action may have completed. Take a snapshot before retrying.`);
|
|
423
441
|
const kept = await this.keepIfResponsive(params.tabId);
|
|
424
442
|
throw new BrowseToolError(timedOut ? "timeout" : "cancelled", `${timedOut ? "Operation timed out" : "Operation cancelled"}; the action may have completed. ${{
|
|
425
443
|
kept: "The browser still responds and was kept: take a snapshot before retrying.",
|
|
@@ -441,7 +459,7 @@ export class BrowseSession {
|
|
|
441
459
|
this.generation++;
|
|
442
460
|
this.active?.abort(abortError("The conversation ended; browser cleanup requested."));
|
|
443
461
|
// Begin releasing immediately, in case the host cuts shutdown handlers short.
|
|
444
|
-
await this.closeOwned();
|
|
462
|
+
await Promise.all([this.closeOwned(), this.dropDelegate()]);
|
|
445
463
|
// Only after release: a live session may still be using the extension. Best-effort within the host's shutdown time.
|
|
446
464
|
// Content-Type is cleared on the bodyless DELETE as Stagehand's own cleanup does.
|
|
447
465
|
const extension = this.extension;
|
|
@@ -492,6 +510,18 @@ export class BrowseSession {
|
|
|
492
510
|
}
|
|
493
511
|
/** Runs one operation; a dropped connection is repaired and the operation repeated only when that cannot double an action. */
|
|
494
512
|
async dispatch(params, context, ai) {
|
|
513
|
+
if (!this.delegate && !this.session && this.profileBroker && !ai && OPENS_BROWSER.has(params.action)) {
|
|
514
|
+
// SAFETY: only browse actions open a browser, and browse_ai calls were excluded above.
|
|
515
|
+
const key = await this.sharedKey(params, context);
|
|
516
|
+
if (key) {
|
|
517
|
+
const connection = await BrokerConnection.for(key);
|
|
518
|
+
const conv = randomUUID();
|
|
519
|
+
connection.openConversation(conv, this.identity, { resolveConfig: this.resolveConfig, generate: this.stagehandModel.model?.generate, classify: this.hostClassify });
|
|
520
|
+
this.delegate = { conv, owner: this.owner(context), connection };
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (this.delegate)
|
|
524
|
+
return this.forward(params, context, ai);
|
|
495
525
|
const attempt = () => ai ? this.ai(params, context) : this.browse(params, context);
|
|
496
526
|
try {
|
|
497
527
|
return await attempt();
|
|
@@ -506,11 +536,45 @@ export class BrowseSession {
|
|
|
506
536
|
throw new BrowseToolError("connection_restored", `The connection dropped during ${params.action} and was restored with pages and logins intact, but the action's outcome is unknown. Take a snapshot before retrying.`);
|
|
507
537
|
}
|
|
508
538
|
}
|
|
539
|
+
/** The shared browser a call would open, as the broker keys it: an attached browser or a persistent profile; else none. */
|
|
540
|
+
async sharedKey(p, context) {
|
|
541
|
+
if ((p.backend ?? this.defaultBackend) !== "local")
|
|
542
|
+
return undefined;
|
|
543
|
+
if (p.cdpUrl)
|
|
544
|
+
return `attach:${p.cdpUrl}`;
|
|
545
|
+
const config = await this.config(context, "local");
|
|
546
|
+
if (p.endpoint) {
|
|
547
|
+
const remote = config.remoteBrowsers?.[p.endpoint];
|
|
548
|
+
return remote ? `attach:${remote.cdpUrl}` : undefined;
|
|
549
|
+
}
|
|
550
|
+
return config.localUserDataDir ? `launch:${config.localUserDataDir}` : undefined;
|
|
551
|
+
}
|
|
552
|
+
/** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
|
|
553
|
+
async forward(params, context, ai) {
|
|
554
|
+
const { conv, connection } = this.delegate;
|
|
555
|
+
const { signal, purpose: _purpose, ...rest } = context;
|
|
556
|
+
try {
|
|
557
|
+
const output = await connection.run(conv, params, rest, ai, this.defaultBackend, signal);
|
|
558
|
+
if (params.action === "close")
|
|
559
|
+
await this.dropDelegate();
|
|
560
|
+
return output;
|
|
561
|
+
}
|
|
562
|
+
catch (error) {
|
|
563
|
+
if (connection.closed && this.delegate?.connection === connection)
|
|
564
|
+
this.delegate = undefined;
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
async dropDelegate() {
|
|
569
|
+
const delegate = this.delegate;
|
|
570
|
+
this.delegate = undefined;
|
|
571
|
+
await delegate?.connection.closeConversation(delegate.conv).catch(() => undefined);
|
|
572
|
+
}
|
|
509
573
|
/** Reattaches to a remote session that outlived its connection; otherwise releases it and reports the loss. */
|
|
510
574
|
async reconnect(session, context) {
|
|
511
575
|
if (session.backend === "local") {
|
|
512
576
|
await this.closeOwned(session);
|
|
513
|
-
throw new BrowseToolError("session_lost", `The local browser connection was lost; the action may have completed. ${session.cdpUrl ? "The attached browser was left running; start again with backend local and the same cdpUrl or endpoint, then inspect the page before retrying." : "The owned browser was closed; start again with backend local."}`);
|
|
577
|
+
throw new BrowseToolError("session_lost", `The local browser connection was lost; the action may have completed. ${session.cdpUrl ? "The attached browser was left running; start again with backend local and the same cdpUrl or endpoint, then inspect the page before retrying." : session.shared ? "This conversation left the profile's browser; start again with backend local." : "The owned browser was closed; start again with backend local."}`);
|
|
514
578
|
}
|
|
515
579
|
const sessionId = session.browser.sessionId;
|
|
516
580
|
const remote = await session.client.sessions.retrieve(sessionId, { timeout: 5000, maxRetries: 0 }).catch(() => undefined);
|
|
@@ -755,38 +819,15 @@ export class BrowseSession {
|
|
|
755
819
|
if (secret)
|
|
756
820
|
this.secrets.add(secret);
|
|
757
821
|
const userDataDir = attach ? undefined : config.localUserDataDir || undefined;
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
let browser;
|
|
768
|
-
try {
|
|
769
|
-
browser = guard ? await connectRetrying(() => localBrowser.connect({ cdpUrl: guard.url, ...(extensionCdpUrl ? { extensionCdpUrl } : {}) }), context.signal).catch(error => {
|
|
770
|
-
if (!extensionCdpUrl)
|
|
771
|
-
throw error;
|
|
772
|
-
throw new BrowseToolError("attach_failed", `Could not attach to the remote 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.`);
|
|
773
|
-
}) : await localBrowser.launch({
|
|
774
|
-
headless: headless ?? false, viewport: { width: 1280, height: 800 },
|
|
775
|
-
...(config.localExecutablePath ? { executablePath: config.localExecutablePath } : {}),
|
|
776
|
-
port, ...(userDataDir ? { userDataDir, ignoreDefaultArgs: PERSISTENT_PROFILE_IGNORED_ARGS } : {}),
|
|
777
|
-
}).catch(error => {
|
|
778
|
-
// Chrome exits with code 21 when another Chrome process holds the user data directory.
|
|
779
|
-
if (userDataDir && /\bcode 21\b/.test(messageOf(error))) {
|
|
780
|
-
throw new BrowseToolError("profile_in_use", `The persistent local Chrome profile (${userDataDir}) is already in use, likely by another conversation's browser. Close that browser, then start again.`);
|
|
781
|
-
}
|
|
782
|
-
throw error;
|
|
783
|
-
});
|
|
784
|
-
}
|
|
785
|
-
catch (error) {
|
|
786
|
-
await guard?.close();
|
|
787
|
-
throw error;
|
|
788
|
-
}
|
|
789
|
-
return this.initialize({ owner: this.owner(context), backend, config, browser, cdpUrl: attach?.cdpUrl, endpoint: p.endpoint, guard, headless: attach ? undefined : headless ?? false, quitPort: userDataDir ? port : undefined, debugPort: port, snapshots: new Map(), keepAlive: false, domainPolicy }, context);
|
|
822
|
+
if (attach || userDataDir)
|
|
823
|
+
return this.joinShared(context, config, p, domainPolicy, attach, userDataDir);
|
|
824
|
+
// A temporary profile belongs to this conversation alone.
|
|
825
|
+
const port = await freePort();
|
|
826
|
+
const browser = await localBrowser.launch({
|
|
827
|
+
headless: headless ?? false, viewport: { width: 1280, height: 800 },
|
|
828
|
+
...(config.localExecutablePath ? { executablePath: config.localExecutablePath } : {}), port,
|
|
829
|
+
});
|
|
830
|
+
return this.initialize({ owner: this.owner(context), backend, config, browser, headless: headless ?? false, debugPort: port, snapshots: new Map(), keepAlive: false, domainPolicy, ownedTabs: new Set(), createdTabs: new Set() }, context);
|
|
790
831
|
}
|
|
791
832
|
const client = this.client(config);
|
|
792
833
|
if (contextId) {
|
|
@@ -829,7 +870,7 @@ export class BrowseSession {
|
|
|
829
870
|
context.signal.throwIfAborted();
|
|
830
871
|
browser = await launch(false);
|
|
831
872
|
}
|
|
832
|
-
return this.initialize({ owner: this.owner(context), backend, config, client, browser, contextId, snapshots: new Map(), keepAlive, proxyCountry, domainPolicy }, context);
|
|
873
|
+
return this.initialize({ owner: this.owner(context), backend, config, client, browser, contextId, snapshots: new Map(), keepAlive, proxyCountry, domainPolicy, ownedTabs: new Set(), createdTabs: new Set() }, context);
|
|
833
874
|
}
|
|
834
875
|
async initialize(session, context) {
|
|
835
876
|
const { browser } = session;
|
|
@@ -855,6 +896,218 @@ export class BrowseSession {
|
|
|
855
896
|
throw error;
|
|
856
897
|
}
|
|
857
898
|
}
|
|
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
|
+
*/
|
|
904
|
+
async joinShared(context, config, p, domainPolicy, attach, userDataDir) {
|
|
905
|
+
const key = attach ? `attach:${attach.cdpUrl}` : `launch:${userDataDir}`;
|
|
906
|
+
let shared;
|
|
907
|
+
for (;;) {
|
|
908
|
+
const pending = sharedBrowsers.get(key);
|
|
909
|
+
if (!pending) {
|
|
910
|
+
const opening = this.openShared(key, context, p, domainPolicy, config, attach, userDataDir);
|
|
911
|
+
sharedBrowsers.set(key, opening);
|
|
912
|
+
opening.catch(() => { if (sharedBrowsers.get(key) === opening)
|
|
913
|
+
sharedBrowsers.delete(key); });
|
|
914
|
+
shared = await opening;
|
|
915
|
+
break;
|
|
916
|
+
}
|
|
917
|
+
const existing = await pending.catch(() => undefined);
|
|
918
|
+
if (existing && !existing.closing && !existing.browser.closed) {
|
|
919
|
+
shared = existing;
|
|
920
|
+
break;
|
|
921
|
+
}
|
|
922
|
+
// Gone, failed, or quitting: open a fresh one once Chrome has let go of the profile.
|
|
923
|
+
if (sharedBrowsers.get(key) === pending)
|
|
924
|
+
sharedBrowsers.delete(key);
|
|
925
|
+
await existing?.closing?.catch(() => undefined);
|
|
926
|
+
context.signal.throwIfAborted();
|
|
927
|
+
}
|
|
928
|
+
try {
|
|
929
|
+
context.signal.throwIfAborted();
|
|
930
|
+
if (!attach && p.headless !== undefined && p.headless !== shared.headless) {
|
|
931
|
+
throw new BrowseToolError("shared_browser", `This profile's browser is already running ${shared.headless ? "headless" : "with a visible window"} for another conversation, so this start cannot change that. Start again without headless.`);
|
|
932
|
+
}
|
|
933
|
+
if (JSON.stringify(domainPolicy) !== JSON.stringify(shared.domainPolicy)) {
|
|
934
|
+
throw new BrowseToolError("shared_browser", "Another conversation is using this browser with different allowed or blocked domains, and one browser has one domain policy. Start without allowedDomains and blockedDomains, or use another backend.");
|
|
935
|
+
}
|
|
936
|
+
const session = {
|
|
937
|
+
owner: this.owner(context), backend: "local", config, browser: shared.browser, stagehand: shared.stagehand, cdpUrl: shared.cdpUrl,
|
|
938
|
+
endpoint: shared.endpoint, headless: shared.headless, debugPort: shared.debugPort, snapshots: new Map(), keepAlive: false,
|
|
939
|
+
domainPolicy: shared.domainPolicy, shared, ownedTabs: new Set(), createdTabs: new Set(),
|
|
940
|
+
};
|
|
941
|
+
const first = shared.firstTab;
|
|
942
|
+
shared.firstTab = undefined;
|
|
943
|
+
if (first || !attach) {
|
|
944
|
+
const tab = first ?? (await shared.browser.context.newPage("about:blank")).pageId;
|
|
945
|
+
session.ownedTabs.add(tab);
|
|
946
|
+
session.createdTabs.add(tab);
|
|
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
|
+
}
|
|
954
|
+
shared.users.add(session);
|
|
955
|
+
this.session = session;
|
|
956
|
+
return session;
|
|
957
|
+
}
|
|
958
|
+
catch (error) {
|
|
959
|
+
if (!shared.users.size)
|
|
960
|
+
await this.retire(shared).catch(() => undefined);
|
|
961
|
+
throw error;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
/** Launches a persistent profile or attaches to a browser, with one Stagehand whose default inference follows the AI turn. */
|
|
965
|
+
async openShared(key, context, p, domainPolicy, config, attach, userDataDir) {
|
|
966
|
+
await retiringBrowsers.get(key);
|
|
967
|
+
let browser;
|
|
968
|
+
let guard;
|
|
969
|
+
let quitPort;
|
|
970
|
+
if (attach) {
|
|
971
|
+
// Stagehand's close() would send Browser.close to an attached browser: connect through a guard that drops it.
|
|
972
|
+
const opened = await guardEndpoint(attach.cdpUrl, context.signal, attach.headers).catch(error => {
|
|
973
|
+
if (context.signal.aborted)
|
|
974
|
+
throw error;
|
|
975
|
+
throw new BrowseToolError("attach_failed", `Could not reach the DevTools endpoint: ${messageOf(error).slice(0, 200)}. Check cdpUrl and any headers it needs.`);
|
|
976
|
+
});
|
|
977
|
+
guard = opened;
|
|
978
|
+
// Stagehand's in-browser extension would follow the client to the loopback guard, which a browser elsewhere cannot reach.
|
|
979
|
+
const extensionCdpUrl = attach.extensionCdpUrl ?? (!LOOPBACK.has(new URL(attach.cdpUrl).hostname) ? opened.browserUrl : undefined);
|
|
980
|
+
try {
|
|
981
|
+
browser = await connectRetrying(() => localBrowser.connect({ cdpUrl: opened.url, ...(extensionCdpUrl ? { extensionCdpUrl } : {}) }), context.signal).catch(error => {
|
|
982
|
+
if (!extensionCdpUrl)
|
|
983
|
+
throw error;
|
|
984
|
+
throw new BrowseToolError("attach_failed", `Could not attach to the remote 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.`);
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
catch (error) {
|
|
988
|
+
await opened.close();
|
|
989
|
+
throw error;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
else {
|
|
993
|
+
// The avatar and profile menu then say which harness owns the window; a profile Chrome cannot rename still launches.
|
|
994
|
+
await nameChromeProfile(userDataDir, `${this.identity.name} browse`).catch(() => undefined);
|
|
995
|
+
quitPort = await freePort();
|
|
996
|
+
browser = await localBrowser.launch({
|
|
997
|
+
headless: p.headless ?? false, viewport: { width: 1280, height: 800 },
|
|
998
|
+
...(config.localExecutablePath ? { executablePath: config.localExecutablePath } : {}),
|
|
999
|
+
port: quitPort, userDataDir, ignoreDefaultArgs: PERSISTENT_PROFILE_IGNORED_ARGS,
|
|
1000
|
+
}).catch(error => {
|
|
1001
|
+
// Another Chrome holds the user data directory: Linux Chrome exits with code 21, macOS Chrome hands the launch
|
|
1002
|
+
// to it and exits with code 0 before opening a debugging port.
|
|
1003
|
+
if (/\bcode (?:21|0)\b/.test(messageOf(error))) {
|
|
1004
|
+
throw new BrowseToolError("profile_in_use", `The persistent local Chrome profile (${userDataDir}) is open in a Chrome this tool does not manage, such as one a conversation running an older browse version launched. Close that browser or restart that conversation, then start again.`);
|
|
1005
|
+
}
|
|
1006
|
+
throw error;
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
const inference = {};
|
|
1010
|
+
const model = { model: { generate: ((params) => {
|
|
1011
|
+
if (!inference.generate)
|
|
1012
|
+
throw new Error("Stagehand asked for inference outside a browse_ai call.");
|
|
1013
|
+
return inference.generate(params);
|
|
1014
|
+
}) } };
|
|
1015
|
+
let stagehand;
|
|
1016
|
+
try {
|
|
1017
|
+
context.signal.throwIfAborted();
|
|
1018
|
+
for (let attempt = 0; !stagehand; attempt++) {
|
|
1019
|
+
try {
|
|
1020
|
+
stagehand = await Stagehand.create({ browser, logging: { level: "off" }, ...model });
|
|
1021
|
+
}
|
|
1022
|
+
catch (error) {
|
|
1023
|
+
// A client that died while attached leaves the browser's runtime initialized; this process now owns it.
|
|
1024
|
+
if (!guard || attempt > 0 || !/already initialized/i.test(messageOf(error)))
|
|
1025
|
+
throw error;
|
|
1026
|
+
await resetStagehandRuntime(guard.url, context.signal);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
// The fence goes up before any page loads; Stagehand intercepts every http(s) request in the context.
|
|
1030
|
+
const [, active] = await Promise.all([browser.context.addInitScript(DIALOG_GUARD), browser.context.activePage(),
|
|
1031
|
+
domainPolicy ? browser.context.setDomainPolicy(stagehandPolicy(domainPolicy)) : undefined]);
|
|
1032
|
+
context.signal.throwIfAborted();
|
|
1033
|
+
return {
|
|
1034
|
+
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 ? undefined : active?.pageId,
|
|
1036
|
+
inference, aiTurn: Promise.resolve(),
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
catch (error) {
|
|
1040
|
+
await deadline(stagehand?.close() ?? Promise.resolve(), 1500).catch(() => undefined);
|
|
1041
|
+
if (quitPort)
|
|
1042
|
+
await deadline(quitChrome(quitPort), 5000).catch(() => undefined);
|
|
1043
|
+
await deadline(browser.close(), 5000).catch(() => undefined);
|
|
1044
|
+
await guard?.close();
|
|
1045
|
+
throw error;
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Releases a shared browser no conversation uses: quits a launched profile's Chrome so it writes its cookies, and only
|
|
1050
|
+
* disconnects from an attached one. Set synchronously, so a conversation joining meanwhile opens a fresh browser instead.
|
|
1051
|
+
*/
|
|
1052
|
+
retire(shared, before) {
|
|
1053
|
+
if (!shared.closing) {
|
|
1054
|
+
shared.closing = (async () => {
|
|
1055
|
+
await before?.().catch(() => undefined);
|
|
1056
|
+
await deadline(shared.stagehand.close(), 1500).catch(() => undefined);
|
|
1057
|
+
if (shared.quitPort)
|
|
1058
|
+
await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
|
|
1059
|
+
try {
|
|
1060
|
+
await deadline(shared.browser.close(), 5000);
|
|
1061
|
+
}
|
|
1062
|
+
finally {
|
|
1063
|
+
await shared.guard?.close();
|
|
1064
|
+
}
|
|
1065
|
+
})();
|
|
1066
|
+
const settled = shared.closing.catch(() => undefined);
|
|
1067
|
+
retiringBrowsers.set(shared.key, settled);
|
|
1068
|
+
void settled.then(() => { if (retiringBrowsers.get(shared.key) === settled)
|
|
1069
|
+
retiringBrowsers.delete(shared.key); });
|
|
1070
|
+
}
|
|
1071
|
+
return shared.closing;
|
|
1072
|
+
}
|
|
1073
|
+
/** Runs a browse_ai call on a shared Stagehand in turn, lending it this conversation's default inference meanwhile. */
|
|
1074
|
+
takeAiTurn(shared, signal, run) {
|
|
1075
|
+
const turn = shared.aiTurn.then(async () => {
|
|
1076
|
+
signal.throwIfAborted();
|
|
1077
|
+
shared.inference.generate = this.stagehandModel.model?.generate;
|
|
1078
|
+
try {
|
|
1079
|
+
return await run();
|
|
1080
|
+
}
|
|
1081
|
+
finally {
|
|
1082
|
+
shared.inference.generate = undefined;
|
|
1083
|
+
}
|
|
1084
|
+
});
|
|
1085
|
+
shared.aiTurn = turn.catch(() => undefined);
|
|
1086
|
+
return turn;
|
|
1087
|
+
}
|
|
1088
|
+
/** Closes the tabs a conversation opened in a shared browser; claimed tabs, the user's own, stay open. */
|
|
1089
|
+
async closeCreatedTabs(session) {
|
|
1090
|
+
if (!session.createdTabs.size)
|
|
1091
|
+
return;
|
|
1092
|
+
const pages = await deadline(session.browser.context.pages(), 2_000).catch(() => []);
|
|
1093
|
+
for (const tab of session.createdTabs)
|
|
1094
|
+
session.shared?.closedTabs.add(tab);
|
|
1095
|
+
await Promise.allSettled(pages.filter(page => session.createdTabs.has(page.pageId)).map(page => deadline(page.close(), 3_000)));
|
|
1096
|
+
}
|
|
1097
|
+
/** Whether another conversation sharing this browser uses the tab, or one closed it. */
|
|
1098
|
+
ownedByOther(session, tabId) {
|
|
1099
|
+
if (session.shared?.closedTabs.has(tabId))
|
|
1100
|
+
return true;
|
|
1101
|
+
for (const user of session.shared?.users ?? [])
|
|
1102
|
+
if (user !== session && user.ownedTabs.has(tabId))
|
|
1103
|
+
return true;
|
|
1104
|
+
return false;
|
|
1105
|
+
}
|
|
1106
|
+
/** The tabs this conversation may use: all of them, except in a shared browser the ones another conversation uses. */
|
|
1107
|
+
async visiblePages(session) {
|
|
1108
|
+
const pages = await session.browser.context.pages();
|
|
1109
|
+
return session.shared ? pages.filter(page => !this.ownedByOther(session, page.pageId)) : pages;
|
|
1110
|
+
}
|
|
858
1111
|
/** Starts recording every tab's network traffic over a DevTools connection of its own. */
|
|
859
1112
|
async harStart(session, context) {
|
|
860
1113
|
if (session.har)
|
|
@@ -874,8 +1127,10 @@ export class BrowseSession {
|
|
|
874
1127
|
this.secrets.add(browserUrl);
|
|
875
1128
|
}
|
|
876
1129
|
context.signal.throwIfAborted();
|
|
1130
|
+
// A shared browser holds other conversations' tabs: record only this one's, and the popups they open.
|
|
1131
|
+
const include = session.shared ? (targetId) => session.ownedTabs.has(targetId) : undefined;
|
|
877
1132
|
try {
|
|
878
|
-
session.har = await HarRecorder.start(browserUrl, AbortSignal.any([context.signal, AbortSignal.timeout(15_000)]));
|
|
1133
|
+
session.har = await HarRecorder.start(browserUrl, AbortSignal.any([context.signal, AbortSignal.timeout(15_000)]), include);
|
|
879
1134
|
}
|
|
880
1135
|
catch (error) {
|
|
881
1136
|
context.signal.throwIfAborted();
|
|
@@ -891,6 +1146,21 @@ export class BrowseSession {
|
|
|
891
1146
|
session.har?.close();
|
|
892
1147
|
session.har = undefined;
|
|
893
1148
|
session.closing = (async () => {
|
|
1149
|
+
const shared = session.shared;
|
|
1150
|
+
if (shared) {
|
|
1151
|
+
if (this.session === session)
|
|
1152
|
+
this.session = undefined;
|
|
1153
|
+
const closeTabs = () => this.closeCreatedTabs(session);
|
|
1154
|
+
// Still a user while its tabs close, so no other conversation sees them as free meanwhile.
|
|
1155
|
+
if (shared.users.size > 1)
|
|
1156
|
+
await closeTabs();
|
|
1157
|
+
shared.users.delete(session);
|
|
1158
|
+
// The last to leave retires the browser, in the same tick, so a conversation joining meanwhile never adopts a
|
|
1159
|
+
// browser about to quit. Quitting a launched profile closes its tabs anyway; an attached one keeps running.
|
|
1160
|
+
if (!shared.users.size)
|
|
1161
|
+
await this.retire(shared, shared.guard ? closeTabs : undefined);
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
894
1164
|
if (session.backend === "local") {
|
|
895
1165
|
// Release the in-browser runtime before disconnecting so it can be attached again.
|
|
896
1166
|
await deadline(session.stagehand?.close() ?? Promise.resolve(), 1500).catch(() => undefined);
|
|
@@ -932,13 +1202,16 @@ export class BrowseSession {
|
|
|
932
1202
|
}
|
|
933
1203
|
}
|
|
934
1204
|
async page(session, tabId) {
|
|
935
|
-
const pages = await
|
|
1205
|
+
const pages = await this.visiblePages(session);
|
|
936
1206
|
const id = tabId ?? session.tabId;
|
|
937
|
-
const page = id ? pages.find(page => page.pageId === id) : pages[0];
|
|
938
|
-
if (!page)
|
|
939
|
-
throw new BrowseToolError("tab_missing",
|
|
1207
|
+
const page = id ? pages.find(page => page.pageId === id) : pages.find(page => session.ownedTabs.has(page.pageId)) ?? pages[0];
|
|
1208
|
+
if (!page) {
|
|
1209
|
+
throw new BrowseToolError("tab_missing", `The target tab is closed or missing${session.shared ? ", or another conversation sharing this browser uses it" : ""}. List tabs, select an existing tab, or create a new one.`);
|
|
1210
|
+
}
|
|
940
1211
|
if (!session.tabId)
|
|
941
1212
|
session.tabId = page.pageId;
|
|
1213
|
+
// In a shared browser, acting on a tab claims it, so no other conversation can use it meanwhile.
|
|
1214
|
+
session.ownedTabs.add(page.pageId);
|
|
942
1215
|
return page;
|
|
943
1216
|
}
|
|
944
1217
|
/**
|
|
@@ -1193,7 +1466,7 @@ export class BrowseSession {
|
|
|
1193
1466
|
}
|
|
1194
1467
|
return this.output(p.action, session, undefined, { browser: source.browser, profile, domains: imported.domains,
|
|
1195
1468
|
matched: imported.matched, imported: imported.cookies.length, skipped: imported.skipped,
|
|
1196
|
-
reloadRequired: imported.cookies.length > 0, persistedOnClose: Boolean(session.contextId || session.quitPort) });
|
|
1469
|
+
reloadRequired: imported.cookies.length > 0, persistedOnClose: Boolean(session.contextId || session.quitPort || session.shared?.quitPort) });
|
|
1197
1470
|
}
|
|
1198
1471
|
if (!p.target && DIRECT_ACTIONS.has(p.action) && !(p.action === "tab_select" && session.backend === "local"))
|
|
1199
1472
|
return this.direct(session, p, context);
|
|
@@ -1207,7 +1480,7 @@ export class BrowseSession {
|
|
|
1207
1480
|
return tabsOperation({ context: session.browser.context }, input);
|
|
1208
1481
|
});
|
|
1209
1482
|
context.signal.throwIfAborted();
|
|
1210
|
-
return this.output(p.action, session, undefined, { tabs });
|
|
1483
|
+
return this.output(p.action, session, undefined, { tabs: tabs.filter(tab => !this.ownedByOther(session, tab.tabId)) });
|
|
1211
1484
|
}
|
|
1212
1485
|
if (p.action === "tab_new") {
|
|
1213
1486
|
const refused = p.url ? fenced(p.url, session.domainPolicy) : undefined;
|
|
@@ -1217,6 +1490,9 @@ export class BrowseSession {
|
|
|
1217
1490
|
context.signal.throwIfAborted();
|
|
1218
1491
|
await session.browser.context.setActivePage(page);
|
|
1219
1492
|
session.tabId = page.pageId;
|
|
1493
|
+
session.ownedTabs.add(page.pageId);
|
|
1494
|
+
session.createdTabs.add(page.pageId);
|
|
1495
|
+
await session.har?.follow(page.pageId);
|
|
1220
1496
|
return this.output(p.action, session, page);
|
|
1221
1497
|
}
|
|
1222
1498
|
const page = await this.page(session, p.tabId);
|
|
@@ -1235,10 +1511,15 @@ export class BrowseSession {
|
|
|
1235
1511
|
}
|
|
1236
1512
|
if (p.action === "tab_close") {
|
|
1237
1513
|
context.signal.throwIfAborted();
|
|
1514
|
+
session.shared?.closedTabs.add(page.pageId);
|
|
1238
1515
|
await page.close();
|
|
1239
1516
|
session.snapshots.delete(page.pageId);
|
|
1240
|
-
|
|
1241
|
-
|
|
1517
|
+
session.ownedTabs.delete(page.pageId);
|
|
1518
|
+
session.createdTabs.delete(page.pageId);
|
|
1519
|
+
if (session.tabId === page.pageId) {
|
|
1520
|
+
const rest = await this.visiblePages(session);
|
|
1521
|
+
session.tabId = (rest.find(tab => session.ownedTabs.has(tab.pageId)) ?? (session.shared ? undefined : rest[0]))?.pageId;
|
|
1522
|
+
}
|
|
1242
1523
|
return this.output(p.action, session, undefined, { closedTabId: page.pageId, selectedTabId: session.tabId ?? null });
|
|
1243
1524
|
}
|
|
1244
1525
|
if (p.action === "screenshot") {
|
|
@@ -1405,22 +1686,23 @@ export class BrowseSession {
|
|
|
1405
1686
|
const page = await this.page(session, p.tabId);
|
|
1406
1687
|
const options = { page, timeout: p.timeoutMs ?? 120_000, ...(model ? { model: model } : {}) };
|
|
1407
1688
|
context.signal.throwIfAborted();
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1689
|
+
const stagehand = session.stagehand;
|
|
1690
|
+
const run = async () => {
|
|
1691
|
+
try {
|
|
1692
|
+
if (p.action === "act") {
|
|
1693
|
+
const acted = await stagehand.act(p.instruction, options);
|
|
1694
|
+
return { result: acted, isError: !acted.data.success };
|
|
1695
|
+
}
|
|
1696
|
+
if (p.action === "observe")
|
|
1697
|
+
return { result: await stagehand.observe(p.instruction, options), isError: false };
|
|
1698
|
+
return { result: schema ? await stagehand.extract(p.instruction, schema, options) : await stagehand.extract(p.instruction, options), isError: false };
|
|
1414
1699
|
}
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
if (p.action === "act")
|
|
1422
|
-
session.snapshots.clear();
|
|
1423
|
-
}
|
|
1700
|
+
finally {
|
|
1701
|
+
if (p.action === "act")
|
|
1702
|
+
session.snapshots.clear();
|
|
1703
|
+
}
|
|
1704
|
+
};
|
|
1705
|
+
const { result, isError } = session.shared ? await this.takeAiTurn(session.shared, context.signal, run) : await run();
|
|
1424
1706
|
return { ...await this.output(p.action, session, page, result), isError, ...(isError ? { code: "act_failed" } : {}) };
|
|
1425
1707
|
}
|
|
1426
1708
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@edlsh/browse-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.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",
|
|
@@ -42,7 +42,8 @@
|
|
|
42
42
|
"prepublishOnly": "bun run build",
|
|
43
43
|
"test": "bun test",
|
|
44
44
|
"test:local": "bun test/local-browser.integration.ts",
|
|
45
|
-
"test:hosted": "bun test/hosted-browser.integration.ts"
|
|
45
|
+
"test:hosted": "bun test/hosted-browser.integration.ts",
|
|
46
|
+
"test:shared": "bun test/shared-profile.integration.ts"
|
|
46
47
|
},
|
|
47
48
|
"engines": {
|
|
48
49
|
"node": ">=22.19.0",
|