@edlsh/browse-core 0.2.1 → 0.3.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 CHANGED
@@ -15,6 +15,7 @@ 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
 
@@ -113,8 +113,8 @@ export declare const brokerMessage: z.ZodUnion<readonly [z.ZodObject<{
113
113
  }>>;
114
114
  classifier: z.ZodOptional<z.ZodString>;
115
115
  purpose: z.ZodEnum<{
116
- ask: "ask";
117
116
  browser: "browser";
117
+ ask: "ask";
118
118
  ai: "ai";
119
119
  jev: "jev";
120
120
  }>;
@@ -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;
@@ -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
+ };
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. */
@@ -249,8 +253,8 @@ export declare class BrowseSession {
249
253
  private reference;
250
254
  private target;
251
255
  private output;
252
- /** Installed supported browsers, optionally only the requested one. */
253
- private cookieSources;
256
+ /** A cookie provider call, with its refusals as tool errors. */
257
+ private fromCookies;
254
258
  /** 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
259
  private cookieProfile;
256
260
  private browse;
package/dist/session.js CHANGED
@@ -14,7 +14,7 @@ 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 { BROWSERS, findBrowserProfiles, installedBrowsers, listBrowserProfiles, normalizeCookieDomains, readBrowserCookies } from "./browser-cookies.js";
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
20
  const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -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, ...(sessionId ? { sessionId } : {}) }));
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
- const { targetInfos } = await send("Target.getTargets");
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)
@@ -374,6 +394,7 @@ export class BrowseSession {
374
394
  /** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
375
395
  keepAliveAllowed = true;
376
396
  profileBroker;
397
+ cookies;
377
398
  /** This conversation's calls run in the broker that owns its shared browser, until close. */
378
399
  delegate;
379
400
  /** Stagehand's runtime extension, uploaded once per tool instance instead of on every launch. */
@@ -388,6 +409,7 @@ export class BrowseSession {
388
409
  this.hostClassify = hostClassify;
389
410
  this.identity = identity;
390
411
  this.profileBroker = options.profileBroker ?? true;
412
+ this.cookies = options.cookies ?? localCookieProvider;
391
413
  this.stagehandModel = inference ? { model: { generate: inference.generate } } : {};
392
414
  this.describeInference = inference?.describe ?? (async () => "gateway-auto");
393
415
  }
@@ -513,6 +535,10 @@ export class BrowseSession {
513
535
  if (!this.delegate && !this.session && this.profileBroker && !ai && OPENS_BROWSER.has(params.action)) {
514
536
  // SAFETY: only browse actions open a browser, and browse_ai calls were excluded above.
515
537
  const key = await this.sharedKey(params, context);
538
+ // The broker reads cookies with its own machine's browsers, not a host's provider.
539
+ if (key && params.action === "cookie_import" && this.cookies !== localCookieProvider) {
540
+ throw new BrowseToolError("unsupported_backend", "This host's cookie source imports into Browserbase sessions only. Start with backend \"browserbase\", then cookie_import.");
541
+ }
516
542
  if (key) {
517
543
  const connection = await BrokerConnection.for(key);
518
544
  const conv = randomUUID();
@@ -520,6 +546,9 @@ export class BrowseSession {
520
546
  this.delegate = { conv, owner: this.owner(context), connection };
521
547
  }
522
548
  }
549
+ if (this.delegate && !ai && params.action === "cookie_import" && this.cookies !== localCookieProvider) {
550
+ throw new BrowseToolError("unsupported_backend", "This host's cookie source imports into Browserbase sessions only. Close, start with backend \"browserbase\", then cookie_import.");
551
+ }
523
552
  if (this.delegate)
524
553
  return this.forward(params, context, ai);
525
554
  const attempt = () => ai ? this.ai(params, context) : this.browse(params, context);
@@ -958,6 +987,8 @@ export class BrowseSession {
958
987
  let browser;
959
988
  let guard;
960
989
  let quitPort;
990
+ /** A tab opened in an attached browser that had none; the first conversation takes it as its own. */
991
+ let createdTab;
961
992
  if (attach) {
962
993
  // Stagehand's close() would send Browser.close to an attached browser: connect through a guard that drops it.
963
994
  const opened = await guardEndpoint(attach.cdpUrl, context.signal, attach.headers).catch(error => {
@@ -966,6 +997,11 @@ export class BrowseSession {
966
997
  throw new BrowseToolError("attach_failed", `Could not reach the DevTools endpoint: ${messageOf(error).slice(0, 200)}. Check cdpUrl and any headers it needs.`);
967
998
  });
968
999
  guard = opened;
1000
+ createdTab = await ensurePageTarget(opened.url, context.signal).catch(error => {
1001
+ if (context.signal.aborted)
1002
+ throw error;
1003
+ return undefined;
1004
+ });
969
1005
  // Stagehand's in-browser extension would follow the client to the loopback guard, which a browser elsewhere cannot reach.
970
1006
  const extensionCdpUrl = attach.extensionCdpUrl ?? (!LOOPBACK.has(new URL(attach.cdpUrl).hostname) ? opened.browserUrl : undefined);
971
1007
  try {
@@ -1023,7 +1059,7 @@ export class BrowseSession {
1023
1059
  context.signal.throwIfAborted();
1024
1060
  return {
1025
1061
  key, browser, stagehand, quitPort, debugPort: quitPort, guard, cdpUrl: attach?.cdpUrl, endpoint: p.endpoint,
1026
- headless: attach ? undefined : p.headless ?? false, domainPolicy, users: new Set(), closedTabs: new Set(), firstTab: attach ? undefined : active?.pageId,
1062
+ headless: attach ? undefined : p.headless ?? false, domainPolicy, users: new Set(), closedTabs: new Set(), firstTab: attach ? createdTab : active?.pageId,
1027
1063
  inference, aiTurn: Promise.resolve(),
1028
1064
  };
1029
1065
  }
@@ -1337,28 +1373,27 @@ export class BrowseSession {
1337
1373
  ...(data === undefined ? {} : { data }),
1338
1374
  };
1339
1375
  }
1340
- /** Installed supported browsers, optionally only the requested one. */
1341
- async cookieSources(browser) {
1342
- const installed = await installedBrowsers();
1343
- const sources = browser ? installed.filter(source => source.browser === browser) : installed;
1344
- if (sources.length)
1345
- return sources;
1346
- const supported = BROWSERS.map(entry => entry.name).join(", ");
1347
- throw new BrowseToolError("browser_not_installed", browser
1348
- ? `${BROWSERS.find(entry => entry.id === browser).name} is not installed in /Applications or ~/Applications. Call cookie_profiles to see the installed browsers.`
1349
- : `No supported browser is installed in /Applications or ~/Applications. Supported browsers: ${supported}.`);
1376
+ /** A cookie provider call, with its refusals as tool errors. */
1377
+ async fromCookies(read) {
1378
+ try {
1379
+ return await read();
1380
+ }
1381
+ catch (error) {
1382
+ if (error instanceof CookieSourceError)
1383
+ throw new BrowseToolError(error.code, error.message);
1384
+ throw error;
1385
+ }
1350
1386
  }
1351
1387
  /** 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. */
1352
1388
  async cookieProfile(p, signal) {
1353
- const sources = await this.cookieSources(p.browser);
1354
1389
  if (p.browser && p.profile)
1355
- return { source: sources[0], profile: p.profile };
1356
- const matches = (await findBrowserProfiles(p.domains, signal, sources)).filter(match => !p.profile || match.profile === p.profile);
1390
+ return { browser: p.browser, profile: p.profile };
1391
+ const matches = (await this.fromCookies(() => this.cookies.find(p.domains, p.browser, signal))).filter(match => !p.profile || match.profile === p.profile);
1357
1392
  if (matches.length === 1)
1358
- return { source: sources.find(source => source.browser === matches[0].browser), profile: matches[0].profile };
1359
- const names = sources.map(source => source.name).join(", ");
1393
+ return { browser: matches[0].browser, profile: matches[0].profile };
1360
1394
  if (!matches.length) {
1361
- throw new BrowseToolError("cookies_not_found", `No ${p.profile ? `${p.profile} profile` : "profile"} in the installed 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.`);
1395
+ const names = (await this.fromCookies(() => this.cookies.list(p.browser, signal))).map(browser => browser.name).join(", ");
1396
+ 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.`);
1362
1397
  }
1363
1398
  const listed = matches.map(match => `${match.browser} ${match.profile}${match.name ? ` (${match.name})` : ""}: ${match.cookies} cookies`).join("; ");
1364
1399
  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.`);
@@ -1368,8 +1403,7 @@ export class BrowseSession {
1368
1403
  const budget = operationTimeout(p, false);
1369
1404
  const pageTimeout = Math.ceil(Math.max(budget - 2_000, budget / 2));
1370
1405
  if (p.action === "cookie_profiles") {
1371
- const browsers = await Promise.all((await this.cookieSources(p.browser)).map(async (source) => ({ browser: source.browser, name: source.name,
1372
- profiles: (await listBrowserProfiles(source)).map(({ profile, name }) => name ? { profile, name } : { profile }) })));
1406
+ const browsers = await this.fromCookies(() => this.cookies.list(p.browser, context.signal));
1373
1407
  return { action: p.action, sessionId: null, data: { browsers } };
1374
1408
  }
1375
1409
  if (p.action === "status") {
@@ -1437,8 +1471,8 @@ export class BrowseSession {
1437
1471
  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.");
1438
1472
  }
1439
1473
  if (cookieSource) {
1440
- const { source, profile } = cookieSource;
1441
- const imported = await readBrowserCookies(source, profile, p.domains, context.signal, { cacheKey: true });
1474
+ const { browser, profile } = cookieSource;
1475
+ const imported = await this.fromCookies(() => this.cookies.read(browser, profile, p.domains, context.signal));
1442
1476
  // Imported values stay redacted from this binding's later output, e.g. evaluate reading document.cookie.
1443
1477
  // ponytail: values under 8 characters are too generic to redact without mangling ordinary output.
1444
1478
  for (const { value } of imported.cookies)
@@ -1458,7 +1492,7 @@ export class BrowseSession {
1458
1492
  session.snapshots.clear();
1459
1493
  }
1460
1494
  }
1461
- return this.output(p.action, session, undefined, { browser: source.browser, profile, domains: imported.domains,
1495
+ return this.output(p.action, session, undefined, { browser, profile, domains: imported.domains,
1462
1496
  matched: imported.matched, imported: imported.cookies.length, skipped: imported.skipped,
1463
1497
  reloadRequired: imported.cookies.length > 0, persistedOnClose: Boolean(session.contextId || session.quitPort || session.shared?.quitPort) });
1464
1498
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edlsh/browse-core",
3
- "version": "0.2.1",
3
+ "version": "0.3.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",